index.esm2017.js 828 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387
  1. import { _registerComponent, registerVersion, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app';
  2. import { Component } from '@firebase/component';
  3. import { Logger, LogLevel } from '@firebase/logger';
  4. import { FirebaseError, createMockUserToken, getModularInstance, deepEqual, getDefaultEmulatorHostnameAndPort, getUA, isIndexedDBAvailable, isSafari } from '@firebase/util';
  5. import { Integer, XhrIo, EventType, ErrorCode, createWebChannelTransport, getStatEventTarget, FetchXmlHttpFactory, WebChannel, Event, Stat, Md5 } from '@firebase/webchannel-wrapper';
  6. const b = "@firebase/firestore";
  7. /**
  8. * @license
  9. * Copyright 2017 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /**
  24. * Simple wrapper around a nullable UID. Mostly exists to make code more
  25. * readable.
  26. */
  27. class V {
  28. constructor(t) {
  29. this.uid = t;
  30. }
  31. isAuthenticated() {
  32. return null != this.uid;
  33. }
  34. /**
  35. * Returns a key representing this user, suitable for inclusion in a
  36. * dictionary.
  37. */ toKey() {
  38. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  39. }
  40. isEqual(t) {
  41. return t.uid === this.uid;
  42. }
  43. }
  44. /** A user with a null UID. */ V.UNAUTHENTICATED = new V(null),
  45. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  46. // non-FirebaseAuth providers.
  47. V.GOOGLE_CREDENTIALS = new V("google-credentials-uid"), V.FIRST_PARTY = new V("first-party-uid"),
  48. V.MOCK_USER = new V("mock-user");
  49. /**
  50. * @license
  51. * Copyright 2017 Google LLC
  52. *
  53. * Licensed under the Apache License, Version 2.0 (the "License");
  54. * you may not use this file except in compliance with the License.
  55. * You may obtain a copy of the License at
  56. *
  57. * http://www.apache.org/licenses/LICENSE-2.0
  58. *
  59. * Unless required by applicable law or agreed to in writing, software
  60. * distributed under the License is distributed on an "AS IS" BASIS,
  61. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62. * See the License for the specific language governing permissions and
  63. * limitations under the License.
  64. */
  65. let S = "9.23.0";
  66. /**
  67. * @license
  68. * Copyright 2017 Google LLC
  69. *
  70. * Licensed under the Apache License, Version 2.0 (the "License");
  71. * you may not use this file except in compliance with the License.
  72. * You may obtain a copy of the License at
  73. *
  74. * http://www.apache.org/licenses/LICENSE-2.0
  75. *
  76. * Unless required by applicable law or agreed to in writing, software
  77. * distributed under the License is distributed on an "AS IS" BASIS,
  78. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  79. * See the License for the specific language governing permissions and
  80. * limitations under the License.
  81. */
  82. const D = new Logger("@firebase/firestore");
  83. // Helper methods are needed because variables can't be exported as read/write
  84. function C() {
  85. return D.logLevel;
  86. }
  87. /**
  88. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  89. *
  90. * @param logLevel - The verbosity you set for activity and error logging. Can
  91. * be any of the following values:
  92. *
  93. * <ul>
  94. * <li>`debug` for the most verbose logging level, primarily for
  95. * debugging.</li>
  96. * <li>`error` to log errors only.</li>
  97. * <li><code>`silent` to turn off logging.</li>
  98. * </ul>
  99. */ function x(t) {
  100. D.setLogLevel(t);
  101. }
  102. function N(t, ...e) {
  103. if (D.logLevel <= LogLevel.DEBUG) {
  104. const n = e.map($);
  105. D.debug(`Firestore (${S}): ${t}`, ...n);
  106. }
  107. }
  108. function k(t, ...e) {
  109. if (D.logLevel <= LogLevel.ERROR) {
  110. const n = e.map($);
  111. D.error(`Firestore (${S}): ${t}`, ...n);
  112. }
  113. }
  114. /**
  115. * @internal
  116. */ function M(t, ...e) {
  117. if (D.logLevel <= LogLevel.WARN) {
  118. const n = e.map($);
  119. D.warn(`Firestore (${S}): ${t}`, ...n);
  120. }
  121. }
  122. /**
  123. * Converts an additional log parameter to a string representation.
  124. */ function $(t) {
  125. if ("string" == typeof t) return t;
  126. try {
  127. return e = t, JSON.stringify(e);
  128. } catch (e) {
  129. // Converting to JSON failed, just log the object directly
  130. return t;
  131. }
  132. /**
  133. * @license
  134. * Copyright 2020 Google LLC
  135. *
  136. * Licensed under the Apache License, Version 2.0 (the "License");
  137. * you may not use this file except in compliance with the License.
  138. * You may obtain a copy of the License at
  139. *
  140. * http://www.apache.org/licenses/LICENSE-2.0
  141. *
  142. * Unless required by applicable law or agreed to in writing, software
  143. * distributed under the License is distributed on an "AS IS" BASIS,
  144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  145. * See the License for the specific language governing permissions and
  146. * limitations under the License.
  147. */
  148. /** Formats an object as a JSON string, suitable for logging. */
  149. var e;
  150. }
  151. /**
  152. * @license
  153. * Copyright 2017 Google LLC
  154. *
  155. * Licensed under the Apache License, Version 2.0 (the "License");
  156. * you may not use this file except in compliance with the License.
  157. * You may obtain a copy of the License at
  158. *
  159. * http://www.apache.org/licenses/LICENSE-2.0
  160. *
  161. * Unless required by applicable law or agreed to in writing, software
  162. * distributed under the License is distributed on an "AS IS" BASIS,
  163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  164. * See the License for the specific language governing permissions and
  165. * limitations under the License.
  166. */
  167. /**
  168. * Unconditionally fails, throwing an Error with the given message.
  169. * Messages are stripped in production builds.
  170. *
  171. * Returns `never` and can be used in expressions:
  172. * @example
  173. * let futureVar = fail('not implemented yet');
  174. */ function O(t = "Unexpected state") {
  175. // Log the failure in addition to throw an exception, just in case the
  176. // exception is swallowed.
  177. const e = `FIRESTORE (${S}) INTERNAL ASSERTION FAILED: ` + t;
  178. // NOTE: We don't use FirestoreError here because these are internal failures
  179. // that cannot be handled by the user. (Also it would create a circular
  180. // dependency between the error and assert modules which doesn't work.)
  181. throw k(e), new Error(e);
  182. }
  183. /**
  184. * Fails if the given assertion condition is false, throwing an Error with the
  185. * given message if it did.
  186. *
  187. * Messages are stripped in production builds.
  188. */ function F(t, e) {
  189. t || O();
  190. }
  191. /**
  192. * Fails if the given assertion condition is false, throwing an Error with the
  193. * given message if it did.
  194. *
  195. * The code of callsites invoking this function are stripped out in production
  196. * builds. Any side-effects of code within the debugAssert() invocation will not
  197. * happen in this case.
  198. *
  199. * @internal
  200. */ function B(t, e) {
  201. t || O();
  202. }
  203. /**
  204. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  205. * instance of `T` before casting.
  206. */ function L(t,
  207. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  208. e) {
  209. return t;
  210. }
  211. /**
  212. * @license
  213. * Copyright 2017 Google LLC
  214. *
  215. * Licensed under the Apache License, Version 2.0 (the "License");
  216. * you may not use this file except in compliance with the License.
  217. * You may obtain a copy of the License at
  218. *
  219. * http://www.apache.org/licenses/LICENSE-2.0
  220. *
  221. * Unless required by applicable law or agreed to in writing, software
  222. * distributed under the License is distributed on an "AS IS" BASIS,
  223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  224. * See the License for the specific language governing permissions and
  225. * limitations under the License.
  226. */ const q = {
  227. // Causes are copied from:
  228. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  229. /** Not an error; returned on success. */
  230. OK: "ok",
  231. /** The operation was cancelled (typically by the caller). */
  232. CANCELLED: "cancelled",
  233. /** Unknown error or an error from a different error domain. */
  234. UNKNOWN: "unknown",
  235. /**
  236. * Client specified an invalid argument. Note that this differs from
  237. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  238. * problematic regardless of the state of the system (e.g., a malformed file
  239. * name).
  240. */
  241. INVALID_ARGUMENT: "invalid-argument",
  242. /**
  243. * Deadline expired before operation could complete. For operations that
  244. * change the state of the system, this error may be returned even if the
  245. * operation has completed successfully. For example, a successful response
  246. * from a server could have been delayed long enough for the deadline to
  247. * expire.
  248. */
  249. DEADLINE_EXCEEDED: "deadline-exceeded",
  250. /** Some requested entity (e.g., file or directory) was not found. */
  251. NOT_FOUND: "not-found",
  252. /**
  253. * Some entity that we attempted to create (e.g., file or directory) already
  254. * exists.
  255. */
  256. ALREADY_EXISTS: "already-exists",
  257. /**
  258. * The caller does not have permission to execute the specified operation.
  259. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  260. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  261. * PERMISSION_DENIED must not be used if the caller can not be identified
  262. * (use UNAUTHENTICATED instead for those errors).
  263. */
  264. PERMISSION_DENIED: "permission-denied",
  265. /**
  266. * The request does not have valid authentication credentials for the
  267. * operation.
  268. */
  269. UNAUTHENTICATED: "unauthenticated",
  270. /**
  271. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  272. * entire file system is out of space.
  273. */
  274. RESOURCE_EXHAUSTED: "resource-exhausted",
  275. /**
  276. * Operation was rejected because the system is not in a state required for
  277. * the operation's execution. For example, directory to be deleted may be
  278. * non-empty, an rmdir operation is applied to a non-directory, etc.
  279. *
  280. * A litmus test that may help a service implementor in deciding
  281. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  282. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  283. * (b) Use ABORTED if the client should retry at a higher-level
  284. * (e.g., restarting a read-modify-write sequence).
  285. * (c) Use FAILED_PRECONDITION if the client should not retry until
  286. * the system state has been explicitly fixed. E.g., if an "rmdir"
  287. * fails because the directory is non-empty, FAILED_PRECONDITION
  288. * should be returned since the client should not retry unless
  289. * they have first fixed up the directory by deleting files from it.
  290. * (d) Use FAILED_PRECONDITION if the client performs conditional
  291. * REST Get/Update/Delete on a resource and the resource on the
  292. * server does not match the condition. E.g., conflicting
  293. * read-modify-write on the same resource.
  294. */
  295. FAILED_PRECONDITION: "failed-precondition",
  296. /**
  297. * The operation was aborted, typically due to a concurrency issue like
  298. * sequencer check failures, transaction aborts, etc.
  299. *
  300. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  301. * and UNAVAILABLE.
  302. */
  303. ABORTED: "aborted",
  304. /**
  305. * Operation was attempted past the valid range. E.g., seeking or reading
  306. * past end of file.
  307. *
  308. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  309. * if the system state changes. For example, a 32-bit file system will
  310. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  311. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  312. * an offset past the current file size.
  313. *
  314. * There is a fair bit of overlap between FAILED_PRECONDITION and
  315. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  316. * when it applies so that callers who are iterating through a space can
  317. * easily look for an OUT_OF_RANGE error to detect when they are done.
  318. */
  319. OUT_OF_RANGE: "out-of-range",
  320. /** Operation is not implemented or not supported/enabled in this service. */
  321. UNIMPLEMENTED: "unimplemented",
  322. /**
  323. * Internal errors. Means some invariants expected by underlying System has
  324. * been broken. If you see one of these errors, Something is very broken.
  325. */
  326. INTERNAL: "internal",
  327. /**
  328. * The service is currently unavailable. This is a most likely a transient
  329. * condition and may be corrected by retrying with a backoff.
  330. *
  331. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  332. * and UNAVAILABLE.
  333. */
  334. UNAVAILABLE: "unavailable",
  335. /** Unrecoverable data loss or corruption. */
  336. DATA_LOSS: "data-loss"
  337. };
  338. /** An error returned by a Firestore operation. */ class U extends FirebaseError {
  339. /** @hideconstructor */
  340. constructor(
  341. /**
  342. * The backend error code associated with this error.
  343. */
  344. t,
  345. /**
  346. * A custom error description.
  347. */
  348. e) {
  349. super(t, e), this.code = t, this.message = e,
  350. // HACK: We write a toString property directly because Error is not a real
  351. // class and so inheritance does not work correctly. We could alternatively
  352. // do the same "back-door inheritance" trick that FirebaseError does.
  353. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  354. }
  355. }
  356. /**
  357. * @license
  358. * Copyright 2017 Google LLC
  359. *
  360. * Licensed under the Apache License, Version 2.0 (the "License");
  361. * you may not use this file except in compliance with the License.
  362. * You may obtain a copy of the License at
  363. *
  364. * http://www.apache.org/licenses/LICENSE-2.0
  365. *
  366. * Unless required by applicable law or agreed to in writing, software
  367. * distributed under the License is distributed on an "AS IS" BASIS,
  368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  369. * See the License for the specific language governing permissions and
  370. * limitations under the License.
  371. */ class K {
  372. constructor() {
  373. this.promise = new Promise(((t, e) => {
  374. this.resolve = t, this.reject = e;
  375. }));
  376. }
  377. }
  378. /**
  379. * @license
  380. * Copyright 2017 Google LLC
  381. *
  382. * Licensed under the Apache License, Version 2.0 (the "License");
  383. * you may not use this file except in compliance with the License.
  384. * You may obtain a copy of the License at
  385. *
  386. * http://www.apache.org/licenses/LICENSE-2.0
  387. *
  388. * Unless required by applicable law or agreed to in writing, software
  389. * distributed under the License is distributed on an "AS IS" BASIS,
  390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  391. * See the License for the specific language governing permissions and
  392. * limitations under the License.
  393. */ class G {
  394. constructor(t, e) {
  395. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`);
  396. }
  397. }
  398. /**
  399. * A CredentialsProvider that always yields an empty token.
  400. * @internal
  401. */ class Q {
  402. getToken() {
  403. return Promise.resolve(null);
  404. }
  405. invalidateToken() {}
  406. start(t, e) {
  407. // Fire with initial user.
  408. t.enqueueRetryable((() => e(V.UNAUTHENTICATED)));
  409. }
  410. shutdown() {}
  411. }
  412. /**
  413. * A CredentialsProvider that always returns a constant token. Used for
  414. * emulator token mocking.
  415. */ class j {
  416. constructor(t) {
  417. this.token = t,
  418. /**
  419. * Stores the listener registered with setChangeListener()
  420. * This isn't actually necessary since the UID never changes, but we use this
  421. * to verify the listen contract is adhered to in tests.
  422. */
  423. this.changeListener = null;
  424. }
  425. getToken() {
  426. return Promise.resolve(this.token);
  427. }
  428. invalidateToken() {}
  429. start(t, e) {
  430. this.changeListener = e,
  431. // Fire with initial user.
  432. t.enqueueRetryable((() => e(this.token.user)));
  433. }
  434. shutdown() {
  435. this.changeListener = null;
  436. }
  437. }
  438. class z {
  439. constructor(t) {
  440. this.t = t,
  441. /** Tracks the current User. */
  442. this.currentUser = V.UNAUTHENTICATED,
  443. /**
  444. * Counter used to detect if the token changed while a getToken request was
  445. * outstanding.
  446. */
  447. this.i = 0, this.forceRefresh = !1, this.auth = null;
  448. }
  449. start(t, e) {
  450. let n = this.i;
  451. // A change listener that prevents double-firing for the same token change.
  452. const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();
  453. // A promise that can be waited on to block on the next token change.
  454. // This promise is re-created after each change.
  455. let i = new K;
  456. this.o = () => {
  457. this.i++, this.currentUser = this.u(), i.resolve(), i = new K, t.enqueueRetryable((() => s(this.currentUser)));
  458. };
  459. const r = () => {
  460. const e = i;
  461. t.enqueueRetryable((async () => {
  462. await e.promise, await s(this.currentUser);
  463. }));
  464. }, o = t => {
  465. N("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = t, this.auth.addAuthTokenListener(this.o),
  466. r();
  467. };
  468. this.t.onInit((t => o(t))),
  469. // Our users can initialize Auth right after Firestore, so we give it
  470. // a chance to register itself with the component framework before we
  471. // determine whether to start up in unauthenticated mode.
  472. setTimeout((() => {
  473. if (!this.auth) {
  474. const t = this.t.getImmediate({
  475. optional: !0
  476. });
  477. t ? o(t) : (
  478. // If auth is still not available, proceed with `null` user
  479. N("FirebaseAuthCredentialsProvider", "Auth not yet detected"), i.resolve(), i = new K);
  480. }
  481. }), 0), r();
  482. }
  483. getToken() {
  484. // Take note of the current value of the tokenCounter so that this method
  485. // can fail (with an ABORTED error) if there is a token change while the
  486. // request is outstanding.
  487. const t = this.i, e = this.forceRefresh;
  488. return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e =>
  489. // Cancel the request since the token changed while the request was
  490. // outstanding so the response is potentially for a previous user (which
  491. // user, we can't be sure).
  492. this.i !== t ? (N("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."),
  493. this.getToken()) : e ? (F("string" == typeof e.accessToken), new G(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);
  494. }
  495. invalidateToken() {
  496. this.forceRefresh = !0;
  497. }
  498. shutdown() {
  499. this.auth && this.auth.removeAuthTokenListener(this.o);
  500. }
  501. // Auth.getUid() can return null even with a user logged in. It is because
  502. // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  503. // This method should only be called in the AuthTokenListener callback
  504. // to guarantee to get the actual user.
  505. u() {
  506. const t = this.auth && this.auth.getUid();
  507. return F(null === t || "string" == typeof t), new V(t);
  508. }
  509. }
  510. /*
  511. * FirstPartyToken provides a fresh token each time its value
  512. * is requested, because if the token is too old, requests will be rejected.
  513. * Technically this may no longer be necessary since the SDK should gracefully
  514. * recover from unauthenticated errors (see b/33147818 for context), but it's
  515. * safer to keep the implementation as-is.
  516. */ class W {
  517. constructor(t, e, n) {
  518. this.h = t, this.l = e, this.m = n, this.type = "FirstParty", this.user = V.FIRST_PARTY,
  519. this.g = new Map;
  520. }
  521. /**
  522. * Gets an authorization token, using a provided factory function, or return
  523. * null.
  524. */ p() {
  525. return this.m ? this.m() : null;
  526. }
  527. get headers() {
  528. this.g.set("X-Goog-AuthUser", this.h);
  529. // Use array notation to prevent minification
  530. const t = this.p();
  531. return t && this.g.set("Authorization", t), this.l && this.g.set("X-Goog-Iam-Authorization-Token", this.l),
  532. this.g;
  533. }
  534. }
  535. /*
  536. * Provides user credentials required for the Firestore JavaScript SDK
  537. * to authenticate the user, using technique that is only available
  538. * to applications hosted by Google.
  539. */ class H {
  540. constructor(t, e, n) {
  541. this.h = t, this.l = e, this.m = n;
  542. }
  543. getToken() {
  544. return Promise.resolve(new W(this.h, this.l, this.m));
  545. }
  546. start(t, e) {
  547. // Fire with initial uid.
  548. t.enqueueRetryable((() => e(V.FIRST_PARTY)));
  549. }
  550. shutdown() {}
  551. invalidateToken() {}
  552. }
  553. class J {
  554. constructor(t) {
  555. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  556. }
  557. }
  558. class Y {
  559. constructor(t) {
  560. this.I = t, this.forceRefresh = !1, this.appCheck = null, this.T = null;
  561. }
  562. start(t, e) {
  563. const n = t => {
  564. null != t.error && N("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);
  565. const n = t.token !== this.T;
  566. return this.T = t.token, N("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`),
  567. n ? e(t.token) : Promise.resolve();
  568. };
  569. this.o = e => {
  570. t.enqueueRetryable((() => n(e)));
  571. };
  572. const s = t => {
  573. N("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = t, this.appCheck.addTokenListener(this.o);
  574. };
  575. this.I.onInit((t => s(t))),
  576. // Our users can initialize AppCheck after Firestore, so we give it
  577. // a chance to register itself with the component framework.
  578. setTimeout((() => {
  579. if (!this.appCheck) {
  580. const t = this.I.getImmediate({
  581. optional: !0
  582. });
  583. t ? s(t) :
  584. // If AppCheck is still not available, proceed without it.
  585. N("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
  586. }
  587. }), 0);
  588. }
  589. getToken() {
  590. const t = this.forceRefresh;
  591. return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (F("string" == typeof t.token),
  592. this.T = t.token, new J(t.token)) : null)) : Promise.resolve(null);
  593. }
  594. invalidateToken() {
  595. this.forceRefresh = !0;
  596. }
  597. shutdown() {
  598. this.appCheck && this.appCheck.removeTokenListener(this.o);
  599. }
  600. }
  601. /**
  602. * An AppCheck token provider that always yields an empty token.
  603. * @internal
  604. */ class X {
  605. getToken() {
  606. return Promise.resolve(new J(""));
  607. }
  608. invalidateToken() {}
  609. start(t, e) {}
  610. shutdown() {}
  611. }
  612. /**
  613. * Builds a CredentialsProvider depending on the type of
  614. * the credentials passed in.
  615. */
  616. /**
  617. * @license
  618. * Copyright 2020 Google LLC
  619. *
  620. * Licensed under the Apache License, Version 2.0 (the "License");
  621. * you may not use this file except in compliance with the License.
  622. * You may obtain a copy of the License at
  623. *
  624. * http://www.apache.org/licenses/LICENSE-2.0
  625. *
  626. * Unless required by applicable law or agreed to in writing, software
  627. * distributed under the License is distributed on an "AS IS" BASIS,
  628. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  629. * See the License for the specific language governing permissions and
  630. * limitations under the License.
  631. */
  632. /**
  633. * Generates `nBytes` of random bytes.
  634. *
  635. * If `nBytes < 0` , an error will be thrown.
  636. */
  637. function Z(t) {
  638. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  639. const e =
  640. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  641. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  642. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  643. // Falls back to Math.random
  644. for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
  645. return n;
  646. }
  647. /**
  648. * @license
  649. * Copyright 2017 Google LLC
  650. *
  651. * Licensed under the Apache License, Version 2.0 (the "License");
  652. * you may not use this file except in compliance with the License.
  653. * You may obtain a copy of the License at
  654. *
  655. * http://www.apache.org/licenses/LICENSE-2.0
  656. *
  657. * Unless required by applicable law or agreed to in writing, software
  658. * distributed under the License is distributed on an "AS IS" BASIS,
  659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  660. * See the License for the specific language governing permissions and
  661. * limitations under the License.
  662. */ class tt {
  663. static A() {
  664. // Alphanumeric characters
  665. const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
  666. // The largest byte value that is a multiple of `char.length`.
  667. let n = "";
  668. for (;n.length < 20; ) {
  669. const s = Z(40);
  670. for (let i = 0; i < s.length; ++i)
  671. // Only accept values that are [0, maxMultiple), this ensures they can
  672. // be evenly mapped to indices of `chars` via a modulo operation.
  673. n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));
  674. }
  675. return n;
  676. }
  677. }
  678. function et(t, e) {
  679. return t < e ? -1 : t > e ? 1 : 0;
  680. }
  681. /** Helper to compare arrays using isEqual(). */ function nt(t, e, n) {
  682. return t.length === e.length && t.every(((t, s) => n(t, e[s])));
  683. }
  684. /**
  685. * Returns the immediate lexicographically-following string. This is useful to
  686. * construct an inclusive range for indexeddb iterators.
  687. */ function st(t) {
  688. // Return the input string, with an additional NUL byte appended.
  689. return t + "\0";
  690. }
  691. /**
  692. * @license
  693. * Copyright 2017 Google LLC
  694. *
  695. * Licensed under the Apache License, Version 2.0 (the "License");
  696. * you may not use this file except in compliance with the License.
  697. * You may obtain a copy of the License at
  698. *
  699. * http://www.apache.org/licenses/LICENSE-2.0
  700. *
  701. * Unless required by applicable law or agreed to in writing, software
  702. * distributed under the License is distributed on an "AS IS" BASIS,
  703. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  704. * See the License for the specific language governing permissions and
  705. * limitations under the License.
  706. */
  707. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  708. /**
  709. * A `Timestamp` represents a point in time independent of any time zone or
  710. * calendar, represented as seconds and fractions of seconds at nanosecond
  711. * resolution in UTC Epoch time.
  712. *
  713. * It is encoded using the Proleptic Gregorian Calendar which extends the
  714. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  715. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  716. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  717. * 9999-12-31T23:59:59.999999999Z.
  718. *
  719. * For examples and further specifications, refer to the
  720. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  721. */
  722. class it {
  723. /**
  724. * Creates a new timestamp.
  725. *
  726. * @param seconds - The number of seconds of UTC time since Unix epoch
  727. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  728. * 9999-12-31T23:59:59Z inclusive.
  729. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  730. * resolution. Negative second values with fractions must still have
  731. * non-negative nanoseconds values that count forward in time. Must be
  732. * from 0 to 999,999,999 inclusive.
  733. */
  734. constructor(
  735. /**
  736. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  737. */
  738. t,
  739. /**
  740. * The fractions of a second at nanosecond resolution.*
  741. */
  742. e) {
  743. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new U(q.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  744. if (e >= 1e9) throw new U(q.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  745. if (t < -62135596800) throw new U(q.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  746. // This will break in the year 10,000.
  747. if (t >= 253402300800) throw new U(q.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  748. }
  749. /**
  750. * Creates a new timestamp with the current date, with millisecond precision.
  751. *
  752. * @returns a new timestamp representing the current date.
  753. */ static now() {
  754. return it.fromMillis(Date.now());
  755. }
  756. /**
  757. * Creates a new timestamp from the given date.
  758. *
  759. * @param date - The date to initialize the `Timestamp` from.
  760. * @returns A new `Timestamp` representing the same point in time as the given
  761. * date.
  762. */ static fromDate(t) {
  763. return it.fromMillis(t.getTime());
  764. }
  765. /**
  766. * Creates a new timestamp from the given number of milliseconds.
  767. *
  768. * @param milliseconds - Number of milliseconds since Unix epoch
  769. * 1970-01-01T00:00:00Z.
  770. * @returns A new `Timestamp` representing the same point in time as the given
  771. * number of milliseconds.
  772. */ static fromMillis(t) {
  773. const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
  774. return new it(e, n);
  775. }
  776. /**
  777. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  778. * causes a loss of precision since `Date` objects only support millisecond
  779. * precision.
  780. *
  781. * @returns JavaScript `Date` object representing the same point in time as
  782. * this `Timestamp`, with millisecond precision.
  783. */ toDate() {
  784. return new Date(this.toMillis());
  785. }
  786. /**
  787. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  788. * epoch). This operation causes a loss of precision.
  789. *
  790. * @returns The point in time corresponding to this timestamp, represented as
  791. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  792. */ toMillis() {
  793. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  794. }
  795. _compareTo(t) {
  796. return this.seconds === t.seconds ? et(this.nanoseconds, t.nanoseconds) : et(this.seconds, t.seconds);
  797. }
  798. /**
  799. * Returns true if this `Timestamp` is equal to the provided one.
  800. *
  801. * @param other - The `Timestamp` to compare against.
  802. * @returns true if this `Timestamp` is equal to the provided one.
  803. */ isEqual(t) {
  804. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  805. }
  806. /** Returns a textual representation of this `Timestamp`. */ toString() {
  807. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  808. }
  809. /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
  810. return {
  811. seconds: this.seconds,
  812. nanoseconds: this.nanoseconds
  813. };
  814. }
  815. /**
  816. * Converts this object to a primitive string, which allows `Timestamp` objects
  817. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  818. */ valueOf() {
  819. // This method returns a string of the form <seconds>.<nanoseconds> where
  820. // <seconds> is translated to have a non-negative value and both <seconds>
  821. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  822. // Strings with this format then have a lexiographical ordering that matches
  823. // the expected ordering. The <seconds> translation is done to avoid having
  824. // a leading negative sign (i.e. a leading '-' character) in its string
  825. // representation, which would affect its lexiographical ordering.
  826. const t = this.seconds - -62135596800;
  827. // Note: Up to 12 decimal digits are required to represent all valid
  828. // 'seconds' values.
  829. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  830. }
  831. }
  832. /**
  833. * @license
  834. * Copyright 2017 Google LLC
  835. *
  836. * Licensed under the Apache License, Version 2.0 (the "License");
  837. * you may not use this file except in compliance with the License.
  838. * You may obtain a copy of the License at
  839. *
  840. * http://www.apache.org/licenses/LICENSE-2.0
  841. *
  842. * Unless required by applicable law or agreed to in writing, software
  843. * distributed under the License is distributed on an "AS IS" BASIS,
  844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  845. * See the License for the specific language governing permissions and
  846. * limitations under the License.
  847. */
  848. /**
  849. * A version of a document in Firestore. This corresponds to the version
  850. * timestamp, such as update_time or read_time.
  851. */ class rt {
  852. constructor(t) {
  853. this.timestamp = t;
  854. }
  855. static fromTimestamp(t) {
  856. return new rt(t);
  857. }
  858. static min() {
  859. return new rt(new it(0, 0));
  860. }
  861. static max() {
  862. return new rt(new it(253402300799, 999999999));
  863. }
  864. compareTo(t) {
  865. return this.timestamp._compareTo(t.timestamp);
  866. }
  867. isEqual(t) {
  868. return this.timestamp.isEqual(t.timestamp);
  869. }
  870. /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
  871. // Convert to microseconds.
  872. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  873. }
  874. toString() {
  875. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  876. }
  877. toTimestamp() {
  878. return this.timestamp;
  879. }
  880. }
  881. /**
  882. * @license
  883. * Copyright 2017 Google LLC
  884. *
  885. * Licensed under the Apache License, Version 2.0 (the "License");
  886. * you may not use this file except in compliance with the License.
  887. * You may obtain a copy of the License at
  888. *
  889. * http://www.apache.org/licenses/LICENSE-2.0
  890. *
  891. * Unless required by applicable law or agreed to in writing, software
  892. * distributed under the License is distributed on an "AS IS" BASIS,
  893. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  894. * See the License for the specific language governing permissions and
  895. * limitations under the License.
  896. */
  897. /**
  898. * Path represents an ordered sequence of string segments.
  899. */
  900. class ot {
  901. constructor(t, e, n) {
  902. void 0 === e ? e = 0 : e > t.length && O(), void 0 === n ? n = t.length - e : n > t.length - e && O(),
  903. this.segments = t, this.offset = e, this.len = n;
  904. }
  905. get length() {
  906. return this.len;
  907. }
  908. isEqual(t) {
  909. return 0 === ot.comparator(this, t);
  910. }
  911. child(t) {
  912. const e = this.segments.slice(this.offset, this.limit());
  913. return t instanceof ot ? t.forEach((t => {
  914. e.push(t);
  915. })) : e.push(t), this.construct(e);
  916. }
  917. /** The index of one past the last segment of the path. */ limit() {
  918. return this.offset + this.length;
  919. }
  920. popFirst(t) {
  921. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  922. }
  923. popLast() {
  924. return this.construct(this.segments, this.offset, this.length - 1);
  925. }
  926. firstSegment() {
  927. return this.segments[this.offset];
  928. }
  929. lastSegment() {
  930. return this.get(this.length - 1);
  931. }
  932. get(t) {
  933. return this.segments[this.offset + t];
  934. }
  935. isEmpty() {
  936. return 0 === this.length;
  937. }
  938. isPrefixOf(t) {
  939. if (t.length < this.length) return !1;
  940. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  941. return !0;
  942. }
  943. isImmediateParentOf(t) {
  944. if (this.length + 1 !== t.length) return !1;
  945. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  946. return !0;
  947. }
  948. forEach(t) {
  949. for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  950. }
  951. toArray() {
  952. return this.segments.slice(this.offset, this.limit());
  953. }
  954. static comparator(t, e) {
  955. const n = Math.min(t.length, e.length);
  956. for (let s = 0; s < n; s++) {
  957. const n = t.get(s), i = e.get(s);
  958. if (n < i) return -1;
  959. if (n > i) return 1;
  960. }
  961. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  962. }
  963. }
  964. /**
  965. * A slash-separated path for navigating resources (documents and collections)
  966. * within Firestore.
  967. *
  968. * @internal
  969. */ class ut extends ot {
  970. construct(t, e, n) {
  971. return new ut(t, e, n);
  972. }
  973. canonicalString() {
  974. // NOTE: The client is ignorant of any path segments containing escape
  975. // sequences (e.g. __id123__) and just passes them through raw (they exist
  976. // for legacy reasons and should not be used frequently).
  977. return this.toArray().join("/");
  978. }
  979. toString() {
  980. return this.canonicalString();
  981. }
  982. /**
  983. * Creates a resource path from the given slash-delimited string. If multiple
  984. * arguments are provided, all components are combined. Leading and trailing
  985. * slashes from all components are ignored.
  986. */ static fromString(...t) {
  987. // NOTE: The client is ignorant of any path segments containing escape
  988. // sequences (e.g. __id123__) and just passes them through raw (they exist
  989. // for legacy reasons and should not be used frequently).
  990. const e = [];
  991. for (const n of t) {
  992. if (n.indexOf("//") >= 0) throw new U(q.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
  993. // Strip leading and traling slashed.
  994. e.push(...n.split("/").filter((t => t.length > 0)));
  995. }
  996. return new ut(e);
  997. }
  998. static emptyPath() {
  999. return new ut([]);
  1000. }
  1001. }
  1002. const ct = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  1003. /**
  1004. * A dot-separated path for navigating sub-objects within a document.
  1005. * @internal
  1006. */ class at extends ot {
  1007. construct(t, e, n) {
  1008. return new at(t, e, n);
  1009. }
  1010. /**
  1011. * Returns true if the string could be used as a segment in a field path
  1012. * without escaping.
  1013. */ static isValidIdentifier(t) {
  1014. return ct.test(t);
  1015. }
  1016. canonicalString() {
  1017. return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"),
  1018. at.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join(".");
  1019. }
  1020. toString() {
  1021. return this.canonicalString();
  1022. }
  1023. /**
  1024. * Returns true if this field references the key of a document.
  1025. */ isKeyField() {
  1026. return 1 === this.length && "__name__" === this.get(0);
  1027. }
  1028. /**
  1029. * The field designating the key of a document.
  1030. */ static keyField() {
  1031. return new at([ "__name__" ]);
  1032. }
  1033. /**
  1034. * Parses a field string from the given server-formatted string.
  1035. *
  1036. * - Splitting the empty string is not allowed (for now at least).
  1037. * - Empty segments within the string (e.g. if there are two consecutive
  1038. * separators) are not allowed.
  1039. *
  1040. * TODO(b/37244157): we should make this more strict. Right now, it allows
  1041. * non-identifier path components, even if they aren't escaped.
  1042. */ static fromServerFormat(t) {
  1043. const e = [];
  1044. let n = "", s = 0;
  1045. const i = () => {
  1046. if (0 === n.length) throw new U(q.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
  1047. e.push(n), n = "";
  1048. };
  1049. let r = !1;
  1050. for (;s < t.length; ) {
  1051. const e = t[s];
  1052. if ("\\" === e) {
  1053. if (s + 1 === t.length) throw new U(q.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
  1054. const e = t[s + 1];
  1055. if ("\\" !== e && "." !== e && "`" !== e) throw new U(q.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
  1056. n += e, s += 2;
  1057. } else "`" === e ? (r = !r, s++) : "." !== e || r ? (n += e, s++) : (i(), s++);
  1058. }
  1059. if (i(), r) throw new U(q.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
  1060. return new at(e);
  1061. }
  1062. static emptyPath() {
  1063. return new at([]);
  1064. }
  1065. }
  1066. /**
  1067. * @license
  1068. * Copyright 2017 Google LLC
  1069. *
  1070. * Licensed under the Apache License, Version 2.0 (the "License");
  1071. * you may not use this file except in compliance with the License.
  1072. * You may obtain a copy of the License at
  1073. *
  1074. * http://www.apache.org/licenses/LICENSE-2.0
  1075. *
  1076. * Unless required by applicable law or agreed to in writing, software
  1077. * distributed under the License is distributed on an "AS IS" BASIS,
  1078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1079. * See the License for the specific language governing permissions and
  1080. * limitations under the License.
  1081. */
  1082. /**
  1083. * @internal
  1084. */ class ht {
  1085. constructor(t) {
  1086. this.path = t;
  1087. }
  1088. static fromPath(t) {
  1089. return new ht(ut.fromString(t));
  1090. }
  1091. static fromName(t) {
  1092. return new ht(ut.fromString(t).popFirst(5));
  1093. }
  1094. static empty() {
  1095. return new ht(ut.emptyPath());
  1096. }
  1097. get collectionGroup() {
  1098. return this.path.popLast().lastSegment();
  1099. }
  1100. /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
  1101. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  1102. }
  1103. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {
  1104. return this.path.get(this.path.length - 2);
  1105. }
  1106. /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {
  1107. return this.path.popLast();
  1108. }
  1109. isEqual(t) {
  1110. return null !== t && 0 === ut.comparator(this.path, t.path);
  1111. }
  1112. toString() {
  1113. return this.path.toString();
  1114. }
  1115. static comparator(t, e) {
  1116. return ut.comparator(t.path, e.path);
  1117. }
  1118. static isDocumentKey(t) {
  1119. return t.length % 2 == 0;
  1120. }
  1121. /**
  1122. * Creates and returns a new document key with the given segments.
  1123. *
  1124. * @param segments - The segments of the path to the document
  1125. * @returns A new instance of DocumentKey
  1126. */ static fromSegments(t) {
  1127. return new ht(new ut(t.slice()));
  1128. }
  1129. }
  1130. /**
  1131. * @license
  1132. * Copyright 2021 Google LLC
  1133. *
  1134. * Licensed under the Apache License, Version 2.0 (the "License");
  1135. * you may not use this file except in compliance with the License.
  1136. * You may obtain a copy of the License at
  1137. *
  1138. * http://www.apache.org/licenses/LICENSE-2.0
  1139. *
  1140. * Unless required by applicable law or agreed to in writing, software
  1141. * distributed under the License is distributed on an "AS IS" BASIS,
  1142. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1143. * See the License for the specific language governing permissions and
  1144. * limitations under the License.
  1145. */
  1146. /**
  1147. * The initial mutation batch id for each index. Gets updated during index
  1148. * backfill.
  1149. */
  1150. /**
  1151. * An index definition for field indexes in Firestore.
  1152. *
  1153. * Every index is associated with a collection. The definition contains a list
  1154. * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
  1155. * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
  1156. *
  1157. * Unlike the backend, the SDK does not differentiate between collection or
  1158. * collection group-scoped indices. Every index can be used for both single
  1159. * collection and collection group queries.
  1160. */
  1161. class lt {
  1162. constructor(
  1163. /**
  1164. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1165. * has not yet been persisted).
  1166. */
  1167. t,
  1168. /** The collection ID this index applies to. */
  1169. e,
  1170. /** The field segments for this index. */
  1171. n,
  1172. /** Shows how up-to-date the index is for the current user. */
  1173. s) {
  1174. this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;
  1175. }
  1176. }
  1177. /** An ID for an index that has not yet been added to persistence. */
  1178. /** Returns the ArrayContains/ArrayContainsAny segment for this index. */
  1179. function ft(t) {
  1180. return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));
  1181. }
  1182. /** Returns all directional (ascending/descending) segments for this index. */ function dt(t) {
  1183. return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));
  1184. }
  1185. /**
  1186. * Returns the order of the document key component for the given index.
  1187. *
  1188. * PORTING NOTE: This is only used in the Web IndexedDb implementation.
  1189. */
  1190. /**
  1191. * Compares indexes by collection group and segments. Ignores update time and
  1192. * index ID.
  1193. */
  1194. function wt(t, e) {
  1195. let n = et(t.collectionGroup, e.collectionGroup);
  1196. if (0 !== n) return n;
  1197. for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = mt(t.fields[s], e.fields[s]),
  1198. 0 !== n) return n;
  1199. return et(t.fields.length, e.fields.length);
  1200. }
  1201. /** Returns a debug representation of the field index */ lt.UNKNOWN_ID = -1;
  1202. /** An index component consisting of field path and index type. */
  1203. class _t {
  1204. constructor(
  1205. /** The field path of the component. */
  1206. t,
  1207. /** The fields sorting order. */
  1208. e) {
  1209. this.fieldPath = t, this.kind = e;
  1210. }
  1211. }
  1212. function mt(t, e) {
  1213. const n = at.comparator(t.fieldPath, e.fieldPath);
  1214. return 0 !== n ? n : et(t.kind, e.kind);
  1215. }
  1216. /**
  1217. * Stores the "high water mark" that indicates how updated the Index is for the
  1218. * current user.
  1219. */ class gt {
  1220. constructor(
  1221. /**
  1222. * Indicates when the index was last updated (relative to other indexes).
  1223. */
  1224. t,
  1225. /** The the latest indexed read time, document and batch id. */
  1226. e) {
  1227. this.sequenceNumber = t, this.offset = e;
  1228. }
  1229. /** The state of an index that has not yet been backfilled. */ static empty() {
  1230. return new gt(0, It.min());
  1231. }
  1232. }
  1233. /**
  1234. * Creates an offset that matches all documents with a read time higher than
  1235. * `readTime`.
  1236. */ function yt(t, e) {
  1237. // We want to create an offset that matches all documents with a read time
  1238. // greater than the provided read time. To do so, we technically need to
  1239. // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
  1240. // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
  1241. // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
  1242. // all valid document IDs.
  1243. const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = rt.fromTimestamp(1e9 === s ? new it(n + 1, 0) : new it(n, s));
  1244. return new It(i, ht.empty(), e);
  1245. }
  1246. /** Creates a new offset based on the provided document. */ function pt(t) {
  1247. return new It(t.readTime, t.key, -1);
  1248. }
  1249. /**
  1250. * Stores the latest read time, document and batch ID that were processed for an
  1251. * index.
  1252. */ class It {
  1253. constructor(
  1254. /**
  1255. * The latest read time version that has been indexed by Firestore for this
  1256. * field index.
  1257. */
  1258. t,
  1259. /**
  1260. * The key of the last document that was indexed for this query. Use
  1261. * `DocumentKey.empty()` if no document has been indexed.
  1262. */
  1263. e,
  1264. /*
  1265. * The largest mutation batch id that's been processed by Firestore.
  1266. */
  1267. n) {
  1268. this.readTime = t, this.documentKey = e, this.largestBatchId = n;
  1269. }
  1270. /** Returns an offset that sorts before all regular offsets. */ static min() {
  1271. return new It(rt.min(), ht.empty(), -1);
  1272. }
  1273. /** Returns an offset that sorts after all regular offsets. */ static max() {
  1274. return new It(rt.max(), ht.empty(), -1);
  1275. }
  1276. }
  1277. function Tt(t, e) {
  1278. let n = t.readTime.compareTo(e.readTime);
  1279. return 0 !== n ? n : (n = ht.comparator(t.documentKey, e.documentKey), 0 !== n ? n : et(t.largestBatchId, e.largestBatchId));
  1280. }
  1281. /**
  1282. * @license
  1283. * Copyright 2020 Google LLC
  1284. *
  1285. * Licensed under the Apache License, Version 2.0 (the "License");
  1286. * you may not use this file except in compliance with the License.
  1287. * You may obtain a copy of the License at
  1288. *
  1289. * http://www.apache.org/licenses/LICENSE-2.0
  1290. *
  1291. * Unless required by applicable law or agreed to in writing, software
  1292. * distributed under the License is distributed on an "AS IS" BASIS,
  1293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1294. * See the License for the specific language governing permissions and
  1295. * limitations under the License.
  1296. */ const Et = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";
  1297. /**
  1298. * A base class representing a persistence transaction, encapsulating both the
  1299. * transaction's sequence numbers as well as a list of onCommitted listeners.
  1300. *
  1301. * When you call Persistence.runTransaction(), it will create a transaction and
  1302. * pass it to your callback. You then pass it to any method that operates
  1303. * on persistence.
  1304. */ class At {
  1305. constructor() {
  1306. this.onCommittedListeners = [];
  1307. }
  1308. addOnCommittedListener(t) {
  1309. this.onCommittedListeners.push(t);
  1310. }
  1311. raiseOnCommittedEvent() {
  1312. this.onCommittedListeners.forEach((t => t()));
  1313. }
  1314. }
  1315. /**
  1316. * @license
  1317. * Copyright 2017 Google LLC
  1318. *
  1319. * Licensed under the Apache License, Version 2.0 (the "License");
  1320. * you may not use this file except in compliance with the License.
  1321. * You may obtain a copy of the License at
  1322. *
  1323. * http://www.apache.org/licenses/LICENSE-2.0
  1324. *
  1325. * Unless required by applicable law or agreed to in writing, software
  1326. * distributed under the License is distributed on an "AS IS" BASIS,
  1327. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1328. * See the License for the specific language governing permissions and
  1329. * limitations under the License.
  1330. */
  1331. /**
  1332. * Verifies the error thrown by a LocalStore operation. If a LocalStore
  1333. * operation fails because the primary lease has been taken by another client,
  1334. * we ignore the error (the persistence layer will immediately call
  1335. * `applyPrimaryLease` to propagate the primary state change). All other errors
  1336. * are re-thrown.
  1337. *
  1338. * @param err - An error returned by a LocalStore operation.
  1339. * @returns A Promise that resolves after we recovered, or the original error.
  1340. */ async function vt(t) {
  1341. if (t.code !== q.FAILED_PRECONDITION || t.message !== Et) throw t;
  1342. N("LocalStore", "Unexpectedly lost primary lease");
  1343. }
  1344. /**
  1345. * @license
  1346. * Copyright 2017 Google LLC
  1347. *
  1348. * Licensed under the Apache License, Version 2.0 (the "License");
  1349. * you may not use this file except in compliance with the License.
  1350. * You may obtain a copy of the License at
  1351. *
  1352. * http://www.apache.org/licenses/LICENSE-2.0
  1353. *
  1354. * Unless required by applicable law or agreed to in writing, software
  1355. * distributed under the License is distributed on an "AS IS" BASIS,
  1356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1357. * See the License for the specific language governing permissions and
  1358. * limitations under the License.
  1359. */
  1360. /**
  1361. * PersistencePromise is essentially a re-implementation of Promise except
  1362. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  1363. * are executed synchronously when a PersistencePromise resolves rather than
  1364. * asynchronously (Promise implementations use setImmediate() or similar).
  1365. *
  1366. * This is necessary to interoperate with IndexedDB which will automatically
  1367. * commit transactions if control is returned to the event loop without
  1368. * synchronously initiating another operation on the transaction.
  1369. *
  1370. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  1371. * Promises.
  1372. */ class Rt {
  1373. constructor(t) {
  1374. // NOTE: next/catchCallback will always point to our own wrapper functions,
  1375. // not the user's raw next() or catch() callbacks.
  1376. this.nextCallback = null, this.catchCallback = null,
  1377. // When the operation resolves, we'll set result or error and mark isDone.
  1378. this.result = void 0, this.error = void 0, this.isDone = !1,
  1379. // Set to true when .then() or .catch() are called and prevents additional
  1380. // chaining.
  1381. this.callbackAttached = !1, t((t => {
  1382. this.isDone = !0, this.result = t, this.nextCallback &&
  1383. // value should be defined unless T is Void, but we can't express
  1384. // that in the type system.
  1385. this.nextCallback(t);
  1386. }), (t => {
  1387. this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);
  1388. }));
  1389. }
  1390. catch(t) {
  1391. return this.next(void 0, t);
  1392. }
  1393. next(t, e) {
  1394. return this.callbackAttached && O(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new Rt(((n, s) => {
  1395. this.nextCallback = e => {
  1396. this.wrapSuccess(t, e).next(n, s);
  1397. }, this.catchCallback = t => {
  1398. this.wrapFailure(e, t).next(n, s);
  1399. };
  1400. }));
  1401. }
  1402. toPromise() {
  1403. return new Promise(((t, e) => {
  1404. this.next(t, e);
  1405. }));
  1406. }
  1407. wrapUserFunction(t) {
  1408. try {
  1409. const e = t();
  1410. return e instanceof Rt ? e : Rt.resolve(e);
  1411. } catch (t) {
  1412. return Rt.reject(t);
  1413. }
  1414. }
  1415. wrapSuccess(t, e) {
  1416. return t ? this.wrapUserFunction((() => t(e))) : Rt.resolve(e);
  1417. }
  1418. wrapFailure(t, e) {
  1419. return t ? this.wrapUserFunction((() => t(e))) : Rt.reject(e);
  1420. }
  1421. static resolve(t) {
  1422. return new Rt(((e, n) => {
  1423. e(t);
  1424. }));
  1425. }
  1426. static reject(t) {
  1427. return new Rt(((e, n) => {
  1428. n(t);
  1429. }));
  1430. }
  1431. static waitFor(
  1432. // Accept all Promise types in waitFor().
  1433. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1434. t) {
  1435. return new Rt(((e, n) => {
  1436. let s = 0, i = 0, r = !1;
  1437. t.forEach((t => {
  1438. ++s, t.next((() => {
  1439. ++i, r && i === s && e();
  1440. }), (t => n(t)));
  1441. })), r = !0, i === s && e();
  1442. }));
  1443. }
  1444. /**
  1445. * Given an array of predicate functions that asynchronously evaluate to a
  1446. * boolean, implements a short-circuiting `or` between the results. Predicates
  1447. * will be evaluated until one of them returns `true`, then stop. The final
  1448. * result will be whether any of them returned `true`.
  1449. */ static or(t) {
  1450. let e = Rt.resolve(!1);
  1451. for (const n of t) e = e.next((t => t ? Rt.resolve(t) : n()));
  1452. return e;
  1453. }
  1454. static forEach(t, e) {
  1455. const n = [];
  1456. return t.forEach(((t, s) => {
  1457. n.push(e.call(this, t, s));
  1458. })), this.waitFor(n);
  1459. }
  1460. /**
  1461. * Concurrently map all array elements through asynchronous function.
  1462. */ static mapArray(t, e) {
  1463. return new Rt(((n, s) => {
  1464. const i = t.length, r = new Array(i);
  1465. let o = 0;
  1466. for (let u = 0; u < i; u++) {
  1467. const c = u;
  1468. e(t[c]).next((t => {
  1469. r[c] = t, ++o, o === i && n(r);
  1470. }), (t => s(t)));
  1471. }
  1472. }));
  1473. }
  1474. /**
  1475. * An alternative to recursive PersistencePromise calls, that avoids
  1476. * potential memory problems from unbounded chains of promises.
  1477. *
  1478. * The `action` will be called repeatedly while `condition` is true.
  1479. */ static doWhile(t, e) {
  1480. return new Rt(((n, s) => {
  1481. const i = () => {
  1482. !0 === t() ? e().next((() => {
  1483. i();
  1484. }), s) : n();
  1485. };
  1486. i();
  1487. }));
  1488. }
  1489. }
  1490. /**
  1491. * @license
  1492. * Copyright 2017 Google LLC
  1493. *
  1494. * Licensed under the Apache License, Version 2.0 (the "License");
  1495. * you may not use this file except in compliance with the License.
  1496. * You may obtain a copy of the License at
  1497. *
  1498. * http://www.apache.org/licenses/LICENSE-2.0
  1499. *
  1500. * Unless required by applicable law or agreed to in writing, software
  1501. * distributed under the License is distributed on an "AS IS" BASIS,
  1502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1503. * See the License for the specific language governing permissions and
  1504. * limitations under the License.
  1505. */
  1506. // References to `window` are guarded by SimpleDb.isAvailable()
  1507. /* eslint-disable no-restricted-globals */
  1508. /**
  1509. * Wraps an IDBTransaction and exposes a store() method to get a handle to a
  1510. * specific object store.
  1511. */
  1512. class Pt {
  1513. constructor(t, e) {
  1514. this.action = t, this.transaction = e, this.aborted = !1,
  1515. /**
  1516. * A `Promise` that resolves with the result of the IndexedDb transaction.
  1517. */
  1518. this.v = new K, this.transaction.oncomplete = () => {
  1519. this.v.resolve();
  1520. }, this.transaction.onabort = () => {
  1521. e.error ? this.v.reject(new St(t, e.error)) : this.v.resolve();
  1522. }, this.transaction.onerror = e => {
  1523. const n = kt(e.target.error);
  1524. this.v.reject(new St(t, n));
  1525. };
  1526. }
  1527. static open(t, e, n, s) {
  1528. try {
  1529. return new Pt(e, t.transaction(s, n));
  1530. } catch (t) {
  1531. throw new St(e, t);
  1532. }
  1533. }
  1534. get R() {
  1535. return this.v.promise;
  1536. }
  1537. abort(t) {
  1538. t && this.v.reject(t), this.aborted || (N("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"),
  1539. this.aborted = !0, this.transaction.abort());
  1540. }
  1541. P() {
  1542. // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
  1543. // speed up index DB processing if the event loop remains blocks.
  1544. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1545. const t = this.transaction;
  1546. this.aborted || "function" != typeof t.commit || t.commit();
  1547. }
  1548. /**
  1549. * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
  1550. * operations performed on the SimpleDbStore happen within the context of this
  1551. * transaction and it cannot be used anymore once the transaction is
  1552. * completed.
  1553. *
  1554. * Note that we can't actually enforce that the KeyType and ValueType are
  1555. * correct, but they allow type safety through the rest of the consuming code.
  1556. */ store(t) {
  1557. const e = this.transaction.objectStore(t);
  1558. return new Ct(e);
  1559. }
  1560. }
  1561. /**
  1562. * Provides a wrapper around IndexedDb with a simplified interface that uses
  1563. * Promise-like return values to chain operations. Real promises cannot be used
  1564. * since .then() continuations are executed asynchronously (e.g. via
  1565. * .setImmediate), which would cause IndexedDB to end the transaction.
  1566. * See PersistencePromise for more details.
  1567. */ class bt {
  1568. /*
  1569. * Creates a new SimpleDb wrapper for IndexedDb database `name`.
  1570. *
  1571. * Note that `version` must not be a downgrade. IndexedDB does not support
  1572. * downgrading the schema version. We currently do not support any way to do
  1573. * versioning outside of IndexedDB's versioning mechanism, as only
  1574. * version-upgrade transactions are allowed to do things like create
  1575. * objectstores.
  1576. */
  1577. constructor(t, e, n) {
  1578. this.name = t, this.version = e, this.V = n;
  1579. // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
  1580. // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
  1581. // whatever reason it's much harder to hit after 12.2 so we only proactively
  1582. // log on 12.2.
  1583. 12.2 === bt.S(getUA()) && k("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");
  1584. }
  1585. /** Deletes the specified database. */ static delete(t) {
  1586. return N("SimpleDb", "Removing database:", t), xt(window.indexedDB.deleteDatabase(t)).toPromise();
  1587. }
  1588. /** Returns true if IndexedDB is available in the current environment. */ static D() {
  1589. if (!isIndexedDBAvailable()) return !1;
  1590. if (bt.C()) return !0;
  1591. // We extensively use indexed array values and compound keys,
  1592. // which IE and Edge do not support. However, they still have indexedDB
  1593. // defined on the window, so we need to check for them here and make sure
  1594. // to return that persistence is not enabled for those browsers.
  1595. // For tracking support of this feature, see here:
  1596. // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
  1597. // Check the UA string to find out the browser.
  1598. const t = getUA(), e = bt.S(t), n = 0 < e && e < 10, s = bt.N(t), i = 0 < s && s < 4.5;
  1599. // IE 10
  1600. // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
  1601. // IE 11
  1602. // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
  1603. // Edge
  1604. // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
  1605. // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
  1606. // iOS Safari: Disable for users running iOS version < 10.
  1607. return !(t.indexOf("MSIE ") > 0 || t.indexOf("Trident/") > 0 || t.indexOf("Edge/") > 0 || n || i);
  1608. }
  1609. /**
  1610. * Returns true if the backing IndexedDB store is the Node IndexedDBShim
  1611. * (see https://github.com/axemclion/IndexedDBShim).
  1612. */ static C() {
  1613. var t;
  1614. return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.k);
  1615. }
  1616. /** Helper to get a typed SimpleDbStore from a transaction. */ static M(t, e) {
  1617. return t.store(e);
  1618. }
  1619. // visible for testing
  1620. /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  1621. static S(t) {
  1622. const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
  1623. return Number(n);
  1624. }
  1625. // visible for testing
  1626. /** Parse User Agent to determine Android version. Returns -1 if not found. */
  1627. static N(t) {
  1628. const e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
  1629. return Number(n);
  1630. }
  1631. /**
  1632. * Opens the specified database, creating or upgrading it if necessary.
  1633. */ async $(t) {
  1634. return this.db || (N("SimpleDb", "Opening database:", this.name), this.db = await new Promise(((e, n) => {
  1635. // TODO(mikelehen): Investigate browser compatibility.
  1636. // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  1637. // suggests IE9 and older WebKit browsers handle upgrade
  1638. // differently. They expect setVersion, as described here:
  1639. // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
  1640. const s = indexedDB.open(this.name, this.version);
  1641. s.onsuccess = t => {
  1642. const n = t.target.result;
  1643. e(n);
  1644. }, s.onblocked = () => {
  1645. n(new St(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
  1646. }, s.onerror = e => {
  1647. const s = e.target.error;
  1648. "VersionError" === s.name ? n(new U(q.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === s.name ? n(new U(q.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + s)) : n(new St(t, s));
  1649. }, s.onupgradeneeded = t => {
  1650. N("SimpleDb", 'Database "' + this.name + '" requires upgrade from version:', t.oldVersion);
  1651. const e = t.target.result;
  1652. this.V.O(e, s.transaction, t.oldVersion, this.version).next((() => {
  1653. N("SimpleDb", "Database upgrade to version " + this.version + " complete");
  1654. }));
  1655. };
  1656. }))), this.F && (this.db.onversionchange = t => this.F(t)), this.db;
  1657. }
  1658. B(t) {
  1659. this.F = t, this.db && (this.db.onversionchange = e => t(e));
  1660. }
  1661. async runTransaction(t, e, n, s) {
  1662. const i = "readonly" === e;
  1663. let r = 0;
  1664. for (;;) {
  1665. ++r;
  1666. try {
  1667. this.db = await this.$(t);
  1668. const e = Pt.open(this.db, t, i ? "readonly" : "readwrite", n), r = s(e).next((t => (e.P(),
  1669. t))).catch((t => (
  1670. // Abort the transaction if there was an error.
  1671. e.abort(t), Rt.reject(t)))).toPromise();
  1672. // As noted above, errors are propagated by aborting the transaction. So
  1673. // we swallow any error here to avoid the browser logging it as unhandled.
  1674. return r.catch((() => {})),
  1675. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1676. // fire), but still return the original transactionFnResult back to the
  1677. // caller.
  1678. await e.R, r;
  1679. } catch (t) {
  1680. const e = t, n = "FirebaseError" !== e.name && r < 3;
  1681. // TODO(schmidt-sebastian): We could probably be smarter about this and
  1682. // not retry exceptions that are likely unrecoverable (such as quota
  1683. // exceeded errors).
  1684. // Note: We cannot use an instanceof check for FirestoreException, since the
  1685. // exception is wrapped in a generic error by our async/await handling.
  1686. if (N("SimpleDb", "Transaction failed with error:", e.message, "Retrying:", n),
  1687. this.close(), !n) return Promise.reject(e);
  1688. }
  1689. }
  1690. }
  1691. close() {
  1692. this.db && this.db.close(), this.db = void 0;
  1693. }
  1694. }
  1695. /**
  1696. * A controller for iterating over a key range or index. It allows an iterate
  1697. * callback to delete the currently-referenced object, or jump to a new key
  1698. * within the key range or index.
  1699. */ class Vt {
  1700. constructor(t) {
  1701. this.L = t, this.q = !1, this.U = null;
  1702. }
  1703. get isDone() {
  1704. return this.q;
  1705. }
  1706. get K() {
  1707. return this.U;
  1708. }
  1709. set cursor(t) {
  1710. this.L = t;
  1711. }
  1712. /**
  1713. * This function can be called to stop iteration at any point.
  1714. */ done() {
  1715. this.q = !0;
  1716. }
  1717. /**
  1718. * This function can be called to skip to that next key, which could be
  1719. * an index or a primary key.
  1720. */ G(t) {
  1721. this.U = t;
  1722. }
  1723. /**
  1724. * Delete the current cursor value from the object store.
  1725. *
  1726. * NOTE: You CANNOT do this with a keysOnly query.
  1727. */ delete() {
  1728. return xt(this.L.delete());
  1729. }
  1730. }
  1731. /** An error that wraps exceptions that thrown during IndexedDB execution. */ class St extends U {
  1732. constructor(t, e) {
  1733. super(q.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = "IndexedDbTransactionError";
  1734. }
  1735. }
  1736. /** Verifies whether `e` is an IndexedDbTransactionError. */ function Dt(t) {
  1737. // Use name equality, as instanceof checks on errors don't work with errors
  1738. // that wrap other errors.
  1739. return "IndexedDbTransactionError" === t.name;
  1740. }
  1741. /**
  1742. * A wrapper around an IDBObjectStore providing an API that:
  1743. *
  1744. * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
  1745. * methods for acting against the object store.
  1746. * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
  1747. * method return a PersistencePromise instead.
  1748. * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
  1749. * intermediate IndexedDB types (IDBCursorWithValue, etc.)
  1750. */ class Ct {
  1751. constructor(t) {
  1752. this.store = t;
  1753. }
  1754. put(t, e) {
  1755. let n;
  1756. return void 0 !== e ? (N("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : (N("SimpleDb", "PUT", this.store.name, "<auto-key>", t),
  1757. n = this.store.put(t)), xt(n);
  1758. }
  1759. /**
  1760. * Adds a new value into an Object Store and returns the new key. Similar to
  1761. * IndexedDb's `add()`, this method will fail on primary key collisions.
  1762. *
  1763. * @param value - The object to write.
  1764. * @returns The key of the value to add.
  1765. */ add(t) {
  1766. N("SimpleDb", "ADD", this.store.name, t, t);
  1767. return xt(this.store.add(t));
  1768. }
  1769. /**
  1770. * Gets the object with the specified key from the specified store, or null
  1771. * if no object exists with the specified key.
  1772. *
  1773. * @key The key of the object to get.
  1774. * @returns The object with the specified key or null if no object exists.
  1775. */ get(t) {
  1776. // We're doing an unsafe cast to ValueType.
  1777. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1778. return xt(this.store.get(t)).next((e => (
  1779. // Normalize nonexistence to null.
  1780. void 0 === e && (e = null), N("SimpleDb", "GET", this.store.name, t, e), e)));
  1781. }
  1782. delete(t) {
  1783. N("SimpleDb", "DELETE", this.store.name, t);
  1784. return xt(this.store.delete(t));
  1785. }
  1786. /**
  1787. * If we ever need more of the count variants, we can add overloads. For now,
  1788. * all we need is to count everything in a store.
  1789. *
  1790. * Returns the number of rows in the store.
  1791. */ count() {
  1792. N("SimpleDb", "COUNT", this.store.name);
  1793. return xt(this.store.count());
  1794. }
  1795. j(t, e) {
  1796. const n = this.options(t, e);
  1797. // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
  1798. // 20% faster. Unfortunately, getAll() does not support custom indices.
  1799. if (n.index || "function" != typeof this.store.getAll) {
  1800. const t = this.cursor(n), e = [];
  1801. return this.W(t, ((t, n) => {
  1802. e.push(n);
  1803. })).next((() => e));
  1804. }
  1805. {
  1806. const t = this.store.getAll(n.range);
  1807. return new Rt(((e, n) => {
  1808. t.onerror = t => {
  1809. n(t.target.error);
  1810. }, t.onsuccess = t => {
  1811. e(t.target.result);
  1812. };
  1813. }));
  1814. }
  1815. }
  1816. /**
  1817. * Loads the first `count` elements from the provided index range. Loads all
  1818. * elements if no limit is provided.
  1819. */ H(t, e) {
  1820. const n = this.store.getAll(t, null === e ? void 0 : e);
  1821. return new Rt(((t, e) => {
  1822. n.onerror = t => {
  1823. e(t.target.error);
  1824. }, n.onsuccess = e => {
  1825. t(e.target.result);
  1826. };
  1827. }));
  1828. }
  1829. J(t, e) {
  1830. N("SimpleDb", "DELETE ALL", this.store.name);
  1831. const n = this.options(t, e);
  1832. n.Y = !1;
  1833. const s = this.cursor(n);
  1834. return this.W(s, ((t, e, n) => n.delete()));
  1835. }
  1836. X(t, e) {
  1837. let n;
  1838. e ? n = t : (n = {}, e = t);
  1839. const s = this.cursor(n);
  1840. return this.W(s, e);
  1841. }
  1842. /**
  1843. * Iterates over a store, but waits for the given callback to complete for
  1844. * each entry before iterating the next entry. This allows the callback to do
  1845. * asynchronous work to determine if this iteration should continue.
  1846. *
  1847. * The provided callback should return `true` to continue iteration, and
  1848. * `false` otherwise.
  1849. */ Z(t) {
  1850. const e = this.cursor({});
  1851. return new Rt(((n, s) => {
  1852. e.onerror = t => {
  1853. const e = kt(t.target.error);
  1854. s(e);
  1855. }, e.onsuccess = e => {
  1856. const s = e.target.result;
  1857. s ? t(s.primaryKey, s.value).next((t => {
  1858. t ? s.continue() : n();
  1859. })) : n();
  1860. };
  1861. }));
  1862. }
  1863. W(t, e) {
  1864. const n = [];
  1865. return new Rt(((s, i) => {
  1866. t.onerror = t => {
  1867. i(t.target.error);
  1868. }, t.onsuccess = t => {
  1869. const i = t.target.result;
  1870. if (!i) return void s();
  1871. const r = new Vt(i), o = e(i.primaryKey, i.value, r);
  1872. if (o instanceof Rt) {
  1873. const t = o.catch((t => (r.done(), Rt.reject(t))));
  1874. n.push(t);
  1875. }
  1876. r.isDone ? s() : null === r.K ? i.continue() : i.continue(r.K);
  1877. };
  1878. })).next((() => Rt.waitFor(n)));
  1879. }
  1880. options(t, e) {
  1881. let n;
  1882. return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
  1883. index: n,
  1884. range: e
  1885. };
  1886. }
  1887. cursor(t) {
  1888. let e = "next";
  1889. if (t.reverse && (e = "prev"), t.index) {
  1890. const n = this.store.index(t.index);
  1891. return t.Y ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
  1892. }
  1893. return this.store.openCursor(t.range, e);
  1894. }
  1895. }
  1896. /**
  1897. * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
  1898. * handlers to resolve / reject the PersistencePromise as appropriate.
  1899. */ function xt(t) {
  1900. return new Rt(((e, n) => {
  1901. t.onsuccess = t => {
  1902. const n = t.target.result;
  1903. e(n);
  1904. }, t.onerror = t => {
  1905. const e = kt(t.target.error);
  1906. n(e);
  1907. };
  1908. }));
  1909. }
  1910. // Guard so we only report the error once.
  1911. let Nt = !1;
  1912. function kt(t) {
  1913. const e = bt.S(getUA());
  1914. if (e >= 12.2 && e < 13) {
  1915. const e = "An internal error was encountered in the Indexed Database server";
  1916. if (t.message.indexOf(e) >= 0) {
  1917. // Wrap error in a more descriptive one.
  1918. const t = new U("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
  1919. return Nt || (Nt = !0,
  1920. // Throw a global exception outside of this promise chain, for the user to
  1921. // potentially catch.
  1922. setTimeout((() => {
  1923. throw t;
  1924. }), 0)), t;
  1925. }
  1926. }
  1927. return t;
  1928. }
  1929. /** This class is responsible for the scheduling of Index Backfiller. */
  1930. class Mt {
  1931. constructor(t, e) {
  1932. this.asyncQueue = t, this.tt = e, this.task = null;
  1933. }
  1934. start() {
  1935. this.et(15e3);
  1936. }
  1937. stop() {
  1938. this.task && (this.task.cancel(), this.task = null);
  1939. }
  1940. get started() {
  1941. return null !== this.task;
  1942. }
  1943. et(t) {
  1944. N("IndexBackiller", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , t, (async () => {
  1945. this.task = null;
  1946. try {
  1947. N("IndexBackiller", `Documents written: ${await this.tt.nt()}`);
  1948. } catch (t) {
  1949. Dt(t) ? N("IndexBackiller", "Ignoring IndexedDB error during index backfill: ", t) : await vt(t);
  1950. }
  1951. await this.et(6e4);
  1952. }));
  1953. }
  1954. }
  1955. /** Implements the steps for backfilling indexes. */ class $t {
  1956. constructor(
  1957. /**
  1958. * LocalStore provides access to IndexManager and LocalDocumentView.
  1959. * These properties will update when the user changes. Consequently,
  1960. * making a local copy of IndexManager and LocalDocumentView will require
  1961. * updates over time. The simpler solution is to rely on LocalStore to have
  1962. * an up-to-date references to IndexManager and LocalDocumentStore.
  1963. */
  1964. t, e) {
  1965. this.localStore = t, this.persistence = e;
  1966. }
  1967. async nt(t = 50) {
  1968. return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (e => this.st(e, t)));
  1969. }
  1970. /** Writes index entries until the cap is reached. Returns the number of documents processed. */ st(t, e) {
  1971. const n = new Set;
  1972. let s = e, i = !0;
  1973. return Rt.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {
  1974. if (null !== e && !n.has(e)) return N("IndexBackiller", `Processing collection: ${e}`),
  1975. this.it(t, e, s).next((t => {
  1976. s -= t, n.add(e);
  1977. }));
  1978. i = !1;
  1979. })))).next((() => e - s));
  1980. }
  1981. /**
  1982. * Writes entries for the provided collection group. Returns the number of documents processed.
  1983. */ it(t, e, n) {
  1984. // Use the earliest offset of all field indexes to query the local cache.
  1985. return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {
  1986. const i = n.changes;
  1987. return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.rt(s, n))).next((n => (N("IndexBackiller", `Updating offset: ${n}`),
  1988. this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));
  1989. }))));
  1990. }
  1991. /** Returns the next offset based on the provided documents. */ rt(t, e) {
  1992. let n = t;
  1993. return e.changes.forEach(((t, e) => {
  1994. const s = pt(e);
  1995. Tt(s, n) > 0 && (n = s);
  1996. })), new It(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));
  1997. }
  1998. }
  1999. /**
  2000. * @license
  2001. * Copyright 2018 Google LLC
  2002. *
  2003. * Licensed under the Apache License, Version 2.0 (the "License");
  2004. * you may not use this file except in compliance with the License.
  2005. * You may obtain a copy of the License at
  2006. *
  2007. * http://www.apache.org/licenses/LICENSE-2.0
  2008. *
  2009. * Unless required by applicable law or agreed to in writing, software
  2010. * distributed under the License is distributed on an "AS IS" BASIS,
  2011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2012. * See the License for the specific language governing permissions and
  2013. * limitations under the License.
  2014. */
  2015. /**
  2016. * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
  2017. * exceed. All subsequent calls to next will return increasing values. If provided with a
  2018. * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
  2019. * well as write out sequence numbers that it produces via `next()`.
  2020. */ class Ot {
  2021. constructor(t, e) {
  2022. this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ot(t), this.ut = t => e.writeSequenceNumber(t));
  2023. }
  2024. ot(t) {
  2025. return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
  2026. }
  2027. next() {
  2028. const t = ++this.previousValue;
  2029. return this.ut && this.ut(t), t;
  2030. }
  2031. }
  2032. Ot.ct = -1;
  2033. /**
  2034. * Returns whether a variable is either undefined or null.
  2035. */
  2036. function Ft(t) {
  2037. return null == t;
  2038. }
  2039. /** Returns whether the value represents -0. */ function Bt(t) {
  2040. // Detect if the value is -0.0. Based on polyfill from
  2041. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2042. return 0 === t && 1 / t == -1 / 0;
  2043. }
  2044. /**
  2045. * Returns whether a value is an integer and in the safe integer range
  2046. * @param value - The value to test for being an integer and in the safe range
  2047. */ function Lt(t) {
  2048. return "number" == typeof t && Number.isInteger(t) && !Bt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2049. }
  2050. /**
  2051. * @license
  2052. * Copyright 2017 Google LLC
  2053. *
  2054. * Licensed under the Apache License, Version 2.0 (the "License");
  2055. * you may not use this file except in compliance with the License.
  2056. * You may obtain a copy of the License at
  2057. *
  2058. * http://www.apache.org/licenses/LICENSE-2.0
  2059. *
  2060. * Unless required by applicable law or agreed to in writing, software
  2061. * distributed under the License is distributed on an "AS IS" BASIS,
  2062. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2063. * See the License for the specific language governing permissions and
  2064. * limitations under the License.
  2065. */
  2066. /**
  2067. * Encodes a resource path into a IndexedDb-compatible string form.
  2068. */
  2069. function qt(t) {
  2070. let e = "";
  2071. for (let n = 0; n < t.length; n++) e.length > 0 && (e = Kt(e)), e = Ut(t.get(n), e);
  2072. return Kt(e);
  2073. }
  2074. /** Encodes a single segment of a resource path into the given result */ function Ut(t, e) {
  2075. let n = e;
  2076. const s = t.length;
  2077. for (let e = 0; e < s; e++) {
  2078. const s = t.charAt(e);
  2079. switch (s) {
  2080. case "\0":
  2081. n += "";
  2082. break;
  2083. case "":
  2084. n += "";
  2085. break;
  2086. default:
  2087. n += s;
  2088. }
  2089. }
  2090. return n;
  2091. }
  2092. /** Encodes a path separator into the given result */ function Kt(t) {
  2093. return t + "";
  2094. }
  2095. /**
  2096. * Decodes the given IndexedDb-compatible string form of a resource path into
  2097. * a ResourcePath instance. Note that this method is not suitable for use with
  2098. * decoding resource names from the server; those are One Platform format
  2099. * strings.
  2100. */ function Gt(t) {
  2101. // Event the empty path must encode as a path of at least length 2. A path
  2102. // with exactly 2 must be the empty path.
  2103. const e = t.length;
  2104. if (F(e >= 2), 2 === e) return F("" === t.charAt(0) && "" === t.charAt(1)), ut.emptyPath();
  2105. // Escape characters cannot exist past the second-to-last position in the
  2106. // source value.
  2107. const __PRIVATE_lastReasonableEscapeIndex = e - 2, n = [];
  2108. let s = "";
  2109. for (let i = 0; i < e; ) {
  2110. // The last two characters of a valid encoded path must be a separator, so
  2111. // there must be an end to this segment.
  2112. const e = t.indexOf("", i);
  2113. (e < 0 || e > __PRIVATE_lastReasonableEscapeIndex) && O();
  2114. switch (t.charAt(e + 1)) {
  2115. case "":
  2116. const r = t.substring(i, e);
  2117. let o;
  2118. 0 === s.length ?
  2119. // Avoid copying for the common case of a segment that excludes \0
  2120. // and \001
  2121. o = r : (s += r, o = s, s = ""), n.push(o);
  2122. break;
  2123. case "":
  2124. s += t.substring(i, e), s += "\0";
  2125. break;
  2126. case "":
  2127. // The escape character can be used in the output to encode itself.
  2128. s += t.substring(i, e + 1);
  2129. break;
  2130. default:
  2131. O();
  2132. }
  2133. i = e + 2;
  2134. }
  2135. return new ut(n);
  2136. }
  2137. /**
  2138. * @license
  2139. * Copyright 2022 Google LLC
  2140. *
  2141. * Licensed under the Apache License, Version 2.0 (the "License");
  2142. * you may not use this file except in compliance with the License.
  2143. * You may obtain a copy of the License at
  2144. *
  2145. * http://www.apache.org/licenses/LICENSE-2.0
  2146. *
  2147. * Unless required by applicable law or agreed to in writing, software
  2148. * distributed under the License is distributed on an "AS IS" BASIS,
  2149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2150. * See the License for the specific language governing permissions and
  2151. * limitations under the License.
  2152. */ const Qt = [ "userId", "batchId" ];
  2153. /**
  2154. * @license
  2155. * Copyright 2022 Google LLC
  2156. *
  2157. * Licensed under the Apache License, Version 2.0 (the "License");
  2158. * you may not use this file except in compliance with the License.
  2159. * You may obtain a copy of the License at
  2160. *
  2161. * http://www.apache.org/licenses/LICENSE-2.0
  2162. *
  2163. * Unless required by applicable law or agreed to in writing, software
  2164. * distributed under the License is distributed on an "AS IS" BASIS,
  2165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2166. * See the License for the specific language governing permissions and
  2167. * limitations under the License.
  2168. */
  2169. /**
  2170. * Name of the IndexedDb object store.
  2171. *
  2172. * Note that the name 'owner' is chosen to ensure backwards compatibility with
  2173. * older clients that only supported single locked access to the persistence
  2174. * layer.
  2175. */
  2176. /**
  2177. * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
  2178. * index to iterate over all at document mutations for a given path or lower.
  2179. */
  2180. function jt(t, e) {
  2181. return [ t, qt(e) ];
  2182. }
  2183. /**
  2184. * Creates a full index key of [userId, encodedPath, batchId] for inserting
  2185. * and deleting into the DbDocumentMutations index.
  2186. */ function zt(t, e, n) {
  2187. return [ t, qt(e), n ];
  2188. }
  2189. /**
  2190. * Because we store all the useful information for this store in the key,
  2191. * there is no useful information to store as the value. The raw (unencoded)
  2192. * path cannot be stored because IndexedDb doesn't store prototype
  2193. * information.
  2194. */ const Wt = {}, Ht = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], Jt = [ "prefixPath", "collectionGroup", "documentId" ], Yt = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], Xt = [ "canonicalId", "targetId" ], Zt = [ "targetId", "path" ], te = [ "path", "targetId" ], ee = [ "collectionId", "parent" ], ne = [ "indexId", "uid" ], se = [ "uid", "sequenceNumber" ], ie = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], re = [ "indexId", "uid", "orderedDocumentKey" ], oe = [ "userId", "collectionPath", "documentId" ], ue = [ "userId", "collectionPath", "largestBatchId" ], ce = [ "userId", "collectionGroup", "largestBatchId" ], ae = [ ...[ ...[ ...[ ...[ "mutationQueues", "mutations", "documentMutations", "remoteDocuments", "targets", "owner", "targetGlobal", "targetDocuments" ], "clientMetadata" ], "remoteDocumentGlobal" ], "collectionParents" ], "bundles", "namedQueries" ], he = [ ...ae, "documentOverlays" ], le = [ "mutationQueues", "mutations", "documentMutations", "remoteDocumentsV14", "targets", "owner", "targetGlobal", "targetDocuments", "clientMetadata", "remoteDocumentGlobal", "collectionParents", "bundles", "namedQueries", "documentOverlays" ], fe = le, de = [ ...fe, "indexConfiguration", "indexState", "indexEntries" ];
  2195. /**
  2196. * @license
  2197. * Copyright 2020 Google LLC
  2198. *
  2199. * Licensed under the Apache License, Version 2.0 (the "License");
  2200. * you may not use this file except in compliance with the License.
  2201. * You may obtain a copy of the License at
  2202. *
  2203. * http://www.apache.org/licenses/LICENSE-2.0
  2204. *
  2205. * Unless required by applicable law or agreed to in writing, software
  2206. * distributed under the License is distributed on an "AS IS" BASIS,
  2207. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2208. * See the License for the specific language governing permissions and
  2209. * limitations under the License.
  2210. */
  2211. class we extends At {
  2212. constructor(t, e) {
  2213. super(), this.ht = t, this.currentSequenceNumber = e;
  2214. }
  2215. }
  2216. function _e(t, e) {
  2217. const n = L(t);
  2218. return bt.M(n.ht, e);
  2219. }
  2220. /**
  2221. * @license
  2222. * Copyright 2017 Google LLC
  2223. *
  2224. * Licensed under the Apache License, Version 2.0 (the "License");
  2225. * you may not use this file except in compliance with the License.
  2226. * You may obtain a copy of the License at
  2227. *
  2228. * http://www.apache.org/licenses/LICENSE-2.0
  2229. *
  2230. * Unless required by applicable law or agreed to in writing, software
  2231. * distributed under the License is distributed on an "AS IS" BASIS,
  2232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2233. * See the License for the specific language governing permissions and
  2234. * limitations under the License.
  2235. */ function me(t) {
  2236. let e = 0;
  2237. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  2238. return e;
  2239. }
  2240. function ge(t, e) {
  2241. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  2242. }
  2243. function ye(t) {
  2244. for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  2245. return !0;
  2246. }
  2247. /**
  2248. * @license
  2249. * Copyright 2017 Google LLC
  2250. *
  2251. * Licensed under the Apache License, Version 2.0 (the "License");
  2252. * you may not use this file except in compliance with the License.
  2253. * You may obtain a copy of the License at
  2254. *
  2255. * http://www.apache.org/licenses/LICENSE-2.0
  2256. *
  2257. * Unless required by applicable law or agreed to in writing, software
  2258. * distributed under the License is distributed on an "AS IS" BASIS,
  2259. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2260. * See the License for the specific language governing permissions and
  2261. * limitations under the License.
  2262. */
  2263. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2264. // tree.
  2265. class pe {
  2266. constructor(t, e) {
  2267. this.comparator = t, this.root = e || Te.EMPTY;
  2268. }
  2269. // Returns a copy of the map, with the specified key/value added or replaced.
  2270. insert(t, e) {
  2271. return new pe(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, Te.BLACK, null, null));
  2272. }
  2273. // Returns a copy of the map, with the specified key removed.
  2274. remove(t) {
  2275. return new pe(this.comparator, this.root.remove(t, this.comparator).copy(null, null, Te.BLACK, null, null));
  2276. }
  2277. // Returns the value of the node with the given key, or null.
  2278. get(t) {
  2279. let e = this.root;
  2280. for (;!e.isEmpty(); ) {
  2281. const n = this.comparator(t, e.key);
  2282. if (0 === n) return e.value;
  2283. n < 0 ? e = e.left : n > 0 && (e = e.right);
  2284. }
  2285. return null;
  2286. }
  2287. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2288. // exist.
  2289. indexOf(t) {
  2290. // Number of nodes that were pruned when descending right
  2291. let e = 0, n = this.root;
  2292. for (;!n.isEmpty(); ) {
  2293. const s = this.comparator(t, n.key);
  2294. if (0 === s) return e + n.left.size;
  2295. s < 0 ? n = n.left : (
  2296. // Count all nodes left of the node plus the node itself
  2297. e += n.left.size + 1, n = n.right);
  2298. }
  2299. // Node not found
  2300. return -1;
  2301. }
  2302. isEmpty() {
  2303. return this.root.isEmpty();
  2304. }
  2305. // Returns the total number of nodes in the map.
  2306. get size() {
  2307. return this.root.size;
  2308. }
  2309. // Returns the minimum key in the map.
  2310. minKey() {
  2311. return this.root.minKey();
  2312. }
  2313. // Returns the maximum key in the map.
  2314. maxKey() {
  2315. return this.root.maxKey();
  2316. }
  2317. // Traverses the map in key order and calls the specified action function
  2318. // for each key/value pair. If action returns true, traversal is aborted.
  2319. // Returns the first truthy value returned by action, or the last falsey
  2320. // value returned by action.
  2321. inorderTraversal(t) {
  2322. return this.root.inorderTraversal(t);
  2323. }
  2324. forEach(t) {
  2325. this.inorderTraversal(((e, n) => (t(e, n), !1)));
  2326. }
  2327. toString() {
  2328. const t = [];
  2329. return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
  2330. }
  2331. // Traverses the map in reverse key order and calls the specified action
  2332. // function for each key/value pair. If action returns true, traversal is
  2333. // aborted.
  2334. // Returns the first truthy value returned by action, or the last falsey
  2335. // value returned by action.
  2336. reverseTraversal(t) {
  2337. return this.root.reverseTraversal(t);
  2338. }
  2339. // Returns an iterator over the SortedMap.
  2340. getIterator() {
  2341. return new Ie(this.root, null, this.comparator, !1);
  2342. }
  2343. getIteratorFrom(t) {
  2344. return new Ie(this.root, t, this.comparator, !1);
  2345. }
  2346. getReverseIterator() {
  2347. return new Ie(this.root, null, this.comparator, !0);
  2348. }
  2349. getReverseIteratorFrom(t) {
  2350. return new Ie(this.root, t, this.comparator, !0);
  2351. }
  2352. }
  2353. // end SortedMap
  2354. // An iterator over an LLRBNode.
  2355. class Ie {
  2356. constructor(t, e, n, s) {
  2357. this.isReverse = s, this.nodeStack = [];
  2358. let i = 1;
  2359. for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1,
  2360. // flip the comparison if we're going in reverse
  2361. e && s && (i *= -1), i < 0)
  2362. // This node is less than our start key. ignore it
  2363. t = this.isReverse ? t.left : t.right; else {
  2364. if (0 === i) {
  2365. // This node is exactly equal to our start key. Push it on the stack,
  2366. // but stop iterating;
  2367. this.nodeStack.push(t);
  2368. break;
  2369. }
  2370. // This node is greater than our start key, add it to the stack and move
  2371. // to the next one
  2372. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  2373. }
  2374. }
  2375. getNext() {
  2376. let t = this.nodeStack.pop();
  2377. const e = {
  2378. key: t.key,
  2379. value: t.value
  2380. };
  2381. if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t),
  2382. t = t.left;
  2383. return e;
  2384. }
  2385. hasNext() {
  2386. return this.nodeStack.length > 0;
  2387. }
  2388. peek() {
  2389. if (0 === this.nodeStack.length) return null;
  2390. const t = this.nodeStack[this.nodeStack.length - 1];
  2391. return {
  2392. key: t.key,
  2393. value: t.value
  2394. };
  2395. }
  2396. }
  2397. // end SortedMapIterator
  2398. // Represents a node in a Left-leaning Red-Black tree.
  2399. class Te {
  2400. constructor(t, e, n, s, i) {
  2401. this.key = t, this.value = e, this.color = null != n ? n : Te.RED, this.left = null != s ? s : Te.EMPTY,
  2402. this.right = null != i ? i : Te.EMPTY, this.size = this.left.size + 1 + this.right.size;
  2403. }
  2404. // Returns a copy of the current node, optionally replacing pieces of it.
  2405. copy(t, e, n, s, i) {
  2406. return new Te(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);
  2407. }
  2408. isEmpty() {
  2409. return !1;
  2410. }
  2411. // Traverses the tree in key order and calls the specified action function
  2412. // for each node. If action returns true, traversal is aborted.
  2413. // Returns the first truthy value returned by action, or the last falsey
  2414. // value returned by action.
  2415. inorderTraversal(t) {
  2416. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  2417. }
  2418. // Traverses the tree in reverse key order and calls the specified action
  2419. // function for each node. If action returns true, traversal is aborted.
  2420. // Returns the first truthy value returned by action, or the last falsey
  2421. // value returned by action.
  2422. reverseTraversal(t) {
  2423. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  2424. }
  2425. // Returns the minimum node in the tree.
  2426. min() {
  2427. return this.left.isEmpty() ? this : this.left.min();
  2428. }
  2429. // Returns the maximum key in the tree.
  2430. minKey() {
  2431. return this.min().key;
  2432. }
  2433. // Returns the maximum key in the tree.
  2434. maxKey() {
  2435. return this.right.isEmpty() ? this.key : this.right.maxKey();
  2436. }
  2437. // Returns new tree, with the key/value added.
  2438. insert(t, e, n) {
  2439. let s = this;
  2440. const i = n(t, s.key);
  2441. return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)),
  2442. s.fixUp();
  2443. }
  2444. removeMin() {
  2445. if (this.left.isEmpty()) return Te.EMPTY;
  2446. let t = this;
  2447. return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null),
  2448. t.fixUp();
  2449. }
  2450. // Returns new tree, with the specified item removed.
  2451. remove(t, e) {
  2452. let n, s = this;
  2453. if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()),
  2454. s = s.copy(null, null, null, s.left.remove(t, e), null); else {
  2455. if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()),
  2456. 0 === e(t, s.key)) {
  2457. if (s.right.isEmpty()) return Te.EMPTY;
  2458. n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());
  2459. }
  2460. s = s.copy(null, null, null, null, s.right.remove(t, e));
  2461. }
  2462. return s.fixUp();
  2463. }
  2464. isRed() {
  2465. return this.color;
  2466. }
  2467. // Returns new tree after performing any needed rotations.
  2468. fixUp() {
  2469. let t = this;
  2470. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  2471. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  2472. }
  2473. moveRedLeft() {
  2474. let t = this.colorFlip();
  2475. return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()),
  2476. t = t.rotateLeft(), t = t.colorFlip()), t;
  2477. }
  2478. moveRedRight() {
  2479. let t = this.colorFlip();
  2480. return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;
  2481. }
  2482. rotateLeft() {
  2483. const t = this.copy(null, null, Te.RED, null, this.right.left);
  2484. return this.right.copy(null, null, this.color, t, null);
  2485. }
  2486. rotateRight() {
  2487. const t = this.copy(null, null, Te.RED, this.left.right, null);
  2488. return this.left.copy(null, null, this.color, null, t);
  2489. }
  2490. colorFlip() {
  2491. const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  2492. return this.copy(null, null, !this.color, t, e);
  2493. }
  2494. // For testing.
  2495. checkMaxDepth() {
  2496. const t = this.check();
  2497. return Math.pow(2, t) <= this.size + 1;
  2498. }
  2499. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  2500. // leaves is equal on both sides. This function verifies that or asserts.
  2501. check() {
  2502. if (this.isRed() && this.left.isRed()) throw O();
  2503. if (this.right.isRed()) throw O();
  2504. const t = this.left.check();
  2505. if (t !== this.right.check()) throw O();
  2506. return t + (this.isRed() ? 0 : 1);
  2507. }
  2508. }
  2509. // end LLRBNode
  2510. // Empty node is shared between all LLRB trees.
  2511. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2512. Te.EMPTY = null, Te.RED = !0, Te.BLACK = !1;
  2513. // end LLRBEmptyNode
  2514. Te.EMPTY = new
  2515. // Represents an empty node (a leaf node in the Red-Black Tree).
  2516. class {
  2517. constructor() {
  2518. this.size = 0;
  2519. }
  2520. get key() {
  2521. throw O();
  2522. }
  2523. get value() {
  2524. throw O();
  2525. }
  2526. get color() {
  2527. throw O();
  2528. }
  2529. get left() {
  2530. throw O();
  2531. }
  2532. get right() {
  2533. throw O();
  2534. }
  2535. // Returns a copy of the current node.
  2536. copy(t, e, n, s, i) {
  2537. return this;
  2538. }
  2539. // Returns a copy of the tree, with the specified key/value added.
  2540. insert(t, e, n) {
  2541. return new Te(t, e);
  2542. }
  2543. // Returns a copy of the tree, with the specified key removed.
  2544. remove(t, e) {
  2545. return this;
  2546. }
  2547. isEmpty() {
  2548. return !0;
  2549. }
  2550. inorderTraversal(t) {
  2551. return !1;
  2552. }
  2553. reverseTraversal(t) {
  2554. return !1;
  2555. }
  2556. minKey() {
  2557. return null;
  2558. }
  2559. maxKey() {
  2560. return null;
  2561. }
  2562. isRed() {
  2563. return !1;
  2564. }
  2565. // For testing.
  2566. checkMaxDepth() {
  2567. return !0;
  2568. }
  2569. check() {
  2570. return 0;
  2571. }
  2572. };
  2573. /**
  2574. * @license
  2575. * Copyright 2017 Google LLC
  2576. *
  2577. * Licensed under the Apache License, Version 2.0 (the "License");
  2578. * you may not use this file except in compliance with the License.
  2579. * You may obtain a copy of the License at
  2580. *
  2581. * http://www.apache.org/licenses/LICENSE-2.0
  2582. *
  2583. * Unless required by applicable law or agreed to in writing, software
  2584. * distributed under the License is distributed on an "AS IS" BASIS,
  2585. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2586. * See the License for the specific language governing permissions and
  2587. * limitations under the License.
  2588. */
  2589. /**
  2590. * SortedSet is an immutable (copy-on-write) collection that holds elements
  2591. * in order specified by the provided comparator.
  2592. *
  2593. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  2594. * be equal!
  2595. */
  2596. class Ee {
  2597. constructor(t) {
  2598. this.comparator = t, this.data = new pe(this.comparator);
  2599. }
  2600. has(t) {
  2601. return null !== this.data.get(t);
  2602. }
  2603. first() {
  2604. return this.data.minKey();
  2605. }
  2606. last() {
  2607. return this.data.maxKey();
  2608. }
  2609. get size() {
  2610. return this.data.size;
  2611. }
  2612. indexOf(t) {
  2613. return this.data.indexOf(t);
  2614. }
  2615. /** Iterates elements in order defined by "comparator" */ forEach(t) {
  2616. this.data.inorderTraversal(((e, n) => (t(e), !1)));
  2617. }
  2618. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {
  2619. const n = this.data.getIteratorFrom(t[0]);
  2620. for (;n.hasNext(); ) {
  2621. const s = n.getNext();
  2622. if (this.comparator(s.key, t[1]) >= 0) return;
  2623. e(s.key);
  2624. }
  2625. }
  2626. /**
  2627. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  2628. */ forEachWhile(t, e) {
  2629. let n;
  2630. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {
  2631. if (!t(n.getNext().key)) return;
  2632. }
  2633. }
  2634. /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
  2635. const e = this.data.getIteratorFrom(t);
  2636. return e.hasNext() ? e.getNext().key : null;
  2637. }
  2638. getIterator() {
  2639. return new Ae(this.data.getIterator());
  2640. }
  2641. getIteratorFrom(t) {
  2642. return new Ae(this.data.getIteratorFrom(t));
  2643. }
  2644. /** Inserts or updates an element */ add(t) {
  2645. return this.copy(this.data.remove(t).insert(t, !0));
  2646. }
  2647. /** Deletes an element */ delete(t) {
  2648. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  2649. }
  2650. isEmpty() {
  2651. return this.data.isEmpty();
  2652. }
  2653. unionWith(t) {
  2654. let e = this;
  2655. // Make sure `result` always refers to the larger one of the two sets.
  2656. return e.size < t.size && (e = t, t = this), t.forEach((t => {
  2657. e = e.add(t);
  2658. })), e;
  2659. }
  2660. isEqual(t) {
  2661. if (!(t instanceof Ee)) return !1;
  2662. if (this.size !== t.size) return !1;
  2663. const e = this.data.getIterator(), n = t.data.getIterator();
  2664. for (;e.hasNext(); ) {
  2665. const t = e.getNext().key, s = n.getNext().key;
  2666. if (0 !== this.comparator(t, s)) return !1;
  2667. }
  2668. return !0;
  2669. }
  2670. toArray() {
  2671. const t = [];
  2672. return this.forEach((e => {
  2673. t.push(e);
  2674. })), t;
  2675. }
  2676. toString() {
  2677. const t = [];
  2678. return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
  2679. }
  2680. copy(t) {
  2681. const e = new Ee(this.comparator);
  2682. return e.data = t, e;
  2683. }
  2684. }
  2685. class Ae {
  2686. constructor(t) {
  2687. this.iter = t;
  2688. }
  2689. getNext() {
  2690. return this.iter.getNext().key;
  2691. }
  2692. hasNext() {
  2693. return this.iter.hasNext();
  2694. }
  2695. }
  2696. /**
  2697. * Compares two sorted sets for equality using their natural ordering. The
  2698. * method computes the intersection and invokes `onAdd` for every element that
  2699. * is in `after` but not `before`. `onRemove` is invoked for every element in
  2700. * `before` but missing from `after`.
  2701. *
  2702. * The method creates a copy of both `before` and `after` and runs in O(n log
  2703. * n), where n is the size of the two lists.
  2704. *
  2705. * @param before - The elements that exist in the original set.
  2706. * @param after - The elements to diff against the original set.
  2707. * @param comparator - The comparator for the elements in before and after.
  2708. * @param onAdd - A function to invoke for every element that is part of `
  2709. * after` but not `before`.
  2710. * @param onRemove - A function to invoke for every element that is part of
  2711. * `before` but not `after`.
  2712. */
  2713. /**
  2714. * Returns the next element from the iterator or `undefined` if none available.
  2715. */
  2716. function ve(t) {
  2717. return t.hasNext() ? t.getNext() : void 0;
  2718. }
  2719. /**
  2720. * @license
  2721. * Copyright 2020 Google LLC
  2722. *
  2723. * Licensed under the Apache License, Version 2.0 (the "License");
  2724. * you may not use this file except in compliance with the License.
  2725. * You may obtain a copy of the License at
  2726. *
  2727. * http://www.apache.org/licenses/LICENSE-2.0
  2728. *
  2729. * Unless required by applicable law or agreed to in writing, software
  2730. * distributed under the License is distributed on an "AS IS" BASIS,
  2731. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2732. * See the License for the specific language governing permissions and
  2733. * limitations under the License.
  2734. */
  2735. /**
  2736. * Provides a set of fields that can be used to partially patch a document.
  2737. * FieldMask is used in conjunction with ObjectValue.
  2738. * Examples:
  2739. * foo - Overwrites foo entirely with the provided value. If foo is not
  2740. * present in the companion ObjectValue, the field is deleted.
  2741. * foo.bar - Overwrites only the field bar of the object foo.
  2742. * If foo is not an object, foo is replaced with an object
  2743. * containing foo
  2744. */ class Re {
  2745. constructor(t) {
  2746. this.fields = t,
  2747. // TODO(dimond): validation of FieldMask
  2748. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  2749. t.sort(at.comparator);
  2750. }
  2751. static empty() {
  2752. return new Re([]);
  2753. }
  2754. /**
  2755. * Returns a new FieldMask object that is the result of adding all the given
  2756. * fields paths to this field mask.
  2757. */ unionWith(t) {
  2758. let e = new Ee(at.comparator);
  2759. for (const t of this.fields) e = e.add(t);
  2760. for (const n of t) e = e.add(n);
  2761. return new Re(e.toArray());
  2762. }
  2763. /**
  2764. * Verifies that `fieldPath` is included by at least one field in this field
  2765. * mask.
  2766. *
  2767. * This is an O(n) operation, where `n` is the size of the field mask.
  2768. */ covers(t) {
  2769. for (const e of this.fields) if (e.isPrefixOf(t)) return !0;
  2770. return !1;
  2771. }
  2772. isEqual(t) {
  2773. return nt(this.fields, t.fields, ((t, e) => t.isEqual(e)));
  2774. }
  2775. }
  2776. /**
  2777. * @license
  2778. * Copyright 2023 Google LLC
  2779. *
  2780. * Licensed under the Apache License, Version 2.0 (the "License");
  2781. * you may not use this file except in compliance with the License.
  2782. * You may obtain a copy of the License at
  2783. *
  2784. * http://www.apache.org/licenses/LICENSE-2.0
  2785. *
  2786. * Unless required by applicable law or agreed to in writing, software
  2787. * distributed under the License is distributed on an "AS IS" BASIS,
  2788. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2789. * See the License for the specific language governing permissions and
  2790. * limitations under the License.
  2791. */
  2792. /**
  2793. * An error encountered while decoding base64 string.
  2794. */ class Pe extends Error {
  2795. constructor() {
  2796. super(...arguments), this.name = "Base64DecodeError";
  2797. }
  2798. }
  2799. /**
  2800. * @license
  2801. * Copyright 2020 Google LLC
  2802. *
  2803. * Licensed under the Apache License, Version 2.0 (the "License");
  2804. * you may not use this file except in compliance with the License.
  2805. * You may obtain a copy of the License at
  2806. *
  2807. * http://www.apache.org/licenses/LICENSE-2.0
  2808. *
  2809. * Unless required by applicable law or agreed to in writing, software
  2810. * distributed under the License is distributed on an "AS IS" BASIS,
  2811. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2812. * See the License for the specific language governing permissions and
  2813. * limitations under the License.
  2814. */
  2815. /** Converts a Base64 encoded string to a binary string. */
  2816. /** True if and only if the Base64 conversion functions are available. */
  2817. function be() {
  2818. return "undefined" != typeof atob;
  2819. }
  2820. /**
  2821. * @license
  2822. * Copyright 2020 Google LLC
  2823. *
  2824. * Licensed under the Apache License, Version 2.0 (the "License");
  2825. * you may not use this file except in compliance with the License.
  2826. * You may obtain a copy of the License at
  2827. *
  2828. * http://www.apache.org/licenses/LICENSE-2.0
  2829. *
  2830. * Unless required by applicable law or agreed to in writing, software
  2831. * distributed under the License is distributed on an "AS IS" BASIS,
  2832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2833. * See the License for the specific language governing permissions and
  2834. * limitations under the License.
  2835. */
  2836. /**
  2837. * Immutable class that represents a "proto" byte string.
  2838. *
  2839. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  2840. * sent on the wire. This class abstracts away this differentiation by holding
  2841. * the proto byte string in a common class that must be converted into a string
  2842. * before being sent as a proto.
  2843. * @internal
  2844. */ class Ve {
  2845. constructor(t) {
  2846. this.binaryString = t;
  2847. }
  2848. static fromBase64String(t) {
  2849. const e = function(t) {
  2850. try {
  2851. return atob(t);
  2852. } catch (t) {
  2853. // Check that `DOMException` is defined before using it to avoid
  2854. // "ReferenceError: Property 'DOMException' doesn't exist" in react-native.
  2855. // (https://github.com/firebase/firebase-js-sdk/issues/7115)
  2856. throw "undefined" != typeof DOMException && t instanceof DOMException ? new Pe("Invalid base64 string: " + t) : t;
  2857. }
  2858. }
  2859. /** Converts a binary string to a Base64 encoded string. */ (t);
  2860. return new Ve(e);
  2861. }
  2862. static fromUint8Array(t) {
  2863. // TODO(indexing); Remove the copy of the byte string here as this method
  2864. // is frequently called during indexing.
  2865. const e =
  2866. /**
  2867. * Helper function to convert an Uint8array to a binary string.
  2868. */
  2869. function(t) {
  2870. let e = "";
  2871. for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  2872. return e;
  2873. }
  2874. /**
  2875. * Helper function to convert a binary string to an Uint8Array.
  2876. */ (t);
  2877. return new Ve(e);
  2878. }
  2879. [Symbol.iterator]() {
  2880. let t = 0;
  2881. return {
  2882. next: () => t < this.binaryString.length ? {
  2883. value: this.binaryString.charCodeAt(t++),
  2884. done: !1
  2885. } : {
  2886. value: void 0,
  2887. done: !0
  2888. }
  2889. };
  2890. }
  2891. toBase64() {
  2892. return t = this.binaryString, btoa(t);
  2893. var t;
  2894. }
  2895. toUint8Array() {
  2896. return function(t) {
  2897. const e = new Uint8Array(t.length);
  2898. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2899. return e;
  2900. }
  2901. /**
  2902. * @license
  2903. * Copyright 2020 Google LLC
  2904. *
  2905. * Licensed under the Apache License, Version 2.0 (the "License");
  2906. * you may not use this file except in compliance with the License.
  2907. * You may obtain a copy of the License at
  2908. *
  2909. * http://www.apache.org/licenses/LICENSE-2.0
  2910. *
  2911. * Unless required by applicable law or agreed to in writing, software
  2912. * distributed under the License is distributed on an "AS IS" BASIS,
  2913. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2914. * See the License for the specific language governing permissions and
  2915. * limitations under the License.
  2916. */
  2917. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  2918. (this.binaryString);
  2919. }
  2920. approximateByteSize() {
  2921. return 2 * this.binaryString.length;
  2922. }
  2923. compareTo(t) {
  2924. return et(this.binaryString, t.binaryString);
  2925. }
  2926. isEqual(t) {
  2927. return this.binaryString === t.binaryString;
  2928. }
  2929. }
  2930. Ve.EMPTY_BYTE_STRING = new Ve("");
  2931. const Se = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  2932. /**
  2933. * Converts the possible Proto values for a timestamp value into a "seconds and
  2934. * nanos" representation.
  2935. */ function De(t) {
  2936. // The json interface (for the browser) will return an iso timestamp string,
  2937. // while the proto js library (for node) will return a
  2938. // google.protobuf.Timestamp instance.
  2939. if (F(!!t), "string" == typeof t) {
  2940. // The date string can have higher precision (nanos) than the Date class
  2941. // (millis), so we do some custom parsing here.
  2942. // Parse the nanos right out of the string.
  2943. let e = 0;
  2944. const n = Se.exec(t);
  2945. if (F(!!n), n[1]) {
  2946. // Pad the fraction out to 9 digits (nanos).
  2947. let t = n[1];
  2948. t = (t + "000000000").substr(0, 9), e = Number(t);
  2949. }
  2950. // Parse the date to get the seconds.
  2951. const s = new Date(t);
  2952. return {
  2953. seconds: Math.floor(s.getTime() / 1e3),
  2954. nanos: e
  2955. };
  2956. }
  2957. return {
  2958. seconds: Ce(t.seconds),
  2959. nanos: Ce(t.nanos)
  2960. };
  2961. }
  2962. /**
  2963. * Converts the possible Proto types for numbers into a JavaScript number.
  2964. * Returns 0 if the value is not numeric.
  2965. */ function Ce(t) {
  2966. // TODO(bjornick): Handle int64 greater than 53 bits.
  2967. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  2968. }
  2969. /** Converts the possible Proto types for Blobs into a ByteString. */ function xe(t) {
  2970. return "string" == typeof t ? Ve.fromBase64String(t) : Ve.fromUint8Array(t);
  2971. }
  2972. /**
  2973. * @license
  2974. * Copyright 2020 Google LLC
  2975. *
  2976. * Licensed under the Apache License, Version 2.0 (the "License");
  2977. * you may not use this file except in compliance with the License.
  2978. * You may obtain a copy of the License at
  2979. *
  2980. * http://www.apache.org/licenses/LICENSE-2.0
  2981. *
  2982. * Unless required by applicable law or agreed to in writing, software
  2983. * distributed under the License is distributed on an "AS IS" BASIS,
  2984. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2985. * See the License for the specific language governing permissions and
  2986. * limitations under the License.
  2987. */
  2988. /**
  2989. * Represents a locally-applied ServerTimestamp.
  2990. *
  2991. * Server Timestamps are backed by MapValues that contain an internal field
  2992. * `__type__` with a value of `server_timestamp`. The previous value and local
  2993. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2994. * fields respectively.
  2995. *
  2996. * Notes:
  2997. * - ServerTimestampValue instances are created as the result of applying a
  2998. * transform. They can only exist in the local view of a document. Therefore
  2999. * they do not need to be parsed or serialized.
  3000. * - When evaluated locally (e.g. for snapshot.data()), they by default
  3001. * evaluate to `null`. This behavior can be configured by passing custom
  3002. * FieldValueOptions to value().
  3003. * - With respect to other ServerTimestampValues, they sort by their
  3004. * localWriteTime.
  3005. */ function Ne(t) {
  3006. var e, n;
  3007. return "server_timestamp" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);
  3008. }
  3009. /**
  3010. * Creates a new ServerTimestamp proto value (using the internal format).
  3011. */
  3012. /**
  3013. * Returns the value of the field before this ServerTimestamp was set.
  3014. *
  3015. * Preserving the previous values allows the user to display the last resoled
  3016. * value until the backend responds with the timestamp.
  3017. */
  3018. function ke(t) {
  3019. const e = t.mapValue.fields.__previous_value__;
  3020. return Ne(e) ? ke(e) : e;
  3021. }
  3022. /**
  3023. * Returns the local time at which this timestamp was first set.
  3024. */ function Me(t) {
  3025. const e = De(t.mapValue.fields.__local_write_time__.timestampValue);
  3026. return new it(e.seconds, e.nanos);
  3027. }
  3028. /**
  3029. * @license
  3030. * Copyright 2017 Google LLC
  3031. *
  3032. * Licensed under the Apache License, Version 2.0 (the "License");
  3033. * you may not use this file except in compliance with the License.
  3034. * You may obtain a copy of the License at
  3035. *
  3036. * http://www.apache.org/licenses/LICENSE-2.0
  3037. *
  3038. * Unless required by applicable law or agreed to in writing, software
  3039. * distributed under the License is distributed on an "AS IS" BASIS,
  3040. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3041. * See the License for the specific language governing permissions and
  3042. * limitations under the License.
  3043. */ class $e {
  3044. /**
  3045. * Constructs a DatabaseInfo using the provided host, databaseId and
  3046. * persistenceKey.
  3047. *
  3048. * @param databaseId - The database to use.
  3049. * @param appId - The Firebase App Id.
  3050. * @param persistenceKey - A unique identifier for this Firestore's local
  3051. * storage (used in conjunction with the databaseId).
  3052. * @param host - The Firestore backend host to connect to.
  3053. * @param ssl - Whether to use SSL when connecting.
  3054. * @param forceLongPolling - Whether to use the forceLongPolling option
  3055. * when using WebChannel as the network transport.
  3056. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  3057. * option when using WebChannel as the network transport.
  3058. * @param longPollingOptions Options that configure long-polling.
  3059. * @param useFetchStreams Whether to use the Fetch API instead of
  3060. * XMLHTTPRequest
  3061. */
  3062. constructor(t, e, n, s, i, r, o, u, c) {
  3063. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i,
  3064. this.forceLongPolling = r, this.autoDetectLongPolling = o, this.longPollingOptions = u,
  3065. this.useFetchStreams = c;
  3066. }
  3067. }
  3068. /** The default database name for a project. */
  3069. /**
  3070. * Represents the database ID a Firestore client is associated with.
  3071. * @internal
  3072. */
  3073. class Oe {
  3074. constructor(t, e) {
  3075. this.projectId = t, this.database = e || "(default)";
  3076. }
  3077. static empty() {
  3078. return new Oe("", "");
  3079. }
  3080. get isDefaultDatabase() {
  3081. return "(default)" === this.database;
  3082. }
  3083. isEqual(t) {
  3084. return t instanceof Oe && t.projectId === this.projectId && t.database === this.database;
  3085. }
  3086. }
  3087. /**
  3088. * @license
  3089. * Copyright 2020 Google LLC
  3090. *
  3091. * Licensed under the Apache License, Version 2.0 (the "License");
  3092. * you may not use this file except in compliance with the License.
  3093. * You may obtain a copy of the License at
  3094. *
  3095. * http://www.apache.org/licenses/LICENSE-2.0
  3096. *
  3097. * Unless required by applicable law or agreed to in writing, software
  3098. * distributed under the License is distributed on an "AS IS" BASIS,
  3099. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3100. * See the License for the specific language governing permissions and
  3101. * limitations under the License.
  3102. */
  3103. const Fe = {
  3104. mapValue: {
  3105. fields: {
  3106. __type__: {
  3107. stringValue: "__max__"
  3108. }
  3109. }
  3110. }
  3111. }, Be = {
  3112. nullValue: "NULL_VALUE"
  3113. };
  3114. /** Extracts the backend's type order for the provided value. */
  3115. function Le(t) {
  3116. return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? Ne(t) ? 4 /* TypeOrder.ServerTimestampValue */ : en(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : O();
  3117. }
  3118. /** Tests `left` and `right` for equality based on the backend semantics. */ function qe(t, e) {
  3119. if (t === e) return !0;
  3120. const n = Le(t);
  3121. if (n !== Le(e)) return !1;
  3122. switch (n) {
  3123. case 0 /* TypeOrder.NullValue */ :
  3124. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3125. return !0;
  3126. case 1 /* TypeOrder.BooleanValue */ :
  3127. return t.booleanValue === e.booleanValue;
  3128. case 4 /* TypeOrder.ServerTimestampValue */ :
  3129. return Me(t).isEqual(Me(e));
  3130. case 3 /* TypeOrder.TimestampValue */ :
  3131. return function(t, e) {
  3132. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  3133. // Use string equality for ISO 8601 timestamps
  3134. return t.timestampValue === e.timestampValue;
  3135. const n = De(t.timestampValue), s = De(e.timestampValue);
  3136. return n.seconds === s.seconds && n.nanos === s.nanos;
  3137. }(t, e);
  3138. case 5 /* TypeOrder.StringValue */ :
  3139. return t.stringValue === e.stringValue;
  3140. case 6 /* TypeOrder.BlobValue */ :
  3141. return function(t, e) {
  3142. return xe(t.bytesValue).isEqual(xe(e.bytesValue));
  3143. }(t, e);
  3144. case 7 /* TypeOrder.RefValue */ :
  3145. return t.referenceValue === e.referenceValue;
  3146. case 8 /* TypeOrder.GeoPointValue */ :
  3147. return function(t, e) {
  3148. return Ce(t.geoPointValue.latitude) === Ce(e.geoPointValue.latitude) && Ce(t.geoPointValue.longitude) === Ce(e.geoPointValue.longitude);
  3149. }(t, e);
  3150. case 2 /* TypeOrder.NumberValue */ :
  3151. return function(t, e) {
  3152. if ("integerValue" in t && "integerValue" in e) return Ce(t.integerValue) === Ce(e.integerValue);
  3153. if ("doubleValue" in t && "doubleValue" in e) {
  3154. const n = Ce(t.doubleValue), s = Ce(e.doubleValue);
  3155. return n === s ? Bt(n) === Bt(s) : isNaN(n) && isNaN(s);
  3156. }
  3157. return !1;
  3158. }(t, e);
  3159. case 9 /* TypeOrder.ArrayValue */ :
  3160. return nt(t.arrayValue.values || [], e.arrayValue.values || [], qe);
  3161. case 10 /* TypeOrder.ObjectValue */ :
  3162. return function(t, e) {
  3163. const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};
  3164. if (me(n) !== me(s)) return !1;
  3165. for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !qe(n[t], s[t]))) return !1;
  3166. return !0;
  3167. }
  3168. /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  3169. default:
  3170. return O();
  3171. }
  3172. }
  3173. function Ue(t, e) {
  3174. return void 0 !== (t.values || []).find((t => qe(t, e)));
  3175. }
  3176. function Ke(t, e) {
  3177. if (t === e) return 0;
  3178. const n = Le(t), s = Le(e);
  3179. if (n !== s) return et(n, s);
  3180. switch (n) {
  3181. case 0 /* TypeOrder.NullValue */ :
  3182. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3183. return 0;
  3184. case 1 /* TypeOrder.BooleanValue */ :
  3185. return et(t.booleanValue, e.booleanValue);
  3186. case 2 /* TypeOrder.NumberValue */ :
  3187. return function(t, e) {
  3188. const n = Ce(t.integerValue || t.doubleValue), s = Ce(e.integerValue || e.doubleValue);
  3189. return n < s ? -1 : n > s ? 1 : n === s ? 0 :
  3190. // one or both are NaN.
  3191. isNaN(n) ? isNaN(s) ? 0 : -1 : 1;
  3192. }(t, e);
  3193. case 3 /* TypeOrder.TimestampValue */ :
  3194. return Ge(t.timestampValue, e.timestampValue);
  3195. case 4 /* TypeOrder.ServerTimestampValue */ :
  3196. return Ge(Me(t), Me(e));
  3197. case 5 /* TypeOrder.StringValue */ :
  3198. return et(t.stringValue, e.stringValue);
  3199. case 6 /* TypeOrder.BlobValue */ :
  3200. return function(t, e) {
  3201. const n = xe(t), s = xe(e);
  3202. return n.compareTo(s);
  3203. }(t.bytesValue, e.bytesValue);
  3204. case 7 /* TypeOrder.RefValue */ :
  3205. return function(t, e) {
  3206. const n = t.split("/"), s = e.split("/");
  3207. for (let t = 0; t < n.length && t < s.length; t++) {
  3208. const e = et(n[t], s[t]);
  3209. if (0 !== e) return e;
  3210. }
  3211. return et(n.length, s.length);
  3212. }(t.referenceValue, e.referenceValue);
  3213. case 8 /* TypeOrder.GeoPointValue */ :
  3214. return function(t, e) {
  3215. const n = et(Ce(t.latitude), Ce(e.latitude));
  3216. if (0 !== n) return n;
  3217. return et(Ce(t.longitude), Ce(e.longitude));
  3218. }(t.geoPointValue, e.geoPointValue);
  3219. case 9 /* TypeOrder.ArrayValue */ :
  3220. return function(t, e) {
  3221. const n = t.values || [], s = e.values || [];
  3222. for (let t = 0; t < n.length && t < s.length; ++t) {
  3223. const e = Ke(n[t], s[t]);
  3224. if (e) return e;
  3225. }
  3226. return et(n.length, s.length);
  3227. }(t.arrayValue, e.arrayValue);
  3228. case 10 /* TypeOrder.ObjectValue */ :
  3229. return function(t, e) {
  3230. if (t === Fe.mapValue && e === Fe.mapValue) return 0;
  3231. if (t === Fe.mapValue) return 1;
  3232. if (e === Fe.mapValue) return -1;
  3233. const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);
  3234. // Even though MapValues are likely sorted correctly based on their insertion
  3235. // order (e.g. when received from the backend), local modifications can bring
  3236. // elements out of order. We need to re-sort the elements to ensure that
  3237. // canonical IDs are independent of insertion order.
  3238. s.sort(), r.sort();
  3239. for (let t = 0; t < s.length && t < r.length; ++t) {
  3240. const e = et(s[t], r[t]);
  3241. if (0 !== e) return e;
  3242. const o = Ke(n[s[t]], i[r[t]]);
  3243. if (0 !== o) return o;
  3244. }
  3245. return et(s.length, r.length);
  3246. }
  3247. /**
  3248. * Generates the canonical ID for the provided field value (as used in Target
  3249. * serialization).
  3250. */ (t.mapValue, e.mapValue);
  3251. default:
  3252. throw O();
  3253. }
  3254. }
  3255. function Ge(t, e) {
  3256. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return et(t, e);
  3257. const n = De(t), s = De(e), i = et(n.seconds, s.seconds);
  3258. return 0 !== i ? i : et(n.nanos, s.nanos);
  3259. }
  3260. function Qe(t) {
  3261. return je(t);
  3262. }
  3263. function je(t) {
  3264. return "nullValue" in t ? "null" : "booleanValue" in t ? "" + t.booleanValue : "integerValue" in t ? "" + t.integerValue : "doubleValue" in t ? "" + t.doubleValue : "timestampValue" in t ? function(t) {
  3265. const e = De(t);
  3266. return `time(${e.seconds},${e.nanos})`;
  3267. }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? xe(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue,
  3268. ht.fromName(n).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
  3269. let e = "[", n = !0;
  3270. for (const s of t.values || []) n ? n = !1 : e += ",", e += je(s);
  3271. return e + "]";
  3272. }
  3273. /**
  3274. * Returns an approximate (and wildly inaccurate) in-memory size for the field
  3275. * value.
  3276. *
  3277. * The memory size takes into account only the actual user data as it resides
  3278. * in memory and ignores object overhead.
  3279. */ (t.arrayValue) : "mapValue" in t ? function(t) {
  3280. // Iteration order in JavaScript is not guaranteed. To ensure that we generate
  3281. // matching canonical IDs for identical maps, we need to sort the keys.
  3282. const e = Object.keys(t.fields || {}).sort();
  3283. let n = "{", s = !0;
  3284. for (const i of e) s ? s = !1 : n += ",", n += `${i}:${je(t.fields[i])}`;
  3285. return n + "}";
  3286. }(t.mapValue) : O();
  3287. var e, n;
  3288. }
  3289. function ze(t) {
  3290. switch (Le(t)) {
  3291. case 0 /* TypeOrder.NullValue */ :
  3292. case 1 /* TypeOrder.BooleanValue */ :
  3293. return 4;
  3294. case 2 /* TypeOrder.NumberValue */ :
  3295. return 8;
  3296. case 3 /* TypeOrder.TimestampValue */ :
  3297. case 8 /* TypeOrder.GeoPointValue */ :
  3298. // GeoPoints are made up of two distinct numbers (latitude + longitude)
  3299. return 16;
  3300. case 4 /* TypeOrder.ServerTimestampValue */ :
  3301. const e = ke(t);
  3302. return e ? 16 + ze(e) : 16;
  3303. case 5 /* TypeOrder.StringValue */ :
  3304. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:
  3305. // "JavaScript's String type is [...] a set of elements of 16-bit unsigned
  3306. // integer values"
  3307. return 2 * t.stringValue.length;
  3308. case 6 /* TypeOrder.BlobValue */ :
  3309. return xe(t.bytesValue).approximateByteSize();
  3310. case 7 /* TypeOrder.RefValue */ :
  3311. return t.referenceValue.length;
  3312. case 9 /* TypeOrder.ArrayValue */ :
  3313. return (t.arrayValue.values || []).reduce(((t, e) => t + ze(e)), 0);
  3314. case 10 /* TypeOrder.ObjectValue */ :
  3315. return function(t) {
  3316. let e = 0;
  3317. return ge(t.fields, ((t, n) => {
  3318. e += t.length + ze(n);
  3319. })), e;
  3320. }(t.mapValue);
  3321. default:
  3322. throw O();
  3323. }
  3324. }
  3325. /** Returns a reference value for the provided database and key. */
  3326. function We(t, e) {
  3327. return {
  3328. referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`
  3329. };
  3330. }
  3331. /** Returns true if `value` is an IntegerValue . */ function He(t) {
  3332. return !!t && "integerValue" in t;
  3333. }
  3334. /** Returns true if `value` is a DoubleValue. */
  3335. /** Returns true if `value` is an ArrayValue. */
  3336. function Je(t) {
  3337. return !!t && "arrayValue" in t;
  3338. }
  3339. /** Returns true if `value` is a NullValue. */ function Ye(t) {
  3340. return !!t && "nullValue" in t;
  3341. }
  3342. /** Returns true if `value` is NaN. */ function Xe(t) {
  3343. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  3344. }
  3345. /** Returns true if `value` is a MapValue. */ function Ze(t) {
  3346. return !!t && "mapValue" in t;
  3347. }
  3348. /** Creates a deep copy of `source`. */ function tn(t) {
  3349. if (t.geoPointValue) return {
  3350. geoPointValue: Object.assign({}, t.geoPointValue)
  3351. };
  3352. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  3353. timestampValue: Object.assign({}, t.timestampValue)
  3354. };
  3355. if (t.mapValue) {
  3356. const e = {
  3357. mapValue: {
  3358. fields: {}
  3359. }
  3360. };
  3361. return ge(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = tn(n))), e;
  3362. }
  3363. if (t.arrayValue) {
  3364. const e = {
  3365. arrayValue: {
  3366. values: []
  3367. }
  3368. };
  3369. for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = tn(t.arrayValue.values[n]);
  3370. return e;
  3371. }
  3372. return Object.assign({}, t);
  3373. }
  3374. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function en(t) {
  3375. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  3376. }
  3377. /** Returns the lowest value for the given value type (inclusive). */ function nn(t) {
  3378. return "nullValue" in t ? Be : "booleanValue" in t ? {
  3379. booleanValue: !1
  3380. } : "integerValue" in t || "doubleValue" in t ? {
  3381. doubleValue: NaN
  3382. } : "timestampValue" in t ? {
  3383. timestampValue: {
  3384. seconds: Number.MIN_SAFE_INTEGER
  3385. }
  3386. } : "stringValue" in t ? {
  3387. stringValue: ""
  3388. } : "bytesValue" in t ? {
  3389. bytesValue: ""
  3390. } : "referenceValue" in t ? We(Oe.empty(), ht.empty()) : "geoPointValue" in t ? {
  3391. geoPointValue: {
  3392. latitude: -90,
  3393. longitude: -180
  3394. }
  3395. } : "arrayValue" in t ? {
  3396. arrayValue: {}
  3397. } : "mapValue" in t ? {
  3398. mapValue: {}
  3399. } : O();
  3400. }
  3401. /** Returns the largest value for the given value type (exclusive). */ function sn(t) {
  3402. return "nullValue" in t ? {
  3403. booleanValue: !1
  3404. } : "booleanValue" in t ? {
  3405. doubleValue: NaN
  3406. } : "integerValue" in t || "doubleValue" in t ? {
  3407. timestampValue: {
  3408. seconds: Number.MIN_SAFE_INTEGER
  3409. }
  3410. } : "timestampValue" in t ? {
  3411. stringValue: ""
  3412. } : "stringValue" in t ? {
  3413. bytesValue: ""
  3414. } : "bytesValue" in t ? We(Oe.empty(), ht.empty()) : "referenceValue" in t ? {
  3415. geoPointValue: {
  3416. latitude: -90,
  3417. longitude: -180
  3418. }
  3419. } : "geoPointValue" in t ? {
  3420. arrayValue: {}
  3421. } : "arrayValue" in t ? {
  3422. mapValue: {}
  3423. } : "mapValue" in t ? Fe : O();
  3424. }
  3425. function rn(t, e) {
  3426. const n = Ke(t.value, e.value);
  3427. return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;
  3428. }
  3429. function on(t, e) {
  3430. const n = Ke(t.value, e.value);
  3431. return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;
  3432. }
  3433. /**
  3434. * @license
  3435. * Copyright 2017 Google LLC
  3436. *
  3437. * Licensed under the Apache License, Version 2.0 (the "License");
  3438. * you may not use this file except in compliance with the License.
  3439. * You may obtain a copy of the License at
  3440. *
  3441. * http://www.apache.org/licenses/LICENSE-2.0
  3442. *
  3443. * Unless required by applicable law or agreed to in writing, software
  3444. * distributed under the License is distributed on an "AS IS" BASIS,
  3445. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3446. * See the License for the specific language governing permissions and
  3447. * limitations under the License.
  3448. */
  3449. /**
  3450. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3451. * ability to add and remove fields (via the ObjectValueBuilder).
  3452. */ class un {
  3453. constructor(t) {
  3454. this.value = t;
  3455. }
  3456. static empty() {
  3457. return new un({
  3458. mapValue: {}
  3459. });
  3460. }
  3461. /**
  3462. * Returns the value at the given path or null.
  3463. *
  3464. * @param path - the path to search
  3465. * @returns The value at the path or null if the path is not set.
  3466. */ field(t) {
  3467. if (t.isEmpty()) return this.value;
  3468. {
  3469. let e = this.value;
  3470. for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)],
  3471. !Ze(e)) return null;
  3472. return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;
  3473. }
  3474. }
  3475. /**
  3476. * Sets the field to the provided value.
  3477. *
  3478. * @param path - The field path to set.
  3479. * @param value - The value to set.
  3480. */ set(t, e) {
  3481. this.getFieldsMap(t.popLast())[t.lastSegment()] = tn(e);
  3482. }
  3483. /**
  3484. * Sets the provided fields to the provided values.
  3485. *
  3486. * @param data - A map of fields to values (or null for deletes).
  3487. */ setAll(t) {
  3488. let e = at.emptyPath(), n = {}, s = [];
  3489. t.forEach(((t, i) => {
  3490. if (!e.isImmediateParentOf(i)) {
  3491. // Insert the accumulated changes at this parent location
  3492. const t = this.getFieldsMap(e);
  3493. this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();
  3494. }
  3495. t ? n[i.lastSegment()] = tn(t) : s.push(i.lastSegment());
  3496. }));
  3497. const i = this.getFieldsMap(e);
  3498. this.applyChanges(i, n, s);
  3499. }
  3500. /**
  3501. * Removes the field at the specified path. If there is no field at the
  3502. * specified path, nothing is changed.
  3503. *
  3504. * @param path - The field path to remove.
  3505. */ delete(t) {
  3506. const e = this.field(t.popLast());
  3507. Ze(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  3508. }
  3509. isEqual(t) {
  3510. return qe(this.value, t.value);
  3511. }
  3512. /**
  3513. * Returns the map that contains the leaf element of `path`. If the parent
  3514. * entry does not yet exist, or if it is not a map, a new map will be created.
  3515. */ getFieldsMap(t) {
  3516. let e = this.value;
  3517. e.mapValue.fields || (e.mapValue = {
  3518. fields: {}
  3519. });
  3520. for (let n = 0; n < t.length; ++n) {
  3521. let s = e.mapValue.fields[t.get(n)];
  3522. Ze(s) && s.mapValue.fields || (s = {
  3523. mapValue: {
  3524. fields: {}
  3525. }
  3526. }, e.mapValue.fields[t.get(n)] = s), e = s;
  3527. }
  3528. return e.mapValue.fields;
  3529. }
  3530. /**
  3531. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3532. * entries.
  3533. */ applyChanges(t, e, n) {
  3534. ge(e, ((e, n) => t[e] = n));
  3535. for (const e of n) delete t[e];
  3536. }
  3537. clone() {
  3538. return new un(tn(this.value));
  3539. }
  3540. }
  3541. /**
  3542. * Returns a FieldMask built from all fields in a MapValue.
  3543. */ function cn(t) {
  3544. const e = [];
  3545. return ge(t.fields, ((t, n) => {
  3546. const s = new at([ t ]);
  3547. if (Ze(n)) {
  3548. const t = cn(n.mapValue).fields;
  3549. if (0 === t.length)
  3550. // Preserve the empty map by adding it to the FieldMask.
  3551. e.push(s); else
  3552. // For nested and non-empty ObjectValues, add the FieldPath of the
  3553. // leaf nodes.
  3554. for (const n of t) e.push(s.child(n));
  3555. } else
  3556. // For nested and non-empty ObjectValues, add the FieldPath of the leaf
  3557. // nodes.
  3558. e.push(s);
  3559. })), new Re(e);
  3560. }
  3561. /**
  3562. * @license
  3563. * Copyright 2017 Google LLC
  3564. *
  3565. * Licensed under the Apache License, Version 2.0 (the "License");
  3566. * you may not use this file except in compliance with the License.
  3567. * You may obtain a copy of the License at
  3568. *
  3569. * http://www.apache.org/licenses/LICENSE-2.0
  3570. *
  3571. * Unless required by applicable law or agreed to in writing, software
  3572. * distributed under the License is distributed on an "AS IS" BASIS,
  3573. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3574. * See the License for the specific language governing permissions and
  3575. * limitations under the License.
  3576. */
  3577. /**
  3578. * Represents a document in Firestore with a key, version, data and whether it
  3579. * has local mutations applied to it.
  3580. *
  3581. * Documents can transition between states via `convertToFoundDocument()`,
  3582. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3583. * not transition to one of these states even after all mutations have been
  3584. * applied, `isValidDocument()` returns false and the document should be removed
  3585. * from all views.
  3586. */ class an {
  3587. constructor(t, e, n, s, i, r, o) {
  3588. this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i,
  3589. this.data = r, this.documentState = o;
  3590. }
  3591. /**
  3592. * Creates a document with no known version or data, but which can serve as
  3593. * base document for mutations.
  3594. */ static newInvalidDocument(t) {
  3595. return new an(t, 0 /* DocumentType.INVALID */ ,
  3596. /* version */ rt.min(),
  3597. /* readTime */ rt.min(),
  3598. /* createTime */ rt.min(), un.empty(), 0 /* DocumentState.SYNCED */);
  3599. }
  3600. /**
  3601. * Creates a new document that is known to exist with the given data at the
  3602. * given version.
  3603. */ static newFoundDocument(t, e, n, s) {
  3604. return new an(t, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  3605. /* version */ e,
  3606. /* readTime */ rt.min(),
  3607. /* createTime */ n, s, 0 /* DocumentState.SYNCED */);
  3608. }
  3609. /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
  3610. return new an(t, 2 /* DocumentType.NO_DOCUMENT */ ,
  3611. /* version */ e,
  3612. /* readTime */ rt.min(),
  3613. /* createTime */ rt.min(), un.empty(), 0 /* DocumentState.SYNCED */);
  3614. }
  3615. /**
  3616. * Creates a new document that is known to exist at the given version but
  3617. * whose data is not known (e.g. a document that was updated without a known
  3618. * base document).
  3619. */ static newUnknownDocument(t, e) {
  3620. return new an(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3621. /* version */ e,
  3622. /* readTime */ rt.min(),
  3623. /* createTime */ rt.min(), un.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3624. }
  3625. /**
  3626. * Changes the document type to indicate that it exists and that its version
  3627. * and data are known.
  3628. */ convertToFoundDocument(t, e) {
  3629. // If a document is switching state from being an invalid or deleted
  3630. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3631. // update from Watch or due to applying a local set mutation on top
  3632. // of a deleted document, our best guess about its createTime would be the
  3633. // version at which the document transitioned to a FOUND_DOCUMENT.
  3634. return !this.createTime.isEqual(rt.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  3635. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  3636. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3637. }
  3638. /**
  3639. * Changes the document type to indicate that it doesn't exist at the given
  3640. * version.
  3641. */ convertToNoDocument(t) {
  3642. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  3643. this.data = un.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3644. }
  3645. /**
  3646. * Changes the document type to indicate that it exists at a given version but
  3647. * that its data is not known (e.g. a document that was updated without a known
  3648. * base document).
  3649. */ convertToUnknownDocument(t) {
  3650. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3651. this.data = un.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  3652. this;
  3653. }
  3654. setHasCommittedMutations() {
  3655. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  3656. }
  3657. setHasLocalMutations() {
  3658. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = rt.min(),
  3659. this;
  3660. }
  3661. setReadTime(t) {
  3662. return this.readTime = t, this;
  3663. }
  3664. get hasLocalMutations() {
  3665. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  3666. }
  3667. get hasCommittedMutations() {
  3668. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  3669. }
  3670. get hasPendingWrites() {
  3671. return this.hasLocalMutations || this.hasCommittedMutations;
  3672. }
  3673. isValidDocument() {
  3674. return 0 /* DocumentType.INVALID */ !== this.documentType;
  3675. }
  3676. isFoundDocument() {
  3677. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  3678. }
  3679. isNoDocument() {
  3680. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  3681. }
  3682. isUnknownDocument() {
  3683. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  3684. }
  3685. isEqual(t) {
  3686. return t instanceof an && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
  3687. }
  3688. mutableCopy() {
  3689. return new an(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3690. }
  3691. toString() {
  3692. return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  3693. }
  3694. }
  3695. /**
  3696. * Compares the value for field `field` in the provided documents. Throws if
  3697. * the field does not exist in both documents.
  3698. */
  3699. /**
  3700. * @license
  3701. * Copyright 2022 Google LLC
  3702. *
  3703. * Licensed under the Apache License, Version 2.0 (the "License");
  3704. * you may not use this file except in compliance with the License.
  3705. * You may obtain a copy of the License at
  3706. *
  3707. * http://www.apache.org/licenses/LICENSE-2.0
  3708. *
  3709. * Unless required by applicable law or agreed to in writing, software
  3710. * distributed under the License is distributed on an "AS IS" BASIS,
  3711. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3712. * See the License for the specific language governing permissions and
  3713. * limitations under the License.
  3714. */
  3715. /**
  3716. * Represents a bound of a query.
  3717. *
  3718. * The bound is specified with the given components representing a position and
  3719. * whether it's just before or just after the position (relative to whatever the
  3720. * query order is).
  3721. *
  3722. * The position represents a logical index position for a query. It's a prefix
  3723. * of values for the (potentially implicit) order by clauses of a query.
  3724. *
  3725. * Bound provides a function to determine whether a document comes before or
  3726. * after a bound. This is influenced by whether the position is just before or
  3727. * just after the provided values.
  3728. */
  3729. class hn {
  3730. constructor(t, e) {
  3731. this.position = t, this.inclusive = e;
  3732. }
  3733. }
  3734. function ln(t, e, n) {
  3735. let s = 0;
  3736. for (let i = 0; i < t.position.length; i++) {
  3737. const r = e[i], o = t.position[i];
  3738. if (r.field.isKeyField()) s = ht.comparator(ht.fromName(o.referenceValue), n.key); else {
  3739. s = Ke(o, n.data.field(r.field));
  3740. }
  3741. if ("desc" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;
  3742. }
  3743. return s;
  3744. }
  3745. /**
  3746. * Returns true if a document sorts after a bound using the provided sort
  3747. * order.
  3748. */ function fn(t, e) {
  3749. if (null === t) return null === e;
  3750. if (null === e) return !1;
  3751. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  3752. for (let n = 0; n < t.position.length; n++) {
  3753. if (!qe(t.position[n], e.position[n])) return !1;
  3754. }
  3755. return !0;
  3756. }
  3757. /**
  3758. * @license
  3759. * Copyright 2022 Google LLC
  3760. *
  3761. * Licensed under the Apache License, Version 2.0 (the "License");
  3762. * you may not use this file except in compliance with the License.
  3763. * You may obtain a copy of the License at
  3764. *
  3765. * http://www.apache.org/licenses/LICENSE-2.0
  3766. *
  3767. * Unless required by applicable law or agreed to in writing, software
  3768. * distributed under the License is distributed on an "AS IS" BASIS,
  3769. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3770. * See the License for the specific language governing permissions and
  3771. * limitations under the License.
  3772. */
  3773. /**
  3774. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  3775. */ class dn {
  3776. constructor(t, e = "asc" /* Direction.ASCENDING */) {
  3777. this.field = t, this.dir = e;
  3778. }
  3779. }
  3780. function wn(t, e) {
  3781. return t.dir === e.dir && t.field.isEqual(e.field);
  3782. }
  3783. /**
  3784. * @license
  3785. * Copyright 2022 Google LLC
  3786. *
  3787. * Licensed under the Apache License, Version 2.0 (the "License");
  3788. * you may not use this file except in compliance with the License.
  3789. * You may obtain a copy of the License at
  3790. *
  3791. * http://www.apache.org/licenses/LICENSE-2.0
  3792. *
  3793. * Unless required by applicable law or agreed to in writing, software
  3794. * distributed under the License is distributed on an "AS IS" BASIS,
  3795. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3796. * See the License for the specific language governing permissions and
  3797. * limitations under the License.
  3798. */ class _n {}
  3799. class mn extends _n {
  3800. constructor(t, e, n) {
  3801. super(), this.field = t, this.op = e, this.value = n;
  3802. }
  3803. /**
  3804. * Creates a filter based on the provided arguments.
  3805. */ static create(t, e, n) {
  3806. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new Pn(t, e, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new Dn(t, n) : "in" /* Operator.IN */ === e ? new Cn(t, n) : "not-in" /* Operator.NOT_IN */ === e ? new xn(t, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new Nn(t, n) : new mn(t, e, n);
  3807. }
  3808. static createKeyFieldInFilter(t, e, n) {
  3809. return "in" /* Operator.IN */ === e ? new bn(t, n) : new Vn(t, n);
  3810. }
  3811. matches(t) {
  3812. const e = t.data.field(this.field);
  3813. // Types do not have to match in NOT_EQUAL filters.
  3814. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(Ke(e, this.value)) : null !== e && Le(this.value) === Le(e) && this.matchesComparison(Ke(e, this.value));
  3815. // Only compare types with matching backend order (such as double and int).
  3816. }
  3817. matchesComparison(t) {
  3818. switch (this.op) {
  3819. case "<" /* Operator.LESS_THAN */ :
  3820. return t < 0;
  3821. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3822. return t <= 0;
  3823. case "==" /* Operator.EQUAL */ :
  3824. return 0 === t;
  3825. case "!=" /* Operator.NOT_EQUAL */ :
  3826. return 0 !== t;
  3827. case ">" /* Operator.GREATER_THAN */ :
  3828. return t > 0;
  3829. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3830. return t >= 0;
  3831. default:
  3832. return O();
  3833. }
  3834. }
  3835. isInequality() {
  3836. return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;
  3837. }
  3838. getFlattenedFilters() {
  3839. return [ this ];
  3840. }
  3841. getFilters() {
  3842. return [ this ];
  3843. }
  3844. getFirstInequalityField() {
  3845. return this.isInequality() ? this.field : null;
  3846. }
  3847. }
  3848. class gn extends _n {
  3849. constructor(t, e) {
  3850. super(), this.filters = t, this.op = e, this.lt = null;
  3851. }
  3852. /**
  3853. * Creates a filter based on the provided arguments.
  3854. */ static create(t, e) {
  3855. return new gn(t, e);
  3856. }
  3857. matches(t) {
  3858. return yn(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));
  3859. }
  3860. getFlattenedFilters() {
  3861. return null !== this.lt || (this.lt = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])),
  3862. this.lt;
  3863. }
  3864. // Returns a mutable copy of `this.filters`
  3865. getFilters() {
  3866. return Object.assign([], this.filters);
  3867. }
  3868. getFirstInequalityField() {
  3869. const t = this.ft((t => t.isInequality()));
  3870. return null !== t ? t.field : null;
  3871. }
  3872. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  3873. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  3874. // predicate.
  3875. ft(t) {
  3876. for (const e of this.getFlattenedFilters()) if (t(e)) return e;
  3877. return null;
  3878. }
  3879. }
  3880. function yn(t) {
  3881. return "and" /* CompositeOperator.AND */ === t.op;
  3882. }
  3883. function pn(t) {
  3884. return "or" /* CompositeOperator.OR */ === t.op;
  3885. }
  3886. /**
  3887. * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
  3888. */ function In(t) {
  3889. return Tn(t) && yn(t);
  3890. }
  3891. /**
  3892. * Returns true if this filter does not contain any composite filters. Returns false otherwise.
  3893. */ function Tn(t) {
  3894. for (const e of t.filters) if (e instanceof gn) return !1;
  3895. return !0;
  3896. }
  3897. function En(t) {
  3898. if (t instanceof mn)
  3899. // TODO(b/29183165): Technically, this won't be unique if two values have
  3900. // the same description, such as the int 3 and the string "3". So we should
  3901. // add the types in here somehow, too.
  3902. return t.field.canonicalString() + t.op.toString() + Qe(t.value);
  3903. if (In(t))
  3904. // Older SDK versions use an implicit AND operation between their filters.
  3905. // In the new SDK versions, the developer may use an explicit AND filter.
  3906. // To stay consistent with the old usages, we add a special case to ensure
  3907. // the canonical ID for these two are the same. For example:
  3908. // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
  3909. // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
  3910. return t.filters.map((t => En(t))).join(",");
  3911. {
  3912. // filter instanceof CompositeFilter
  3913. const e = t.filters.map((t => En(t))).join(",");
  3914. return `${t.op}(${e})`;
  3915. }
  3916. }
  3917. function An(t, e) {
  3918. return t instanceof mn ? function(t, e) {
  3919. return e instanceof mn && t.op === e.op && t.field.isEqual(e.field) && qe(t.value, e.value);
  3920. }(t, e) : t instanceof gn ? function(t, e) {
  3921. if (e instanceof gn && t.op === e.op && t.filters.length === e.filters.length) {
  3922. return t.filters.reduce(((t, n, s) => t && An(n, e.filters[s])), !0);
  3923. }
  3924. return !1;
  3925. }
  3926. /**
  3927. * Returns a new composite filter that contains all filter from
  3928. * `compositeFilter` plus all the given filters in `otherFilters`.
  3929. */ (t, e) : void O();
  3930. }
  3931. function vn(t, e) {
  3932. const n = t.filters.concat(e);
  3933. return gn.create(n, t.op);
  3934. }
  3935. /** Returns a debug description for `filter`. */ function Rn(t) {
  3936. return t instanceof mn ? function(t) {
  3937. return `${t.field.canonicalString()} ${t.op} ${Qe(t.value)}`;
  3938. }
  3939. /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof gn ? function(t) {
  3940. return t.op.toString() + " {" + t.getFilters().map(Rn).join(" ,") + "}";
  3941. }(t) : "Filter";
  3942. }
  3943. class Pn extends mn {
  3944. constructor(t, e, n) {
  3945. super(t, e, n), this.key = ht.fromName(n.referenceValue);
  3946. }
  3947. matches(t) {
  3948. const e = ht.comparator(t.key, this.key);
  3949. return this.matchesComparison(e);
  3950. }
  3951. }
  3952. /** Filter that matches on key fields within an array. */ class bn extends mn {
  3953. constructor(t, e) {
  3954. super(t, "in" /* Operator.IN */ , e), this.keys = Sn("in" /* Operator.IN */ , e);
  3955. }
  3956. matches(t) {
  3957. return this.keys.some((e => e.isEqual(t.key)));
  3958. }
  3959. }
  3960. /** Filter that matches on key fields not present within an array. */ class Vn extends mn {
  3961. constructor(t, e) {
  3962. super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = Sn("not-in" /* Operator.NOT_IN */ , e);
  3963. }
  3964. matches(t) {
  3965. return !this.keys.some((e => e.isEqual(t.key)));
  3966. }
  3967. }
  3968. function Sn(t, e) {
  3969. var n;
  3970. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => ht.fromName(t.referenceValue)));
  3971. }
  3972. /** A Filter that implements the array-contains operator. */ class Dn extends mn {
  3973. constructor(t, e) {
  3974. super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e);
  3975. }
  3976. matches(t) {
  3977. const e = t.data.field(this.field);
  3978. return Je(e) && Ue(e.arrayValue, this.value);
  3979. }
  3980. }
  3981. /** A Filter that implements the IN operator. */ class Cn extends mn {
  3982. constructor(t, e) {
  3983. super(t, "in" /* Operator.IN */ , e);
  3984. }
  3985. matches(t) {
  3986. const e = t.data.field(this.field);
  3987. return null !== e && Ue(this.value.arrayValue, e);
  3988. }
  3989. }
  3990. /** A Filter that implements the not-in operator. */ class xn extends mn {
  3991. constructor(t, e) {
  3992. super(t, "not-in" /* Operator.NOT_IN */ , e);
  3993. }
  3994. matches(t) {
  3995. if (Ue(this.value.arrayValue, {
  3996. nullValue: "NULL_VALUE"
  3997. })) return !1;
  3998. const e = t.data.field(this.field);
  3999. return null !== e && !Ue(this.value.arrayValue, e);
  4000. }
  4001. }
  4002. /** A Filter that implements the array-contains-any operator. */ class Nn extends mn {
  4003. constructor(t, e) {
  4004. super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e);
  4005. }
  4006. matches(t) {
  4007. const e = t.data.field(this.field);
  4008. return !(!Je(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => Ue(this.value.arrayValue, t)));
  4009. }
  4010. }
  4011. /**
  4012. * @license
  4013. * Copyright 2019 Google LLC
  4014. *
  4015. * Licensed under the Apache License, Version 2.0 (the "License");
  4016. * you may not use this file except in compliance with the License.
  4017. * You may obtain a copy of the License at
  4018. *
  4019. * http://www.apache.org/licenses/LICENSE-2.0
  4020. *
  4021. * Unless required by applicable law or agreed to in writing, software
  4022. * distributed under the License is distributed on an "AS IS" BASIS,
  4023. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4024. * See the License for the specific language governing permissions and
  4025. * limitations under the License.
  4026. */
  4027. // Visible for testing
  4028. class kn {
  4029. constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  4030. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i,
  4031. this.startAt = r, this.endAt = o, this.dt = null;
  4032. }
  4033. }
  4034. /**
  4035. * Initializes a Target with a path and optional additional query constraints.
  4036. * Path must currently be empty if this is a collection group query.
  4037. *
  4038. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  4039. * using this factory method, because `Query` provides an implicit `orderBy`
  4040. * property.
  4041. */ function Mn(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  4042. return new kn(t, e, n, s, i, r, o);
  4043. }
  4044. function $n(t) {
  4045. const e = L(t);
  4046. if (null === e.dt) {
  4047. let t = e.path.canonicalString();
  4048. null !== e.collectionGroup && (t += "|cg:" + e.collectionGroup), t += "|f:", t += e.filters.map((t => En(t))).join(","),
  4049. t += "|ob:", t += e.orderBy.map((t => function(t) {
  4050. // TODO(b/29183165): Make this collision robust.
  4051. return t.field.canonicalString() + t.dir;
  4052. }(t))).join(","), Ft(e.limit) || (t += "|l:", t += e.limit), e.startAt && (t += "|lb:",
  4053. t += e.startAt.inclusive ? "b:" : "a:", t += e.startAt.position.map((t => Qe(t))).join(",")),
  4054. e.endAt && (t += "|ub:", t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((t => Qe(t))).join(",")),
  4055. e.dt = t;
  4056. }
  4057. return e.dt;
  4058. }
  4059. function On(t, e) {
  4060. if (t.limit !== e.limit) return !1;
  4061. if (t.orderBy.length !== e.orderBy.length) return !1;
  4062. for (let n = 0; n < t.orderBy.length; n++) if (!wn(t.orderBy[n], e.orderBy[n])) return !1;
  4063. if (t.filters.length !== e.filters.length) return !1;
  4064. for (let n = 0; n < t.filters.length; n++) if (!An(t.filters[n], e.filters[n])) return !1;
  4065. return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!fn(t.startAt, e.startAt) && fn(t.endAt, e.endAt)));
  4066. }
  4067. function Fn(t) {
  4068. return ht.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  4069. }
  4070. /** Returns the field filters that target the given field path. */ function Bn(t, e) {
  4071. return t.filters.filter((t => t instanceof mn && t.field.isEqual(e)));
  4072. }
  4073. /**
  4074. * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
  4075. * filters. Returns `null` if there are no such filters.
  4076. */
  4077. /**
  4078. * Returns the value to use as the lower bound for ascending index segment at
  4079. * the provided `fieldPath` (or the upper bound for an descending segment).
  4080. */
  4081. function Ln(t, e, n) {
  4082. let s = Be, i = !0;
  4083. // Process all filters to find a value for the current field segment
  4084. for (const n of Bn(t, e)) {
  4085. let t = Be, e = !0;
  4086. switch (n.op) {
  4087. case "<" /* Operator.LESS_THAN */ :
  4088. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  4089. t = nn(n.value);
  4090. break;
  4091. case "==" /* Operator.EQUAL */ :
  4092. case "in" /* Operator.IN */ :
  4093. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  4094. t = n.value;
  4095. break;
  4096. case ">" /* Operator.GREATER_THAN */ :
  4097. t = n.value, e = !1;
  4098. break;
  4099. case "!=" /* Operator.NOT_EQUAL */ :
  4100. case "not-in" /* Operator.NOT_IN */ :
  4101. t = Be;
  4102. // Remaining filters cannot be used as lower bounds.
  4103. }
  4104. rn({
  4105. value: s,
  4106. inclusive: i
  4107. }, {
  4108. value: t,
  4109. inclusive: e
  4110. }) < 0 && (s = t, i = e);
  4111. }
  4112. // If there is an additional bound, compare the values against the existing
  4113. // range to see if we can narrow the scope.
  4114. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  4115. if (t.orderBy[r].field.isEqual(e)) {
  4116. const t = n.position[r];
  4117. rn({
  4118. value: s,
  4119. inclusive: i
  4120. }, {
  4121. value: t,
  4122. inclusive: n.inclusive
  4123. }) < 0 && (s = t, i = n.inclusive);
  4124. break;
  4125. }
  4126. }
  4127. return {
  4128. value: s,
  4129. inclusive: i
  4130. };
  4131. }
  4132. /**
  4133. * Returns the value to use as the upper bound for ascending index segment at
  4134. * the provided `fieldPath` (or the lower bound for a descending segment).
  4135. */ function qn(t, e, n) {
  4136. let s = Fe, i = !0;
  4137. // Process all filters to find a value for the current field segment
  4138. for (const n of Bn(t, e)) {
  4139. let t = Fe, e = !0;
  4140. switch (n.op) {
  4141. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  4142. case ">" /* Operator.GREATER_THAN */ :
  4143. t = sn(n.value), e = !1;
  4144. break;
  4145. case "==" /* Operator.EQUAL */ :
  4146. case "in" /* Operator.IN */ :
  4147. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  4148. t = n.value;
  4149. break;
  4150. case "<" /* Operator.LESS_THAN */ :
  4151. t = n.value, e = !1;
  4152. break;
  4153. case "!=" /* Operator.NOT_EQUAL */ :
  4154. case "not-in" /* Operator.NOT_IN */ :
  4155. t = Fe;
  4156. // Remaining filters cannot be used as upper bounds.
  4157. }
  4158. on({
  4159. value: s,
  4160. inclusive: i
  4161. }, {
  4162. value: t,
  4163. inclusive: e
  4164. }) > 0 && (s = t, i = e);
  4165. }
  4166. // If there is an additional bound, compare the values against the existing
  4167. // range to see if we can narrow the scope.
  4168. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  4169. if (t.orderBy[r].field.isEqual(e)) {
  4170. const t = n.position[r];
  4171. on({
  4172. value: s,
  4173. inclusive: i
  4174. }, {
  4175. value: t,
  4176. inclusive: n.inclusive
  4177. }) > 0 && (s = t, i = n.inclusive);
  4178. break;
  4179. }
  4180. }
  4181. return {
  4182. value: s,
  4183. inclusive: i
  4184. };
  4185. }
  4186. /** Returns the number of segments of a perfect index for this target. */
  4187. /**
  4188. * @license
  4189. * Copyright 2017 Google LLC
  4190. *
  4191. * Licensed under the Apache License, Version 2.0 (the "License");
  4192. * you may not use this file except in compliance with the License.
  4193. * You may obtain a copy of the License at
  4194. *
  4195. * http://www.apache.org/licenses/LICENSE-2.0
  4196. *
  4197. * Unless required by applicable law or agreed to in writing, software
  4198. * distributed under the License is distributed on an "AS IS" BASIS,
  4199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4200. * See the License for the specific language governing permissions and
  4201. * limitations under the License.
  4202. */
  4203. /**
  4204. * Query encapsulates all the query attributes we support in the SDK. It can
  4205. * be run against the LocalStore, as well as be converted to a `Target` to
  4206. * query the RemoteStore results.
  4207. *
  4208. * Visible for testing.
  4209. */
  4210. class Un {
  4211. /**
  4212. * Initializes a Query with a path and optional additional query constraints.
  4213. * Path must currently be empty if this is a collection group query.
  4214. */
  4215. constructor(t, e = null, n = [], s = [], i = null, r = "F" /* LimitType.First */ , o = null, u = null) {
  4216. this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s,
  4217. this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.wt = null,
  4218. // The corresponding `Target` of this `Query` instance.
  4219. this._t = null, this.startAt, this.endAt;
  4220. }
  4221. }
  4222. /** Creates a new Query instance with the options provided. */ function Kn(t, e, n, s, i, r, o, u) {
  4223. return new Un(t, e, n, s, i, r, o, u);
  4224. }
  4225. /** Creates a new Query for a query that matches all documents at `path` */ function Gn(t) {
  4226. return new Un(t);
  4227. }
  4228. /**
  4229. * Helper to convert a collection group query into a collection query at a
  4230. * specific path. This is used when executing collection group queries, since
  4231. * we have to split the query into a set of collection queries at multiple
  4232. * paths.
  4233. */
  4234. /**
  4235. * Returns true if this query does not specify any query constraints that
  4236. * could remove results.
  4237. */
  4238. function Qn(t) {
  4239. return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());
  4240. }
  4241. function jn(t) {
  4242. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  4243. }
  4244. function zn(t) {
  4245. for (const e of t.filters) {
  4246. const t = e.getFirstInequalityField();
  4247. if (null !== t) return t;
  4248. }
  4249. return null;
  4250. }
  4251. /**
  4252. * Creates a new Query for a collection group query that matches all documents
  4253. * within the provided collection group.
  4254. */
  4255. /**
  4256. * Returns whether the query matches a collection group rather than a specific
  4257. * collection.
  4258. */
  4259. function Wn(t) {
  4260. return null !== t.collectionGroup;
  4261. }
  4262. /**
  4263. * Returns the implicit order by constraint that is used to execute the Query,
  4264. * which can be different from the order by constraints the user provided (e.g.
  4265. * the SDK and backend always orders by `__name__`).
  4266. */ function Hn(t) {
  4267. const e = L(t);
  4268. if (null === e.wt) {
  4269. e.wt = [];
  4270. const t = zn(e), n = jn(e);
  4271. if (null !== t && null === n)
  4272. // In order to implicitly add key ordering, we must also add the
  4273. // inequality filter field for it to be a valid query.
  4274. // Note that the default inequality field and key ordering is ascending.
  4275. t.isKeyField() || e.wt.push(new dn(t)), e.wt.push(new dn(at.keyField(), "asc" /* Direction.ASCENDING */)); else {
  4276. let t = !1;
  4277. for (const n of e.explicitOrderBy) e.wt.push(n), n.field.isKeyField() && (t = !0);
  4278. if (!t) {
  4279. // The order of the implicit key ordering always matches the last
  4280. // explicit order by
  4281. const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  4282. e.wt.push(new dn(at.keyField(), t));
  4283. }
  4284. }
  4285. }
  4286. return e.wt;
  4287. }
  4288. /**
  4289. * Converts this `Query` instance to it's corresponding `Target` representation.
  4290. */ function Jn(t) {
  4291. const e = L(t);
  4292. if (!e._t) if ("F" /* LimitType.First */ === e.limitType) e._t = Mn(e.path, e.collectionGroup, Hn(e), e.filters, e.limit, e.startAt, e.endAt); else {
  4293. // Flip the orderBy directions since we want the last results
  4294. const t = [];
  4295. for (const n of Hn(e)) {
  4296. const e = "desc" /* Direction.DESCENDING */ === n.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  4297. t.push(new dn(n.field, e));
  4298. }
  4299. // We need to swap the cursors to match the now-flipped query ordering.
  4300. const n = e.endAt ? new hn(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new hn(e.startAt.position, e.startAt.inclusive) : null;
  4301. // Now return as a LimitType.First query.
  4302. e._t = Mn(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);
  4303. }
  4304. return e._t;
  4305. }
  4306. function Yn(t, e) {
  4307. e.getFirstInequalityField(), zn(t);
  4308. const n = t.filters.concat([ e ]);
  4309. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  4310. }
  4311. function Xn(t, e, n) {
  4312. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  4313. }
  4314. function Zn(t, e) {
  4315. return On(Jn(t), Jn(e)) && t.limitType === e.limitType;
  4316. }
  4317. // TODO(b/29183165): This is used to get a unique string from a query to, for
  4318. // example, use as a dictionary key, but the implementation is subject to
  4319. // collisions. Make it collision-free.
  4320. function ts(t) {
  4321. return `${$n(Jn(t))}|lt:${t.limitType}`;
  4322. }
  4323. function es(t) {
  4324. return `Query(target=${function(t) {
  4325. let e = t.path.canonicalString();
  4326. return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup),
  4327. t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Rn(t))).join(", ")}]`),
  4328. Ft(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {
  4329. return `${t.field.canonicalString()} (${t.dir})`;
  4330. }(t))).join(", ")}]`), t.startAt && (e += ", startAt: ", e += t.startAt.inclusive ? "b:" : "a:",
  4331. e += t.startAt.position.map((t => Qe(t))).join(",")), t.endAt && (e += ", endAt: ",
  4332. e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((t => Qe(t))).join(",")),
  4333. `Target(${e})`;
  4334. }(Jn(t))}; limitType=${t.limitType})`;
  4335. }
  4336. /** Returns whether `doc` matches the constraints of `query`. */ function ns(t, e) {
  4337. return e.isFoundDocument() && function(t, e) {
  4338. const n = e.key.path;
  4339. return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ht.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
  4340. }
  4341. /**
  4342. * A document must have a value for every ordering clause in order to show up
  4343. * in the results.
  4344. */ (t, e) && function(t, e) {
  4345. // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
  4346. // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
  4347. // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
  4348. // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
  4349. // A document with content of {b:1} matches the filters, but does not match the orderBy because
  4350. // it's missing the field 'a'.
  4351. for (const n of Hn(t))
  4352. // order by key always matches
  4353. if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;
  4354. return !0;
  4355. }(t, e) && function(t, e) {
  4356. for (const n of t.filters) if (!n.matches(e)) return !1;
  4357. return !0;
  4358. }
  4359. /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {
  4360. if (t.startAt && !
  4361. /**
  4362. * Returns true if a document sorts before a bound using the provided sort
  4363. * order.
  4364. */
  4365. function(t, e, n) {
  4366. const s = ln(t, e, n);
  4367. return t.inclusive ? s <= 0 : s < 0;
  4368. }(t.startAt, Hn(t), e)) return !1;
  4369. if (t.endAt && !function(t, e, n) {
  4370. const s = ln(t, e, n);
  4371. return t.inclusive ? s >= 0 : s > 0;
  4372. }(t.endAt, Hn(t), e)) return !1;
  4373. return !0;
  4374. }
  4375. /**
  4376. * Returns the collection group that this query targets.
  4377. *
  4378. * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
  4379. * synchronization for query results.
  4380. */ (t, e);
  4381. }
  4382. function ss(t) {
  4383. return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));
  4384. }
  4385. /**
  4386. * Returns a new comparator function that can be used to compare two documents
  4387. * based on the Query's ordering constraint.
  4388. */ function is(t) {
  4389. return (e, n) => {
  4390. let s = !1;
  4391. for (const i of Hn(t)) {
  4392. const t = rs(i, e, n);
  4393. if (0 !== t) return t;
  4394. s = s || i.field.isKeyField();
  4395. }
  4396. return 0;
  4397. };
  4398. }
  4399. function rs(t, e, n) {
  4400. const s = t.field.isKeyField() ? ht.comparator(e.key, n.key) : function(t, e, n) {
  4401. const s = e.data.field(t), i = n.data.field(t);
  4402. return null !== s && null !== i ? Ke(s, i) : O();
  4403. }(t.field, e, n);
  4404. switch (t.dir) {
  4405. case "asc" /* Direction.ASCENDING */ :
  4406. return s;
  4407. case "desc" /* Direction.DESCENDING */ :
  4408. return -1 * s;
  4409. default:
  4410. return O();
  4411. }
  4412. }
  4413. /**
  4414. * @license
  4415. * Copyright 2017 Google LLC
  4416. *
  4417. * Licensed under the Apache License, Version 2.0 (the "License");
  4418. * you may not use this file except in compliance with the License.
  4419. * You may obtain a copy of the License at
  4420. *
  4421. * http://www.apache.org/licenses/LICENSE-2.0
  4422. *
  4423. * Unless required by applicable law or agreed to in writing, software
  4424. * distributed under the License is distributed on an "AS IS" BASIS,
  4425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4426. * See the License for the specific language governing permissions and
  4427. * limitations under the License.
  4428. */
  4429. /**
  4430. * A map implementation that uses objects as keys. Objects must have an
  4431. * associated equals function and must be immutable. Entries in the map are
  4432. * stored together with the key being produced from the mapKeyFn. This map
  4433. * automatically handles collisions of keys.
  4434. */ class os {
  4435. constructor(t, e) {
  4436. this.mapKeyFn = t, this.equalsFn = e,
  4437. /**
  4438. * The inner map for a key/value pair. Due to the possibility of collisions we
  4439. * keep a list of entries that we do a linear search through to find an actual
  4440. * match. Note that collisions should be rare, so we still expect near
  4441. * constant time lookups in practice.
  4442. */
  4443. this.inner = {},
  4444. /** The number of entries stored in the map */
  4445. this.innerSize = 0;
  4446. }
  4447. /** Get a value for this key, or undefined if it does not exist. */ get(t) {
  4448. const e = this.mapKeyFn(t), n = this.inner[e];
  4449. if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;
  4450. }
  4451. has(t) {
  4452. return void 0 !== this.get(t);
  4453. }
  4454. /** Put this key and value in the map. */ set(t, e) {
  4455. const n = this.mapKeyFn(t), s = this.inner[n];
  4456. if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;
  4457. for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t))
  4458. // This is updating an existing entry and does not increase `innerSize`.
  4459. return void (s[n] = [ t, e ]);
  4460. s.push([ t, e ]), this.innerSize++;
  4461. }
  4462. /**
  4463. * Remove this key from the map. Returns a boolean if anything was deleted.
  4464. */ delete(t) {
  4465. const e = this.mapKeyFn(t), n = this.inner[e];
  4466. if (void 0 === n) return !1;
  4467. for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1),
  4468. this.innerSize--, !0;
  4469. return !1;
  4470. }
  4471. forEach(t) {
  4472. ge(this.inner, ((e, n) => {
  4473. for (const [e, s] of n) t(e, s);
  4474. }));
  4475. }
  4476. isEmpty() {
  4477. return ye(this.inner);
  4478. }
  4479. size() {
  4480. return this.innerSize;
  4481. }
  4482. }
  4483. /**
  4484. * @license
  4485. * Copyright 2017 Google LLC
  4486. *
  4487. * Licensed under the Apache License, Version 2.0 (the "License");
  4488. * you may not use this file except in compliance with the License.
  4489. * You may obtain a copy of the License at
  4490. *
  4491. * http://www.apache.org/licenses/LICENSE-2.0
  4492. *
  4493. * Unless required by applicable law or agreed to in writing, software
  4494. * distributed under the License is distributed on an "AS IS" BASIS,
  4495. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4496. * See the License for the specific language governing permissions and
  4497. * limitations under the License.
  4498. */ const us = new pe(ht.comparator);
  4499. function cs() {
  4500. return us;
  4501. }
  4502. const as = new pe(ht.comparator);
  4503. function hs(...t) {
  4504. let e = as;
  4505. for (const n of t) e = e.insert(n.key, n);
  4506. return e;
  4507. }
  4508. function ls(t) {
  4509. let e = as;
  4510. return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;
  4511. }
  4512. function fs() {
  4513. return ws();
  4514. }
  4515. function ds() {
  4516. return ws();
  4517. }
  4518. function ws() {
  4519. return new os((t => t.toString()), ((t, e) => t.isEqual(e)));
  4520. }
  4521. const _s = new pe(ht.comparator);
  4522. const ms = new Ee(ht.comparator);
  4523. function gs(...t) {
  4524. let e = ms;
  4525. for (const n of t) e = e.add(n);
  4526. return e;
  4527. }
  4528. const ys = new Ee(et);
  4529. function ps() {
  4530. return ys;
  4531. }
  4532. /**
  4533. * @license
  4534. * Copyright 2020 Google LLC
  4535. *
  4536. * Licensed under the Apache License, Version 2.0 (the "License");
  4537. * you may not use this file except in compliance with the License.
  4538. * You may obtain a copy of the License at
  4539. *
  4540. * http://www.apache.org/licenses/LICENSE-2.0
  4541. *
  4542. * Unless required by applicable law or agreed to in writing, software
  4543. * distributed under the License is distributed on an "AS IS" BASIS,
  4544. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4545. * See the License for the specific language governing permissions and
  4546. * limitations under the License.
  4547. */
  4548. /**
  4549. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4550. * `useProto3Json` setting.
  4551. */ function Is(t, e) {
  4552. if (t.useProto3Json) {
  4553. if (isNaN(e)) return {
  4554. doubleValue: "NaN"
  4555. };
  4556. if (e === 1 / 0) return {
  4557. doubleValue: "Infinity"
  4558. };
  4559. if (e === -1 / 0) return {
  4560. doubleValue: "-Infinity"
  4561. };
  4562. }
  4563. return {
  4564. doubleValue: Bt(e) ? "-0" : e
  4565. };
  4566. }
  4567. /**
  4568. * Returns an IntegerValue for `value`.
  4569. */ function Ts(t) {
  4570. return {
  4571. integerValue: "" + t
  4572. };
  4573. }
  4574. /**
  4575. * Returns a value for a number that's appropriate to put into a proto.
  4576. * The return value is an IntegerValue if it can safely represent the value,
  4577. * otherwise a DoubleValue is returned.
  4578. */ function Es(t, e) {
  4579. return Lt(e) ? Ts(e) : Is(t, e);
  4580. }
  4581. /**
  4582. * @license
  4583. * Copyright 2018 Google LLC
  4584. *
  4585. * Licensed under the Apache License, Version 2.0 (the "License");
  4586. * you may not use this file except in compliance with the License.
  4587. * You may obtain a copy of the License at
  4588. *
  4589. * http://www.apache.org/licenses/LICENSE-2.0
  4590. *
  4591. * Unless required by applicable law or agreed to in writing, software
  4592. * distributed under the License is distributed on an "AS IS" BASIS,
  4593. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4594. * See the License for the specific language governing permissions and
  4595. * limitations under the License.
  4596. */
  4597. /** Used to represent a field transform on a mutation. */ class As {
  4598. constructor() {
  4599. // Make sure that the structural type of `TransformOperation` is unique.
  4600. // See https://github.com/microsoft/TypeScript/issues/5451
  4601. this._ = void 0;
  4602. }
  4603. }
  4604. /**
  4605. * Computes the local transform result against the provided `previousValue`,
  4606. * optionally using the provided localWriteTime.
  4607. */ function vs(t, e, n) {
  4608. return t instanceof bs ? function(t, e) {
  4609. const n = {
  4610. fields: {
  4611. __type__: {
  4612. stringValue: "server_timestamp"
  4613. },
  4614. __local_write_time__: {
  4615. timestampValue: {
  4616. seconds: t.seconds,
  4617. nanos: t.nanoseconds
  4618. }
  4619. }
  4620. }
  4621. };
  4622. // We should avoid storing deeply nested server timestamp map values
  4623. // because we never use the intermediate "previous values".
  4624. // For example:
  4625. // previous: 42L, add: t1, result: t1 -> 42L
  4626. // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)
  4627. // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)
  4628. // `getPreviousValue` recursively traverses server timestamps to find the
  4629. // least recent Value.
  4630. return e && Ne(e) && (e = ke(e)), e && (n.fields.__previous_value__ = e),
  4631. {
  4632. mapValue: n
  4633. };
  4634. }(n, e) : t instanceof Vs ? Ss(t, e) : t instanceof Ds ? Cs(t, e) : function(t, e) {
  4635. // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
  4636. // precision and resolves overflows by reducing precision, we do not
  4637. // manually cap overflows at 2^63.
  4638. const n = Ps(t, e), s = Ns(n) + Ns(t.gt);
  4639. return He(n) && He(t.gt) ? Ts(s) : Is(t.serializer, s);
  4640. }(t, e);
  4641. }
  4642. /**
  4643. * Computes a final transform result after the transform has been acknowledged
  4644. * by the server, potentially using the server-provided transformResult.
  4645. */ function Rs(t, e, n) {
  4646. // The server just sends null as the transform result for array operations,
  4647. // so we have to calculate a result the same as we do for local
  4648. // applications.
  4649. return t instanceof Vs ? Ss(t, e) : t instanceof Ds ? Cs(t, e) : n;
  4650. }
  4651. /**
  4652. * If this transform operation is not idempotent, returns the base value to
  4653. * persist for this transform. If a base value is returned, the transform
  4654. * operation is always applied to this base value, even if document has
  4655. * already been updated.
  4656. *
  4657. * Base values provide consistent behavior for non-idempotent transforms and
  4658. * allow us to return the same latency-compensated value even if the backend
  4659. * has already applied the transform operation. The base value is null for
  4660. * idempotent transforms, as they can be re-played even if the backend has
  4661. * already applied them.
  4662. *
  4663. * @returns a base value to store along with the mutation, or null for
  4664. * idempotent transforms.
  4665. */ function Ps(t, e) {
  4666. return t instanceof xs ? He(n = e) || function(t) {
  4667. return !!t && "doubleValue" in t;
  4668. }
  4669. /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {
  4670. integerValue: 0
  4671. } : null;
  4672. var n;
  4673. }
  4674. /** Transforms a value into a server-generated timestamp. */
  4675. class bs extends As {}
  4676. /** Transforms an array value via a union operation. */ class Vs extends As {
  4677. constructor(t) {
  4678. super(), this.elements = t;
  4679. }
  4680. }
  4681. function Ss(t, e) {
  4682. const n = ks(e);
  4683. for (const e of t.elements) n.some((t => qe(t, e))) || n.push(e);
  4684. return {
  4685. arrayValue: {
  4686. values: n
  4687. }
  4688. };
  4689. }
  4690. /** Transforms an array value via a remove operation. */ class Ds extends As {
  4691. constructor(t) {
  4692. super(), this.elements = t;
  4693. }
  4694. }
  4695. function Cs(t, e) {
  4696. let n = ks(e);
  4697. for (const e of t.elements) n = n.filter((t => !qe(t, e)));
  4698. return {
  4699. arrayValue: {
  4700. values: n
  4701. }
  4702. };
  4703. }
  4704. /**
  4705. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4706. * transforms. Converts all field values to integers or doubles, but unlike the
  4707. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4708. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4709. */ class xs extends As {
  4710. constructor(t, e) {
  4711. super(), this.serializer = t, this.gt = e;
  4712. }
  4713. }
  4714. function Ns(t) {
  4715. return Ce(t.integerValue || t.doubleValue);
  4716. }
  4717. function ks(t) {
  4718. return Je(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
  4719. }
  4720. /**
  4721. * @license
  4722. * Copyright 2017 Google LLC
  4723. *
  4724. * Licensed under the Apache License, Version 2.0 (the "License");
  4725. * you may not use this file except in compliance with the License.
  4726. * You may obtain a copy of the License at
  4727. *
  4728. * http://www.apache.org/licenses/LICENSE-2.0
  4729. *
  4730. * Unless required by applicable law or agreed to in writing, software
  4731. * distributed under the License is distributed on an "AS IS" BASIS,
  4732. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4733. * See the License for the specific language governing permissions and
  4734. * limitations under the License.
  4735. */
  4736. /** A field path and the TransformOperation to perform upon it. */ class Ms {
  4737. constructor(t, e) {
  4738. this.field = t, this.transform = e;
  4739. }
  4740. }
  4741. function $s(t, e) {
  4742. return t.field.isEqual(e.field) && function(t, e) {
  4743. return t instanceof Vs && e instanceof Vs || t instanceof Ds && e instanceof Ds ? nt(t.elements, e.elements, qe) : t instanceof xs && e instanceof xs ? qe(t.gt, e.gt) : t instanceof bs && e instanceof bs;
  4744. }(t.transform, e.transform);
  4745. }
  4746. /** The result of successfully applying a mutation to the backend. */
  4747. class Os {
  4748. constructor(
  4749. /**
  4750. * The version at which the mutation was committed:
  4751. *
  4752. * - For most operations, this is the updateTime in the WriteResult.
  4753. * - For deletes, the commitTime of the WriteResponse (because deletes are
  4754. * not stored and have no updateTime).
  4755. *
  4756. * Note that these versions can be different: No-op writes will not change
  4757. * the updateTime even though the commitTime advances.
  4758. */
  4759. t,
  4760. /**
  4761. * The resulting fields returned from the backend after a mutation
  4762. * containing field transforms has been committed. Contains one FieldValue
  4763. * for each FieldTransform that was in the mutation.
  4764. *
  4765. * Will be empty if the mutation did not contain any field transforms.
  4766. */
  4767. e) {
  4768. this.version = t, this.transformResults = e;
  4769. }
  4770. }
  4771. /**
  4772. * Encodes a precondition for a mutation. This follows the model that the
  4773. * backend accepts with the special case of an explicit "empty" precondition
  4774. * (meaning no precondition).
  4775. */ class Fs {
  4776. constructor(t, e) {
  4777. this.updateTime = t, this.exists = e;
  4778. }
  4779. /** Creates a new empty Precondition. */ static none() {
  4780. return new Fs;
  4781. }
  4782. /** Creates a new Precondition with an exists flag. */ static exists(t) {
  4783. return new Fs(void 0, t);
  4784. }
  4785. /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {
  4786. return new Fs(t);
  4787. }
  4788. /** Returns whether this Precondition is empty. */ get isNone() {
  4789. return void 0 === this.updateTime && void 0 === this.exists;
  4790. }
  4791. isEqual(t) {
  4792. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  4793. }
  4794. }
  4795. /** Returns true if the preconditions is valid for the given document. */ function Bs(t, e) {
  4796. return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
  4797. }
  4798. /**
  4799. * A mutation describes a self-contained change to a document. Mutations can
  4800. * create, replace, delete, and update subsets of documents.
  4801. *
  4802. * Mutations not only act on the value of the document but also its version.
  4803. *
  4804. * For local mutations (mutations that haven't been committed yet), we preserve
  4805. * the existing version for Set and Patch mutations. For Delete mutations, we
  4806. * reset the version to 0.
  4807. *
  4808. * Here's the expected transition table.
  4809. *
  4810. * MUTATION APPLIED TO RESULTS IN
  4811. *
  4812. * SetMutation Document(v3) Document(v3)
  4813. * SetMutation NoDocument(v3) Document(v0)
  4814. * SetMutation InvalidDocument(v0) Document(v0)
  4815. * PatchMutation Document(v3) Document(v3)
  4816. * PatchMutation NoDocument(v3) NoDocument(v3)
  4817. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4818. * DeleteMutation Document(v3) NoDocument(v0)
  4819. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4820. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4821. *
  4822. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4823. * the resulting version for Set and Patch mutations. As deletes have no
  4824. * explicit update time, we use the commitTime of the WriteResponse for
  4825. * Delete mutations.
  4826. *
  4827. * If a mutation is acknowledged by the backend but fails the precondition check
  4828. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4829. * the updated version.
  4830. *
  4831. * Field transforms are used only with Patch and Set Mutations. We use the
  4832. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4833. * messages.
  4834. *
  4835. * ## Subclassing Notes
  4836. *
  4837. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4838. * applyToLocalView() to implement the actual behavior of applying the mutation
  4839. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4840. * example).
  4841. */ class Ls {}
  4842. /**
  4843. * A utility method to calculate a `Mutation` representing the overlay from the
  4844. * final state of the document, and a `FieldMask` representing the fields that
  4845. * are mutated by the local mutations.
  4846. */ function qs(t, e) {
  4847. if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;
  4848. // mask is null when sets or deletes are applied to the current document.
  4849. if (null === e) return t.isNoDocument() ? new Ys(t.key, Fs.none()) : new js(t.key, t.data, Fs.none());
  4850. {
  4851. const n = t.data, s = un.empty();
  4852. let i = new Ee(at.comparator);
  4853. for (let t of e.fields) if (!i.has(t)) {
  4854. let e = n.field(t);
  4855. // If we are deleting a nested field, we take the immediate parent as
  4856. // the mask used to construct the resulting mutation.
  4857. // Justification: Nested fields can create parent fields implicitly. If
  4858. // only a leaf entry is deleted in later mutations, the parent field
  4859. // should still remain, but we may have lost this information.
  4860. // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
  4861. // This leaves the final result (foo, {}). Despite the fact that `doc`
  4862. // has the correct result, `foo` is not in `mask`, and the resulting
  4863. // mutation would miss `foo`.
  4864. null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e),
  4865. i = i.add(t);
  4866. }
  4867. return new zs(t.key, s, new Re(i.toArray()), Fs.none());
  4868. }
  4869. }
  4870. /**
  4871. * Applies this mutation to the given document for the purposes of computing a
  4872. * new remote document. If the input document doesn't match the expected state
  4873. * (e.g. it is invalid or outdated), the document type may transition to
  4874. * unknown.
  4875. *
  4876. * @param mutation - The mutation to apply.
  4877. * @param document - The document to mutate. The input document can be an
  4878. * invalid document if the client has no knowledge of the pre-mutation state
  4879. * of the document.
  4880. * @param mutationResult - The result of applying the mutation from the backend.
  4881. */ function Us(t, e, n) {
  4882. t instanceof js ? function(t, e, n) {
  4883. // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
  4884. // remote document the server has accepted the mutation so the precondition
  4885. // must have held.
  4886. const s = t.value.clone(), i = Hs(t.fieldTransforms, e, n.transformResults);
  4887. s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();
  4888. }(t, e, n) : t instanceof zs ? function(t, e, n) {
  4889. if (!Bs(t.precondition, e))
  4890. // Since the mutation was not rejected, we know that the precondition
  4891. // matched on the backend. We therefore must not have the expected version
  4892. // of the document in our cache and convert to an UnknownDocument with a
  4893. // known updateTime.
  4894. return void e.convertToUnknownDocument(n.version);
  4895. const s = Hs(t.fieldTransforms, e, n.transformResults), i = e.data;
  4896. i.setAll(Ws(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
  4897. }(t, e, n) : function(t, e, n) {
  4898. // Unlike applyToLocalView, if we're applying a mutation to a remote
  4899. // document the server has accepted the mutation so the precondition must
  4900. // have held.
  4901. e.convertToNoDocument(n.version).setHasCommittedMutations();
  4902. }(0, e, n);
  4903. }
  4904. /**
  4905. * Applies this mutation to the given document for the purposes of computing
  4906. * the new local view of a document. If the input document doesn't match the
  4907. * expected state, the document is not modified.
  4908. *
  4909. * @param mutation - The mutation to apply.
  4910. * @param document - The document to mutate. The input document can be an
  4911. * invalid document if the client has no knowledge of the pre-mutation state
  4912. * of the document.
  4913. * @param previousMask - The fields that have been updated before applying this mutation.
  4914. * @param localWriteTime - A timestamp indicating the local write time of the
  4915. * batch this mutation is a part of.
  4916. * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
  4917. */ function Ks(t, e, n, s) {
  4918. return t instanceof js ? function(t, e, n, s) {
  4919. if (!Bs(t.precondition, e))
  4920. // The mutation failed to apply (e.g. a document ID created with add()
  4921. // caused a name collision).
  4922. return n;
  4923. const i = t.value.clone(), r = Js(t.fieldTransforms, s, e);
  4924. return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(),
  4925. null;
  4926. // SetMutation overwrites all fields.
  4927. }
  4928. /**
  4929. * A mutation that modifies fields of the document at the given key with the
  4930. * given values. The values are applied through a field mask:
  4931. *
  4932. * * When a field is in both the mask and the values, the corresponding field
  4933. * is updated.
  4934. * * When a field is in neither the mask nor the values, the corresponding
  4935. * field is unmodified.
  4936. * * When a field is in the mask but not in the values, the corresponding field
  4937. * is deleted.
  4938. * * When a field is not in the mask but is in the values, the values map is
  4939. * ignored.
  4940. */ (t, e, n, s) : t instanceof zs ? function(t, e, n, s) {
  4941. if (!Bs(t.precondition, e)) return n;
  4942. const i = Js(t.fieldTransforms, s, e), r = e.data;
  4943. if (r.setAll(Ws(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(),
  4944. null === n) return null;
  4945. return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));
  4946. }
  4947. /**
  4948. * Returns a FieldPath/Value map with the content of the PatchMutation.
  4949. */ (t, e, n, s) : function(t, e, n) {
  4950. if (Bs(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(),
  4951. null;
  4952. return n;
  4953. }
  4954. /**
  4955. * A mutation that verifies the existence of the document at the given key with
  4956. * the provided precondition.
  4957. *
  4958. * The `verify` operation is only used in Transactions, and this class serves
  4959. * primarily to facilitate serialization into protos.
  4960. */ (t, e, n);
  4961. }
  4962. /**
  4963. * If this mutation is not idempotent, returns the base value to persist with
  4964. * this mutation. If a base value is returned, the mutation is always applied
  4965. * to this base value, even if document has already been updated.
  4966. *
  4967. * The base value is a sparse object that consists of only the document
  4968. * fields for which this mutation contains a non-idempotent transformation
  4969. * (e.g. a numeric increment). The provided value guarantees consistent
  4970. * behavior for non-idempotent transforms and allow us to return the same
  4971. * latency-compensated value even if the backend has already applied the
  4972. * mutation. The base value is null for idempotent mutations, as they can be
  4973. * re-played even if the backend has already applied them.
  4974. *
  4975. * @returns a base value to store along with the mutation, or null for
  4976. * idempotent mutations.
  4977. */ function Gs(t, e) {
  4978. let n = null;
  4979. for (const s of t.fieldTransforms) {
  4980. const t = e.data.field(s.field), i = Ps(s.transform, t || null);
  4981. null != i && (null === n && (n = un.empty()), n.set(s.field, i));
  4982. }
  4983. return n || null;
  4984. }
  4985. function Qs(t, e) {
  4986. return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {
  4987. return void 0 === t && void 0 === e || !(!t || !e) && nt(t, e, ((t, e) => $s(t, e)));
  4988. }(t.fieldTransforms, e.fieldTransforms) && (0 /* MutationType.Set */ === t.type ? t.value.isEqual(e.value) : 1 /* MutationType.Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask)))));
  4989. }
  4990. /**
  4991. * A mutation that creates or replaces the document at the given key with the
  4992. * object value contents.
  4993. */ class js extends Ls {
  4994. constructor(t, e, n, s = []) {
  4995. super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s,
  4996. this.type = 0 /* MutationType.Set */;
  4997. }
  4998. getFieldMask() {
  4999. return null;
  5000. }
  5001. }
  5002. class zs extends Ls {
  5003. constructor(t, e, n, s, i = []) {
  5004. super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s,
  5005. this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;
  5006. }
  5007. getFieldMask() {
  5008. return this.fieldMask;
  5009. }
  5010. }
  5011. function Ws(t) {
  5012. const e = new Map;
  5013. return t.fieldMask.fields.forEach((n => {
  5014. if (!n.isEmpty()) {
  5015. const s = t.data.field(n);
  5016. e.set(n, s);
  5017. }
  5018. })), e;
  5019. }
  5020. /**
  5021. * Creates a list of "transform results" (a transform result is a field value
  5022. * representing the result of applying a transform) for use after a mutation
  5023. * containing transforms has been acknowledged by the server.
  5024. *
  5025. * @param fieldTransforms - The field transforms to apply the result to.
  5026. * @param mutableDocument - The current state of the document after applying all
  5027. * previous mutations.
  5028. * @param serverTransformResults - The transform results received by the server.
  5029. * @returns The transform results list.
  5030. */ function Hs(t, e, n) {
  5031. const s = new Map;
  5032. F(t.length === n.length);
  5033. for (let i = 0; i < n.length; i++) {
  5034. const r = t[i], o = r.transform, u = e.data.field(r.field);
  5035. s.set(r.field, Rs(o, u, n[i]));
  5036. }
  5037. return s;
  5038. }
  5039. /**
  5040. * Creates a list of "transform results" (a transform result is a field value
  5041. * representing the result of applying a transform) for use when applying a
  5042. * transform locally.
  5043. *
  5044. * @param fieldTransforms - The field transforms to apply the result to.
  5045. * @param localWriteTime - The local time of the mutation (used to
  5046. * generate ServerTimestampValues).
  5047. * @param mutableDocument - The document to apply transforms on.
  5048. * @returns The transform results list.
  5049. */ function Js(t, e, n) {
  5050. const s = new Map;
  5051. for (const i of t) {
  5052. const t = i.transform, r = n.data.field(i.field);
  5053. s.set(i.field, vs(t, r, e));
  5054. }
  5055. return s;
  5056. }
  5057. /** A mutation that deletes the document at the given key. */ class Ys extends Ls {
  5058. constructor(t, e) {
  5059. super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ ,
  5060. this.fieldTransforms = [];
  5061. }
  5062. getFieldMask() {
  5063. return null;
  5064. }
  5065. }
  5066. class Xs extends Ls {
  5067. constructor(t, e) {
  5068. super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ ,
  5069. this.fieldTransforms = [];
  5070. }
  5071. getFieldMask() {
  5072. return null;
  5073. }
  5074. }
  5075. /**
  5076. * @license
  5077. * Copyright 2017 Google LLC
  5078. *
  5079. * Licensed under the Apache License, Version 2.0 (the "License");
  5080. * you may not use this file except in compliance with the License.
  5081. * You may obtain a copy of the License at
  5082. *
  5083. * http://www.apache.org/licenses/LICENSE-2.0
  5084. *
  5085. * Unless required by applicable law or agreed to in writing, software
  5086. * distributed under the License is distributed on an "AS IS" BASIS,
  5087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5088. * See the License for the specific language governing permissions and
  5089. * limitations under the License.
  5090. */
  5091. /**
  5092. * A batch of mutations that will be sent as one unit to the backend.
  5093. */ class Zs {
  5094. /**
  5095. * @param batchId - The unique ID of this mutation batch.
  5096. * @param localWriteTime - The original write time of this mutation.
  5097. * @param baseMutations - Mutations that are used to populate the base
  5098. * values when this mutation is applied locally. This can be used to locally
  5099. * overwrite values that are persisted in the remote document cache. Base
  5100. * mutations are never sent to the backend.
  5101. * @param mutations - The user-provided mutations in this mutation batch.
  5102. * User-provided mutations are applied both locally and remotely on the
  5103. * backend.
  5104. */
  5105. constructor(t, e, n, s) {
  5106. this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;
  5107. }
  5108. /**
  5109. * Applies all the mutations in this MutationBatch to the specified document
  5110. * to compute the state of the remote document
  5111. *
  5112. * @param document - The document to apply mutations to.
  5113. * @param batchResult - The result of applying the MutationBatch to the
  5114. * backend.
  5115. */ applyToRemoteDocument(t, e) {
  5116. const n = e.mutationResults;
  5117. for (let e = 0; e < this.mutations.length; e++) {
  5118. const s = this.mutations[e];
  5119. if (s.key.isEqual(t.key)) {
  5120. Us(s, t, n[e]);
  5121. }
  5122. }
  5123. }
  5124. /**
  5125. * Computes the local view of a document given all the mutations in this
  5126. * batch.
  5127. *
  5128. * @param document - The document to apply mutations to.
  5129. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  5130. * @returns A `FieldMask` representing all the fields that are mutated.
  5131. */ applyToLocalView(t, e) {
  5132. // First, apply the base state. This allows us to apply non-idempotent
  5133. // transform against a consistent set of values.
  5134. for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = Ks(n, t, e, this.localWriteTime));
  5135. // Second, apply all user-provided mutations.
  5136. for (const n of this.mutations) n.key.isEqual(t.key) && (e = Ks(n, t, e, this.localWriteTime));
  5137. return e;
  5138. }
  5139. /**
  5140. * Computes the local view for all provided documents given the mutations in
  5141. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  5142. * replace all the mutation applications.
  5143. */ applyToLocalDocumentSet(t, e) {
  5144. // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
  5145. // directly (as done in `applyToLocalView()`), we can reduce the complexity
  5146. // to O(n).
  5147. const n = ds();
  5148. return this.mutations.forEach((s => {
  5149. const i = t.get(s.key), r = i.overlayedDocument;
  5150. // TODO(mutabledocuments): This method should take a MutableDocumentMap
  5151. // and we should remove this cast.
  5152. let o = this.applyToLocalView(r, i.mutatedFields);
  5153. // Set mutatedFields to null if the document is only from local mutations.
  5154. // This creates a Set or Delete mutation, instead of trying to create a
  5155. // patch mutation as the overlay.
  5156. o = e.has(s.key) ? null : o;
  5157. const u = qs(r, o);
  5158. null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(rt.min());
  5159. })), n;
  5160. }
  5161. keys() {
  5162. return this.mutations.reduce(((t, e) => t.add(e.key)), gs());
  5163. }
  5164. isEqual(t) {
  5165. return this.batchId === t.batchId && nt(this.mutations, t.mutations, ((t, e) => Qs(t, e))) && nt(this.baseMutations, t.baseMutations, ((t, e) => Qs(t, e)));
  5166. }
  5167. }
  5168. /** The result of applying a mutation batch to the backend. */ class ti {
  5169. constructor(t, e, n,
  5170. /**
  5171. * A pre-computed mapping from each mutated document to the resulting
  5172. * version.
  5173. */
  5174. s) {
  5175. this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;
  5176. }
  5177. /**
  5178. * Creates a new MutationBatchResult for the given batch and results. There
  5179. * must be one result for each mutation in the batch. This static factory
  5180. * caches a document=&gt;version mapping (docVersions).
  5181. */ static from(t, e, n) {
  5182. F(t.mutations.length === n.length);
  5183. let s = _s;
  5184. const i = t.mutations;
  5185. for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);
  5186. return new ti(t, e, n, s);
  5187. }
  5188. }
  5189. /**
  5190. * @license
  5191. * Copyright 2022 Google LLC
  5192. *
  5193. * Licensed under the Apache License, Version 2.0 (the "License");
  5194. * you may not use this file except in compliance with the License.
  5195. * You may obtain a copy of the License at
  5196. *
  5197. * http://www.apache.org/licenses/LICENSE-2.0
  5198. *
  5199. * Unless required by applicable law or agreed to in writing, software
  5200. * distributed under the License is distributed on an "AS IS" BASIS,
  5201. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5202. * See the License for the specific language governing permissions and
  5203. * limitations under the License.
  5204. */
  5205. /**
  5206. * Representation of an overlay computed by Firestore.
  5207. *
  5208. * Holds information about a mutation and the largest batch id in Firestore when
  5209. * the mutation was created.
  5210. */ class ei {
  5211. constructor(t, e) {
  5212. this.largestBatchId = t, this.mutation = e;
  5213. }
  5214. getKey() {
  5215. return this.mutation.key;
  5216. }
  5217. isEqual(t) {
  5218. return null !== t && this.mutation === t.mutation;
  5219. }
  5220. toString() {
  5221. return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;
  5222. }
  5223. }
  5224. /**
  5225. * @license
  5226. * Copyright 2023 Google LLC
  5227. *
  5228. * Licensed under the Apache License, Version 2.0 (the "License");
  5229. * you may not use this file except in compliance with the License.
  5230. * You may obtain a copy of the License at
  5231. *
  5232. * http://www.apache.org/licenses/LICENSE-2.0
  5233. *
  5234. * Unless required by applicable law or agreed to in writing, software
  5235. * distributed under the License is distributed on an "AS IS" BASIS,
  5236. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5237. * See the License for the specific language governing permissions and
  5238. * limitations under the License.
  5239. */
  5240. /**
  5241. * Concrete implementation of the Aggregate type.
  5242. */ class ni {
  5243. constructor(t, e, n) {
  5244. this.alias = t, this.yt = e, this.fieldPath = n;
  5245. }
  5246. }
  5247. /**
  5248. * @license
  5249. * Copyright 2017 Google LLC
  5250. *
  5251. * Licensed under the Apache License, Version 2.0 (the "License");
  5252. * you may not use this file except in compliance with the License.
  5253. * You may obtain a copy of the License at
  5254. *
  5255. * http://www.apache.org/licenses/LICENSE-2.0
  5256. *
  5257. * Unless required by applicable law or agreed to in writing, software
  5258. * distributed under the License is distributed on an "AS IS" BASIS,
  5259. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5260. * See the License for the specific language governing permissions and
  5261. * limitations under the License.
  5262. */ class si {
  5263. constructor(t, e) {
  5264. this.count = t, this.unchangedNames = e;
  5265. }
  5266. }
  5267. /**
  5268. * @license
  5269. * Copyright 2017 Google LLC
  5270. *
  5271. * Licensed under the Apache License, Version 2.0 (the "License");
  5272. * you may not use this file except in compliance with the License.
  5273. * You may obtain a copy of the License at
  5274. *
  5275. * http://www.apache.org/licenses/LICENSE-2.0
  5276. *
  5277. * Unless required by applicable law or agreed to in writing, software
  5278. * distributed under the License is distributed on an "AS IS" BASIS,
  5279. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5280. * See the License for the specific language governing permissions and
  5281. * limitations under the License.
  5282. */
  5283. /**
  5284. * Error Codes describing the different ways GRPC can fail. These are copied
  5285. * directly from GRPC's sources here:
  5286. *
  5287. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  5288. *
  5289. * Important! The names of these identifiers matter because the string forms
  5290. * are used for reverse lookups from the webchannel stream. Do NOT change the
  5291. * names of these identifiers or change this into a const enum.
  5292. */ var ii, ri;
  5293. /**
  5294. * Determines whether an error code represents a permanent error when received
  5295. * in response to a non-write operation.
  5296. *
  5297. * See isPermanentWriteError for classifying write errors.
  5298. */
  5299. function oi(t) {
  5300. switch (t) {
  5301. default:
  5302. return O();
  5303. case q.CANCELLED:
  5304. case q.UNKNOWN:
  5305. case q.DEADLINE_EXCEEDED:
  5306. case q.RESOURCE_EXHAUSTED:
  5307. case q.INTERNAL:
  5308. case q.UNAVAILABLE:
  5309. // Unauthenticated means something went wrong with our token and we need
  5310. // to retry with new credentials which will happen automatically.
  5311. case q.UNAUTHENTICATED:
  5312. return !1;
  5313. case q.INVALID_ARGUMENT:
  5314. case q.NOT_FOUND:
  5315. case q.ALREADY_EXISTS:
  5316. case q.PERMISSION_DENIED:
  5317. case q.FAILED_PRECONDITION:
  5318. // Aborted might be retried in some scenarios, but that is dependant on
  5319. // the context and should handled individually by the calling code.
  5320. // See https://cloud.google.com/apis/design/errors.
  5321. case q.ABORTED:
  5322. case q.OUT_OF_RANGE:
  5323. case q.UNIMPLEMENTED:
  5324. case q.DATA_LOSS:
  5325. return !0;
  5326. }
  5327. }
  5328. /**
  5329. * Determines whether an error code represents a permanent error when received
  5330. * in response to a write operation.
  5331. *
  5332. * Write operations must be handled specially because as of b/119437764, ABORTED
  5333. * errors on the write stream should be retried too (even though ABORTED errors
  5334. * are not generally retryable).
  5335. *
  5336. * Note that during the initial handshake on the write stream an ABORTED error
  5337. * signals that we should discard our stream token (i.e. it is permanent). This
  5338. * means a handshake error should be classified with isPermanentError, above.
  5339. */
  5340. /**
  5341. * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
  5342. * are not the same as HTTP status codes.
  5343. *
  5344. * @returns The Code equivalent to the given GRPC status code. Fails if there
  5345. * is no match.
  5346. */
  5347. function ui(t) {
  5348. if (void 0 === t)
  5349. // This shouldn't normally happen, but in certain error cases (like trying
  5350. // to send invalid proto messages) we may get an error with no GRPC code.
  5351. return k("GRPC error has no .code"), q.UNKNOWN;
  5352. switch (t) {
  5353. case ii.OK:
  5354. return q.OK;
  5355. case ii.CANCELLED:
  5356. return q.CANCELLED;
  5357. case ii.UNKNOWN:
  5358. return q.UNKNOWN;
  5359. case ii.DEADLINE_EXCEEDED:
  5360. return q.DEADLINE_EXCEEDED;
  5361. case ii.RESOURCE_EXHAUSTED:
  5362. return q.RESOURCE_EXHAUSTED;
  5363. case ii.INTERNAL:
  5364. return q.INTERNAL;
  5365. case ii.UNAVAILABLE:
  5366. return q.UNAVAILABLE;
  5367. case ii.UNAUTHENTICATED:
  5368. return q.UNAUTHENTICATED;
  5369. case ii.INVALID_ARGUMENT:
  5370. return q.INVALID_ARGUMENT;
  5371. case ii.NOT_FOUND:
  5372. return q.NOT_FOUND;
  5373. case ii.ALREADY_EXISTS:
  5374. return q.ALREADY_EXISTS;
  5375. case ii.PERMISSION_DENIED:
  5376. return q.PERMISSION_DENIED;
  5377. case ii.FAILED_PRECONDITION:
  5378. return q.FAILED_PRECONDITION;
  5379. case ii.ABORTED:
  5380. return q.ABORTED;
  5381. case ii.OUT_OF_RANGE:
  5382. return q.OUT_OF_RANGE;
  5383. case ii.UNIMPLEMENTED:
  5384. return q.UNIMPLEMENTED;
  5385. case ii.DATA_LOSS:
  5386. return q.DATA_LOSS;
  5387. default:
  5388. return O();
  5389. }
  5390. }
  5391. /**
  5392. * Converts an HTTP response's error status to the equivalent error code.
  5393. *
  5394. * @param status - An HTTP error response status ("FAILED_PRECONDITION",
  5395. * "UNKNOWN", etc.)
  5396. * @returns The equivalent Code. Non-matching responses are mapped to
  5397. * Code.UNKNOWN.
  5398. */ (ri = ii || (ii = {}))[ri.OK = 0] = "OK", ri[ri.CANCELLED = 1] = "CANCELLED",
  5399. ri[ri.UNKNOWN = 2] = "UNKNOWN", ri[ri.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  5400. ri[ri.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", ri[ri.NOT_FOUND = 5] = "NOT_FOUND",
  5401. ri[ri.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", ri[ri.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  5402. ri[ri.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", ri[ri.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  5403. ri[ri.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", ri[ri.ABORTED = 10] = "ABORTED",
  5404. ri[ri.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", ri[ri.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  5405. ri[ri.INTERNAL = 13] = "INTERNAL", ri[ri.UNAVAILABLE = 14] = "UNAVAILABLE", ri[ri.DATA_LOSS = 15] = "DATA_LOSS";
  5406. /**
  5407. * @license
  5408. * Copyright 2023 Google LLC
  5409. *
  5410. * Licensed under the Apache License, Version 2.0 (the "License");
  5411. * you may not use this file except in compliance with the License.
  5412. * You may obtain a copy of the License at
  5413. *
  5414. * http://www.apache.org/licenses/LICENSE-2.0
  5415. *
  5416. * Unless required by applicable law or agreed to in writing, software
  5417. * distributed under the License is distributed on an "AS IS" BASIS,
  5418. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5419. * See the License for the specific language governing permissions and
  5420. * limitations under the License.
  5421. */
  5422. /**
  5423. * Manages "testing hooks", hooks into the internals of the SDK to verify
  5424. * internal state and events during integration tests. Do not use this class
  5425. * except for testing purposes.
  5426. *
  5427. * There are two ways to retrieve the global singleton instance of this class:
  5428. * 1. The `instance` property, which returns null if the global singleton
  5429. * instance has not been created. Use this property if the caller should
  5430. * "do nothing" if there are no testing hooks registered, such as when
  5431. * delivering an event to notify registered callbacks.
  5432. * 2. The `getOrCreateInstance()` method, which creates the global singleton
  5433. * instance if it has not been created. Use this method if the instance is
  5434. * needed to, for example, register a callback.
  5435. *
  5436. * @internal
  5437. */
  5438. class ci {
  5439. constructor() {
  5440. this.onExistenceFilterMismatchCallbacks = new Map;
  5441. }
  5442. /**
  5443. * Returns the singleton instance of this class, or null if it has not been
  5444. * initialized.
  5445. */ static get instance() {
  5446. return ai;
  5447. }
  5448. /**
  5449. * Returns the singleton instance of this class, creating it if is has never
  5450. * been created before.
  5451. */ static getOrCreateInstance() {
  5452. return null === ai && (ai = new ci), ai;
  5453. }
  5454. /**
  5455. * Registers a callback to be notified when an existence filter mismatch
  5456. * occurs in the Watch listen stream.
  5457. *
  5458. * The relative order in which callbacks are notified is unspecified; do not
  5459. * rely on any particular ordering. If a given callback is registered multiple
  5460. * times then it will be notified multiple times, once per registration.
  5461. *
  5462. * @param callback the callback to invoke upon existence filter mismatch.
  5463. *
  5464. * @return a function that, when called, unregisters the given callback; only
  5465. * the first invocation of the returned function does anything; all subsequent
  5466. * invocations do nothing.
  5467. */ onExistenceFilterMismatch(t) {
  5468. const e = Symbol();
  5469. return this.onExistenceFilterMismatchCallbacks.set(e, t), () => this.onExistenceFilterMismatchCallbacks.delete(e);
  5470. }
  5471. /**
  5472. * Invokes all currently-registered `onExistenceFilterMismatch` callbacks.
  5473. * @param info Information about the existence filter mismatch.
  5474. */ notifyOnExistenceFilterMismatch(t) {
  5475. this.onExistenceFilterMismatchCallbacks.forEach((e => e(t)));
  5476. }
  5477. }
  5478. /** The global singleton instance of `TestingHooks`. */ let ai = null;
  5479. /**
  5480. * @license
  5481. * Copyright 2023 Google LLC
  5482. *
  5483. * Licensed under the Apache License, Version 2.0 (the "License");
  5484. * you may not use this file except in compliance with the License.
  5485. * You may obtain a copy of the License at
  5486. *
  5487. * http://www.apache.org/licenses/LICENSE-2.0
  5488. *
  5489. * Unless required by applicable law or agreed to in writing, software
  5490. * distributed under the License is distributed on an "AS IS" BASIS,
  5491. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5492. * See the License for the specific language governing permissions and
  5493. * limitations under the License.
  5494. */
  5495. /**
  5496. * An instance of the Platform's 'TextEncoder' implementation.
  5497. */ function hi() {
  5498. return new TextEncoder;
  5499. }
  5500. /**
  5501. * An instance of the Platform's 'TextDecoder' implementation.
  5502. */
  5503. /**
  5504. * @license
  5505. * Copyright 2022 Google LLC
  5506. *
  5507. * Licensed under the Apache License, Version 2.0 (the "License");
  5508. * you may not use this file except in compliance with the License.
  5509. * You may obtain a copy of the License at
  5510. *
  5511. * http://www.apache.org/licenses/LICENSE-2.0
  5512. *
  5513. * Unless required by applicable law or agreed to in writing, software
  5514. * distributed under the License is distributed on an "AS IS" BASIS,
  5515. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5516. * See the License for the specific language governing permissions and
  5517. * limitations under the License.
  5518. */
  5519. const li = new Integer([ 4294967295, 4294967295 ], 0);
  5520. // Hash a string using md5 hashing algorithm.
  5521. function fi(t) {
  5522. const e = hi().encode(t), n = new Md5;
  5523. return n.update(e), new Uint8Array(n.digest());
  5524. }
  5525. // Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using
  5526. // 2’s complement using little endian.
  5527. function di(t) {
  5528. const e = new DataView(t.buffer), n = e.getUint32(0, /* littleEndian= */ !0), s = e.getUint32(4, /* littleEndian= */ !0), i = e.getUint32(8, /* littleEndian= */ !0), r = e.getUint32(12, /* littleEndian= */ !0);
  5529. return [ new Integer([ n, s ], 0), new Integer([ i, r ], 0) ];
  5530. }
  5531. class wi {
  5532. constructor(t, e, n) {
  5533. if (this.bitmap = t, this.padding = e, this.hashCount = n, e < 0 || e >= 8) throw new _i(`Invalid padding: ${e}`);
  5534. if (n < 0) throw new _i(`Invalid hash count: ${n}`);
  5535. if (t.length > 0 && 0 === this.hashCount)
  5536. // Only empty bloom filter can have 0 hash count.
  5537. throw new _i(`Invalid hash count: ${n}`);
  5538. if (0 === t.length && 0 !== e)
  5539. // Empty bloom filter should have 0 padding.
  5540. throw new _i(`Invalid padding when bitmap length is 0: ${e}`);
  5541. this.It = 8 * t.length - e,
  5542. // Set the bit count in Integer to avoid repetition in mightContain().
  5543. this.Tt = Integer.fromNumber(this.It);
  5544. }
  5545. // Calculate the ith hash value based on the hashed 64bit integers,
  5546. // and calculate its corresponding bit index in the bitmap to be checked.
  5547. Et(t, e, n) {
  5548. // Calculate hashed value h(i) = h1 + (i * h2).
  5549. let s = t.add(e.multiply(Integer.fromNumber(n)));
  5550. // Wrap if hash value overflow 64bit.
  5551. return 1 === s.compare(li) && (s = new Integer([ s.getBits(0), s.getBits(1) ], 0)),
  5552. s.modulo(this.Tt).toNumber();
  5553. }
  5554. // Return whether the bit on the given index in the bitmap is set to 1.
  5555. At(t) {
  5556. return 0 != (this.bitmap[Math.floor(t / 8)] & 1 << t % 8);
  5557. }
  5558. vt(t) {
  5559. // Empty bitmap should always return false on membership check.
  5560. if (0 === this.It) return !1;
  5561. const e = fi(t), [n, s] = di(e);
  5562. for (let t = 0; t < this.hashCount; t++) {
  5563. const e = this.Et(n, s, t);
  5564. if (!this.At(e)) return !1;
  5565. }
  5566. return !0;
  5567. }
  5568. /** Create bloom filter for testing purposes only. */ static create(t, e, n) {
  5569. const s = t % 8 == 0 ? 0 : 8 - t % 8, i = new Uint8Array(Math.ceil(t / 8)), r = new wi(i, s, e);
  5570. return n.forEach((t => r.insert(t))), r;
  5571. }
  5572. insert(t) {
  5573. if (0 === this.It) return;
  5574. const e = fi(t), [n, s] = di(e);
  5575. for (let t = 0; t < this.hashCount; t++) {
  5576. const e = this.Et(n, s, t);
  5577. this.Rt(e);
  5578. }
  5579. }
  5580. Rt(t) {
  5581. const e = Math.floor(t / 8), n = t % 8;
  5582. this.bitmap[e] |= 1 << n;
  5583. }
  5584. }
  5585. class _i extends Error {
  5586. constructor() {
  5587. super(...arguments), this.name = "BloomFilterError";
  5588. }
  5589. }
  5590. /**
  5591. * @license
  5592. * Copyright 2017 Google LLC
  5593. *
  5594. * Licensed under the Apache License, Version 2.0 (the "License");
  5595. * you may not use this file except in compliance with the License.
  5596. * You may obtain a copy of the License at
  5597. *
  5598. * http://www.apache.org/licenses/LICENSE-2.0
  5599. *
  5600. * Unless required by applicable law or agreed to in writing, software
  5601. * distributed under the License is distributed on an "AS IS" BASIS,
  5602. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5603. * See the License for the specific language governing permissions and
  5604. * limitations under the License.
  5605. */
  5606. /**
  5607. * An event from the RemoteStore. It is split into targetChanges (changes to the
  5608. * state or the set of documents in our watched targets) and documentUpdates
  5609. * (changes to the actual documents).
  5610. */ class mi {
  5611. constructor(
  5612. /**
  5613. * The snapshot version this event brings us up to, or MIN if not set.
  5614. */
  5615. t,
  5616. /**
  5617. * A map from target to changes to the target. See TargetChange.
  5618. */
  5619. e,
  5620. /**
  5621. * A map of targets that is known to be inconsistent, and the purpose for
  5622. * re-listening. Listens for these targets should be re-established without
  5623. * resume tokens.
  5624. */
  5625. n,
  5626. /**
  5627. * A set of which documents have changed or been deleted, along with the
  5628. * doc's new values (if not deleted).
  5629. */
  5630. s,
  5631. /**
  5632. * A set of which document updates are due only to limbo resolution targets.
  5633. */
  5634. i) {
  5635. this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s,
  5636. this.resolvedLimboDocuments = i;
  5637. }
  5638. /**
  5639. * HACK: Views require RemoteEvents in order to determine whether the view is
  5640. * CURRENT, but secondary tabs don't receive remote events. So this method is
  5641. * used to create a synthesized RemoteEvent that can be used to apply a
  5642. * CURRENT status change to a View, for queries executed in a different tab.
  5643. */
  5644. // PORTING NOTE: Multi-tab only
  5645. static createSynthesizedRemoteEventForCurrentChange(t, e, n) {
  5646. const s = new Map;
  5647. return s.set(t, gi.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new mi(rt.min(), s, new pe(et), cs(), gs());
  5648. }
  5649. }
  5650. /**
  5651. * A TargetChange specifies the set of changes for a specific target as part of
  5652. * a RemoteEvent. These changes track which documents are added, modified or
  5653. * removed, as well as the target's resume token and whether the target is
  5654. * marked CURRENT.
  5655. * The actual changes *to* documents are not part of the TargetChange since
  5656. * documents may be part of multiple targets.
  5657. */ class gi {
  5658. constructor(
  5659. /**
  5660. * An opaque, server-assigned token that allows watching a query to be resumed
  5661. * after disconnecting without retransmitting all the data that matches the
  5662. * query. The resume token essentially identifies a point in time from which
  5663. * the server should resume sending results.
  5664. */
  5665. t,
  5666. /**
  5667. * The "current" (synced) status of this target. Note that "current"
  5668. * has special meaning in the RPC protocol that implies that a target is
  5669. * both up-to-date and consistent with the rest of the watch stream.
  5670. */
  5671. e,
  5672. /**
  5673. * The set of documents that were newly assigned to this target as part of
  5674. * this remote event.
  5675. */
  5676. n,
  5677. /**
  5678. * The set of documents that were already assigned to this target but received
  5679. * an update during this remote event.
  5680. */
  5681. s,
  5682. /**
  5683. * The set of documents that were removed from this target as part of this
  5684. * remote event.
  5685. */
  5686. i) {
  5687. this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s,
  5688. this.removedDocuments = i;
  5689. }
  5690. /**
  5691. * This method is used to create a synthesized TargetChanges that can be used to
  5692. * apply a CURRENT status change to a View (for queries executed in a different
  5693. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5694. */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {
  5695. return new gi(n, e, gs(), gs(), gs());
  5696. }
  5697. }
  5698. /**
  5699. * @license
  5700. * Copyright 2017 Google LLC
  5701. *
  5702. * Licensed under the Apache License, Version 2.0 (the "License");
  5703. * you may not use this file except in compliance with the License.
  5704. * You may obtain a copy of the License at
  5705. *
  5706. * http://www.apache.org/licenses/LICENSE-2.0
  5707. *
  5708. * Unless required by applicable law or agreed to in writing, software
  5709. * distributed under the License is distributed on an "AS IS" BASIS,
  5710. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5711. * See the License for the specific language governing permissions and
  5712. * limitations under the License.
  5713. */
  5714. /**
  5715. * Represents a changed document and a list of target ids to which this change
  5716. * applies.
  5717. *
  5718. * If document has been deleted NoDocument will be provided.
  5719. */ class yi {
  5720. constructor(
  5721. /** The new document applies to all of these targets. */
  5722. t,
  5723. /** The new document is removed from all of these targets. */
  5724. e,
  5725. /** The key of the document for this change. */
  5726. n,
  5727. /**
  5728. * The new document or NoDocument if it was deleted. Is null if the
  5729. * document went out of view without the server sending a new document.
  5730. */
  5731. s) {
  5732. this.Pt = t, this.removedTargetIds = e, this.key = n, this.bt = s;
  5733. }
  5734. }
  5735. class pi {
  5736. constructor(t, e) {
  5737. this.targetId = t, this.Vt = e;
  5738. }
  5739. }
  5740. class Ii {
  5741. constructor(
  5742. /** What kind of change occurred to the watch target. */
  5743. t,
  5744. /** The target IDs that were added/removed/set. */
  5745. e,
  5746. /**
  5747. * An opaque, server-assigned token that allows watching a target to be
  5748. * resumed after disconnecting without retransmitting all the data that
  5749. * matches the target. The resume token essentially identifies a point in
  5750. * time from which the server should resume sending results.
  5751. */
  5752. n = Ve.EMPTY_BYTE_STRING
  5753. /** An RPC error indicating why the watch failed. */ , s = null) {
  5754. this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;
  5755. }
  5756. }
  5757. /** Tracks the internal state of a Watch target. */ class Ti {
  5758. constructor() {
  5759. /**
  5760. * The number of pending responses (adds or removes) that we are waiting on.
  5761. * We only consider targets active that have no pending responses.
  5762. */
  5763. this.St = 0,
  5764. /**
  5765. * Keeps track of the document changes since the last raised snapshot.
  5766. *
  5767. * These changes are continuously updated as we receive document updates and
  5768. * always reflect the current set of changes against the last issued snapshot.
  5769. */
  5770. this.Dt = vi(),
  5771. /** See public getters for explanations of these fields. */
  5772. this.Ct = Ve.EMPTY_BYTE_STRING, this.xt = !1,
  5773. /**
  5774. * Whether this target state should be included in the next snapshot. We
  5775. * initialize to true so that newly-added targets are included in the next
  5776. * RemoteEvent.
  5777. */
  5778. this.Nt = !0;
  5779. }
  5780. /**
  5781. * Whether this target has been marked 'current'.
  5782. *
  5783. * 'Current' has special meaning in the RPC protocol: It implies that the
  5784. * Watch backend has sent us all changes up to the point at which the target
  5785. * was added and that the target is consistent with the rest of the watch
  5786. * stream.
  5787. */ get current() {
  5788. return this.xt;
  5789. }
  5790. /** The last resume token sent to us for this target. */ get resumeToken() {
  5791. return this.Ct;
  5792. }
  5793. /** Whether this target has pending target adds or target removes. */ get kt() {
  5794. return 0 !== this.St;
  5795. }
  5796. /** Whether we have modified any state that should trigger a snapshot. */ get Mt() {
  5797. return this.Nt;
  5798. }
  5799. /**
  5800. * Applies the resume token to the TargetChange, but only when it has a new
  5801. * value. Empty resumeTokens are discarded.
  5802. */ $t(t) {
  5803. t.approximateByteSize() > 0 && (this.Nt = !0, this.Ct = t);
  5804. }
  5805. /**
  5806. * Creates a target change from the current set of changes.
  5807. *
  5808. * To reset the document changes after raising this snapshot, call
  5809. * `clearPendingChanges()`.
  5810. */ Ot() {
  5811. let t = gs(), e = gs(), n = gs();
  5812. return this.Dt.forEach(((s, i) => {
  5813. switch (i) {
  5814. case 0 /* ChangeType.Added */ :
  5815. t = t.add(s);
  5816. break;
  5817. case 2 /* ChangeType.Modified */ :
  5818. e = e.add(s);
  5819. break;
  5820. case 1 /* ChangeType.Removed */ :
  5821. n = n.add(s);
  5822. break;
  5823. default:
  5824. O();
  5825. }
  5826. })), new gi(this.Ct, this.xt, t, e, n);
  5827. }
  5828. /**
  5829. * Resets the document changes and sets `hasPendingChanges` to false.
  5830. */ Ft() {
  5831. this.Nt = !1, this.Dt = vi();
  5832. }
  5833. Bt(t, e) {
  5834. this.Nt = !0, this.Dt = this.Dt.insert(t, e);
  5835. }
  5836. Lt(t) {
  5837. this.Nt = !0, this.Dt = this.Dt.remove(t);
  5838. }
  5839. qt() {
  5840. this.St += 1;
  5841. }
  5842. Ut() {
  5843. this.St -= 1;
  5844. }
  5845. Kt() {
  5846. this.Nt = !0, this.xt = !0;
  5847. }
  5848. }
  5849. /**
  5850. * A helper class to accumulate watch changes into a RemoteEvent.
  5851. */
  5852. class Ei {
  5853. constructor(t) {
  5854. this.Gt = t,
  5855. /** The internal state of all tracked targets. */
  5856. this.Qt = new Map,
  5857. /** Keeps track of the documents to update since the last raised snapshot. */
  5858. this.jt = cs(),
  5859. /** A mapping of document keys to their set of target IDs. */
  5860. this.zt = Ai(),
  5861. /**
  5862. * A map of targets with existence filter mismatches. These targets are
  5863. * known to be inconsistent and their listens needs to be re-established by
  5864. * RemoteStore.
  5865. */
  5866. this.Wt = new pe(et);
  5867. }
  5868. /**
  5869. * Processes and adds the DocumentWatchChange to the current set of changes.
  5870. */ Ht(t) {
  5871. for (const e of t.Pt) t.bt && t.bt.isFoundDocument() ? this.Jt(e, t.bt) : this.Yt(e, t.key, t.bt);
  5872. for (const e of t.removedTargetIds) this.Yt(e, t.key, t.bt);
  5873. }
  5874. /** Processes and adds the WatchTargetChange to the current set of changes. */ Xt(t) {
  5875. this.forEachTarget(t, (e => {
  5876. const n = this.Zt(e);
  5877. switch (t.state) {
  5878. case 0 /* WatchTargetChangeState.NoChange */ :
  5879. this.te(e) && n.$t(t.resumeToken);
  5880. break;
  5881. case 1 /* WatchTargetChangeState.Added */ :
  5882. // We need to decrement the number of pending acks needed from watch
  5883. // for this targetId.
  5884. n.Ut(), n.kt ||
  5885. // We have a freshly added target, so we need to reset any state
  5886. // that we had previously. This can happen e.g. when remove and add
  5887. // back a target for existence filter mismatches.
  5888. n.Ft(), n.$t(t.resumeToken);
  5889. break;
  5890. case 2 /* WatchTargetChangeState.Removed */ :
  5891. // We need to keep track of removed targets to we can post-filter and
  5892. // remove any target changes.
  5893. // We need to decrement the number of pending acks needed from watch
  5894. // for this targetId.
  5895. n.Ut(), n.kt || this.removeTarget(e);
  5896. break;
  5897. case 3 /* WatchTargetChangeState.Current */ :
  5898. this.te(e) && (n.Kt(), n.$t(t.resumeToken));
  5899. break;
  5900. case 4 /* WatchTargetChangeState.Reset */ :
  5901. this.te(e) && (
  5902. // Reset the target and synthesizes removes for all existing
  5903. // documents. The backend will re-add any documents that still
  5904. // match the target before it sends the next global snapshot.
  5905. this.ee(e), n.$t(t.resumeToken));
  5906. break;
  5907. default:
  5908. O();
  5909. }
  5910. }));
  5911. }
  5912. /**
  5913. * Iterates over all targetIds that the watch change applies to: either the
  5914. * targetIds explicitly listed in the change or the targetIds of all currently
  5915. * active targets.
  5916. */ forEachTarget(t, e) {
  5917. t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Qt.forEach(((t, n) => {
  5918. this.te(n) && e(n);
  5919. }));
  5920. }
  5921. /**
  5922. * Handles existence filters and synthesizes deletes for filter mismatches.
  5923. * Targets that are invalidated by filter mismatches are added to
  5924. * `pendingTargetResets`.
  5925. */ ne(t) {
  5926. var e;
  5927. const n = t.targetId, s = t.Vt.count, i = this.se(n);
  5928. if (i) {
  5929. const r = i.target;
  5930. if (Fn(r)) if (0 === s) {
  5931. // The existence filter told us the document does not exist. We deduce
  5932. // that this document does not exist and apply a deleted document to
  5933. // our updates. Without applying this deleted document there might be
  5934. // another query that will raise this document as part of a snapshot
  5935. // until it is resolved, essentially exposing inconsistency between
  5936. // queries.
  5937. const t = new ht(r.path);
  5938. this.Yt(n, t, an.newNoDocument(t, rt.min()));
  5939. } else F(1 === s); else {
  5940. const i = this.ie(n);
  5941. // Existence filter mismatch. Mark the documents as being in limbo, and
  5942. // raise a snapshot with `isFromCache:true`.
  5943. if (i !== s) {
  5944. // Apply bloom filter to identify and mark removed documents.
  5945. const s = this.re(t, i);
  5946. if (0 /* BloomFilterApplicationStatus.Success */ !== s) {
  5947. // If bloom filter application fails, we reset the mapping and
  5948. // trigger re-run of the query.
  5949. this.ee(n);
  5950. const t = 2 /* BloomFilterApplicationStatus.FalsePositive */ === s ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */;
  5951. this.Wt = this.Wt.insert(n, t);
  5952. }
  5953. null === (e = ci.instance) || void 0 === e || e.notifyOnExistenceFilterMismatch(function(t, e, n) {
  5954. var s, i, r, o, u, c;
  5955. const a = {
  5956. localCacheCount: e,
  5957. existenceFilterCount: n.count
  5958. }, h = n.unchangedNames;
  5959. h && (a.bloomFilter = {
  5960. applied: 0 /* BloomFilterApplicationStatus.Success */ === t,
  5961. hashCount: null !== (s = null == h ? void 0 : h.hashCount) && void 0 !== s ? s : 0,
  5962. bitmapLength: null !== (o = null === (r = null === (i = null == h ? void 0 : h.bits) || void 0 === i ? void 0 : i.bitmap) || void 0 === r ? void 0 : r.length) && void 0 !== o ? o : 0,
  5963. padding: null !== (c = null === (u = null == h ? void 0 : h.bits) || void 0 === u ? void 0 : u.padding) && void 0 !== c ? c : 0
  5964. });
  5965. return a;
  5966. }
  5967. /**
  5968. * @license
  5969. * Copyright 2017 Google LLC
  5970. *
  5971. * Licensed under the Apache License, Version 2.0 (the "License");
  5972. * you may not use this file except in compliance with the License.
  5973. * You may obtain a copy of the License at
  5974. *
  5975. * http://www.apache.org/licenses/LICENSE-2.0
  5976. *
  5977. * Unless required by applicable law or agreed to in writing, software
  5978. * distributed under the License is distributed on an "AS IS" BASIS,
  5979. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5980. * See the License for the specific language governing permissions and
  5981. * limitations under the License.
  5982. */ (s, i, t.Vt));
  5983. }
  5984. }
  5985. }
  5986. }
  5987. /**
  5988. * Apply bloom filter to remove the deleted documents, and return the
  5989. * application status.
  5990. */ re(t, e) {
  5991. const {unchangedNames: n, count: s} = t.Vt;
  5992. if (!n || !n.bits) return 1 /* BloomFilterApplicationStatus.Skipped */;
  5993. const {bits: {bitmap: i = "", padding: r = 0}, hashCount: o = 0} = n;
  5994. let u, c;
  5995. try {
  5996. u = xe(i).toUint8Array();
  5997. } catch (t) {
  5998. if (t instanceof Pe) return M("Decoding the base64 bloom filter in existence filter failed (" + t.message + "); ignoring the bloom filter and falling back to full re-query."),
  5999. 1 /* BloomFilterApplicationStatus.Skipped */;
  6000. throw t;
  6001. }
  6002. try {
  6003. // BloomFilter throws error if the inputs are invalid.
  6004. c = new wi(u, r, o);
  6005. } catch (t) {
  6006. return M(t instanceof _i ? "BloomFilter error: " : "Applying bloom filter failed: ", t),
  6007. 1 /* BloomFilterApplicationStatus.Skipped */;
  6008. }
  6009. if (0 === c.It) return 1 /* BloomFilterApplicationStatus.Skipped */;
  6010. return s !== e - this.oe(t.targetId, c) ? 2 /* BloomFilterApplicationStatus.FalsePositive */ : 0 /* BloomFilterApplicationStatus.Success */;
  6011. }
  6012. /**
  6013. * Filter out removed documents based on bloom filter membership result and
  6014. * return number of documents removed.
  6015. */ oe(t, e) {
  6016. const n = this.Gt.getRemoteKeysForTarget(t);
  6017. let s = 0;
  6018. return n.forEach((n => {
  6019. const i = this.Gt.ue(), r = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;
  6020. e.vt(r) || (this.Yt(t, n, /*updatedDocument=*/ null), s++);
  6021. })), s;
  6022. }
  6023. /**
  6024. * Converts the currently accumulated state into a remote event at the
  6025. * provided snapshot version. Resets the accumulated changes before returning.
  6026. */ ce(t) {
  6027. const e = new Map;
  6028. this.Qt.forEach(((n, s) => {
  6029. const i = this.se(s);
  6030. if (i) {
  6031. if (n.current && Fn(i.target)) {
  6032. // Document queries for document that don't exist can produce an empty
  6033. // result set. To update our local cache, we synthesize a document
  6034. // delete if we have not previously received the document. This
  6035. // resolves the limbo state of the document, removing it from
  6036. // limboDocumentRefs.
  6037. // TODO(dimond): Ideally we would have an explicit lookup target
  6038. // instead resulting in an explicit delete message and we could
  6039. // remove this special logic.
  6040. const e = new ht(i.target.path);
  6041. null !== this.jt.get(e) || this.ae(s, e) || this.Yt(s, e, an.newNoDocument(e, t));
  6042. }
  6043. n.Mt && (e.set(s, n.Ot()), n.Ft());
  6044. }
  6045. }));
  6046. let n = gs();
  6047. // We extract the set of limbo-only document updates as the GC logic
  6048. // special-cases documents that do not appear in the target cache.
  6049. // TODO(gsoltis): Expand on this comment once GC is available in the JS
  6050. // client.
  6051. this.zt.forEach(((t, e) => {
  6052. let s = !0;
  6053. e.forEachWhile((t => {
  6054. const e = this.se(t);
  6055. return !e || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1,
  6056. !1);
  6057. })), s && (n = n.add(t));
  6058. })), this.jt.forEach(((e, n) => n.setReadTime(t)));
  6059. const s = new mi(t, e, this.Wt, this.jt, n);
  6060. return this.jt = cs(), this.zt = Ai(), this.Wt = new pe(et), s;
  6061. }
  6062. /**
  6063. * Adds the provided document to the internal list of document updates and
  6064. * its document key to the given target's mapping.
  6065. */
  6066. // Visible for testing.
  6067. Jt(t, e) {
  6068. if (!this.te(t)) return;
  6069. const n = this.ae(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
  6070. this.Zt(t).Bt(e.key, n), this.jt = this.jt.insert(e.key, e), this.zt = this.zt.insert(e.key, this.he(e.key).add(t));
  6071. }
  6072. /**
  6073. * Removes the provided document from the target mapping. If the
  6074. * document no longer matches the target, but the document's state is still
  6075. * known (e.g. we know that the document was deleted or we received the change
  6076. * that caused the filter mismatch), the new document can be provided
  6077. * to update the remote document cache.
  6078. */
  6079. // Visible for testing.
  6080. Yt(t, e, n) {
  6081. if (!this.te(t)) return;
  6082. const s = this.Zt(t);
  6083. this.ae(t, e) ? s.Bt(e, 1 /* ChangeType.Removed */) :
  6084. // The document may have entered and left the target before we raised a
  6085. // snapshot, so we can just ignore the change.
  6086. s.Lt(e), this.zt = this.zt.insert(e, this.he(e).delete(t)), n && (this.jt = this.jt.insert(e, n));
  6087. }
  6088. removeTarget(t) {
  6089. this.Qt.delete(t);
  6090. }
  6091. /**
  6092. * Returns the current count of documents in the target. This includes both
  6093. * the number of documents that the LocalStore considers to be part of the
  6094. * target as well as any accumulated changes.
  6095. */ ie(t) {
  6096. const e = this.Zt(t).Ot();
  6097. return this.Gt.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
  6098. }
  6099. /**
  6100. * Increment the number of acks needed from watch before we can consider the
  6101. * server to be 'in-sync' with the client's active targets.
  6102. */ qt(t) {
  6103. this.Zt(t).qt();
  6104. }
  6105. Zt(t) {
  6106. let e = this.Qt.get(t);
  6107. return e || (e = new Ti, this.Qt.set(t, e)), e;
  6108. }
  6109. he(t) {
  6110. let e = this.zt.get(t);
  6111. return e || (e = new Ee(et), this.zt = this.zt.insert(t, e)), e;
  6112. }
  6113. /**
  6114. * Verifies that the user is still interested in this target (by calling
  6115. * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
  6116. * from watch.
  6117. */ te(t) {
  6118. const e = null !== this.se(t);
  6119. return e || N("WatchChangeAggregator", "Detected inactive target", t), e;
  6120. }
  6121. /**
  6122. * Returns the TargetData for an active target (i.e. a target that the user
  6123. * is still interested in that has no outstanding target change requests).
  6124. */ se(t) {
  6125. const e = this.Qt.get(t);
  6126. return e && e.kt ? null : this.Gt.le(t);
  6127. }
  6128. /**
  6129. * Resets the state of a Watch target to its initial state (e.g. sets
  6130. * 'current' to false, clears the resume token and removes its target mapping
  6131. * from all documents).
  6132. */ ee(t) {
  6133. this.Qt.set(t, new Ti);
  6134. this.Gt.getRemoteKeysForTarget(t).forEach((e => {
  6135. this.Yt(t, e, /*updatedDocument=*/ null);
  6136. }));
  6137. }
  6138. /**
  6139. * Returns whether the LocalStore considers the document to be part of the
  6140. * specified target.
  6141. */ ae(t, e) {
  6142. return this.Gt.getRemoteKeysForTarget(t).has(e);
  6143. }
  6144. }
  6145. function Ai() {
  6146. return new pe(ht.comparator);
  6147. }
  6148. function vi() {
  6149. return new pe(ht.comparator);
  6150. }
  6151. const Ri = (() => {
  6152. const t = {
  6153. asc: "ASCENDING",
  6154. desc: "DESCENDING"
  6155. };
  6156. return t;
  6157. })(), Pi = (() => {
  6158. const t = {
  6159. "<": "LESS_THAN",
  6160. "<=": "LESS_THAN_OR_EQUAL",
  6161. ">": "GREATER_THAN",
  6162. ">=": "GREATER_THAN_OR_EQUAL",
  6163. "==": "EQUAL",
  6164. "!=": "NOT_EQUAL",
  6165. "array-contains": "ARRAY_CONTAINS",
  6166. in: "IN",
  6167. "not-in": "NOT_IN",
  6168. "array-contains-any": "ARRAY_CONTAINS_ANY"
  6169. };
  6170. return t;
  6171. })(), bi = (() => {
  6172. const t = {
  6173. and: "AND",
  6174. or: "OR"
  6175. };
  6176. return t;
  6177. })();
  6178. /**
  6179. * This class generates JsonObject values for the Datastore API suitable for
  6180. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  6181. *
  6182. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  6183. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  6184. * format.
  6185. *
  6186. * For a description of the Proto3 JSON format check
  6187. * https://developers.google.com/protocol-buffers/docs/proto3#json
  6188. *
  6189. * TODO(klimt): We can remove the databaseId argument if we keep the full
  6190. * resource name in documents.
  6191. */
  6192. class Vi {
  6193. constructor(t, e) {
  6194. this.databaseId = t, this.useProto3Json = e;
  6195. }
  6196. }
  6197. /**
  6198. * Returns a value for a number (or null) that's appropriate to put into
  6199. * a google.protobuf.Int32Value proto.
  6200. * DO NOT USE THIS FOR ANYTHING ELSE.
  6201. * This method cheats. It's typed as returning "number" because that's what
  6202. * our generated proto interfaces say Int32Value must be. But GRPC actually
  6203. * expects a { value: <number> } struct.
  6204. */
  6205. function Si(t, e) {
  6206. return t.useProto3Json || Ft(e) ? e : {
  6207. value: e
  6208. };
  6209. }
  6210. /**
  6211. * Returns a number (or null) from a google.protobuf.Int32Value proto.
  6212. */
  6213. /**
  6214. * Returns a value for a Date that's appropriate to put into a proto.
  6215. */
  6216. function Di(t, e) {
  6217. if (t.useProto3Json) {
  6218. return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
  6219. }
  6220. return {
  6221. seconds: "" + e.seconds,
  6222. nanos: e.nanoseconds
  6223. };
  6224. }
  6225. /**
  6226. * Returns a value for bytes that's appropriate to put in a proto.
  6227. *
  6228. * Visible for testing.
  6229. */
  6230. function Ci(t, e) {
  6231. return t.useProto3Json ? e.toBase64() : e.toUint8Array();
  6232. }
  6233. /**
  6234. * Returns a ByteString based on the proto string value.
  6235. */ function xi(t, e) {
  6236. return Di(t, e.toTimestamp());
  6237. }
  6238. function Ni(t) {
  6239. return F(!!t), rt.fromTimestamp(function(t) {
  6240. const e = De(t);
  6241. return new it(e.seconds, e.nanos);
  6242. }(t));
  6243. }
  6244. function ki(t, e) {
  6245. return function(t) {
  6246. return new ut([ "projects", t.projectId, "databases", t.database ]);
  6247. }(t).child("documents").child(e).canonicalString();
  6248. }
  6249. function Mi(t) {
  6250. const e = ut.fromString(t);
  6251. return F(ur(e)), e;
  6252. }
  6253. function $i(t, e) {
  6254. return ki(t.databaseId, e.path);
  6255. }
  6256. function Oi(t, e) {
  6257. const n = Mi(e);
  6258. if (n.get(1) !== t.databaseId.projectId) throw new U(q.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  6259. if (n.get(3) !== t.databaseId.database) throw new U(q.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  6260. return new ht(qi(n));
  6261. }
  6262. function Fi(t, e) {
  6263. return ki(t.databaseId, e);
  6264. }
  6265. function Bi(t) {
  6266. const e = Mi(t);
  6267. // In v1beta1 queries for collections at the root did not have a trailing
  6268. // "/documents". In v1 all resource paths contain "/documents". Preserve the
  6269. // ability to read the v1beta1 form for compatibility with queries persisted
  6270. // in the local target cache.
  6271. return 4 === e.length ? ut.emptyPath() : qi(e);
  6272. }
  6273. function Li(t) {
  6274. return new ut([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  6275. }
  6276. function qi(t) {
  6277. return F(t.length > 4 && "documents" === t.get(4)), t.popFirst(5);
  6278. }
  6279. /** Creates a Document proto from key and fields (but no create/update time) */ function Ui(t, e, n) {
  6280. return {
  6281. name: $i(t, e),
  6282. fields: n.value.mapValue.fields
  6283. };
  6284. }
  6285. function Ki(t, e, n) {
  6286. const s = Oi(t, e.name), i = Ni(e.updateTime), r = e.createTime ? Ni(e.createTime) : rt.min(), o = new un({
  6287. mapValue: {
  6288. fields: e.fields
  6289. }
  6290. }), u = an.newFoundDocument(s, i, r, o);
  6291. return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;
  6292. }
  6293. function Gi(t, e) {
  6294. return "found" in e ? function(t, e) {
  6295. F(!!e.found), e.found.name, e.found.updateTime;
  6296. const n = Oi(t, e.found.name), s = Ni(e.found.updateTime), i = e.found.createTime ? Ni(e.found.createTime) : rt.min(), r = new un({
  6297. mapValue: {
  6298. fields: e.found.fields
  6299. }
  6300. });
  6301. return an.newFoundDocument(n, s, i, r);
  6302. }(t, e) : "missing" in e ? function(t, e) {
  6303. F(!!e.missing), F(!!e.readTime);
  6304. const n = Oi(t, e.missing), s = Ni(e.readTime);
  6305. return an.newNoDocument(n, s);
  6306. }(t, e) : O();
  6307. }
  6308. function Qi(t, e) {
  6309. let n;
  6310. if ("targetChange" in e) {
  6311. e.targetChange;
  6312. // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
  6313. // if unset
  6314. const s = function(t) {
  6315. return "NO_CHANGE" === t ? 0 /* WatchTargetChangeState.NoChange */ : "ADD" === t ? 1 /* WatchTargetChangeState.Added */ : "REMOVE" === t ? 2 /* WatchTargetChangeState.Removed */ : "CURRENT" === t ? 3 /* WatchTargetChangeState.Current */ : "RESET" === t ? 4 /* WatchTargetChangeState.Reset */ : O();
  6316. }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], r = function(t, e) {
  6317. return t.useProto3Json ? (F(void 0 === e || "string" == typeof e), Ve.fromBase64String(e || "")) : (F(void 0 === e || e instanceof Uint8Array),
  6318. Ve.fromUint8Array(e || new Uint8Array));
  6319. }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {
  6320. const e = void 0 === t.code ? q.UNKNOWN : ui(t.code);
  6321. return new U(e, t.message || "");
  6322. }(o);
  6323. n = new Ii(s, i, r, u || null);
  6324. } else if ("documentChange" in e) {
  6325. e.documentChange;
  6326. const s = e.documentChange;
  6327. s.document, s.document.name, s.document.updateTime;
  6328. const i = Oi(t, s.document.name), r = Ni(s.document.updateTime), o = s.document.createTime ? Ni(s.document.createTime) : rt.min(), u = new un({
  6329. mapValue: {
  6330. fields: s.document.fields
  6331. }
  6332. }), c = an.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];
  6333. n = new yi(a, h, c.key, c);
  6334. } else if ("documentDelete" in e) {
  6335. e.documentDelete;
  6336. const s = e.documentDelete;
  6337. s.document;
  6338. const i = Oi(t, s.document), r = s.readTime ? Ni(s.readTime) : rt.min(), o = an.newNoDocument(i, r), u = s.removedTargetIds || [];
  6339. n = new yi([], u, o.key, o);
  6340. } else if ("documentRemove" in e) {
  6341. e.documentRemove;
  6342. const s = e.documentRemove;
  6343. s.document;
  6344. const i = Oi(t, s.document), r = s.removedTargetIds || [];
  6345. n = new yi([], r, i, null);
  6346. } else {
  6347. if (!("filter" in e)) return O();
  6348. {
  6349. e.filter;
  6350. const t = e.filter;
  6351. t.targetId;
  6352. const {count: s = 0, unchangedNames: i} = t, r = new si(s, i), o = t.targetId;
  6353. n = new pi(o, r);
  6354. }
  6355. }
  6356. return n;
  6357. }
  6358. function ji(t, e) {
  6359. let n;
  6360. if (e instanceof js) n = {
  6361. update: Ui(t, e.key, e.value)
  6362. }; else if (e instanceof Ys) n = {
  6363. delete: $i(t, e.key)
  6364. }; else if (e instanceof zs) n = {
  6365. update: Ui(t, e.key, e.data),
  6366. updateMask: or(e.fieldMask)
  6367. }; else {
  6368. if (!(e instanceof Xs)) return O();
  6369. n = {
  6370. verify: $i(t, e.key)
  6371. };
  6372. }
  6373. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
  6374. const n = e.transform;
  6375. if (n instanceof bs) return {
  6376. fieldPath: e.field.canonicalString(),
  6377. setToServerValue: "REQUEST_TIME"
  6378. };
  6379. if (n instanceof Vs) return {
  6380. fieldPath: e.field.canonicalString(),
  6381. appendMissingElements: {
  6382. values: n.elements
  6383. }
  6384. };
  6385. if (n instanceof Ds) return {
  6386. fieldPath: e.field.canonicalString(),
  6387. removeAllFromArray: {
  6388. values: n.elements
  6389. }
  6390. };
  6391. if (n instanceof xs) return {
  6392. fieldPath: e.field.canonicalString(),
  6393. increment: n.gt
  6394. };
  6395. throw O();
  6396. }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  6397. return void 0 !== e.updateTime ? {
  6398. updateTime: xi(t, e.updateTime)
  6399. } : void 0 !== e.exists ? {
  6400. exists: e.exists
  6401. } : O();
  6402. }(t, e.precondition)), n;
  6403. }
  6404. function zi(t, e) {
  6405. const n = e.currentDocument ? function(t) {
  6406. return void 0 !== t.updateTime ? Fs.updateTime(Ni(t.updateTime)) : void 0 !== t.exists ? Fs.exists(t.exists) : Fs.none();
  6407. }(e.currentDocument) : Fs.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {
  6408. let n = null;
  6409. if ("setToServerValue" in e) F("REQUEST_TIME" === e.setToServerValue), n = new bs; else if ("appendMissingElements" in e) {
  6410. const t = e.appendMissingElements.values || [];
  6411. n = new Vs(t);
  6412. } else if ("removeAllFromArray" in e) {
  6413. const t = e.removeAllFromArray.values || [];
  6414. n = new Ds(t);
  6415. } else "increment" in e ? n = new xs(t, e.increment) : O();
  6416. const s = at.fromServerFormat(e.fieldPath);
  6417. return new Ms(s, n);
  6418. }(t, e))) : [];
  6419. if (e.update) {
  6420. e.update.name;
  6421. const i = Oi(t, e.update.name), r = new un({
  6422. mapValue: {
  6423. fields: e.update.fields
  6424. }
  6425. });
  6426. if (e.updateMask) {
  6427. const t = function(t) {
  6428. const e = t.fieldPaths || [];
  6429. return new Re(e.map((t => at.fromServerFormat(t))));
  6430. }(e.updateMask);
  6431. return new zs(i, r, t, n, s);
  6432. }
  6433. return new js(i, r, n, s);
  6434. }
  6435. if (e.delete) {
  6436. const s = Oi(t, e.delete);
  6437. return new Ys(s, n);
  6438. }
  6439. if (e.verify) {
  6440. const s = Oi(t, e.verify);
  6441. return new Xs(s, n);
  6442. }
  6443. return O();
  6444. }
  6445. function Wi(t, e) {
  6446. return t && t.length > 0 ? (F(void 0 !== e), t.map((t => function(t, e) {
  6447. // NOTE: Deletes don't have an updateTime.
  6448. let n = t.updateTime ? Ni(t.updateTime) : Ni(e);
  6449. return n.isEqual(rt.min()) && (
  6450. // The Firestore Emulator currently returns an update time of 0 for
  6451. // deletes of non-existing documents (rather than null). This breaks the
  6452. // test "get deleted doc while offline with source=cache" as NoDocuments
  6453. // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
  6454. // TODO(#2149): Remove this when Emulator is fixed
  6455. n = Ni(e)), new Os(n, t.transformResults || []);
  6456. }(t, e)))) : [];
  6457. }
  6458. function Hi(t, e) {
  6459. return {
  6460. documents: [ Fi(t, e.path) ]
  6461. };
  6462. }
  6463. function Ji(t, e) {
  6464. // Dissect the path into parent, collectionId, and optional key filter.
  6465. const n = {
  6466. structuredQuery: {}
  6467. }, s = e.path;
  6468. null !== e.collectionGroup ? (n.parent = Fi(t, s), n.structuredQuery.from = [ {
  6469. collectionId: e.collectionGroup,
  6470. allDescendants: !0
  6471. } ]) : (n.parent = Fi(t, s.popLast()), n.structuredQuery.from = [ {
  6472. collectionId: s.lastSegment()
  6473. } ]);
  6474. const i = function(t) {
  6475. if (0 === t.length) return;
  6476. return rr(gn.create(t, "and" /* CompositeOperator.AND */));
  6477. }(e.filters);
  6478. i && (n.structuredQuery.where = i);
  6479. const r = function(t) {
  6480. if (0 === t.length) return;
  6481. return t.map((t =>
  6482. // visible for testing
  6483. function(t) {
  6484. return {
  6485. field: sr(t.field),
  6486. direction: tr(t.dir)
  6487. };
  6488. }(t)));
  6489. }(e.orderBy);
  6490. r && (n.structuredQuery.orderBy = r);
  6491. const o = Si(t, e.limit);
  6492. var u;
  6493. return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {
  6494. before: (u = e.startAt).inclusive,
  6495. values: u.position
  6496. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  6497. return {
  6498. before: !t.inclusive,
  6499. values: t.position
  6500. };
  6501. }(e.endAt)), n;
  6502. }
  6503. function Yi(t) {
  6504. let e = Bi(t.parent);
  6505. const n = t.structuredQuery, s = n.from ? n.from.length : 0;
  6506. let i = null;
  6507. if (s > 0) {
  6508. F(1 === s);
  6509. const t = n.from[0];
  6510. t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);
  6511. }
  6512. let r = [];
  6513. n.where && (r = function(t) {
  6514. const e = Zi(t);
  6515. if (e instanceof gn && In(e)) return e.getFilters();
  6516. return [ e ];
  6517. }(n.where));
  6518. let o = [];
  6519. n.orderBy && (o = n.orderBy.map((t => function(t) {
  6520. return new dn(ir(t.field),
  6521. // visible for testing
  6522. function(t) {
  6523. switch (t) {
  6524. case "ASCENDING":
  6525. return "asc" /* Direction.ASCENDING */;
  6526. case "DESCENDING":
  6527. return "desc" /* Direction.DESCENDING */;
  6528. default:
  6529. return;
  6530. }
  6531. }
  6532. // visible for testing
  6533. (t.direction));
  6534. }
  6535. // visible for testing
  6536. (t))));
  6537. let u = null;
  6538. n.limit && (u = function(t) {
  6539. let e;
  6540. return e = "object" == typeof t ? t.value : t, Ft(e) ? null : e;
  6541. }(n.limit));
  6542. let c = null;
  6543. n.startAt && (c = function(t) {
  6544. const e = !!t.before, n = t.values || [];
  6545. return new hn(n, e);
  6546. }(n.startAt));
  6547. let a = null;
  6548. return n.endAt && (a = function(t) {
  6549. const e = !t.before, n = t.values || [];
  6550. return new hn(n, e);
  6551. }
  6552. // visible for testing
  6553. (n.endAt)), Kn(e, i, o, r, u, "F" /* LimitType.First */ , c, a);
  6554. }
  6555. function Xi(t, e) {
  6556. const n = function(t) {
  6557. switch (t) {
  6558. case "TargetPurposeListen" /* TargetPurpose.Listen */ :
  6559. return null;
  6560. case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ :
  6561. return "existence-filter-mismatch";
  6562. case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ :
  6563. return "existence-filter-mismatch-bloom";
  6564. case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ :
  6565. return "limbo-document";
  6566. default:
  6567. return O();
  6568. }
  6569. }(e.purpose);
  6570. return null == n ? null : {
  6571. "goog-listen-tags": n
  6572. };
  6573. }
  6574. function Zi(t) {
  6575. return void 0 !== t.unaryFilter ? function(t) {
  6576. switch (t.unaryFilter.op) {
  6577. case "IS_NAN":
  6578. const e = ir(t.unaryFilter.field);
  6579. return mn.create(e, "==" /* Operator.EQUAL */ , {
  6580. doubleValue: NaN
  6581. });
  6582. case "IS_NULL":
  6583. const n = ir(t.unaryFilter.field);
  6584. return mn.create(n, "==" /* Operator.EQUAL */ , {
  6585. nullValue: "NULL_VALUE"
  6586. });
  6587. case "IS_NOT_NAN":
  6588. const s = ir(t.unaryFilter.field);
  6589. return mn.create(s, "!=" /* Operator.NOT_EQUAL */ , {
  6590. doubleValue: NaN
  6591. });
  6592. case "IS_NOT_NULL":
  6593. const i = ir(t.unaryFilter.field);
  6594. return mn.create(i, "!=" /* Operator.NOT_EQUAL */ , {
  6595. nullValue: "NULL_VALUE"
  6596. });
  6597. default:
  6598. return O();
  6599. }
  6600. }(t) : void 0 !== t.fieldFilter ? function(t) {
  6601. return mn.create(ir(t.fieldFilter.field), function(t) {
  6602. switch (t) {
  6603. case "EQUAL":
  6604. return "==" /* Operator.EQUAL */;
  6605. case "NOT_EQUAL":
  6606. return "!=" /* Operator.NOT_EQUAL */;
  6607. case "GREATER_THAN":
  6608. return ">" /* Operator.GREATER_THAN */;
  6609. case "GREATER_THAN_OR_EQUAL":
  6610. return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;
  6611. case "LESS_THAN":
  6612. return "<" /* Operator.LESS_THAN */;
  6613. case "LESS_THAN_OR_EQUAL":
  6614. return "<=" /* Operator.LESS_THAN_OR_EQUAL */;
  6615. case "ARRAY_CONTAINS":
  6616. return "array-contains" /* Operator.ARRAY_CONTAINS */;
  6617. case "IN":
  6618. return "in" /* Operator.IN */;
  6619. case "NOT_IN":
  6620. return "not-in" /* Operator.NOT_IN */;
  6621. case "ARRAY_CONTAINS_ANY":
  6622. return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;
  6623. default:
  6624. return O();
  6625. }
  6626. }(t.fieldFilter.op), t.fieldFilter.value);
  6627. }(t) : void 0 !== t.compositeFilter ? function(t) {
  6628. return gn.create(t.compositeFilter.filters.map((t => Zi(t))), function(t) {
  6629. switch (t) {
  6630. case "AND":
  6631. return "and" /* CompositeOperator.AND */;
  6632. case "OR":
  6633. return "or" /* CompositeOperator.OR */;
  6634. default:
  6635. return O();
  6636. }
  6637. }(t.compositeFilter.op));
  6638. }(t) : O();
  6639. }
  6640. function tr(t) {
  6641. return Ri[t];
  6642. }
  6643. function er(t) {
  6644. return Pi[t];
  6645. }
  6646. function nr(t) {
  6647. return bi[t];
  6648. }
  6649. function sr(t) {
  6650. return {
  6651. fieldPath: t.canonicalString()
  6652. };
  6653. }
  6654. function ir(t) {
  6655. return at.fromServerFormat(t.fieldPath);
  6656. }
  6657. function rr(t) {
  6658. return t instanceof mn ? function(t) {
  6659. if ("==" /* Operator.EQUAL */ === t.op) {
  6660. if (Xe(t.value)) return {
  6661. unaryFilter: {
  6662. field: sr(t.field),
  6663. op: "IS_NAN"
  6664. }
  6665. };
  6666. if (Ye(t.value)) return {
  6667. unaryFilter: {
  6668. field: sr(t.field),
  6669. op: "IS_NULL"
  6670. }
  6671. };
  6672. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  6673. if (Xe(t.value)) return {
  6674. unaryFilter: {
  6675. field: sr(t.field),
  6676. op: "IS_NOT_NAN"
  6677. }
  6678. };
  6679. if (Ye(t.value)) return {
  6680. unaryFilter: {
  6681. field: sr(t.field),
  6682. op: "IS_NOT_NULL"
  6683. }
  6684. };
  6685. }
  6686. return {
  6687. fieldFilter: {
  6688. field: sr(t.field),
  6689. op: er(t.op),
  6690. value: t.value
  6691. }
  6692. };
  6693. }(t) : t instanceof gn ? function(t) {
  6694. const e = t.getFilters().map((t => rr(t)));
  6695. if (1 === e.length) return e[0];
  6696. return {
  6697. compositeFilter: {
  6698. op: nr(t.op),
  6699. filters: e
  6700. }
  6701. };
  6702. }(t) : O();
  6703. }
  6704. function or(t) {
  6705. const e = [];
  6706. return t.fields.forEach((t => e.push(t.canonicalString()))), {
  6707. fieldPaths: e
  6708. };
  6709. }
  6710. function ur(t) {
  6711. // Resource names have at least 4 components (project ID, database ID)
  6712. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  6713. }
  6714. /**
  6715. * @license
  6716. * Copyright 2017 Google LLC
  6717. *
  6718. * Licensed under the Apache License, Version 2.0 (the "License");
  6719. * you may not use this file except in compliance with the License.
  6720. * You may obtain a copy of the License at
  6721. *
  6722. * http://www.apache.org/licenses/LICENSE-2.0
  6723. *
  6724. * Unless required by applicable law or agreed to in writing, software
  6725. * distributed under the License is distributed on an "AS IS" BASIS,
  6726. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6727. * See the License for the specific language governing permissions and
  6728. * limitations under the License.
  6729. */
  6730. /**
  6731. * An immutable set of metadata that the local store tracks for each target.
  6732. */ class cr {
  6733. constructor(
  6734. /** The target being listened to. */
  6735. t,
  6736. /**
  6737. * The target ID to which the target corresponds; Assigned by the
  6738. * LocalStore for user listens and by the SyncEngine for limbo watches.
  6739. */
  6740. e,
  6741. /** The purpose of the target. */
  6742. n,
  6743. /**
  6744. * The sequence number of the last transaction during which this target data
  6745. * was modified.
  6746. */
  6747. s,
  6748. /** The latest snapshot version seen for this target. */
  6749. i = rt.min()
  6750. /**
  6751. * The maximum snapshot version at which the associated view
  6752. * contained no limbo documents.
  6753. */ , r = rt.min()
  6754. /**
  6755. * An opaque, server-assigned token that allows watching a target to be
  6756. * resumed after disconnecting without retransmitting all the data that
  6757. * matches the target. The resume token essentially identifies a point in
  6758. * time from which the server should resume sending results.
  6759. */ , o = Ve.EMPTY_BYTE_STRING
  6760. /**
  6761. * The number of documents that last matched the query at the resume token or
  6762. * read time. Documents are counted only when making a listen request with
  6763. * resume token or read time, otherwise, keep it null.
  6764. */ , u = null) {
  6765. this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i,
  6766. this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o, this.expectedCount = u;
  6767. }
  6768. /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {
  6769. return new cr(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);
  6770. }
  6771. /**
  6772. * Creates a new target data instance with an updated resume token and
  6773. * snapshot version.
  6774. */ withResumeToken(t, e) {
  6775. return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t,
  6776. /* expectedCount= */ null);
  6777. }
  6778. /**
  6779. * Creates a new target data instance with an updated expected count.
  6780. */ withExpectedCount(t) {
  6781. return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, t);
  6782. }
  6783. /**
  6784. * Creates a new target data instance with an updated last limbo free
  6785. * snapshot version number.
  6786. */ withLastLimboFreeSnapshotVersion(t) {
  6787. return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken, this.expectedCount);
  6788. }
  6789. }
  6790. /**
  6791. * @license
  6792. * Copyright 2017 Google LLC
  6793. *
  6794. * Licensed under the Apache License, Version 2.0 (the "License");
  6795. * you may not use this file except in compliance with the License.
  6796. * You may obtain a copy of the License at
  6797. *
  6798. * http://www.apache.org/licenses/LICENSE-2.0
  6799. *
  6800. * Unless required by applicable law or agreed to in writing, software
  6801. * distributed under the License is distributed on an "AS IS" BASIS,
  6802. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6803. * See the License for the specific language governing permissions and
  6804. * limitations under the License.
  6805. */
  6806. /** Serializer for values stored in the LocalStore. */ class ar {
  6807. constructor(t) {
  6808. this.fe = t;
  6809. }
  6810. }
  6811. /** Decodes a remote document from storage locally to a Document. */ function hr(t, e) {
  6812. let n;
  6813. if (e.document) n = Ki(t.fe, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {
  6814. const t = ht.fromSegments(e.noDocument.path), s = wr(e.noDocument.readTime);
  6815. n = an.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();
  6816. } else {
  6817. if (!e.unknownDocument) return O();
  6818. {
  6819. const t = ht.fromSegments(e.unknownDocument.path), s = wr(e.unknownDocument.version);
  6820. n = an.newUnknownDocument(t, s);
  6821. }
  6822. }
  6823. return e.readTime && n.setReadTime(function(t) {
  6824. const e = new it(t[0], t[1]);
  6825. return rt.fromTimestamp(e);
  6826. }(e.readTime)), n;
  6827. }
  6828. /** Encodes a document for storage locally. */ function lr(t, e) {
  6829. const n = e.key, s = {
  6830. prefixPath: n.getCollectionPath().popLast().toArray(),
  6831. collectionGroup: n.collectionGroup,
  6832. documentId: n.path.lastSegment(),
  6833. readTime: fr(e.readTime),
  6834. hasCommittedMutations: e.hasCommittedMutations
  6835. };
  6836. if (e.isFoundDocument()) s.document = function(t, e) {
  6837. return {
  6838. name: $i(t, e.key),
  6839. fields: e.data.value.mapValue.fields,
  6840. updateTime: Di(t, e.version.toTimestamp()),
  6841. createTime: Di(t, e.createTime.toTimestamp())
  6842. };
  6843. }(t.fe, e); else if (e.isNoDocument()) s.noDocument = {
  6844. path: n.path.toArray(),
  6845. readTime: dr(e.version)
  6846. }; else {
  6847. if (!e.isUnknownDocument()) return O();
  6848. s.unknownDocument = {
  6849. path: n.path.toArray(),
  6850. version: dr(e.version)
  6851. };
  6852. }
  6853. return s;
  6854. }
  6855. function fr(t) {
  6856. const e = t.toTimestamp();
  6857. return [ e.seconds, e.nanoseconds ];
  6858. }
  6859. function dr(t) {
  6860. const e = t.toTimestamp();
  6861. return {
  6862. seconds: e.seconds,
  6863. nanoseconds: e.nanoseconds
  6864. };
  6865. }
  6866. function wr(t) {
  6867. const e = new it(t.seconds, t.nanoseconds);
  6868. return rt.fromTimestamp(e);
  6869. }
  6870. /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
  6871. /** Decodes a DbMutationBatch into a MutationBatch */
  6872. function _r(t, e) {
  6873. const n = (e.baseMutations || []).map((e => zi(t.fe, e)));
  6874. // Squash old transform mutations into existing patch or set mutations.
  6875. // The replacement of representing `transforms` with `update_transforms`
  6876. // on the SDK means that old `transform` mutations stored in IndexedDB need
  6877. // to be updated to `update_transforms`.
  6878. // TODO(b/174608374): Remove this code once we perform a schema migration.
  6879. for (let t = 0; t < e.mutations.length - 1; ++t) {
  6880. const n = e.mutations[t];
  6881. if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {
  6882. const s = e.mutations[t + 1];
  6883. n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1),
  6884. ++t;
  6885. }
  6886. }
  6887. const s = e.mutations.map((e => zi(t.fe, e))), i = it.fromMillis(e.localWriteTimeMs);
  6888. return new Zs(e.batchId, i, n, s);
  6889. }
  6890. /** Decodes a DbTarget into TargetData */ function mr(t) {
  6891. const e = wr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? wr(t.lastLimboFreeSnapshotVersion) : rt.min();
  6892. let s;
  6893. var i;
  6894. return void 0 !== t.query.documents ? (F(1 === (i = t.query).documents.length),
  6895. s = Jn(Gn(Bi(i.documents[0])))) : s = function(t) {
  6896. return Jn(Yi(t));
  6897. }(t.query), new cr(s, t.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Ve.fromBase64String(t.resumeToken));
  6898. }
  6899. /** Encodes TargetData into a DbTarget for storage locally. */ function gr(t, e) {
  6900. const n = dr(e.snapshotVersion), s = dr(e.lastLimboFreeSnapshotVersion);
  6901. let i;
  6902. i = Fn(e.target) ? Hi(t.fe, e.target) : Ji(t.fe, e.target);
  6903. // We can't store the resumeToken as a ByteString in IndexedDb, so we
  6904. // convert it to a base64 string for storage.
  6905. const r = e.resumeToken.toBase64();
  6906. // lastListenSequenceNumber is always 0 until we do real GC.
  6907. return {
  6908. targetId: e.targetId,
  6909. canonicalId: $n(e.target),
  6910. readTime: n,
  6911. resumeToken: r,
  6912. lastListenSequenceNumber: e.sequenceNumber,
  6913. lastLimboFreeSnapshotVersion: s,
  6914. query: i
  6915. };
  6916. }
  6917. /**
  6918. * A helper function for figuring out what kind of query has been stored.
  6919. */
  6920. /**
  6921. * Encodes a `BundledQuery` from bundle proto to a Query object.
  6922. *
  6923. * This reconstructs the original query used to build the bundle being loaded,
  6924. * including features exists only in SDKs (for example: limit-to-last).
  6925. */
  6926. function yr(t) {
  6927. const e = Yi({
  6928. parent: t.parent,
  6929. structuredQuery: t.structuredQuery
  6930. });
  6931. return "LAST" === t.limitType ? Xn(e, e.limit, "L" /* LimitType.Last */) : e;
  6932. }
  6933. /** Encodes a NamedQuery proto object to a NamedQuery model object. */
  6934. /** Encodes a DbDocumentOverlay object to an Overlay model object. */
  6935. function pr(t, e) {
  6936. return new ei(e.largestBatchId, zi(t.fe, e.overlayMutation));
  6937. }
  6938. /** Decodes an Overlay model object into a DbDocumentOverlay object. */
  6939. /**
  6940. * Returns the DbDocumentOverlayKey corresponding to the given user and
  6941. * document key.
  6942. */
  6943. function Ir(t, e) {
  6944. const n = e.path.lastSegment();
  6945. return [ t, qt(e.path.popLast()), n ];
  6946. }
  6947. function Tr(t, e, n, s) {
  6948. return {
  6949. indexId: t,
  6950. uid: e.uid || "",
  6951. sequenceNumber: n,
  6952. readTime: dr(s.readTime),
  6953. documentKey: qt(s.documentKey.path),
  6954. largestBatchId: s.largestBatchId
  6955. };
  6956. }
  6957. /**
  6958. * @license
  6959. * Copyright 2020 Google LLC
  6960. *
  6961. * Licensed under the Apache License, Version 2.0 (the "License");
  6962. * you may not use this file except in compliance with the License.
  6963. * You may obtain a copy of the License at
  6964. *
  6965. * http://www.apache.org/licenses/LICENSE-2.0
  6966. *
  6967. * Unless required by applicable law or agreed to in writing, software
  6968. * distributed under the License is distributed on an "AS IS" BASIS,
  6969. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6970. * See the License for the specific language governing permissions and
  6971. * limitations under the License.
  6972. */ class Er {
  6973. getBundleMetadata(t, e) {
  6974. return Ar(t).get(e).next((t => {
  6975. if (t) return {
  6976. id: (e = t).bundleId,
  6977. createTime: wr(e.createTime),
  6978. version: e.version
  6979. };
  6980. /** Encodes a DbBundle to a BundleMetadata object. */
  6981. var e;
  6982. /** Encodes a BundleMetadata to a DbBundle. */ }));
  6983. }
  6984. saveBundleMetadata(t, e) {
  6985. return Ar(t).put({
  6986. bundleId: (n = e).id,
  6987. createTime: dr(Ni(n.createTime)),
  6988. version: n.version
  6989. });
  6990. var n;
  6991. /** Encodes a DbNamedQuery to a NamedQuery. */ }
  6992. getNamedQuery(t, e) {
  6993. return vr(t).get(e).next((t => {
  6994. if (t) return {
  6995. name: (e = t).name,
  6996. query: yr(e.bundledQuery),
  6997. readTime: wr(e.readTime)
  6998. };
  6999. var e;
  7000. /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));
  7001. }
  7002. saveNamedQuery(t, e) {
  7003. return vr(t).put(function(t) {
  7004. return {
  7005. name: t.name,
  7006. readTime: dr(Ni(t.readTime)),
  7007. bundledQuery: t.bundledQuery
  7008. };
  7009. }(e));
  7010. }
  7011. }
  7012. /**
  7013. * Helper to get a typed SimpleDbStore for the bundles object store.
  7014. */ function Ar(t) {
  7015. return _e(t, "bundles");
  7016. }
  7017. /**
  7018. * Helper to get a typed SimpleDbStore for the namedQueries object store.
  7019. */ function vr(t) {
  7020. return _e(t, "namedQueries");
  7021. }
  7022. /**
  7023. * @license
  7024. * Copyright 2022 Google LLC
  7025. *
  7026. * Licensed under the Apache License, Version 2.0 (the "License");
  7027. * you may not use this file except in compliance with the License.
  7028. * You may obtain a copy of the License at
  7029. *
  7030. * http://www.apache.org/licenses/LICENSE-2.0
  7031. *
  7032. * Unless required by applicable law or agreed to in writing, software
  7033. * distributed under the License is distributed on an "AS IS" BASIS,
  7034. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7035. * See the License for the specific language governing permissions and
  7036. * limitations under the License.
  7037. */
  7038. /**
  7039. * Implementation of DocumentOverlayCache using IndexedDb.
  7040. */ class Rr {
  7041. /**
  7042. * @param serializer - The document serializer.
  7043. * @param userId - The userId for which we are accessing overlays.
  7044. */
  7045. constructor(t, e) {
  7046. this.serializer = t, this.userId = e;
  7047. }
  7048. static de(t, e) {
  7049. const n = e.uid || "";
  7050. return new Rr(t, n);
  7051. }
  7052. getOverlay(t, e) {
  7053. return Pr(t).get(Ir(this.userId, e)).next((t => t ? pr(this.serializer, t) : null));
  7054. }
  7055. getOverlays(t, e) {
  7056. const n = fs();
  7057. return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  7058. null !== t && n.set(e, t);
  7059. })))).next((() => n));
  7060. }
  7061. saveOverlays(t, e, n) {
  7062. const s = [];
  7063. return n.forEach(((n, i) => {
  7064. const r = new ei(e, i);
  7065. s.push(this.we(t, r));
  7066. })), Rt.waitFor(s);
  7067. }
  7068. removeOverlaysForBatchId(t, e, n) {
  7069. const s = new Set;
  7070. // Get the set of unique collection paths.
  7071. e.forEach((t => s.add(qt(t.getCollectionPath()))));
  7072. const i = [];
  7073. return s.forEach((e => {
  7074. const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ],
  7075. /*lowerOpen=*/ !1,
  7076. /*upperOpen=*/ !0);
  7077. i.push(Pr(t).J("collectionPathOverlayIndex", s));
  7078. })), Rt.waitFor(i);
  7079. }
  7080. getOverlaysForCollection(t, e, n) {
  7081. const s = fs(), i = qt(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ],
  7082. /*lowerOpen=*/ !0);
  7083. return Pr(t).j("collectionPathOverlayIndex", r).next((t => {
  7084. for (const e of t) {
  7085. const t = pr(this.serializer, e);
  7086. s.set(t.getKey(), t);
  7087. }
  7088. return s;
  7089. }));
  7090. }
  7091. getOverlaysForCollectionGroup(t, e, n, s) {
  7092. const i = fs();
  7093. let r;
  7094. // We want batch IDs larger than `sinceBatchId`, and so the lower bound
  7095. // is not inclusive.
  7096. const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ],
  7097. /*lowerOpen=*/ !0);
  7098. return Pr(t).X({
  7099. index: "collectionGroupOverlayIndex",
  7100. range: o
  7101. }, ((t, e, n) => {
  7102. // We do not want to return partial batch overlays, even if the size
  7103. // of the result set exceeds the given `count` argument. Therefore, we
  7104. // continue to aggregate results even after the result size exceeds
  7105. // `count` if there are more overlays from the `currentBatchId`.
  7106. const o = pr(this.serializer, e);
  7107. i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();
  7108. })).next((() => i));
  7109. }
  7110. we(t, e) {
  7111. return Pr(t).put(function(t, e, n) {
  7112. const [s, i, r] = Ir(e, n.mutation.key);
  7113. return {
  7114. userId: e,
  7115. collectionPath: i,
  7116. documentId: r,
  7117. collectionGroup: n.mutation.key.getCollectionGroup(),
  7118. largestBatchId: n.largestBatchId,
  7119. overlayMutation: ji(t.fe, n.mutation)
  7120. };
  7121. }(this.serializer, this.userId, e));
  7122. }
  7123. }
  7124. /**
  7125. * Helper to get a typed SimpleDbStore for the document overlay object store.
  7126. */ function Pr(t) {
  7127. return _e(t, "documentOverlays");
  7128. }
  7129. /**
  7130. * @license
  7131. * Copyright 2021 Google LLC
  7132. *
  7133. * Licensed under the Apache License, Version 2.0 (the "License");
  7134. * you may not use this file except in compliance with the License.
  7135. * You may obtain a copy of the License at
  7136. *
  7137. * http://www.apache.org/licenses/LICENSE-2.0
  7138. *
  7139. * Unless required by applicable law or agreed to in writing, software
  7140. * distributed under the License is distributed on an "AS IS" BASIS,
  7141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7142. * See the License for the specific language governing permissions and
  7143. * limitations under the License.
  7144. */
  7145. // Note: This code is copied from the backend. Code that is not used by
  7146. // Firestore was removed.
  7147. /** Firestore index value writer. */
  7148. class br {
  7149. constructor() {}
  7150. // The write methods below short-circuit writing terminators for values
  7151. // containing a (terminating) truncated value.
  7152. // As an example, consider the resulting encoding for:
  7153. // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  7154. // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  7155. // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  7156. /** Writes an index value. */
  7157. _e(t, e) {
  7158. this.me(t, e),
  7159. // Write separator to split index values
  7160. // (see go/firestore-storage-format#encodings).
  7161. e.ge();
  7162. }
  7163. me(t, e) {
  7164. if ("nullValue" in t) this.ye(e, 5); else if ("booleanValue" in t) this.ye(e, 10),
  7165. e.pe(t.booleanValue ? 1 : 0); else if ("integerValue" in t) this.ye(e, 15), e.pe(Ce(t.integerValue)); else if ("doubleValue" in t) {
  7166. const n = Ce(t.doubleValue);
  7167. isNaN(n) ? this.ye(e, 13) : (this.ye(e, 15), Bt(n) ?
  7168. // -0.0, 0 and 0.0 are all considered the same
  7169. e.pe(0) : e.pe(n));
  7170. } else if ("timestampValue" in t) {
  7171. const n = t.timestampValue;
  7172. this.ye(e, 20), "string" == typeof n ? e.Ie(n) : (e.Ie(`${n.seconds || ""}`), e.pe(n.nanos || 0));
  7173. } else if ("stringValue" in t) this.Te(t.stringValue, e), this.Ee(e); else if ("bytesValue" in t) this.ye(e, 30),
  7174. e.Ae(xe(t.bytesValue)), this.Ee(e); else if ("referenceValue" in t) this.ve(t.referenceValue, e); else if ("geoPointValue" in t) {
  7175. const n = t.geoPointValue;
  7176. this.ye(e, 45), e.pe(n.latitude || 0), e.pe(n.longitude || 0);
  7177. } else "mapValue" in t ? en(t) ? this.ye(e, Number.MAX_SAFE_INTEGER) : (this.Re(t.mapValue, e),
  7178. this.Ee(e)) : "arrayValue" in t ? (this.Pe(t.arrayValue, e), this.Ee(e)) : O();
  7179. }
  7180. Te(t, e) {
  7181. this.ye(e, 25), this.be(t, e);
  7182. }
  7183. be(t, e) {
  7184. e.Ie(t);
  7185. }
  7186. Re(t, e) {
  7187. const n = t.fields || {};
  7188. this.ye(e, 55);
  7189. for (const t of Object.keys(n)) this.Te(t, e), this.me(n[t], e);
  7190. }
  7191. Pe(t, e) {
  7192. const n = t.values || [];
  7193. this.ye(e, 50);
  7194. for (const t of n) this.me(t, e);
  7195. }
  7196. ve(t, e) {
  7197. this.ye(e, 37);
  7198. ht.fromName(t).path.forEach((t => {
  7199. this.ye(e, 60), this.be(t, e);
  7200. }));
  7201. }
  7202. ye(t, e) {
  7203. t.pe(e);
  7204. }
  7205. Ee(t) {
  7206. // While the SDK does not implement truncation, the truncation marker is
  7207. // used to terminate all variable length values (which are strings, bytes,
  7208. // references, arrays and maps).
  7209. t.pe(2);
  7210. }
  7211. }
  7212. br.Ve = new br;
  7213. /**
  7214. * Counts the number of zeros in a byte.
  7215. *
  7216. * Visible for testing.
  7217. */
  7218. function Vr(t) {
  7219. if (0 === t) return 8;
  7220. let e = 0;
  7221. return t >> 4 == 0 && (
  7222. // Test if the first four bits are zero.
  7223. e += 4, t <<= 4), t >> 6 == 0 && (
  7224. // Test if the first two (or next two) bits are zero.
  7225. e += 2, t <<= 2), t >> 7 == 0 && (
  7226. // Test if the remaining bit is zero.
  7227. e += 1), e;
  7228. }
  7229. /** Counts the number of leading zeros in the given byte array. */
  7230. /**
  7231. * Returns the number of bytes required to store "value". Leading zero bytes
  7232. * are skipped.
  7233. */
  7234. function Sr(t) {
  7235. // This is just the number of bytes for the unsigned representation of the number.
  7236. const e = 64 - function(t) {
  7237. let e = 0;
  7238. for (let n = 0; n < 8; ++n) {
  7239. const s = Vr(255 & t[n]);
  7240. if (e += s, 8 !== s) break;
  7241. }
  7242. return e;
  7243. }(t);
  7244. return Math.ceil(e / 8);
  7245. }
  7246. /**
  7247. * OrderedCodeWriter is a minimal-allocation implementation of the writing
  7248. * behavior defined by the backend.
  7249. *
  7250. * The code is ported from its Java counterpart.
  7251. */ class Dr {
  7252. constructor() {
  7253. this.buffer = new Uint8Array(1024), this.position = 0;
  7254. }
  7255. Se(t) {
  7256. const e = t[Symbol.iterator]();
  7257. let n = e.next();
  7258. for (;!n.done; ) this.De(n.value), n = e.next();
  7259. this.Ce();
  7260. }
  7261. xe(t) {
  7262. const e = t[Symbol.iterator]();
  7263. let n = e.next();
  7264. for (;!n.done; ) this.Ne(n.value), n = e.next();
  7265. this.ke();
  7266. }
  7267. /** Writes utf8 bytes into this byte sequence, ascending. */ Me(t) {
  7268. for (const e of t) {
  7269. const t = e.charCodeAt(0);
  7270. if (t < 128) this.De(t); else if (t < 2048) this.De(960 | t >>> 6), this.De(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.De(480 | t >>> 12),
  7271. this.De(128 | 63 & t >>> 6), this.De(128 | 63 & t); else {
  7272. const t = e.codePointAt(0);
  7273. this.De(240 | t >>> 18), this.De(128 | 63 & t >>> 12), this.De(128 | 63 & t >>> 6),
  7274. this.De(128 | 63 & t);
  7275. }
  7276. }
  7277. this.Ce();
  7278. }
  7279. /** Writes utf8 bytes into this byte sequence, descending */ $e(t) {
  7280. for (const e of t) {
  7281. const t = e.charCodeAt(0);
  7282. if (t < 128) this.Ne(t); else if (t < 2048) this.Ne(960 | t >>> 6), this.Ne(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.Ne(480 | t >>> 12),
  7283. this.Ne(128 | 63 & t >>> 6), this.Ne(128 | 63 & t); else {
  7284. const t = e.codePointAt(0);
  7285. this.Ne(240 | t >>> 18), this.Ne(128 | 63 & t >>> 12), this.Ne(128 | 63 & t >>> 6),
  7286. this.Ne(128 | 63 & t);
  7287. }
  7288. }
  7289. this.ke();
  7290. }
  7291. Oe(t) {
  7292. // Values are encoded with a single byte length prefix, followed by the
  7293. // actual value in big-endian format with leading 0 bytes dropped.
  7294. const e = this.Fe(t), n = Sr(e);
  7295. this.Be(1 + n), this.buffer[this.position++] = 255 & n;
  7296. // Write the length
  7297. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];
  7298. }
  7299. Le(t) {
  7300. // Values are encoded with a single byte length prefix, followed by the
  7301. // inverted value in big-endian format with leading 0 bytes dropped.
  7302. const e = this.Fe(t), n = Sr(e);
  7303. this.Be(1 + n), this.buffer[this.position++] = ~(255 & n);
  7304. // Write the length
  7305. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);
  7306. }
  7307. /**
  7308. * Writes the "infinity" byte sequence that sorts after all other byte
  7309. * sequences written in ascending order.
  7310. */ qe() {
  7311. this.Ue(255), this.Ue(255);
  7312. }
  7313. /**
  7314. * Writes the "infinity" byte sequence that sorts before all other byte
  7315. * sequences written in descending order.
  7316. */ Ke() {
  7317. this.Ge(255), this.Ge(255);
  7318. }
  7319. /**
  7320. * Resets the buffer such that it is the same as when it was newly
  7321. * constructed.
  7322. */ reset() {
  7323. this.position = 0;
  7324. }
  7325. seed(t) {
  7326. this.Be(t.length), this.buffer.set(t, this.position), this.position += t.length;
  7327. }
  7328. /** Makes a copy of the encoded bytes in this buffer. */ Qe() {
  7329. return this.buffer.slice(0, this.position);
  7330. }
  7331. /**
  7332. * Encodes `val` into an encoding so that the order matches the IEEE 754
  7333. * floating-point comparison results with the following exceptions:
  7334. * -0.0 < 0.0
  7335. * all non-NaN < NaN
  7336. * NaN = NaN
  7337. */ Fe(t) {
  7338. const e =
  7339. /** Converts a JavaScript number to a byte array (using big endian encoding). */
  7340. function(t) {
  7341. const e = new DataView(new ArrayBuffer(8));
  7342. return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);
  7343. }(t), n = 0 != (128 & e[0]);
  7344. // Check if the first bit is set. We use a bit mask since value[0] is
  7345. // encoded as a number from 0 to 255.
  7346. // Revert the two complement to get natural ordering
  7347. e[0] ^= n ? 255 : 128;
  7348. for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;
  7349. return e;
  7350. }
  7351. /** Writes a single byte ascending to the buffer. */ De(t) {
  7352. const e = 255 & t;
  7353. 0 === e ? (this.Ue(0), this.Ue(255)) : 255 === e ? (this.Ue(255), this.Ue(0)) : this.Ue(e);
  7354. }
  7355. /** Writes a single byte descending to the buffer. */ Ne(t) {
  7356. const e = 255 & t;
  7357. 0 === e ? (this.Ge(0), this.Ge(255)) : 255 === e ? (this.Ge(255), this.Ge(0)) : this.Ge(t);
  7358. }
  7359. Ce() {
  7360. this.Ue(0), this.Ue(1);
  7361. }
  7362. ke() {
  7363. this.Ge(0), this.Ge(1);
  7364. }
  7365. Ue(t) {
  7366. this.Be(1), this.buffer[this.position++] = t;
  7367. }
  7368. Ge(t) {
  7369. this.Be(1), this.buffer[this.position++] = ~t;
  7370. }
  7371. Be(t) {
  7372. const e = t + this.position;
  7373. if (e <= this.buffer.length) return;
  7374. // Try doubling.
  7375. let n = 2 * this.buffer.length;
  7376. // Still not big enough? Just allocate the right size.
  7377. n < e && (n = e);
  7378. // Create the new buffer.
  7379. const s = new Uint8Array(n);
  7380. s.set(this.buffer), // copy old data
  7381. this.buffer = s;
  7382. }
  7383. }
  7384. class Cr {
  7385. constructor(t) {
  7386. this.je = t;
  7387. }
  7388. Ae(t) {
  7389. this.je.Se(t);
  7390. }
  7391. Ie(t) {
  7392. this.je.Me(t);
  7393. }
  7394. pe(t) {
  7395. this.je.Oe(t);
  7396. }
  7397. ge() {
  7398. this.je.qe();
  7399. }
  7400. }
  7401. class xr {
  7402. constructor(t) {
  7403. this.je = t;
  7404. }
  7405. Ae(t) {
  7406. this.je.xe(t);
  7407. }
  7408. Ie(t) {
  7409. this.je.$e(t);
  7410. }
  7411. pe(t) {
  7412. this.je.Le(t);
  7413. }
  7414. ge() {
  7415. this.je.Ke();
  7416. }
  7417. }
  7418. /**
  7419. * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the
  7420. * actual encoding.
  7421. */ class Nr {
  7422. constructor() {
  7423. this.je = new Dr, this.ze = new Cr(this.je), this.We = new xr(this.je);
  7424. }
  7425. seed(t) {
  7426. this.je.seed(t);
  7427. }
  7428. He(t) {
  7429. return 0 /* IndexKind.ASCENDING */ === t ? this.ze : this.We;
  7430. }
  7431. Qe() {
  7432. return this.je.Qe();
  7433. }
  7434. reset() {
  7435. this.je.reset();
  7436. }
  7437. }
  7438. /**
  7439. * @license
  7440. * Copyright 2022 Google LLC
  7441. *
  7442. * Licensed under the Apache License, Version 2.0 (the "License");
  7443. * you may not use this file except in compliance with the License.
  7444. * You may obtain a copy of the License at
  7445. *
  7446. * http://www.apache.org/licenses/LICENSE-2.0
  7447. *
  7448. * Unless required by applicable law or agreed to in writing, software
  7449. * distributed under the License is distributed on an "AS IS" BASIS,
  7450. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7451. * See the License for the specific language governing permissions and
  7452. * limitations under the License.
  7453. */
  7454. /** Represents an index entry saved by the SDK in persisted storage. */ class kr {
  7455. constructor(t, e, n, s) {
  7456. this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;
  7457. }
  7458. /**
  7459. * Returns an IndexEntry entry that sorts immediately after the current
  7460. * directional value.
  7461. */ Je() {
  7462. const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);
  7463. return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1],
  7464. new kr(this.indexId, this.documentKey, this.arrayValue, n);
  7465. }
  7466. }
  7467. function Mr(t, e) {
  7468. let n = t.indexId - e.indexId;
  7469. return 0 !== n ? n : (n = $r(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = $r(t.directionalValue, e.directionalValue),
  7470. 0 !== n ? n : ht.comparator(t.documentKey, e.documentKey)));
  7471. }
  7472. function $r(t, e) {
  7473. for (let n = 0; n < t.length && n < e.length; ++n) {
  7474. const s = t[n] - e[n];
  7475. if (0 !== s) return s;
  7476. }
  7477. return t.length - e.length;
  7478. }
  7479. /**
  7480. * @license
  7481. * Copyright 2022 Google LLC
  7482. *
  7483. * Licensed under the Apache License, Version 2.0 (the "License");
  7484. * you may not use this file except in compliance with the License.
  7485. * You may obtain a copy of the License at
  7486. *
  7487. * http://www.apache.org/licenses/LICENSE-2.0
  7488. *
  7489. * Unless required by applicable law or agreed to in writing, software
  7490. * distributed under the License is distributed on an "AS IS" BASIS,
  7491. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7492. * See the License for the specific language governing permissions and
  7493. * limitations under the License.
  7494. */
  7495. /**
  7496. * A light query planner for Firestore.
  7497. *
  7498. * This class matches a `FieldIndex` against a Firestore Query `Target`. It
  7499. * determines whether a given index can be used to serve the specified target.
  7500. *
  7501. * The following table showcases some possible index configurations:
  7502. *
  7503. * Query | Index
  7504. * -----------------------------------------------------------------------------
  7505. * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC
  7506. * where('a', '==', 'a').where('b', '==', 'b') | a ASC
  7507. * where('a', '==', 'a').where('b', '==', 'b') | b DESC
  7508. * where('a', '>=', 'a').orderBy('a') | a ASC
  7509. * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC
  7510. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC
  7511. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC
  7512. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING
  7513. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS
  7514. */ class Or {
  7515. constructor(t) {
  7516. this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(),
  7517. this.Ye = t.orderBy, this.Xe = [];
  7518. for (const e of t.filters) {
  7519. const t = e;
  7520. t.isInequality() ? this.Ze = t : this.Xe.push(t);
  7521. }
  7522. }
  7523. /**
  7524. * Returns whether the index can be used to serve the TargetIndexMatcher's
  7525. * target.
  7526. *
  7527. * An index is considered capable of serving the target when:
  7528. * - The target uses all index segments for its filters and orderBy clauses.
  7529. * The target can have additional filter and orderBy clauses, but not
  7530. * fewer.
  7531. * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
  7532. * have a corresponding `CONTAINS` segment.
  7533. * - All directional index segments can be mapped to the target as a series of
  7534. * equality filters, a single inequality filter and a series of orderBy
  7535. * clauses.
  7536. * - The segments that represent the equality filters may appear out of order.
  7537. * - The optional segment for the inequality filter must appear after all
  7538. * equality segments.
  7539. * - The segments that represent that orderBy clause of the target must appear
  7540. * in order after all equality and inequality segments. Single orderBy
  7541. * clauses cannot be skipped, but a continuous orderBy suffix may be
  7542. * omitted.
  7543. */ tn(t) {
  7544. F(t.collectionGroup === this.collectionId);
  7545. // If there is an array element, find a matching filter.
  7546. const e = ft(t);
  7547. if (void 0 !== e && !this.en(e)) return !1;
  7548. const n = dt(t);
  7549. let s = new Set, i = 0, r = 0;
  7550. // Process all equalities first. Equalities can appear out of order.
  7551. for (;i < n.length && this.en(n[i]); ++i) s = s.add(n[i].fieldPath.canonicalString());
  7552. // If we already have processed all segments, all segments are used to serve
  7553. // the equality filters and we do not need to map any segments to the
  7554. // target's inequality and orderBy clauses.
  7555. if (i === n.length) return !0;
  7556. if (void 0 !== this.Ze) {
  7557. // If there is an inequality filter and the field was not in one of the
  7558. // equality filters above, the next segment must match both the filter
  7559. // and the first orderBy clause.
  7560. if (!s.has(this.Ze.field.canonicalString())) {
  7561. const t = n[i];
  7562. if (!this.nn(this.Ze, t) || !this.sn(this.Ye[r++], t)) return !1;
  7563. }
  7564. ++i;
  7565. }
  7566. // All remaining segments need to represent the prefix of the target's
  7567. // orderBy.
  7568. for (;i < n.length; ++i) {
  7569. const t = n[i];
  7570. if (r >= this.Ye.length || !this.sn(this.Ye[r++], t)) return !1;
  7571. }
  7572. return !0;
  7573. }
  7574. en(t) {
  7575. for (const e of this.Xe) if (this.nn(e, t)) return !0;
  7576. return !1;
  7577. }
  7578. nn(t, e) {
  7579. if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;
  7580. const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;
  7581. return 2 /* IndexKind.CONTAINS */ === e.kind === n;
  7582. }
  7583. sn(t, e) {
  7584. return !!t.field.isEqual(e.fieldPath) && (0 /* IndexKind.ASCENDING */ === e.kind && "asc" /* Direction.ASCENDING */ === t.dir || 1 /* IndexKind.DESCENDING */ === e.kind && "desc" /* Direction.DESCENDING */ === t.dir);
  7585. }
  7586. }
  7587. /**
  7588. * @license
  7589. * Copyright 2022 Google LLC
  7590. *
  7591. * Licensed under the Apache License, Version 2.0 (the "License");
  7592. * you may not use this file except in compliance with the License.
  7593. * You may obtain a copy of the License at
  7594. *
  7595. * http://www.apache.org/licenses/LICENSE-2.0
  7596. *
  7597. * Unless required by applicable law or agreed to in writing, software
  7598. * distributed under the License is distributed on an "AS IS" BASIS,
  7599. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7600. * See the License for the specific language governing permissions and
  7601. * limitations under the License.
  7602. */
  7603. /**
  7604. * Provides utility functions that help with boolean logic transformations needed for handling
  7605. * complex filters used in queries.
  7606. */
  7607. /**
  7608. * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
  7609. * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
  7610. * input into a disjunction of equality filters and returns the expanded filter.
  7611. */ function Fr(t) {
  7612. var e, n;
  7613. if (F(t instanceof mn || t instanceof gn), t instanceof mn) {
  7614. if (t instanceof Cn) {
  7615. const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => mn.create(t.field, "==" /* Operator.EQUAL */ , e)))) || [];
  7616. return gn.create(s, "or" /* CompositeOperator.OR */);
  7617. }
  7618. // We have reached other kinds of field filters.
  7619. return t;
  7620. }
  7621. // We have a composite filter.
  7622. const s = t.filters.map((t => Fr(t)));
  7623. return gn.create(s, t.op);
  7624. }
  7625. /**
  7626. * Given a composite filter, returns the list of terms in its disjunctive normal form.
  7627. *
  7628. * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
  7629. * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
  7630. * with two elements: a composite filter that performs (A && C), and a composite filter that
  7631. * performs (B && C).
  7632. *
  7633. * @param filter the composite filter to calculate DNF transform for.
  7634. * @return the terms in the DNF transform.
  7635. */ function Br(t) {
  7636. if (0 === t.getFilters().length) return [];
  7637. const e = Kr(Fr(t));
  7638. return F(Ur(e)), Lr(e) || qr(e) ? [ e ] : e.getFilters();
  7639. }
  7640. /** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Lr(t) {
  7641. return t instanceof mn;
  7642. }
  7643. /**
  7644. * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
  7645. * && b == 20)
  7646. */ function qr(t) {
  7647. return t instanceof gn && In(t);
  7648. }
  7649. /**
  7650. * Returns whether or not the given filter is in disjunctive normal form (DNF).
  7651. *
  7652. * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
  7653. * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
  7654. *
  7655. * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
  7656. */ function Ur(t) {
  7657. return Lr(t) || qr(t) ||
  7658. /**
  7659. * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  7660. * field filters. e.g. (a == 10) || (b==20 && c==30)
  7661. */
  7662. function(t) {
  7663. if (t instanceof gn && pn(t)) {
  7664. for (const e of t.getFilters()) if (!Lr(e) && !qr(e)) return !1;
  7665. return !0;
  7666. }
  7667. return !1;
  7668. }(t);
  7669. }
  7670. function Kr(t) {
  7671. if (F(t instanceof mn || t instanceof gn), t instanceof mn) return t;
  7672. if (1 === t.filters.length) return Kr(t.filters[0]);
  7673. // Compute DNF for each of the subfilters first
  7674. const e = t.filters.map((t => Kr(t)));
  7675. let n = gn.create(e, t.op);
  7676. return n = jr(n), Ur(n) ? n : (F(n instanceof gn), F(yn(n)), F(n.filters.length > 1),
  7677. n.filters.reduce(((t, e) => Gr(t, e))));
  7678. }
  7679. function Gr(t, e) {
  7680. let n;
  7681. return F(t instanceof mn || t instanceof gn), F(e instanceof mn || e instanceof gn),
  7682. // FieldFilter FieldFilter
  7683. n = t instanceof mn ? e instanceof mn ? function(t, e) {
  7684. // Conjunction distribution for two field filters is the conjunction of them.
  7685. return gn.create([ t, e ], "and" /* CompositeOperator.AND */);
  7686. }(t, e) : Qr(t, e) : e instanceof mn ? Qr(e, t) : function(t, e) {
  7687. // There are four cases:
  7688. // (A & B) & (C & D) --> (A & B & C & D)
  7689. // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
  7690. // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
  7691. // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
  7692. // Case 1 is a merge.
  7693. if (F(t.filters.length > 0 && e.filters.length > 0), yn(t) && yn(e)) return vn(t, e.getFilters());
  7694. // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
  7695. // we should take each element of the disjunction and distribute it over the other side, and
  7696. // return the disjunction of the distribution results.
  7697. const n = pn(t) ? t : e, s = pn(t) ? e : t, i = n.filters.map((t => Gr(t, s)));
  7698. return gn.create(i, "or" /* CompositeOperator.OR */);
  7699. }(t, e), jr(n);
  7700. }
  7701. function Qr(t, e) {
  7702. // There are two cases:
  7703. // A & (B & C) --> (A & B & C)
  7704. // A & (B | C) --> (A & B) | (A & C)
  7705. if (yn(e))
  7706. // Case 1
  7707. return vn(e, t.getFilters());
  7708. {
  7709. // Case 2
  7710. const n = e.filters.map((e => Gr(t, e)));
  7711. return gn.create(n, "or" /* CompositeOperator.OR */);
  7712. }
  7713. }
  7714. /**
  7715. * Applies the associativity property to the given filter and returns the resulting filter.
  7716. *
  7717. * <ul>
  7718. * <li>A | (B | C) == (A | B) | C == (A | B | C)
  7719. * <li>A & (B & C) == (A & B) & C == (A & B & C)
  7720. * </ul>
  7721. *
  7722. * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
  7723. */ function jr(t) {
  7724. if (F(t instanceof mn || t instanceof gn), t instanceof mn) return t;
  7725. const e = t.getFilters();
  7726. // If the composite filter only contains 1 filter, apply associativity to it.
  7727. if (1 === e.length) return jr(e[0]);
  7728. // Associativity applied to a flat composite filter results is itself.
  7729. if (Tn(t)) return t;
  7730. // First apply associativity to all subfilters. This will in turn recursively apply
  7731. // associativity to all nested composite filters and field filters.
  7732. const n = e.map((t => jr(t))), s = [];
  7733. // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
  7734. // take out their filters and add them to `compositeFilter`. For example:
  7735. // compositeFilter = (A | (B | C | D))
  7736. // compositeSubfilter = (B | C | D)
  7737. // Result: (A | B | C | D)
  7738. // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
  7739. // added to the top-level "compositeFilter".
  7740. return n.forEach((e => {
  7741. e instanceof mn ? s.push(e) : e instanceof gn && (e.op === t.op ?
  7742. // compositeFilter: (A | (B | C))
  7743. // compositeSubfilter: (B | C)
  7744. // Result: (A | B | C)
  7745. s.push(...e.filters) :
  7746. // compositeFilter: (A | (B & C))
  7747. // compositeSubfilter: (B & C)
  7748. // Result: (A | (B & C))
  7749. s.push(e));
  7750. })), 1 === s.length ? s[0] : gn.create(s, t.op);
  7751. }
  7752. /**
  7753. * @license
  7754. * Copyright 2019 Google LLC
  7755. *
  7756. * Licensed under the Apache License, Version 2.0 (the "License");
  7757. * you may not use this file except in compliance with the License.
  7758. * You may obtain a copy of the License at
  7759. *
  7760. * http://www.apache.org/licenses/LICENSE-2.0
  7761. *
  7762. * Unless required by applicable law or agreed to in writing, software
  7763. * distributed under the License is distributed on an "AS IS" BASIS,
  7764. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7765. * See the License for the specific language governing permissions and
  7766. * limitations under the License.
  7767. */
  7768. /**
  7769. * An in-memory implementation of IndexManager.
  7770. */ class zr {
  7771. constructor() {
  7772. this.rn = new Wr;
  7773. }
  7774. addToCollectionParentIndex(t, e) {
  7775. return this.rn.add(e), Rt.resolve();
  7776. }
  7777. getCollectionParents(t, e) {
  7778. return Rt.resolve(this.rn.getEntries(e));
  7779. }
  7780. addFieldIndex(t, e) {
  7781. // Field indices are not supported with memory persistence.
  7782. return Rt.resolve();
  7783. }
  7784. deleteFieldIndex(t, e) {
  7785. // Field indices are not supported with memory persistence.
  7786. return Rt.resolve();
  7787. }
  7788. getDocumentsMatchingTarget(t, e) {
  7789. // Field indices are not supported with memory persistence.
  7790. return Rt.resolve(null);
  7791. }
  7792. getIndexType(t, e) {
  7793. // Field indices are not supported with memory persistence.
  7794. return Rt.resolve(0 /* IndexType.NONE */);
  7795. }
  7796. getFieldIndexes(t, e) {
  7797. // Field indices are not supported with memory persistence.
  7798. return Rt.resolve([]);
  7799. }
  7800. getNextCollectionGroupToUpdate(t) {
  7801. // Field indices are not supported with memory persistence.
  7802. return Rt.resolve(null);
  7803. }
  7804. getMinOffset(t, e) {
  7805. return Rt.resolve(It.min());
  7806. }
  7807. getMinOffsetFromCollectionGroup(t, e) {
  7808. return Rt.resolve(It.min());
  7809. }
  7810. updateCollectionGroup(t, e, n) {
  7811. // Field indices are not supported with memory persistence.
  7812. return Rt.resolve();
  7813. }
  7814. updateIndexEntries(t, e) {
  7815. // Field indices are not supported with memory persistence.
  7816. return Rt.resolve();
  7817. }
  7818. }
  7819. /**
  7820. * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
  7821. * Also used for in-memory caching by IndexedDbIndexManager and initial index population
  7822. * in indexeddb_schema.ts
  7823. */ class Wr {
  7824. constructor() {
  7825. this.index = {};
  7826. }
  7827. // Returns false if the entry already existed.
  7828. add(t) {
  7829. const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new Ee(ut.comparator), i = !s.has(n);
  7830. return this.index[e] = s.add(n), i;
  7831. }
  7832. has(t) {
  7833. const e = t.lastSegment(), n = t.popLast(), s = this.index[e];
  7834. return s && s.has(n);
  7835. }
  7836. getEntries(t) {
  7837. return (this.index[t] || new Ee(ut.comparator)).toArray();
  7838. }
  7839. }
  7840. /**
  7841. * @license
  7842. * Copyright 2019 Google LLC
  7843. *
  7844. * Licensed under the Apache License, Version 2.0 (the "License");
  7845. * you may not use this file except in compliance with the License.
  7846. * You may obtain a copy of the License at
  7847. *
  7848. * http://www.apache.org/licenses/LICENSE-2.0
  7849. *
  7850. * Unless required by applicable law or agreed to in writing, software
  7851. * distributed under the License is distributed on an "AS IS" BASIS,
  7852. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7853. * See the License for the specific language governing permissions and
  7854. * limitations under the License.
  7855. */ const Hr = new Uint8Array(0);
  7856. /**
  7857. * A persisted implementation of IndexManager.
  7858. *
  7859. * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index
  7860. * data as it supports multi-tab access.
  7861. */
  7862. class Jr {
  7863. constructor(t, e) {
  7864. this.user = t, this.databaseId = e,
  7865. /**
  7866. * An in-memory copy of the index entries we've already written since the SDK
  7867. * launched. Used to avoid re-writing the same entry repeatedly.
  7868. *
  7869. * This is *NOT* a complete cache of what's in persistence and so can never be
  7870. * used to satisfy reads.
  7871. */
  7872. this.on = new Wr,
  7873. /**
  7874. * Maps from a target to its equivalent list of sub-targets. Each sub-target
  7875. * contains only one term from the target's disjunctive normal form (DNF).
  7876. */
  7877. this.un = new os((t => $n(t)), ((t, e) => On(t, e))), this.uid = t.uid || "";
  7878. }
  7879. /**
  7880. * Adds a new entry to the collection parent index.
  7881. *
  7882. * Repeated calls for the same collectionPath should be avoided within a
  7883. * transaction as IndexedDbIndexManager only caches writes once a transaction
  7884. * has been committed.
  7885. */ addToCollectionParentIndex(t, e) {
  7886. if (!this.on.has(e)) {
  7887. const n = e.lastSegment(), s = e.popLast();
  7888. t.addOnCommittedListener((() => {
  7889. // Add the collection to the in memory cache only if the transaction was
  7890. // successfully committed.
  7891. this.on.add(e);
  7892. }));
  7893. const i = {
  7894. collectionId: n,
  7895. parent: qt(s)
  7896. };
  7897. return Yr(t).put(i);
  7898. }
  7899. return Rt.resolve();
  7900. }
  7901. getCollectionParents(t, e) {
  7902. const n = [], s = IDBKeyRange.bound([ e, "" ], [ st(e), "" ],
  7903. /*lowerOpen=*/ !1,
  7904. /*upperOpen=*/ !0);
  7905. return Yr(t).j(s).next((t => {
  7906. for (const s of t) {
  7907. // This collectionId guard shouldn't be necessary (and isn't as long
  7908. // as we're running in a real browser), but there's a bug in
  7909. // indexeddbshim that breaks our range in our tests running in node:
  7910. // https://github.com/axemclion/IndexedDBShim/issues/334
  7911. if (s.collectionId !== e) break;
  7912. n.push(Gt(s.parent));
  7913. }
  7914. return n;
  7915. }));
  7916. }
  7917. addFieldIndex(t, e) {
  7918. // TODO(indexing): Verify that the auto-incrementing index ID works in
  7919. // Safari & Firefox.
  7920. const n = Zr(t), s = function(t) {
  7921. return {
  7922. indexId: t.indexId,
  7923. collectionGroup: t.collectionGroup,
  7924. fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))
  7925. };
  7926. }(e);
  7927. delete s.indexId;
  7928. // `indexId` is auto-populated by IndexedDb
  7929. const i = n.add(s);
  7930. if (e.indexState) {
  7931. const n = to(t);
  7932. return i.next((t => {
  7933. n.put(Tr(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));
  7934. }));
  7935. }
  7936. return i.next();
  7937. }
  7938. deleteFieldIndex(t, e) {
  7939. const n = Zr(t), s = to(t), i = Xr(t);
  7940. return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7941. /*lowerOpen=*/ !1,
  7942. /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7943. /*lowerOpen=*/ !1,
  7944. /*upperOpen=*/ !0))));
  7945. }
  7946. getDocumentsMatchingTarget(t, e) {
  7947. const n = Xr(t);
  7948. let s = !0;
  7949. const i = new Map;
  7950. return Rt.forEach(this.cn(e), (e => this.an(t, e).next((t => {
  7951. s && (s = !!t), i.set(e, t);
  7952. })))).next((() => {
  7953. if (s) {
  7954. let t = gs();
  7955. const s = [];
  7956. return Rt.forEach(i, ((i, r) => {
  7957. var o;
  7958. N("IndexedDbIndexManager", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(",")}`} to execute ${$n(e)}`);
  7959. const u = function(t, e) {
  7960. const n = ft(e);
  7961. if (void 0 === n) return null;
  7962. for (const e of Bn(t, n.fieldPath)) switch (e.op) {
  7963. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  7964. return e.value.arrayValue.values || [];
  7965. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  7966. return [ e.value ];
  7967. // Remaining filters are not array filters.
  7968. }
  7969. return null;
  7970. }
  7971. /**
  7972. * Returns the list of values that are used in != or NOT_IN filters. Returns
  7973. * `null` if there are no such filters.
  7974. */ (r, i), c = function(t, e) {
  7975. const n = new Map;
  7976. for (const s of dt(e)) for (const e of Bn(t, s.fieldPath)) switch (e.op) {
  7977. case "==" /* Operator.EQUAL */ :
  7978. case "in" /* Operator.IN */ :
  7979. // Encode equality prefix, which is encoded in the index value before
  7980. // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
  7981. // `value != 'ab'`).
  7982. n.set(s.fieldPath.canonicalString(), e.value);
  7983. break;
  7984. case "not-in" /* Operator.NOT_IN */ :
  7985. case "!=" /* Operator.NOT_EQUAL */ :
  7986. // NotIn/NotEqual is always a suffix. There cannot be any remaining
  7987. // segments and hence we can return early here.
  7988. return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());
  7989. // Remaining filters cannot be used as notIn bounds.
  7990. }
  7991. return null;
  7992. }
  7993. /**
  7994. * Returns a lower bound of field values that can be used as a starting point to
  7995. * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
  7996. * exists.
  7997. */ (r, i), a = function(t, e) {
  7998. const n = [];
  7999. let s = !0;
  8000. // For each segment, retrieve a lower bound if there is a suitable filter or
  8001. // startAt.
  8002. for (const i of dt(e)) {
  8003. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? Ln(t, i.fieldPath, t.startAt) : qn(t, i.fieldPath, t.startAt);
  8004. n.push(e.value), s && (s = e.inclusive);
  8005. }
  8006. return new hn(n, s);
  8007. }
  8008. /**
  8009. * Returns an upper bound of field values that can be used as an ending point
  8010. * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
  8011. * upper bound exists.
  8012. */ (r, i), h = function(t, e) {
  8013. const n = [];
  8014. let s = !0;
  8015. // For each segment, retrieve an upper bound if there is a suitable filter or
  8016. // endAt.
  8017. for (const i of dt(e)) {
  8018. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? qn(t, i.fieldPath, t.endAt) : Ln(t, i.fieldPath, t.endAt);
  8019. n.push(e.value), s && (s = e.inclusive);
  8020. }
  8021. return new hn(n, s);
  8022. }(r, i), l = this.hn(i, r, a), f = this.hn(i, r, h), d = this.ln(i, r, c), w = this.fn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);
  8023. return Rt.forEach(w, (i => n.H(i, e.limit).next((e => {
  8024. e.forEach((e => {
  8025. const n = ht.fromSegments(e.documentKey);
  8026. t.has(n) || (t = t.add(n), s.push(n));
  8027. }));
  8028. }))));
  8029. })).next((() => s));
  8030. }
  8031. return Rt.resolve(null);
  8032. }));
  8033. }
  8034. cn(t) {
  8035. let e = this.un.get(t);
  8036. if (e) return e;
  8037. if (0 === t.filters.length) e = [ t ]; else {
  8038. e = Br(gn.create(t.filters, "and" /* CompositeOperator.AND */)).map((e => Mn(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));
  8039. }
  8040. return this.un.set(t, e), e;
  8041. }
  8042. /**
  8043. * Constructs a key range query on `DbIndexEntryStore` that unions all
  8044. * bounds.
  8045. */ fn(t, e, n, s, i, r, o) {
  8046. // The number of total index scans we union together. This is similar to a
  8047. // distributed normal form, but adapted for array values. We create a single
  8048. // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
  8049. // combined with the values from the query bounds.
  8050. const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];
  8051. for (let h = 0; h < u; ++h) {
  8052. const u = e ? this.dn(e[h / c]) : Hr, l = this.wn(t, u, n[h % c], s), f = this._n(t, u, i[h % c], r), d = o.map((e => this.wn(t, u, e,
  8053. /* inclusive= */ !0)));
  8054. a.push(...this.createRange(l, f, d));
  8055. }
  8056. return a;
  8057. }
  8058. /** Generates the lower bound for `arrayValue` and `directionalValue`. */ wn(t, e, n, s) {
  8059. const i = new kr(t, ht.empty(), e, n);
  8060. return s ? i : i.Je();
  8061. }
  8062. /** Generates the upper bound for `arrayValue` and `directionalValue`. */ _n(t, e, n, s) {
  8063. const i = new kr(t, ht.empty(), e, n);
  8064. return s ? i.Je() : i;
  8065. }
  8066. an(t, e) {
  8067. const n = new Or(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();
  8068. return this.getFieldIndexes(t, s).next((t => {
  8069. // Return the index with the most number of segments.
  8070. let e = null;
  8071. for (const s of t) {
  8072. n.tn(s) && (!e || s.fields.length > e.fields.length) && (e = s);
  8073. }
  8074. return e;
  8075. }));
  8076. }
  8077. getIndexType(t, e) {
  8078. let n = 2 /* IndexType.FULL */;
  8079. const s = this.cn(e);
  8080. return Rt.forEach(s, (e => this.an(t, e).next((t => {
  8081. t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {
  8082. let e = new Ee(at.comparator), n = !1;
  8083. for (const s of t.filters) for (const t of s.getFlattenedFilters())
  8084. // __name__ is not an explicit segment of any index, so we don't need to
  8085. // count it.
  8086. t.field.isKeyField() || (
  8087. // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
  8088. // For instance, it is possible to have an index for "a ARRAY a ASC". Even
  8089. // though these are on the same field, they should be counted as two
  8090. // separate segments in an index.
  8091. "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));
  8092. for (const n of t.orderBy)
  8093. // __name__ is not an explicit segment of any index, so we don't need to
  8094. // count it.
  8095. n.field.isKeyField() || (e = e.add(n.field));
  8096. return e.size + (n ? 1 : 0);
  8097. }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;
  8098. })))).next((() =>
  8099. // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
  8100. // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
  8101. // and apply the limit in memory as a post-processing step.
  8102. function(t) {
  8103. return null !== t.limit;
  8104. }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));
  8105. }
  8106. /**
  8107. * Returns the byte encoded form of the directional values in the field index.
  8108. * Returns `null` if the document does not have all fields specified in the
  8109. * index.
  8110. */ mn(t, e) {
  8111. const n = new Nr;
  8112. for (const s of dt(t)) {
  8113. const t = e.data.field(s.fieldPath);
  8114. if (null == t) return null;
  8115. const i = n.He(s.kind);
  8116. br.Ve._e(t, i);
  8117. }
  8118. return n.Qe();
  8119. }
  8120. /** Encodes a single value to the ascending index format. */ dn(t) {
  8121. const e = new Nr;
  8122. return br.Ve._e(t, e.He(0 /* IndexKind.ASCENDING */)), e.Qe();
  8123. }
  8124. /**
  8125. * Returns an encoded form of the document key that sorts based on the key
  8126. * ordering of the field index.
  8127. */ gn(t, e) {
  8128. const n = new Nr;
  8129. return br.Ve._e(We(this.databaseId, e), n.He(function(t) {
  8130. const e = dt(t);
  8131. return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;
  8132. }(t))), n.Qe();
  8133. }
  8134. /**
  8135. * Encodes the given field values according to the specification in `target`.
  8136. * For IN queries, a list of possible values is returned.
  8137. */ ln(t, e, n) {
  8138. if (null === n) return [];
  8139. let s = [];
  8140. s.push(new Nr);
  8141. let i = 0;
  8142. for (const r of dt(t)) {
  8143. const t = n[i++];
  8144. for (const n of s) if (this.yn(e, r.fieldPath) && Je(t)) s = this.pn(s, r, t); else {
  8145. const e = n.He(r.kind);
  8146. br.Ve._e(t, e);
  8147. }
  8148. }
  8149. return this.In(s);
  8150. }
  8151. /**
  8152. * Encodes the given bounds according to the specification in `target`. For IN
  8153. * queries, a list of possible values is returned.
  8154. */ hn(t, e, n) {
  8155. return this.ln(t, e, n.position);
  8156. }
  8157. /** Returns the byte representation for the provided encoders. */ In(t) {
  8158. const e = [];
  8159. for (let n = 0; n < t.length; ++n) e[n] = t[n].Qe();
  8160. return e;
  8161. }
  8162. /**
  8163. * Creates a separate encoder for each element of an array.
  8164. *
  8165. * The method appends each value to all existing encoders (e.g. filter("a",
  8166. * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
  8167. * list of new encoders is returned.
  8168. */ pn(t, e, n) {
  8169. const s = [ ...t ], i = [];
  8170. for (const t of n.arrayValue.values || []) for (const n of s) {
  8171. const s = new Nr;
  8172. s.seed(n.Qe()), br.Ve._e(t, s.He(e.kind)), i.push(s);
  8173. }
  8174. return i;
  8175. }
  8176. yn(t, e) {
  8177. return !!t.filters.find((t => t instanceof mn && t.field.isEqual(e) && ("in" /* Operator.IN */ === t.op || "not-in" /* Operator.NOT_IN */ === t.op)));
  8178. }
  8179. getFieldIndexes(t, e) {
  8180. const n = Zr(t), s = to(t);
  8181. return (e ? n.j("collectionGroupIndex", IDBKeyRange.bound(e, e)) : n.j()).next((t => {
  8182. const e = [];
  8183. return Rt.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {
  8184. e.push(function(t, e) {
  8185. const n = e ? new gt(e.sequenceNumber, new It(wr(e.readTime), new ht(Gt(e.documentKey)), e.largestBatchId)) : gt.empty(), s = t.fields.map((([t, e]) => new _t(at.fromServerFormat(t), e)));
  8186. return new lt(t.indexId, t.collectionGroup, s, n);
  8187. }(t, n));
  8188. })))).next((() => e));
  8189. }));
  8190. }
  8191. getNextCollectionGroupToUpdate(t) {
  8192. return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {
  8193. const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;
  8194. return 0 !== n ? n : et(t.collectionGroup, e.collectionGroup);
  8195. })), t[0].collectionGroup)));
  8196. }
  8197. updateCollectionGroup(t, e, n) {
  8198. const s = Zr(t), i = to(t);
  8199. return this.Tn(t).next((t => s.j("collectionGroupIndex", IDBKeyRange.bound(e, e)).next((e => Rt.forEach(e, (e => i.put(Tr(e.indexId, this.user, t, n))))))));
  8200. }
  8201. updateIndexEntries(t, e) {
  8202. // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
  8203. // it could be used across different IndexedDB transactions. As any cached
  8204. // data might be invalidated by other multi-tab clients, we can only trust
  8205. // data within a single IndexedDB transaction. We therefore add a cache
  8206. // here.
  8207. const n = new Map;
  8208. return Rt.forEach(e, ((e, s) => {
  8209. const i = n.get(e.collectionGroup);
  8210. return (i ? Rt.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i),
  8211. Rt.forEach(i, (n => this.En(t, e, n).next((e => {
  8212. const i = this.An(s, n);
  8213. return e.isEqual(i) ? Rt.resolve() : this.vn(t, s, n, e, i);
  8214. })))))));
  8215. }));
  8216. }
  8217. Rn(t, e, n, s) {
  8218. return Xr(t).put({
  8219. indexId: s.indexId,
  8220. uid: this.uid,
  8221. arrayValue: s.arrayValue,
  8222. directionalValue: s.directionalValue,
  8223. orderedDocumentKey: this.gn(n, e.key),
  8224. documentKey: e.key.path.toArray()
  8225. });
  8226. }
  8227. Pn(t, e, n, s) {
  8228. return Xr(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.gn(n, e.key), e.key.path.toArray() ]);
  8229. }
  8230. En(t, e, n) {
  8231. const s = Xr(t);
  8232. let i = new Ee(Mr);
  8233. return s.X({
  8234. index: "documentKeyIndex",
  8235. range: IDBKeyRange.only([ n.indexId, this.uid, this.gn(n, e) ])
  8236. }, ((t, s) => {
  8237. i = i.add(new kr(n.indexId, e, s.arrayValue, s.directionalValue));
  8238. })).next((() => i));
  8239. }
  8240. /** Creates the index entries for the given document. */ An(t, e) {
  8241. let n = new Ee(Mr);
  8242. const s = this.mn(e, t);
  8243. if (null == s) return n;
  8244. const i = ft(e);
  8245. if (null != i) {
  8246. const r = t.data.field(i.fieldPath);
  8247. if (Je(r)) for (const i of r.arrayValue.values || []) n = n.add(new kr(e.indexId, t.key, this.dn(i), s));
  8248. } else n = n.add(new kr(e.indexId, t.key, Hr, s));
  8249. return n;
  8250. }
  8251. /**
  8252. * Updates the index entries for the provided document by deleting entries
  8253. * that are no longer referenced in `newEntries` and adding all newly added
  8254. * entries.
  8255. */ vn(t, e, n, s, i) {
  8256. N("IndexedDbIndexManager", "Updating index entries for document '%s'", e.key);
  8257. const r = [];
  8258. return function(t, e, n, s, i) {
  8259. const r = t.getIterator(), o = e.getIterator();
  8260. let u = ve(r), c = ve(o);
  8261. // Walk through the two sets at the same time, using the ordering defined by
  8262. // `comparator`.
  8263. for (;u || c; ) {
  8264. let t = !1, e = !1;
  8265. if (u && c) {
  8266. const s = n(u, c);
  8267. s < 0 ?
  8268. // The element was removed if the next element in our ordered
  8269. // walkthrough is only in `before`.
  8270. e = !0 : s > 0 && (
  8271. // The element was added if the next element in our ordered walkthrough
  8272. // is only in `after`.
  8273. t = !0);
  8274. } else null != u ? e = !0 : t = !0;
  8275. t ? (s(c), c = ve(o)) : e ? (i(u), u = ve(r)) : (u = ve(r), c = ve(o));
  8276. }
  8277. }(s, i, Mr, (
  8278. /* onAdd= */ s => {
  8279. r.push(this.Rn(t, e, n, s));
  8280. }), (
  8281. /* onRemove= */ s => {
  8282. r.push(this.Pn(t, e, n, s));
  8283. })), Rt.waitFor(r);
  8284. }
  8285. Tn(t) {
  8286. let e = 1;
  8287. return to(t).X({
  8288. index: "sequenceNumberIndex",
  8289. reverse: !0,
  8290. range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
  8291. }, ((t, n, s) => {
  8292. s.done(), e = n.sequenceNumber + 1;
  8293. })).next((() => e));
  8294. }
  8295. /**
  8296. * Returns a new set of IDB ranges that splits the existing range and excludes
  8297. * any values that match the `notInValue` from these ranges. As an example,
  8298. * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
  8299. */ createRange(t, e, n) {
  8300. // The notIn values need to be sorted and unique so that we can return a
  8301. // sorted set of non-overlapping ranges.
  8302. n = n.sort(((t, e) => Mr(t, e))).filter(((t, e, n) => !e || 0 !== Mr(t, n[e - 1])));
  8303. const s = [];
  8304. s.push(t);
  8305. for (const i of n) {
  8306. const n = Mr(i, t), r = Mr(i, e);
  8307. if (0 === n)
  8308. // `notInValue` is the lower bound. We therefore need to raise the bound
  8309. // to the next value.
  8310. s[0] = t.Je(); else if (n > 0 && r < 0)
  8311. // `notInValue` is in the middle of the range
  8312. s.push(i), s.push(i.Je()); else if (r > 0)
  8313. // `notInValue` (and all following values) are out of the range
  8314. break;
  8315. }
  8316. s.push(e);
  8317. const i = [];
  8318. for (let t = 0; t < s.length; t += 2) {
  8319. // If we encounter two bounds that will create an unmatchable key range,
  8320. // then we return an empty set of key ranges.
  8321. if (this.bn(s[t], s[t + 1])) return [];
  8322. const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Hr, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Hr, [] ];
  8323. i.push(IDBKeyRange.bound(e, n));
  8324. }
  8325. return i;
  8326. }
  8327. bn(t, e) {
  8328. // If lower bound is greater than the upper bound, then the key
  8329. // range can never be matched.
  8330. return Mr(t, e) > 0;
  8331. }
  8332. getMinOffsetFromCollectionGroup(t, e) {
  8333. return this.getFieldIndexes(t, e).next(eo);
  8334. }
  8335. getMinOffset(t, e) {
  8336. return Rt.mapArray(this.cn(e), (e => this.an(t, e).next((t => t || O())))).next(eo);
  8337. }
  8338. }
  8339. /**
  8340. * Helper to get a typed SimpleDbStore for the collectionParents
  8341. * document store.
  8342. */ function Yr(t) {
  8343. return _e(t, "collectionParents");
  8344. }
  8345. /**
  8346. * Helper to get a typed SimpleDbStore for the index entry object store.
  8347. */ function Xr(t) {
  8348. return _e(t, "indexEntries");
  8349. }
  8350. /**
  8351. * Helper to get a typed SimpleDbStore for the index configuration object store.
  8352. */ function Zr(t) {
  8353. return _e(t, "indexConfiguration");
  8354. }
  8355. /**
  8356. * Helper to get a typed SimpleDbStore for the index state object store.
  8357. */ function to(t) {
  8358. return _e(t, "indexState");
  8359. }
  8360. function eo(t) {
  8361. F(0 !== t.length);
  8362. let e = t[0].indexState.offset, n = e.largestBatchId;
  8363. for (let s = 1; s < t.length; s++) {
  8364. const i = t[s].indexState.offset;
  8365. Tt(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);
  8366. }
  8367. return new It(e.readTime, e.documentKey, n);
  8368. }
  8369. /**
  8370. * @license
  8371. * Copyright 2018 Google LLC
  8372. *
  8373. * Licensed under the Apache License, Version 2.0 (the "License");
  8374. * you may not use this file except in compliance with the License.
  8375. * You may obtain a copy of the License at
  8376. *
  8377. * http://www.apache.org/licenses/LICENSE-2.0
  8378. *
  8379. * Unless required by applicable law or agreed to in writing, software
  8380. * distributed under the License is distributed on an "AS IS" BASIS,
  8381. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8382. * See the License for the specific language governing permissions and
  8383. * limitations under the License.
  8384. */ const no = {
  8385. didRun: !1,
  8386. sequenceNumbersCollected: 0,
  8387. targetsRemoved: 0,
  8388. documentsRemoved: 0
  8389. };
  8390. class so {
  8391. constructor(
  8392. // When we attempt to collect, we will only do so if the cache size is greater than this
  8393. // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
  8394. t,
  8395. // The percentage of sequence numbers that we will attempt to collect
  8396. e,
  8397. // A cap on the total number of sequence numbers that will be collected. This prevents
  8398. // us from collecting a huge number of sequence numbers if the cache has grown very large.
  8399. n) {
  8400. this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
  8401. }
  8402. static withCacheSize(t) {
  8403. return new so(t, so.DEFAULT_COLLECTION_PERCENTILE, so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  8404. }
  8405. }
  8406. /**
  8407. * @license
  8408. * Copyright 2020 Google LLC
  8409. *
  8410. * Licensed under the Apache License, Version 2.0 (the "License");
  8411. * you may not use this file except in compliance with the License.
  8412. * You may obtain a copy of the License at
  8413. *
  8414. * http://www.apache.org/licenses/LICENSE-2.0
  8415. *
  8416. * Unless required by applicable law or agreed to in writing, software
  8417. * distributed under the License is distributed on an "AS IS" BASIS,
  8418. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8419. * See the License for the specific language governing permissions and
  8420. * limitations under the License.
  8421. */
  8422. /**
  8423. * Delete a mutation batch and the associated document mutations.
  8424. * @returns A PersistencePromise of the document mutations that were removed.
  8425. */
  8426. function io(t, e, n) {
  8427. const s = t.store("mutations"), i = t.store("documentMutations"), r = [], o = IDBKeyRange.only(n.batchId);
  8428. let u = 0;
  8429. const c = s.X({
  8430. range: o
  8431. }, ((t, e, n) => (u++, n.delete())));
  8432. r.push(c.next((() => {
  8433. F(1 === u);
  8434. })));
  8435. const a = [];
  8436. for (const t of n.mutations) {
  8437. const s = zt(e, t.key.path, n.batchId);
  8438. r.push(i.delete(s)), a.push(t.key);
  8439. }
  8440. return Rt.waitFor(r).next((() => a));
  8441. }
  8442. /**
  8443. * Returns an approximate size for the given document.
  8444. */ function ro(t) {
  8445. if (!t) return 0;
  8446. let e;
  8447. if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
  8448. if (!t.noDocument) throw O();
  8449. e = t.noDocument;
  8450. }
  8451. return JSON.stringify(e).length;
  8452. }
  8453. /**
  8454. * @license
  8455. * Copyright 2017 Google LLC
  8456. *
  8457. * Licensed under the Apache License, Version 2.0 (the "License");
  8458. * you may not use this file except in compliance with the License.
  8459. * You may obtain a copy of the License at
  8460. *
  8461. * http://www.apache.org/licenses/LICENSE-2.0
  8462. *
  8463. * Unless required by applicable law or agreed to in writing, software
  8464. * distributed under the License is distributed on an "AS IS" BASIS,
  8465. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8466. * See the License for the specific language governing permissions and
  8467. * limitations under the License.
  8468. */
  8469. /** A mutation queue for a specific user, backed by IndexedDB. */ so.DEFAULT_COLLECTION_PERCENTILE = 10,
  8470. so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, so.DEFAULT = new so(41943040, so.DEFAULT_COLLECTION_PERCENTILE, so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),
  8471. so.DISABLED = new so(-1, 0, 0);
  8472. class oo {
  8473. constructor(
  8474. /**
  8475. * The normalized userId (e.g. null UID => "" userId) used to store /
  8476. * retrieve mutations.
  8477. */
  8478. t, e, n, s) {
  8479. this.userId = t, this.serializer = e, this.indexManager = n, this.referenceDelegate = s,
  8480. /**
  8481. * Caches the document keys for pending mutation batches. If the mutation
  8482. * has been removed from IndexedDb, the cached value may continue to
  8483. * be used to retrieve the batch's document keys. To remove a cached value
  8484. * locally, `removeCachedMutationKeys()` should be invoked either directly
  8485. * or through `removeMutationBatches()`.
  8486. *
  8487. * With multi-tab, when the primary client acknowledges or rejects a mutation,
  8488. * this cache is used by secondary clients to invalidate the local
  8489. * view of the documents that were previously affected by the mutation.
  8490. */
  8491. // PORTING NOTE: Multi-tab only.
  8492. this.Vn = {};
  8493. }
  8494. /**
  8495. * Creates a new mutation queue for the given user.
  8496. * @param user - The user for which to create a mutation queue.
  8497. * @param serializer - The serializer to use when persisting to IndexedDb.
  8498. */ static de(t, e, n, s) {
  8499. // TODO(mcg): Figure out what constraints there are on userIDs
  8500. // In particular, are there any reserved characters? are empty ids allowed?
  8501. // For the moment store these together in the same mutations table assuming
  8502. // that empty userIDs aren't allowed.
  8503. F("" !== t.uid);
  8504. const i = t.isAuthenticated() ? t.uid : "";
  8505. return new oo(i, e, n, s);
  8506. }
  8507. checkEmpty(t) {
  8508. let e = !0;
  8509. const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8510. return co(t).X({
  8511. index: "userMutationsIndex",
  8512. range: n
  8513. }, ((t, n, s) => {
  8514. e = !1, s.done();
  8515. })).next((() => e));
  8516. }
  8517. addMutationBatch(t, e, n, s) {
  8518. const i = ao(t), r = co(t);
  8519. // The IndexedDb implementation in Chrome (and Firefox) does not handle
  8520. // compound indices that include auto-generated keys correctly. To ensure
  8521. // that the index entry is added correctly in all browsers, we perform two
  8522. // writes: The first write is used to retrieve the next auto-generated Batch
  8523. // ID, and the second write populates the index and stores the actual
  8524. // mutation batch.
  8525. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
  8526. // We write an empty object to obtain key
  8527. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8528. return r.add({}).next((o => {
  8529. F("number" == typeof o);
  8530. const u = new Zs(o, e, n, s), c = function(t, e, n) {
  8531. const s = n.baseMutations.map((e => ji(t.fe, e))), i = n.mutations.map((e => ji(t.fe, e)));
  8532. return {
  8533. userId: e,
  8534. batchId: n.batchId,
  8535. localWriteTimeMs: n.localWriteTime.toMillis(),
  8536. baseMutations: s,
  8537. mutations: i
  8538. };
  8539. }(this.serializer, this.userId, u), a = [];
  8540. let h = new Ee(((t, e) => et(t.canonicalString(), e.canonicalString())));
  8541. for (const t of s) {
  8542. const e = zt(this.userId, t.key.path, o);
  8543. h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, Wt));
  8544. }
  8545. return h.forEach((e => {
  8546. a.push(this.indexManager.addToCollectionParentIndex(t, e));
  8547. })), t.addOnCommittedListener((() => {
  8548. this.Vn[o] = u.keys();
  8549. })), Rt.waitFor(a).next((() => u));
  8550. }));
  8551. }
  8552. lookupMutationBatch(t, e) {
  8553. return co(t).get(e).next((t => t ? (F(t.userId === this.userId), _r(this.serializer, t)) : null));
  8554. }
  8555. /**
  8556. * Returns the document keys for the mutation batch with the given batchId.
  8557. * For primary clients, this method returns `null` after
  8558. * `removeMutationBatches()` has been called. Secondary clients return a
  8559. * cached result until `removeCachedMutationKeys()` is invoked.
  8560. */
  8561. // PORTING NOTE: Multi-tab only.
  8562. Sn(t, e) {
  8563. return this.Vn[e] ? Rt.resolve(this.Vn[e]) : this.lookupMutationBatch(t, e).next((t => {
  8564. if (t) {
  8565. const n = t.keys();
  8566. return this.Vn[e] = n, n;
  8567. }
  8568. return null;
  8569. }));
  8570. }
  8571. getNextMutationBatchAfterBatchId(t, e) {
  8572. const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);
  8573. let i = null;
  8574. return co(t).X({
  8575. index: "userMutationsIndex",
  8576. range: s
  8577. }, ((t, e, s) => {
  8578. e.userId === this.userId && (F(e.batchId >= n), i = _r(this.serializer, e)), s.done();
  8579. })).next((() => i));
  8580. }
  8581. getHighestUnacknowledgedBatchId(t) {
  8582. const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
  8583. let n = -1;
  8584. return co(t).X({
  8585. index: "userMutationsIndex",
  8586. range: e,
  8587. reverse: !0
  8588. }, ((t, e, s) => {
  8589. n = e.batchId, s.done();
  8590. })).next((() => n));
  8591. }
  8592. getAllMutationBatches(t) {
  8593. const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8594. return co(t).j("userMutationsIndex", e).next((t => t.map((t => _r(this.serializer, t)))));
  8595. }
  8596. getAllMutationBatchesAffectingDocumentKey(t, e) {
  8597. // Scan the document-mutation index starting with a prefix starting with
  8598. // the given documentKey.
  8599. const n = jt(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];
  8600. return ao(t).X({
  8601. range: s
  8602. }, ((n, s, r) => {
  8603. const [o, u, c] = n, a = Gt(u);
  8604. // Only consider rows matching exactly the specific key of
  8605. // interest. Note that because we order by path first, and we
  8606. // order terminators before path separators, we'll encounter all
  8607. // the index rows for documentKey contiguously. In particular, all
  8608. // the rows for documentKey will occur before any rows for
  8609. // documents nested in a subcollection beneath documentKey so we
  8610. // can stop as soon as we hit any such row.
  8611. if (o === this.userId && e.path.isEqual(a))
  8612. // Look up the mutation batch in the store.
  8613. return co(t).get(c).next((t => {
  8614. if (!t) throw O();
  8615. F(t.userId === this.userId), i.push(_r(this.serializer, t));
  8616. }));
  8617. r.done();
  8618. })).next((() => i));
  8619. }
  8620. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  8621. let n = new Ee(et);
  8622. const s = [];
  8623. return e.forEach((e => {
  8624. const i = jt(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = ao(t).X({
  8625. range: r
  8626. }, ((t, s, i) => {
  8627. const [r, o, u] = t, c = Gt(o);
  8628. // Only consider rows matching exactly the specific key of
  8629. // interest. Note that because we order by path first, and we
  8630. // order terminators before path separators, we'll encounter all
  8631. // the index rows for documentKey contiguously. In particular, all
  8632. // the rows for documentKey will occur before any rows for
  8633. // documents nested in a subcollection beneath documentKey so we
  8634. // can stop as soon as we hit any such row.
  8635. r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();
  8636. }));
  8637. s.push(o);
  8638. })), Rt.waitFor(s).next((() => this.Dn(t, n)));
  8639. }
  8640. getAllMutationBatchesAffectingQuery(t, e) {
  8641. const n = e.path, s = n.length + 1, i = jt(this.userId, n), r = IDBKeyRange.lowerBound(i);
  8642. // Collect up unique batchIDs encountered during a scan of the index. Use a
  8643. // SortedSet to accumulate batch IDs so they can be traversed in order in a
  8644. // scan of the main table.
  8645. let o = new Ee(et);
  8646. return ao(t).X({
  8647. range: r
  8648. }, ((t, e, i) => {
  8649. const [r, u, c] = t, a = Gt(u);
  8650. r === this.userId && n.isPrefixOf(a) ?
  8651. // Rows with document keys more than one segment longer than the
  8652. // query path can't be matches. For example, a query on 'rooms'
  8653. // can't match the document /rooms/abc/messages/xyx.
  8654. // TODO(mcg): we'll need a different scanner when we implement
  8655. // ancestor queries.
  8656. a.length === s && (o = o.add(c)) : i.done();
  8657. })).next((() => this.Dn(t, o)));
  8658. }
  8659. Dn(t, e) {
  8660. const n = [], s = [];
  8661. // TODO(rockwood): Implement this using iterate.
  8662. return e.forEach((e => {
  8663. s.push(co(t).get(e).next((t => {
  8664. if (null === t) throw O();
  8665. F(t.userId === this.userId), n.push(_r(this.serializer, t));
  8666. })));
  8667. })), Rt.waitFor(s).next((() => n));
  8668. }
  8669. removeMutationBatch(t, e) {
  8670. return io(t.ht, this.userId, e).next((n => (t.addOnCommittedListener((() => {
  8671. this.Cn(e.batchId);
  8672. })), Rt.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));
  8673. }
  8674. /**
  8675. * Clears the cached keys for a mutation batch. This method should be
  8676. * called by secondary clients after they process mutation updates.
  8677. *
  8678. * Note that this method does not have to be called from primary clients as
  8679. * the corresponding cache entries are cleared when an acknowledged or
  8680. * rejected batch is removed from the mutation queue.
  8681. */
  8682. // PORTING NOTE: Multi-tab only
  8683. Cn(t) {
  8684. delete this.Vn[t];
  8685. }
  8686. performConsistencyCheck(t) {
  8687. return this.checkEmpty(t).next((e => {
  8688. if (!e) return Rt.resolve();
  8689. // Verify that there are no entries in the documentMutations index if
  8690. // the queue is empty.
  8691. const n = IDBKeyRange.lowerBound([ this.userId ]);
  8692. const s = [];
  8693. return ao(t).X({
  8694. range: n
  8695. }, ((t, e, n) => {
  8696. if (t[0] === this.userId) {
  8697. const e = Gt(t[1]);
  8698. s.push(e);
  8699. } else n.done();
  8700. })).next((() => {
  8701. F(0 === s.length);
  8702. }));
  8703. }));
  8704. }
  8705. containsKey(t, e) {
  8706. return uo(t, this.userId, e);
  8707. }
  8708. // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  8709. /** Returns the mutation queue's metadata from IndexedDb. */
  8710. xn(t) {
  8711. return ho(t).get(this.userId).next((t => t || {
  8712. userId: this.userId,
  8713. lastAcknowledgedBatchId: -1,
  8714. lastStreamToken: ""
  8715. }));
  8716. }
  8717. }
  8718. /**
  8719. * @returns true if the mutation queue for the given user contains a pending
  8720. * mutation for the given key.
  8721. */ function uo(t, e, n) {
  8722. const s = jt(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);
  8723. let o = !1;
  8724. return ao(t).X({
  8725. range: r,
  8726. Y: !0
  8727. }, ((t, n, s) => {
  8728. const [r, u, /*batchID*/ c] = t;
  8729. r === e && u === i && (o = !0), s.done();
  8730. })).next((() => o));
  8731. }
  8732. /** Returns true if any mutation queue contains the given document. */
  8733. /**
  8734. * Helper to get a typed SimpleDbStore for the mutations object store.
  8735. */
  8736. function co(t) {
  8737. return _e(t, "mutations");
  8738. }
  8739. /**
  8740. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8741. */ function ao(t) {
  8742. return _e(t, "documentMutations");
  8743. }
  8744. /**
  8745. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8746. */ function ho(t) {
  8747. return _e(t, "mutationQueues");
  8748. }
  8749. /**
  8750. * @license
  8751. * Copyright 2017 Google LLC
  8752. *
  8753. * Licensed under the Apache License, Version 2.0 (the "License");
  8754. * you may not use this file except in compliance with the License.
  8755. * You may obtain a copy of the License at
  8756. *
  8757. * http://www.apache.org/licenses/LICENSE-2.0
  8758. *
  8759. * Unless required by applicable law or agreed to in writing, software
  8760. * distributed under the License is distributed on an "AS IS" BASIS,
  8761. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8762. * See the License for the specific language governing permissions and
  8763. * limitations under the License.
  8764. */
  8765. /** Offset to ensure non-overlapping target ids. */
  8766. /**
  8767. * Generates monotonically increasing target IDs for sending targets to the
  8768. * watch stream.
  8769. *
  8770. * The client constructs two generators, one for the target cache, and one for
  8771. * for the sync engine (to generate limbo documents targets). These
  8772. * generators produce non-overlapping IDs (by using even and odd IDs
  8773. * respectively).
  8774. *
  8775. * By separating the target ID space, the query cache can generate target IDs
  8776. * that persist across client restarts, while sync engine can independently
  8777. * generate in-memory target IDs that are transient and can be reused after a
  8778. * restart.
  8779. */
  8780. class lo {
  8781. constructor(t) {
  8782. this.Nn = t;
  8783. }
  8784. next() {
  8785. return this.Nn += 2, this.Nn;
  8786. }
  8787. static kn() {
  8788. // The target cache generator must return '2' in its first call to `next()`
  8789. // as there is no differentiation in the protocol layer between an unset
  8790. // number and the number '0'. If we were to sent a target with target ID
  8791. // '0', the backend would consider it unset and replace it with its own ID.
  8792. return new lo(0);
  8793. }
  8794. static Mn() {
  8795. // Sync engine assigns target IDs for limbo document detection.
  8796. return new lo(-1);
  8797. }
  8798. }
  8799. /**
  8800. * @license
  8801. * Copyright 2017 Google LLC
  8802. *
  8803. * Licensed under the Apache License, Version 2.0 (the "License");
  8804. * you may not use this file except in compliance with the License.
  8805. * You may obtain a copy of the License at
  8806. *
  8807. * http://www.apache.org/licenses/LICENSE-2.0
  8808. *
  8809. * Unless required by applicable law or agreed to in writing, software
  8810. * distributed under the License is distributed on an "AS IS" BASIS,
  8811. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8812. * See the License for the specific language governing permissions and
  8813. * limitations under the License.
  8814. */ class fo {
  8815. constructor(t, e) {
  8816. this.referenceDelegate = t, this.serializer = e;
  8817. }
  8818. // PORTING NOTE: We don't cache global metadata for the target cache, since
  8819. // some of it (in particular `highestTargetId`) can be modified by secondary
  8820. // tabs. We could perhaps be more granular (and e.g. still cache
  8821. // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  8822. // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  8823. // out to have a meaningful performance impact.
  8824. allocateTargetId(t) {
  8825. return this.$n(t).next((e => {
  8826. const n = new lo(e.highestTargetId);
  8827. return e.highestTargetId = n.next(), this.On(t, e).next((() => e.highestTargetId));
  8828. }));
  8829. }
  8830. getLastRemoteSnapshotVersion(t) {
  8831. return this.$n(t).next((t => rt.fromTimestamp(new it(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));
  8832. }
  8833. getHighestSequenceNumber(t) {
  8834. return this.$n(t).next((t => t.highestListenSequenceNumber));
  8835. }
  8836. setTargetsMetadata(t, e, n) {
  8837. return this.$n(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()),
  8838. e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.On(t, s))));
  8839. }
  8840. addTargetData(t, e) {
  8841. return this.Fn(t, e).next((() => this.$n(t).next((n => (n.targetCount += 1, this.Bn(e, n),
  8842. this.On(t, n))))));
  8843. }
  8844. updateTargetData(t, e) {
  8845. return this.Fn(t, e);
  8846. }
  8847. removeTargetData(t, e) {
  8848. return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => wo(t).delete(e.targetId))).next((() => this.$n(t))).next((e => (F(e.targetCount > 0),
  8849. e.targetCount -= 1, this.On(t, e))));
  8850. }
  8851. /**
  8852. * Drops any targets with sequence number less than or equal to the upper bound, excepting those
  8853. * present in `activeTargetIds`. Document associations for the removed targets are also removed.
  8854. * Returns the number of targets removed.
  8855. */ removeTargets(t, e, n) {
  8856. let s = 0;
  8857. const i = [];
  8858. return wo(t).X(((r, o) => {
  8859. const u = mr(o);
  8860. u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));
  8861. })).next((() => Rt.waitFor(i))).next((() => s));
  8862. }
  8863. /**
  8864. * Call provided function with each `TargetData` that we have cached.
  8865. */ forEachTarget(t, e) {
  8866. return wo(t).X(((t, n) => {
  8867. const s = mr(n);
  8868. e(s);
  8869. }));
  8870. }
  8871. $n(t) {
  8872. return _o(t).get("targetGlobalKey").next((t => (F(null !== t), t)));
  8873. }
  8874. On(t, e) {
  8875. return _o(t).put("targetGlobalKey", e);
  8876. }
  8877. Fn(t, e) {
  8878. return wo(t).put(gr(this.serializer, e));
  8879. }
  8880. /**
  8881. * In-place updates the provided metadata to account for values in the given
  8882. * TargetData. Saving is done separately. Returns true if there were any
  8883. * changes to the metadata.
  8884. */ Bn(t, e) {
  8885. let n = !1;
  8886. return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0),
  8887. t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber,
  8888. n = !0), n;
  8889. }
  8890. getTargetCount(t) {
  8891. return this.$n(t).next((t => t.targetCount));
  8892. }
  8893. getTargetData(t, e) {
  8894. // Iterating by the canonicalId may yield more than one result because
  8895. // canonicalId values are not required to be unique per target. This query
  8896. // depends on the queryTargets index to be efficient.
  8897. const n = $n(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);
  8898. let i = null;
  8899. return wo(t).X({
  8900. range: s,
  8901. index: "queryTargetsIndex"
  8902. }, ((t, n, s) => {
  8903. const r = mr(n);
  8904. // After finding a potential match, check that the target is
  8905. // actually equal to the requested target.
  8906. On(e, r.target) && (i = r, s.done());
  8907. })).next((() => i));
  8908. }
  8909. addMatchingKeys(t, e, n) {
  8910. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8911. // IndexedDb.
  8912. const s = [], i = mo(t);
  8913. return e.forEach((e => {
  8914. const r = qt(e.path);
  8915. s.push(i.put({
  8916. targetId: n,
  8917. path: r
  8918. })), s.push(this.referenceDelegate.addReference(t, n, e));
  8919. })), Rt.waitFor(s);
  8920. }
  8921. removeMatchingKeys(t, e, n) {
  8922. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8923. // IndexedDb.
  8924. const s = mo(t);
  8925. return Rt.forEach(e, (e => {
  8926. const i = qt(e.path);
  8927. return Rt.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);
  8928. }));
  8929. }
  8930. removeMatchingKeysForTargetId(t, e) {
  8931. const n = mo(t), s = IDBKeyRange.bound([ e ], [ e + 1 ],
  8932. /*lowerOpen=*/ !1,
  8933. /*upperOpen=*/ !0);
  8934. return n.delete(s);
  8935. }
  8936. getMatchingKeysForTargetId(t, e) {
  8937. const n = IDBKeyRange.bound([ e ], [ e + 1 ],
  8938. /*lowerOpen=*/ !1,
  8939. /*upperOpen=*/ !0), s = mo(t);
  8940. let i = gs();
  8941. return s.X({
  8942. range: n,
  8943. Y: !0
  8944. }, ((t, e, n) => {
  8945. const s = Gt(t[1]), r = new ht(s);
  8946. i = i.add(r);
  8947. })).next((() => i));
  8948. }
  8949. containsKey(t, e) {
  8950. const n = qt(e.path), s = IDBKeyRange.bound([ n ], [ st(n) ],
  8951. /*lowerOpen=*/ !1,
  8952. /*upperOpen=*/ !0);
  8953. let i = 0;
  8954. return mo(t).X({
  8955. index: "documentTargetsIndex",
  8956. Y: !0,
  8957. range: s
  8958. }, (([t, e], n, s) => {
  8959. // Having a sentinel row for a document does not count as containing that document;
  8960. // For the target cache, containing the document means the document is part of some
  8961. // target.
  8962. 0 !== t && (i++, s.done());
  8963. })).next((() => i > 0));
  8964. }
  8965. /**
  8966. * Looks up a TargetData entry by target ID.
  8967. *
  8968. * @param targetId - The target ID of the TargetData entry to look up.
  8969. * @returns The cached TargetData entry, or null if the cache has no entry for
  8970. * the target.
  8971. */
  8972. // PORTING NOTE: Multi-tab only.
  8973. le(t, e) {
  8974. return wo(t).get(e).next((t => t ? mr(t) : null));
  8975. }
  8976. }
  8977. /**
  8978. * Helper to get a typed SimpleDbStore for the queries object store.
  8979. */ function wo(t) {
  8980. return _e(t, "targets");
  8981. }
  8982. /**
  8983. * Helper to get a typed SimpleDbStore for the target globals object store.
  8984. */ function _o(t) {
  8985. return _e(t, "targetGlobal");
  8986. }
  8987. /**
  8988. * Helper to get a typed SimpleDbStore for the document target object store.
  8989. */ function mo(t) {
  8990. return _e(t, "targetDocuments");
  8991. }
  8992. /**
  8993. * @license
  8994. * Copyright 2020 Google LLC
  8995. *
  8996. * Licensed under the Apache License, Version 2.0 (the "License");
  8997. * you may not use this file except in compliance with the License.
  8998. * You may obtain a copy of the License at
  8999. *
  9000. * http://www.apache.org/licenses/LICENSE-2.0
  9001. *
  9002. * Unless required by applicable law or agreed to in writing, software
  9003. * distributed under the License is distributed on an "AS IS" BASIS,
  9004. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9005. * See the License for the specific language governing permissions and
  9006. * limitations under the License.
  9007. */ function go([t, e], [n, s]) {
  9008. const i = et(t, n);
  9009. return 0 === i ? et(e, s) : i;
  9010. }
  9011. /**
  9012. * Used to calculate the nth sequence number. Keeps a rolling buffer of the
  9013. * lowest n values passed to `addElement`, and finally reports the largest of
  9014. * them in `maxValue`.
  9015. */ class yo {
  9016. constructor(t) {
  9017. this.Ln = t, this.buffer = new Ee(go), this.qn = 0;
  9018. }
  9019. Un() {
  9020. return ++this.qn;
  9021. }
  9022. Kn(t) {
  9023. const e = [ t, this.Un() ];
  9024. if (this.buffer.size < this.Ln) this.buffer = this.buffer.add(e); else {
  9025. const t = this.buffer.last();
  9026. go(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));
  9027. }
  9028. }
  9029. get maxValue() {
  9030. // Guaranteed to be non-empty. If we decide we are not collecting any
  9031. // sequence numbers, nthSequenceNumber below short-circuits. If we have
  9032. // decided that we are collecting n sequence numbers, it's because n is some
  9033. // percentage of the existing sequence numbers. That means we should never
  9034. // be in a situation where we are collecting sequence numbers but don't
  9035. // actually have any.
  9036. return this.buffer.last()[0];
  9037. }
  9038. }
  9039. /**
  9040. * This class is responsible for the scheduling of LRU garbage collection. It handles checking
  9041. * whether or not GC is enabled, as well as which delay to use before the next run.
  9042. */ class po {
  9043. constructor(t, e, n) {
  9044. this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Gn = null;
  9045. }
  9046. start() {
  9047. -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Qn(6e4);
  9048. }
  9049. stop() {
  9050. this.Gn && (this.Gn.cancel(), this.Gn = null);
  9051. }
  9052. get started() {
  9053. return null !== this.Gn;
  9054. }
  9055. Qn(t) {
  9056. N("LruGarbageCollector", `Garbage collection scheduled in ${t}ms`), this.Gn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , t, (async () => {
  9057. this.Gn = null;
  9058. try {
  9059. await this.localStore.collectGarbage(this.garbageCollector);
  9060. } catch (t) {
  9061. Dt(t) ? N("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await vt(t);
  9062. }
  9063. await this.Qn(3e5);
  9064. }));
  9065. }
  9066. }
  9067. /**
  9068. * Implements the steps for LRU garbage collection.
  9069. */ class Io {
  9070. constructor(t, e) {
  9071. this.jn = t, this.params = e;
  9072. }
  9073. calculateTargetCount(t, e) {
  9074. return this.jn.zn(t).next((t => Math.floor(e / 100 * t)));
  9075. }
  9076. nthSequenceNumber(t, e) {
  9077. if (0 === e) return Rt.resolve(Ot.ct);
  9078. const n = new yo(e);
  9079. return this.jn.forEachTarget(t, (t => n.Kn(t.sequenceNumber))).next((() => this.jn.Wn(t, (t => n.Kn(t))))).next((() => n.maxValue));
  9080. }
  9081. removeTargets(t, e, n) {
  9082. return this.jn.removeTargets(t, e, n);
  9083. }
  9084. removeOrphanedDocuments(t, e) {
  9085. return this.jn.removeOrphanedDocuments(t, e);
  9086. }
  9087. collect(t, e) {
  9088. return -1 === this.params.cacheSizeCollectionThreshold ? (N("LruGarbageCollector", "Garbage collection skipped; disabled"),
  9089. Rt.resolve(no)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (N("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),
  9090. no) : this.Hn(t, e)));
  9091. }
  9092. getCacheSize(t) {
  9093. return this.jn.getCacheSize(t);
  9094. }
  9095. Hn(t, e) {
  9096. let n, s, i, r, o, c, a;
  9097. const h = Date.now();
  9098. return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (
  9099. // Cap at the configured max
  9100. e > this.params.maximumSequenceNumbersToCollect ? (N("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),
  9101. s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s,
  9102. o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(),
  9103. this.removeOrphanedDocuments(t, n)))).next((t => {
  9104. if (a = Date.now(), C() <= LogLevel.DEBUG) {
  9105. N("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${r - h}ms\n\tDetermined least recently used ${s} in ` + (o - r) + "ms\n" + `\tRemoved ${i} targets in ` + (c - o) + "ms\n" + `\tRemoved ${t} documents in ` + (a - c) + "ms\n" + `Total Duration: ${a - h}ms`);
  9106. }
  9107. return Rt.resolve({
  9108. didRun: !0,
  9109. sequenceNumbersCollected: s,
  9110. targetsRemoved: i,
  9111. documentsRemoved: t
  9112. });
  9113. }));
  9114. }
  9115. }
  9116. function To(t, e) {
  9117. return new Io(t, e);
  9118. }
  9119. /**
  9120. * @license
  9121. * Copyright 2020 Google LLC
  9122. *
  9123. * Licensed under the Apache License, Version 2.0 (the "License");
  9124. * you may not use this file except in compliance with the License.
  9125. * You may obtain a copy of the License at
  9126. *
  9127. * http://www.apache.org/licenses/LICENSE-2.0
  9128. *
  9129. * Unless required by applicable law or agreed to in writing, software
  9130. * distributed under the License is distributed on an "AS IS" BASIS,
  9131. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9132. * See the License for the specific language governing permissions and
  9133. * limitations under the License.
  9134. */
  9135. /** Provides LRU functionality for IndexedDB persistence. */ class Eo {
  9136. constructor(t, e) {
  9137. this.db = t, this.garbageCollector = To(this, e);
  9138. }
  9139. zn(t) {
  9140. const e = this.Jn(t);
  9141. return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  9142. }
  9143. Jn(t) {
  9144. let e = 0;
  9145. return this.Wn(t, (t => {
  9146. e++;
  9147. })).next((() => e));
  9148. }
  9149. forEachTarget(t, e) {
  9150. return this.db.getTargetCache().forEachTarget(t, e);
  9151. }
  9152. Wn(t, e) {
  9153. return this.Yn(t, ((t, n) => e(n)));
  9154. }
  9155. addReference(t, e, n) {
  9156. return Ao(t, n);
  9157. }
  9158. removeReference(t, e, n) {
  9159. return Ao(t, n);
  9160. }
  9161. removeTargets(t, e, n) {
  9162. return this.db.getTargetCache().removeTargets(t, e, n);
  9163. }
  9164. markPotentiallyOrphaned(t, e) {
  9165. return Ao(t, e);
  9166. }
  9167. /**
  9168. * Returns true if anything would prevent this document from being garbage
  9169. * collected, given that the document in question is not present in any
  9170. * targets and has a sequence number less than or equal to the upper bound for
  9171. * the collection run.
  9172. */ Xn(t, e) {
  9173. return function(t, e) {
  9174. let n = !1;
  9175. return ho(t).Z((s => uo(t, s, e).next((t => (t && (n = !0), Rt.resolve(!t)))))).next((() => n));
  9176. }(t, e);
  9177. }
  9178. removeOrphanedDocuments(t, e) {
  9179. const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];
  9180. let i = 0;
  9181. return this.Yn(t, ((r, o) => {
  9182. if (o <= e) {
  9183. const e = this.Xn(t, r).next((e => {
  9184. if (!e)
  9185. // Our size accounting requires us to read all documents before
  9186. // removing them.
  9187. return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, rt.min()), mo(t).delete([ 0, qt(r.path) ]))));
  9188. }));
  9189. s.push(e);
  9190. }
  9191. })).next((() => Rt.waitFor(s))).next((() => n.apply(t))).next((() => i));
  9192. }
  9193. removeTarget(t, e) {
  9194. const n = e.withSequenceNumber(t.currentSequenceNumber);
  9195. return this.db.getTargetCache().updateTargetData(t, n);
  9196. }
  9197. updateLimboDocument(t, e) {
  9198. return Ao(t, e);
  9199. }
  9200. /**
  9201. * Call provided function for each document in the cache that is 'orphaned'. Orphaned
  9202. * means not a part of any target, so the only entry in the target-document index for
  9203. * that document will be the sentinel row (targetId 0), which will also have the sequence
  9204. * number for the last time the document was accessed.
  9205. */ Yn(t, e) {
  9206. const n = mo(t);
  9207. let s, i = Ot.ct;
  9208. return n.X({
  9209. index: "documentTargetsIndex"
  9210. }, (([t, n], {path: r, sequenceNumber: o}) => {
  9211. 0 === t ? (
  9212. // if nextToReport is valid, report it, this is a new key so the
  9213. // last one must not be a member of any targets.
  9214. i !== Ot.ct && e(new ht(Gt(s)), i),
  9215. // set nextToReport to be this sequence number. It's the next one we
  9216. // might report, if we don't find any targets for this document.
  9217. // Note that the sequence number must be defined when the targetId
  9218. // is 0.
  9219. i = o, s = r) :
  9220. // set nextToReport to be invalid, we know we don't need to report
  9221. // this one since we found a target for it.
  9222. i = Ot.ct;
  9223. })).next((() => {
  9224. // Since we report sequence numbers after getting to the next key, we
  9225. // need to check if the last key we iterated over was an orphaned
  9226. // document and report it.
  9227. i !== Ot.ct && e(new ht(Gt(s)), i);
  9228. }));
  9229. }
  9230. getCacheSize(t) {
  9231. return this.db.getRemoteDocumentCache().getSize(t);
  9232. }
  9233. }
  9234. function Ao(t, e) {
  9235. return mo(t).put(
  9236. /**
  9237. * @returns A value suitable for writing a sentinel row in the target-document
  9238. * store.
  9239. */
  9240. function(t, e) {
  9241. return {
  9242. targetId: 0,
  9243. path: qt(t.path),
  9244. sequenceNumber: e
  9245. };
  9246. }(e, t.currentSequenceNumber));
  9247. }
  9248. /**
  9249. * @license
  9250. * Copyright 2017 Google LLC
  9251. *
  9252. * Licensed under the Apache License, Version 2.0 (the "License");
  9253. * you may not use this file except in compliance with the License.
  9254. * You may obtain a copy of the License at
  9255. *
  9256. * http://www.apache.org/licenses/LICENSE-2.0
  9257. *
  9258. * Unless required by applicable law or agreed to in writing, software
  9259. * distributed under the License is distributed on an "AS IS" BASIS,
  9260. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9261. * See the License for the specific language governing permissions and
  9262. * limitations under the License.
  9263. */
  9264. /**
  9265. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  9266. * It can be used to batch up a set of changes to be written to the cache, but
  9267. * additionally supports reading entries back with the `getEntry()` method,
  9268. * falling back to the underlying RemoteDocumentCache if no entry is
  9269. * buffered.
  9270. *
  9271. * Entries added to the cache *must* be read first. This is to facilitate
  9272. * calculating the size delta of the pending changes.
  9273. *
  9274. * PORTING NOTE: This class was implemented then removed from other platforms.
  9275. * If byte-counting ends up being needed on the other platforms, consider
  9276. * porting this class as part of that implementation work.
  9277. */ class vo {
  9278. constructor() {
  9279. // A mapping of document key to the new cache entry that should be written.
  9280. this.changes = new os((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;
  9281. }
  9282. /**
  9283. * Buffers a `RemoteDocumentCache.addEntry()` call.
  9284. *
  9285. * You can only modify documents that have already been retrieved via
  9286. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  9287. */ addEntry(t) {
  9288. this.assertNotApplied(), this.changes.set(t.key, t);
  9289. }
  9290. /**
  9291. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  9292. *
  9293. * You can only remove documents that have already been retrieved via
  9294. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  9295. */ removeEntry(t, e) {
  9296. this.assertNotApplied(), this.changes.set(t, an.newInvalidDocument(t).setReadTime(e));
  9297. }
  9298. /**
  9299. * Looks up an entry in the cache. The buffered changes will first be checked,
  9300. * and if no buffered change applies, this will forward to
  9301. * `RemoteDocumentCache.getEntry()`.
  9302. *
  9303. * @param transaction - The transaction in which to perform any persistence
  9304. * operations.
  9305. * @param documentKey - The key of the entry to look up.
  9306. * @returns The cached document or an invalid document if we have nothing
  9307. * cached.
  9308. */ getEntry(t, e) {
  9309. this.assertNotApplied();
  9310. const n = this.changes.get(e);
  9311. return void 0 !== n ? Rt.resolve(n) : this.getFromCache(t, e);
  9312. }
  9313. /**
  9314. * Looks up several entries in the cache, forwarding to
  9315. * `RemoteDocumentCache.getEntry()`.
  9316. *
  9317. * @param transaction - The transaction in which to perform any persistence
  9318. * operations.
  9319. * @param documentKeys - The keys of the entries to look up.
  9320. * @returns A map of cached documents, indexed by key. If an entry cannot be
  9321. * found, the corresponding key will be mapped to an invalid document.
  9322. */ getEntries(t, e) {
  9323. return this.getAllFromCache(t, e);
  9324. }
  9325. /**
  9326. * Applies buffered changes to the underlying RemoteDocumentCache, using
  9327. * the provided transaction.
  9328. */ apply(t) {
  9329. return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
  9330. }
  9331. /** Helper to assert this.changes is not null */ assertNotApplied() {}
  9332. }
  9333. /**
  9334. * @license
  9335. * Copyright 2017 Google LLC
  9336. *
  9337. * Licensed under the Apache License, Version 2.0 (the "License");
  9338. * you may not use this file except in compliance with the License.
  9339. * You may obtain a copy of the License at
  9340. *
  9341. * http://www.apache.org/licenses/LICENSE-2.0
  9342. *
  9343. * Unless required by applicable law or agreed to in writing, software
  9344. * distributed under the License is distributed on an "AS IS" BASIS,
  9345. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9346. * See the License for the specific language governing permissions and
  9347. * limitations under the License.
  9348. */
  9349. /**
  9350. * The RemoteDocumentCache for IndexedDb. To construct, invoke
  9351. * `newIndexedDbRemoteDocumentCache()`.
  9352. */ class Ro {
  9353. constructor(t) {
  9354. this.serializer = t;
  9355. }
  9356. setIndexManager(t) {
  9357. this.indexManager = t;
  9358. }
  9359. /**
  9360. * Adds the supplied entries to the cache.
  9361. *
  9362. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9363. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9364. */ addEntry(t, e, n) {
  9365. return So(t).put(n);
  9366. }
  9367. /**
  9368. * Removes a document from the cache.
  9369. *
  9370. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9371. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9372. */ removeEntry(t, e, n) {
  9373. return So(t).delete(
  9374. /**
  9375. * Returns a key that can be used for document lookups via the primary key of
  9376. * the DbRemoteDocument object store.
  9377. */
  9378. function(t, e) {
  9379. const n = t.path.toArray();
  9380. return [
  9381. /* prefix path */ n.slice(0, n.length - 2),
  9382. /* collection id */ n[n.length - 2], fr(e),
  9383. /* document id */ n[n.length - 1] ];
  9384. }
  9385. /**
  9386. * Returns a key that can be used for document lookups on the
  9387. * `DbRemoteDocumentDocumentCollectionGroupIndex` index.
  9388. */ (e, n));
  9389. }
  9390. /**
  9391. * Updates the current cache size.
  9392. *
  9393. * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
  9394. * cache's metadata.
  9395. */ updateMetadata(t, e) {
  9396. return this.getMetadata(t).next((n => (n.byteSize += e, this.Zn(t, n))));
  9397. }
  9398. getEntry(t, e) {
  9399. let n = an.newInvalidDocument(e);
  9400. return So(t).X({
  9401. index: "documentKeyIndex",
  9402. range: IDBKeyRange.only(Do(e))
  9403. }, ((t, s) => {
  9404. n = this.ts(e, s);
  9405. })).next((() => n));
  9406. }
  9407. /**
  9408. * Looks up an entry in the cache.
  9409. *
  9410. * @param documentKey - The key of the entry to look up.
  9411. * @returns The cached document entry and its size.
  9412. */ es(t, e) {
  9413. let n = {
  9414. size: 0,
  9415. document: an.newInvalidDocument(e)
  9416. };
  9417. return So(t).X({
  9418. index: "documentKeyIndex",
  9419. range: IDBKeyRange.only(Do(e))
  9420. }, ((t, s) => {
  9421. n = {
  9422. document: this.ts(e, s),
  9423. size: ro(s)
  9424. };
  9425. })).next((() => n));
  9426. }
  9427. getEntries(t, e) {
  9428. let n = cs();
  9429. return this.ns(t, e, ((t, e) => {
  9430. const s = this.ts(t, e);
  9431. n = n.insert(t, s);
  9432. })).next((() => n));
  9433. }
  9434. /**
  9435. * Looks up several entries in the cache.
  9436. *
  9437. * @param documentKeys - The set of keys entries to look up.
  9438. * @returns A map of documents indexed by key and a map of sizes indexed by
  9439. * key (zero if the document does not exist).
  9440. */ ss(t, e) {
  9441. let n = cs(), s = new pe(ht.comparator);
  9442. return this.ns(t, e, ((t, e) => {
  9443. const i = this.ts(t, e);
  9444. n = n.insert(t, i), s = s.insert(t, ro(e));
  9445. })).next((() => ({
  9446. documents: n,
  9447. rs: s
  9448. })));
  9449. }
  9450. ns(t, e, n) {
  9451. if (e.isEmpty()) return Rt.resolve();
  9452. let s = new Ee(xo);
  9453. e.forEach((t => s = s.add(t)));
  9454. const i = IDBKeyRange.bound(Do(s.first()), Do(s.last())), r = s.getIterator();
  9455. let o = r.getNext();
  9456. return So(t).X({
  9457. index: "documentKeyIndex",
  9458. range: i
  9459. }, ((t, e, s) => {
  9460. const i = ht.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);
  9461. // Go through keys not found in cache.
  9462. for (;o && xo(o, i) < 0; ) n(o, null), o = r.getNext();
  9463. o && o.isEqual(i) && (
  9464. // Key found in cache.
  9465. n(o, e), o = r.hasNext() ? r.getNext() : null),
  9466. // Skip to the next key (if there is one).
  9467. o ? s.G(Do(o)) : s.done();
  9468. })).next((() => {
  9469. // The rest of the keys are not in the cache. One case where `iterate`
  9470. // above won't go through them is when the cache is empty.
  9471. for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;
  9472. }));
  9473. }
  9474. getDocumentsMatchingQuery(t, e, n, s) {
  9475. const i = e.path, r = [ i.popLast().toArray(), i.lastSegment(), fr(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], o = [ i.popLast().toArray(), i.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
  9476. return So(t).j(IDBKeyRange.bound(r, o, !0)).next((t => {
  9477. let n = cs();
  9478. for (const i of t) {
  9479. const t = this.ts(ht.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);
  9480. t.isFoundDocument() && (ns(e, t) || s.has(t.key)) && (
  9481. // Either the document matches the given query, or it is mutated.
  9482. n = n.insert(t.key, t));
  9483. }
  9484. return n;
  9485. }));
  9486. }
  9487. getAllFromCollectionGroup(t, e, n, s) {
  9488. let i = cs();
  9489. const r = Co(e, n), o = Co(e, It.max());
  9490. return So(t).X({
  9491. index: "collectionGroupIndex",
  9492. range: IDBKeyRange.bound(r, o, !0)
  9493. }, ((t, e, n) => {
  9494. const r = this.ts(ht.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);
  9495. i = i.insert(r.key, r), i.size === s && n.done();
  9496. })).next((() => i));
  9497. }
  9498. newChangeBuffer(t) {
  9499. return new bo(this, !!t && t.trackRemovals);
  9500. }
  9501. getSize(t) {
  9502. return this.getMetadata(t).next((t => t.byteSize));
  9503. }
  9504. getMetadata(t) {
  9505. return Vo(t).get("remoteDocumentGlobalKey").next((t => (F(!!t), t)));
  9506. }
  9507. Zn(t, e) {
  9508. return Vo(t).put("remoteDocumentGlobalKey", e);
  9509. }
  9510. /**
  9511. * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
  9512. * the document corresponds to the format used for sentinel deletes).
  9513. */ ts(t, e) {
  9514. if (e) {
  9515. const t = hr(this.serializer, e);
  9516. // Whether the document is a sentinel removal and should only be used in the
  9517. // `getNewDocumentChanges()`
  9518. if (!(t.isNoDocument() && t.version.isEqual(rt.min()))) return t;
  9519. }
  9520. return an.newInvalidDocument(t);
  9521. }
  9522. }
  9523. /** Creates a new IndexedDbRemoteDocumentCache. */ function Po(t) {
  9524. return new Ro(t);
  9525. }
  9526. /**
  9527. * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
  9528. *
  9529. * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
  9530. * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
  9531. * when we apply the changes.
  9532. */ class bo extends vo {
  9533. /**
  9534. * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
  9535. * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
  9536. * `getNewDocumentChanges()`.
  9537. */
  9538. constructor(t, e) {
  9539. super(), this.os = t, this.trackRemovals = e,
  9540. // A map of document sizes and read times prior to applying the changes in
  9541. // this buffer.
  9542. this.us = new os((t => t.toString()), ((t, e) => t.isEqual(e)));
  9543. }
  9544. applyChanges(t) {
  9545. const e = [];
  9546. let n = 0, s = new Ee(((t, e) => et(t.canonicalString(), e.canonicalString())));
  9547. return this.changes.forEach(((i, r) => {
  9548. const o = this.us.get(i);
  9549. if (e.push(this.os.removeEntry(t, i, o.readTime)), r.isValidDocument()) {
  9550. const u = lr(this.os.serializer, r);
  9551. s = s.add(i.path.popLast());
  9552. const c = ro(u);
  9553. n += c - o.size, e.push(this.os.addEntry(t, i, u));
  9554. } else if (n -= o.size, this.trackRemovals) {
  9555. // In order to track removals, we store a "sentinel delete" in the
  9556. // RemoteDocumentCache. This entry is represented by a NoDocument
  9557. // with a version of 0 and ignored by `maybeDecodeDocument()` but
  9558. // preserved in `getNewDocumentChanges()`.
  9559. const n = lr(this.os.serializer, r.convertToNoDocument(rt.min()));
  9560. e.push(this.os.addEntry(t, i, n));
  9561. }
  9562. })), s.forEach((n => {
  9563. e.push(this.os.indexManager.addToCollectionParentIndex(t, n));
  9564. })), e.push(this.os.updateMetadata(t, n)), Rt.waitFor(e);
  9565. }
  9566. getFromCache(t, e) {
  9567. // Record the size of everything we load from the cache so we can compute a delta later.
  9568. return this.os.es(t, e).next((t => (this.us.set(e, {
  9569. size: t.size,
  9570. readTime: t.document.readTime
  9571. }), t.document)));
  9572. }
  9573. getAllFromCache(t, e) {
  9574. // Record the size of everything we load from the cache so we can compute
  9575. // a delta later.
  9576. return this.os.ss(t, e).next((({documents: t, rs: e}) => (
  9577. // Note: `getAllFromCache` returns two maps instead of a single map from
  9578. // keys to `DocumentSizeEntry`s. This is to allow returning the
  9579. // `MutableDocumentMap` directly, without a conversion.
  9580. e.forEach(((e, n) => {
  9581. this.us.set(e, {
  9582. size: n,
  9583. readTime: t.get(e).readTime
  9584. });
  9585. })), t)));
  9586. }
  9587. }
  9588. function Vo(t) {
  9589. return _e(t, "remoteDocumentGlobal");
  9590. }
  9591. /**
  9592. * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
  9593. */ function So(t) {
  9594. return _e(t, "remoteDocumentsV14");
  9595. }
  9596. /**
  9597. * Returns a key that can be used for document lookups on the
  9598. * `DbRemoteDocumentDocumentKeyIndex` index.
  9599. */ function Do(t) {
  9600. const e = t.path.toArray();
  9601. return [
  9602. /* prefix path */ e.slice(0, e.length - 2),
  9603. /* collection id */ e[e.length - 2],
  9604. /* document id */ e[e.length - 1] ];
  9605. }
  9606. function Co(t, e) {
  9607. const n = e.documentKey.path.toArray();
  9608. return [
  9609. /* collection id */ t, fr(e.readTime),
  9610. /* prefix path */ n.slice(0, n.length - 2),
  9611. /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
  9612. }
  9613. /**
  9614. * Comparator that compares document keys according to the primary key sorting
  9615. * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
  9616. * and then document ID).
  9617. *
  9618. * Visible for testing.
  9619. */ function xo(t, e) {
  9620. const n = t.path.toArray(), s = e.path.toArray();
  9621. // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
  9622. let i = 0;
  9623. for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = et(n[t], s[t]),
  9624. i) return i;
  9625. return i = et(n.length, s.length), i || (i = et(n[n.length - 2], s[s.length - 2]),
  9626. i || et(n[n.length - 1], s[s.length - 1]));
  9627. }
  9628. /**
  9629. * @license
  9630. * Copyright 2017 Google LLC
  9631. *
  9632. * Licensed under the Apache License, Version 2.0 (the "License");
  9633. * you may not use this file except in compliance with the License.
  9634. * You may obtain a copy of the License at
  9635. *
  9636. * http://www.apache.org/licenses/LICENSE-2.0
  9637. *
  9638. * Unless required by applicable law or agreed to in writing, software
  9639. * distributed under the License is distributed on an "AS IS" BASIS,
  9640. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9641. * See the License for the specific language governing permissions and
  9642. * limitations under the License.
  9643. */
  9644. /**
  9645. * Schema Version for the Web client:
  9646. * 1. Initial version including Mutation Queue, Query Cache, and Remote
  9647. * Document Cache
  9648. * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
  9649. * longer required because migration 3 unconditionally clears it.
  9650. * 3. Dropped and re-created Query Cache to deal with cache corruption related
  9651. * to limbo resolution. Addresses
  9652. * https://github.com/firebase/firebase-ios-sdk/issues/1548
  9653. * 4. Multi-Tab Support.
  9654. * 5. Removal of held write acks.
  9655. * 6. Create document global for tracking document cache size.
  9656. * 7. Ensure every cached document has a sentinel row with a sequence number.
  9657. * 8. Add collection-parent index for Collection Group queries.
  9658. * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
  9659. * an auto-incrementing ID. This is required for Index-Free queries.
  9660. * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
  9661. * 11. Add bundles and named_queries for bundle support.
  9662. * 12. Add document overlays.
  9663. * 13. Rewrite the keys of the remote document cache to allow for efficient
  9664. * document lookup via `getAll()`.
  9665. * 14. Add overlays.
  9666. * 15. Add indexing support.
  9667. */
  9668. /**
  9669. * @license
  9670. * Copyright 2022 Google LLC
  9671. *
  9672. * Licensed under the Apache License, Version 2.0 (the "License");
  9673. * you may not use this file except in compliance with the License.
  9674. * You may obtain a copy of the License at
  9675. *
  9676. * http://www.apache.org/licenses/LICENSE-2.0
  9677. *
  9678. * Unless required by applicable law or agreed to in writing, software
  9679. * distributed under the License is distributed on an "AS IS" BASIS,
  9680. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9681. * See the License for the specific language governing permissions and
  9682. * limitations under the License.
  9683. */
  9684. /**
  9685. * Represents a local view (overlay) of a document, and the fields that are
  9686. * locally mutated.
  9687. */
  9688. class No {
  9689. constructor(t,
  9690. /**
  9691. * The fields that are locally mutated by patch mutations.
  9692. *
  9693. * If the overlayed document is from set or delete mutations, this is `null`.
  9694. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  9695. */
  9696. e) {
  9697. this.overlayedDocument = t, this.mutatedFields = e;
  9698. }
  9699. }
  9700. /**
  9701. * @license
  9702. * Copyright 2017 Google LLC
  9703. *
  9704. * Licensed under the Apache License, Version 2.0 (the "License");
  9705. * you may not use this file except in compliance with the License.
  9706. * You may obtain a copy of the License at
  9707. *
  9708. * http://www.apache.org/licenses/LICENSE-2.0
  9709. *
  9710. * Unless required by applicable law or agreed to in writing, software
  9711. * distributed under the License is distributed on an "AS IS" BASIS,
  9712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9713. * See the License for the specific language governing permissions and
  9714. * limitations under the License.
  9715. */
  9716. /**
  9717. * A readonly view of the local state of all documents we're tracking (i.e. we
  9718. * have a cached version in remoteDocumentCache or local mutations for the
  9719. * document). The view is computed by applying the mutations in the
  9720. * MutationQueue to the RemoteDocumentCache.
  9721. */ class ko {
  9722. constructor(t, e, n, s) {
  9723. this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n,
  9724. this.indexManager = s;
  9725. }
  9726. /**
  9727. * Get the local view of the document identified by `key`.
  9728. *
  9729. * @returns Local view of the document or null if we don't have any cached
  9730. * state for it.
  9731. */ getDocument(t, e) {
  9732. let n = null;
  9733. return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && Ks(n.mutation, t, Re.empty(), it.now()),
  9734. t)));
  9735. }
  9736. /**
  9737. * Gets the local view of the documents identified by `keys`.
  9738. *
  9739. * If we don't have cached state for a document in `keys`, a NoDocument will
  9740. * be stored for that key in the resulting set.
  9741. */ getDocuments(t, e) {
  9742. return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, gs()).next((() => e))));
  9743. }
  9744. /**
  9745. * Similar to `getDocuments`, but creates the local view from the given
  9746. * `baseDocs` without retrieving documents from the local store.
  9747. *
  9748. * @param transaction - The transaction this operation is scoped to.
  9749. * @param docs - The documents to apply local mutations to get the local views.
  9750. * @param existenceStateChanged - The set of document keys whose existence state
  9751. * is changed. This is useful to determine if some documents overlay needs
  9752. * to be recalculated.
  9753. */ getLocalViewOfDocuments(t, e, n = gs()) {
  9754. const s = fs();
  9755. return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {
  9756. let e = hs();
  9757. return t.forEach(((t, n) => {
  9758. e = e.insert(t, n.overlayedDocument);
  9759. })), e;
  9760. }))));
  9761. }
  9762. /**
  9763. * Gets the overlayed documents for the given document map, which will include
  9764. * the local view of those documents and a `FieldMask` indicating which fields
  9765. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  9766. */ getOverlayedDocuments(t, e) {
  9767. const n = fs();
  9768. return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, gs())));
  9769. }
  9770. /**
  9771. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  9772. * if the map does not already contain an entry for the given document key.
  9773. */ populateOverlays(t, e, n) {
  9774. const s = [];
  9775. return n.forEach((t => {
  9776. e.has(t) || s.push(t);
  9777. })), this.documentOverlayCache.getOverlays(t, s).next((t => {
  9778. t.forEach(((t, n) => {
  9779. e.set(t, n);
  9780. }));
  9781. }));
  9782. }
  9783. /**
  9784. * Computes the local view for the given documents.
  9785. *
  9786. * @param docs - The documents to compute views for. It also has the base
  9787. * version of the documents.
  9788. * @param overlays - The overlays that need to be applied to the given base
  9789. * version of the documents.
  9790. * @param existenceStateChanged - A set of documents whose existence states
  9791. * might have changed. This is used to determine if we need to re-calculate
  9792. * overlays from mutation queues.
  9793. * @return A map represents the local documents view.
  9794. */ computeViews(t, e, n, s) {
  9795. let i = cs();
  9796. const r = ws(), o = ws();
  9797. return e.forEach(((t, e) => {
  9798. const o = n.get(e.key);
  9799. // Recalculate an overlay if the document's existence state changed due to
  9800. // a remote event *and* the overlay is a PatchMutation. This is because
  9801. // document existence state can change if some patch mutation's
  9802. // preconditions are met.
  9803. // NOTE: we recalculate when `overlay` is undefined as well, because there
  9804. // might be a patch mutation whose precondition does not match before the
  9805. // change (hence overlay is undefined), but would now match.
  9806. s.has(e.key) && (void 0 === o || o.mutation instanceof zs) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()),
  9807. Ks(o.mutation, e, o.mutation.getFieldMask(), it.now())) :
  9808. // no overlay exists
  9809. // Using EMPTY to indicate there is no overlay for the document.
  9810. r.set(e.key, Re.empty());
  9811. })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))),
  9812. e.forEach(((t, e) => {
  9813. var n;
  9814. return o.set(t, new No(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));
  9815. })), o)));
  9816. }
  9817. recalculateAndSaveOverlays(t, e) {
  9818. const n = ws();
  9819. // A reverse lookup map from batch id to the documents within that batch.
  9820. let s = new pe(((t, e) => t - e)), i = gs();
  9821. return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {
  9822. for (const i of t) i.keys().forEach((t => {
  9823. const r = e.get(t);
  9824. if (null === r) return;
  9825. let o = n.get(t) || Re.empty();
  9826. o = i.applyToLocalView(r, o), n.set(t, o);
  9827. const u = (s.get(i.batchId) || gs()).add(t);
  9828. s = s.insert(i.batchId, u);
  9829. }));
  9830. })).next((() => {
  9831. const r = [], o = s.getReverseIterator();
  9832. // Iterate in descending order of batch IDs, and skip documents that are
  9833. // already saved.
  9834. for (;o.hasNext(); ) {
  9835. const s = o.getNext(), u = s.key, c = s.value, a = ds();
  9836. c.forEach((t => {
  9837. if (!i.has(t)) {
  9838. const s = qs(e.get(t), n.get(t));
  9839. null !== s && a.set(t, s), i = i.add(t);
  9840. }
  9841. })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));
  9842. }
  9843. return Rt.waitFor(r);
  9844. })).next((() => n));
  9845. }
  9846. /**
  9847. * Recalculates overlays by reading the documents from remote document cache
  9848. * first, and saves them after they are calculated.
  9849. */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {
  9850. return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));
  9851. }
  9852. /**
  9853. * Performs a query against the local view of all documents.
  9854. *
  9855. * @param transaction - The persistence transaction.
  9856. * @param query - The query to match documents against.
  9857. * @param offset - Read time and key to start scanning by (exclusive).
  9858. */ getDocumentsMatchingQuery(t, e, n) {
  9859. /**
  9860. * Returns whether the query matches a single document by path (rather than a
  9861. * collection).
  9862. */
  9863. return function(t) {
  9864. return ht.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  9865. }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : Wn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);
  9866. }
  9867. /**
  9868. * Given a collection group, returns the next documents that follow the provided offset, along
  9869. * with an updated batch ID.
  9870. *
  9871. * <p>The documents returned by this method are ordered by remote version from the provided
  9872. * offset. If there are no more remote documents after the provided offset, documents with
  9873. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  9874. * returned together, the total number of documents returned can exceed {@code count}.
  9875. *
  9876. * @param transaction
  9877. * @param collectionGroup The collection group for the documents.
  9878. * @param offset The offset to index into.
  9879. * @param count The number of documents to return
  9880. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  9881. */ getNextDocuments(t, e, n, s) {
  9882. return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {
  9883. const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : Rt.resolve(fs());
  9884. // The callsite will use the largest batch ID together with the latest read time to create
  9885. // a new index offset. Since we only process batch IDs if all remote documents have been read,
  9886. // no overlay will increase the overall read time. This is why we only need to special case
  9887. // the batch id.
  9888. let o = -1, u = i;
  9889. return r.next((e => Rt.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId),
  9890. i.get(e) ? Rt.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {
  9891. u = u.insert(e, t);
  9892. }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, gs()))).next((t => ({
  9893. batchId: o,
  9894. changes: ls(t)
  9895. })))));
  9896. }));
  9897. }
  9898. getDocumentsMatchingDocumentQuery(t, e) {
  9899. // Just do a simple document lookup.
  9900. return this.getDocument(t, new ht(e)).next((t => {
  9901. let e = hs();
  9902. return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
  9903. }));
  9904. }
  9905. getDocumentsMatchingCollectionGroupQuery(t, e, n) {
  9906. const s = e.collectionGroup;
  9907. let i = hs();
  9908. return this.indexManager.getCollectionParents(t, s).next((r => Rt.forEach(r, (r => {
  9909. const o = function(t, e) {
  9910. return new Un(e,
  9911. /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  9912. }(e, r.child(s));
  9913. return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {
  9914. t.forEach(((t, e) => {
  9915. i = i.insert(t, e);
  9916. }));
  9917. }));
  9918. })).next((() => i))));
  9919. }
  9920. getDocumentsMatchingCollectionQuery(t, e, n) {
  9921. // Query the remote documents and overlay mutations.
  9922. let s;
  9923. return this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId).next((i => (s = i,
  9924. this.remoteDocumentCache.getDocumentsMatchingQuery(t, e, n, s)))).next((t => {
  9925. // As documents might match the query because of their overlay we need to
  9926. // include documents for all overlays in the initial document set.
  9927. s.forEach(((e, n) => {
  9928. const s = n.getKey();
  9929. null === t.get(s) && (t = t.insert(s, an.newInvalidDocument(s)));
  9930. }));
  9931. // Apply the overlays and match against the query.
  9932. let n = hs();
  9933. return t.forEach(((t, i) => {
  9934. const r = s.get(t);
  9935. void 0 !== r && Ks(r.mutation, i, Re.empty(), it.now()),
  9936. // Finally, insert the documents that still match the query
  9937. ns(e, i) && (n = n.insert(t, i));
  9938. })), n;
  9939. }));
  9940. }
  9941. }
  9942. /**
  9943. * @license
  9944. * Copyright 2020 Google LLC
  9945. *
  9946. * Licensed under the Apache License, Version 2.0 (the "License");
  9947. * you may not use this file except in compliance with the License.
  9948. * You may obtain a copy of the License at
  9949. *
  9950. * http://www.apache.org/licenses/LICENSE-2.0
  9951. *
  9952. * Unless required by applicable law or agreed to in writing, software
  9953. * distributed under the License is distributed on an "AS IS" BASIS,
  9954. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9955. * See the License for the specific language governing permissions and
  9956. * limitations under the License.
  9957. */ class Mo {
  9958. constructor(t) {
  9959. this.serializer = t, this.cs = new Map, this.hs = new Map;
  9960. }
  9961. getBundleMetadata(t, e) {
  9962. return Rt.resolve(this.cs.get(e));
  9963. }
  9964. saveBundleMetadata(t, e) {
  9965. /** Decodes a BundleMetadata proto into a BundleMetadata object. */
  9966. var n;
  9967. return this.cs.set(e.id, {
  9968. id: (n = e).id,
  9969. version: n.version,
  9970. createTime: Ni(n.createTime)
  9971. }), Rt.resolve();
  9972. }
  9973. getNamedQuery(t, e) {
  9974. return Rt.resolve(this.hs.get(e));
  9975. }
  9976. saveNamedQuery(t, e) {
  9977. return this.hs.set(e.name, function(t) {
  9978. return {
  9979. name: t.name,
  9980. query: yr(t.bundledQuery),
  9981. readTime: Ni(t.readTime)
  9982. };
  9983. }(e)), Rt.resolve();
  9984. }
  9985. }
  9986. /**
  9987. * @license
  9988. * Copyright 2022 Google LLC
  9989. *
  9990. * Licensed under the Apache License, Version 2.0 (the "License");
  9991. * you may not use this file except in compliance with the License.
  9992. * You may obtain a copy of the License at
  9993. *
  9994. * http://www.apache.org/licenses/LICENSE-2.0
  9995. *
  9996. * Unless required by applicable law or agreed to in writing, software
  9997. * distributed under the License is distributed on an "AS IS" BASIS,
  9998. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9999. * See the License for the specific language governing permissions and
  10000. * limitations under the License.
  10001. */
  10002. /**
  10003. * An in-memory implementation of DocumentOverlayCache.
  10004. */ class $o {
  10005. constructor() {
  10006. // A map sorted by DocumentKey, whose value is a pair of the largest batch id
  10007. // for the overlay and the overlay itself.
  10008. this.overlays = new pe(ht.comparator), this.ls = new Map;
  10009. }
  10010. getOverlay(t, e) {
  10011. return Rt.resolve(this.overlays.get(e));
  10012. }
  10013. getOverlays(t, e) {
  10014. const n = fs();
  10015. return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  10016. null !== t && n.set(e, t);
  10017. })))).next((() => n));
  10018. }
  10019. saveOverlays(t, e, n) {
  10020. return n.forEach(((n, s) => {
  10021. this.we(t, e, s);
  10022. })), Rt.resolve();
  10023. }
  10024. removeOverlaysForBatchId(t, e, n) {
  10025. const s = this.ls.get(n);
  10026. return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))),
  10027. this.ls.delete(n)), Rt.resolve();
  10028. }
  10029. getOverlaysForCollection(t, e, n) {
  10030. const s = fs(), i = e.length + 1, r = new ht(e.child("")), o = this.overlays.getIteratorFrom(r);
  10031. for (;o.hasNext(); ) {
  10032. const t = o.getNext().value, r = t.getKey();
  10033. if (!e.isPrefixOf(r.path)) break;
  10034. // Documents from sub-collections
  10035. r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));
  10036. }
  10037. return Rt.resolve(s);
  10038. }
  10039. getOverlaysForCollectionGroup(t, e, n, s) {
  10040. let i = new pe(((t, e) => t - e));
  10041. const r = this.overlays.getIterator();
  10042. for (;r.hasNext(); ) {
  10043. const t = r.getNext().value;
  10044. if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {
  10045. let e = i.get(t.largestBatchId);
  10046. null === e && (e = fs(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);
  10047. }
  10048. }
  10049. const o = fs(), u = i.getIterator();
  10050. for (;u.hasNext(); ) {
  10051. if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;
  10052. }
  10053. return Rt.resolve(o);
  10054. }
  10055. we(t, e, n) {
  10056. // Remove the association of the overlay to its batch id.
  10057. const s = this.overlays.get(n.key);
  10058. if (null !== s) {
  10059. const t = this.ls.get(s.largestBatchId).delete(n.key);
  10060. this.ls.set(s.largestBatchId, t);
  10061. }
  10062. this.overlays = this.overlays.insert(n.key, new ei(e, n));
  10063. // Create the association of this overlay to the given largestBatchId.
  10064. let i = this.ls.get(e);
  10065. void 0 === i && (i = gs(), this.ls.set(e, i)), this.ls.set(e, i.add(n.key));
  10066. }
  10067. }
  10068. /**
  10069. * @license
  10070. * Copyright 2017 Google LLC
  10071. *
  10072. * Licensed under the Apache License, Version 2.0 (the "License");
  10073. * you may not use this file except in compliance with the License.
  10074. * You may obtain a copy of the License at
  10075. *
  10076. * http://www.apache.org/licenses/LICENSE-2.0
  10077. *
  10078. * Unless required by applicable law or agreed to in writing, software
  10079. * distributed under the License is distributed on an "AS IS" BASIS,
  10080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10081. * See the License for the specific language governing permissions and
  10082. * limitations under the License.
  10083. */
  10084. /**
  10085. * A collection of references to a document from some kind of numbered entity
  10086. * (either a target ID or batch ID). As references are added to or removed from
  10087. * the set corresponding events are emitted to a registered garbage collector.
  10088. *
  10089. * Each reference is represented by a DocumentReference object. Each of them
  10090. * contains enough information to uniquely identify the reference. They are all
  10091. * stored primarily in a set sorted by key. A document is considered garbage if
  10092. * there's no references in that set (this can be efficiently checked thanks to
  10093. * sorting by key).
  10094. *
  10095. * ReferenceSet also keeps a secondary set that contains references sorted by
  10096. * IDs. This one is used to efficiently implement removal of all references by
  10097. * some target ID.
  10098. */ class Oo {
  10099. constructor() {
  10100. // A set of outstanding references to a document sorted by key.
  10101. this.fs = new Ee(Fo.ds),
  10102. // A set of outstanding references to a document sorted by target id.
  10103. this.ws = new Ee(Fo._s);
  10104. }
  10105. /** Returns true if the reference set contains no references. */ isEmpty() {
  10106. return this.fs.isEmpty();
  10107. }
  10108. /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {
  10109. const n = new Fo(t, e);
  10110. this.fs = this.fs.add(n), this.ws = this.ws.add(n);
  10111. }
  10112. /** Add references to the given document keys for the given ID. */ gs(t, e) {
  10113. t.forEach((t => this.addReference(t, e)));
  10114. }
  10115. /**
  10116. * Removes a reference to the given document key for the given
  10117. * ID.
  10118. */ removeReference(t, e) {
  10119. this.ys(new Fo(t, e));
  10120. }
  10121. ps(t, e) {
  10122. t.forEach((t => this.removeReference(t, e)));
  10123. }
  10124. /**
  10125. * Clears all references with a given ID. Calls removeRef() for each key
  10126. * removed.
  10127. */ Is(t) {
  10128. const e = new ht(new ut([])), n = new Fo(e, t), s = new Fo(e, t + 1), i = [];
  10129. return this.ws.forEachInRange([ n, s ], (t => {
  10130. this.ys(t), i.push(t.key);
  10131. })), i;
  10132. }
  10133. Ts() {
  10134. this.fs.forEach((t => this.ys(t)));
  10135. }
  10136. ys(t) {
  10137. this.fs = this.fs.delete(t), this.ws = this.ws.delete(t);
  10138. }
  10139. Es(t) {
  10140. const e = new ht(new ut([])), n = new Fo(e, t), s = new Fo(e, t + 1);
  10141. let i = gs();
  10142. return this.ws.forEachInRange([ n, s ], (t => {
  10143. i = i.add(t.key);
  10144. })), i;
  10145. }
  10146. containsKey(t) {
  10147. const e = new Fo(t, 0), n = this.fs.firstAfterOrEqual(e);
  10148. return null !== n && t.isEqual(n.key);
  10149. }
  10150. }
  10151. class Fo {
  10152. constructor(t, e) {
  10153. this.key = t, this.As = e;
  10154. }
  10155. /** Compare by key then by ID */ static ds(t, e) {
  10156. return ht.comparator(t.key, e.key) || et(t.As, e.As);
  10157. }
  10158. /** Compare by ID then by key */ static _s(t, e) {
  10159. return et(t.As, e.As) || ht.comparator(t.key, e.key);
  10160. }
  10161. }
  10162. /**
  10163. * @license
  10164. * Copyright 2017 Google LLC
  10165. *
  10166. * Licensed under the Apache License, Version 2.0 (the "License");
  10167. * you may not use this file except in compliance with the License.
  10168. * You may obtain a copy of the License at
  10169. *
  10170. * http://www.apache.org/licenses/LICENSE-2.0
  10171. *
  10172. * Unless required by applicable law or agreed to in writing, software
  10173. * distributed under the License is distributed on an "AS IS" BASIS,
  10174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10175. * See the License for the specific language governing permissions and
  10176. * limitations under the License.
  10177. */ class Bo {
  10178. constructor(t, e) {
  10179. this.indexManager = t, this.referenceDelegate = e,
  10180. /**
  10181. * The set of all mutations that have been sent but not yet been applied to
  10182. * the backend.
  10183. */
  10184. this.mutationQueue = [],
  10185. /** Next value to use when assigning sequential IDs to each mutation batch. */
  10186. this.vs = 1,
  10187. /** An ordered mapping between documents and the mutations batch IDs. */
  10188. this.Rs = new Ee(Fo.ds);
  10189. }
  10190. checkEmpty(t) {
  10191. return Rt.resolve(0 === this.mutationQueue.length);
  10192. }
  10193. addMutationBatch(t, e, n, s) {
  10194. const i = this.vs;
  10195. this.vs++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
  10196. const r = new Zs(i, e, n, s);
  10197. this.mutationQueue.push(r);
  10198. // Track references by document key and index collection parents.
  10199. for (const e of s) this.Rs = this.Rs.add(new Fo(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());
  10200. return Rt.resolve(r);
  10201. }
  10202. lookupMutationBatch(t, e) {
  10203. return Rt.resolve(this.Ps(e));
  10204. }
  10205. getNextMutationBatchAfterBatchId(t, e) {
  10206. const n = e + 1, s = this.bs(n), i = s < 0 ? 0 : s;
  10207. // The requested batchId may still be out of range so normalize it to the
  10208. // start of the queue.
  10209. return Rt.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
  10210. }
  10211. getHighestUnacknowledgedBatchId() {
  10212. return Rt.resolve(0 === this.mutationQueue.length ? -1 : this.vs - 1);
  10213. }
  10214. getAllMutationBatches(t) {
  10215. return Rt.resolve(this.mutationQueue.slice());
  10216. }
  10217. getAllMutationBatchesAffectingDocumentKey(t, e) {
  10218. const n = new Fo(e, 0), s = new Fo(e, Number.POSITIVE_INFINITY), i = [];
  10219. return this.Rs.forEachInRange([ n, s ], (t => {
  10220. const e = this.Ps(t.As);
  10221. i.push(e);
  10222. })), Rt.resolve(i);
  10223. }
  10224. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  10225. let n = new Ee(et);
  10226. return e.forEach((t => {
  10227. const e = new Fo(t, 0), s = new Fo(t, Number.POSITIVE_INFINITY);
  10228. this.Rs.forEachInRange([ e, s ], (t => {
  10229. n = n.add(t.As);
  10230. }));
  10231. })), Rt.resolve(this.Vs(n));
  10232. }
  10233. getAllMutationBatchesAffectingQuery(t, e) {
  10234. // Use the query path as a prefix for testing if a document matches the
  10235. // query.
  10236. const n = e.path, s = n.length + 1;
  10237. // Construct a document reference for actually scanning the index. Unlike
  10238. // the prefix the document key in this reference must have an even number of
  10239. // segments. The empty segment can be used a suffix of the query path
  10240. // because it precedes all other segments in an ordered traversal.
  10241. let i = n;
  10242. ht.isDocumentKey(i) || (i = i.child(""));
  10243. const r = new Fo(new ht(i), 0);
  10244. // Find unique batchIDs referenced by all documents potentially matching the
  10245. // query.
  10246. let o = new Ee(et);
  10247. return this.Rs.forEachWhile((t => {
  10248. const e = t.key.path;
  10249. return !!n.isPrefixOf(e) && (
  10250. // Rows with document keys more than one segment longer than the query
  10251. // path can't be matches. For example, a query on 'rooms' can't match
  10252. // the document /rooms/abc/messages/xyx.
  10253. // TODO(mcg): we'll need a different scanner when we implement
  10254. // ancestor queries.
  10255. e.length === s && (o = o.add(t.As)), !0);
  10256. }), r), Rt.resolve(this.Vs(o));
  10257. }
  10258. Vs(t) {
  10259. // Construct an array of matching batches, sorted by batchID to ensure that
  10260. // multiple mutations affecting the same document key are applied in order.
  10261. const e = [];
  10262. return t.forEach((t => {
  10263. const n = this.Ps(t);
  10264. null !== n && e.push(n);
  10265. })), e;
  10266. }
  10267. removeMutationBatch(t, e) {
  10268. F(0 === this.Ss(e.batchId, "removed")), this.mutationQueue.shift();
  10269. let n = this.Rs;
  10270. return Rt.forEach(e.mutations, (s => {
  10271. const i = new Fo(s.key, e.batchId);
  10272. return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);
  10273. })).next((() => {
  10274. this.Rs = n;
  10275. }));
  10276. }
  10277. Cn(t) {
  10278. // No-op since the memory mutation queue does not maintain a separate cache.
  10279. }
  10280. containsKey(t, e) {
  10281. const n = new Fo(e, 0), s = this.Rs.firstAfterOrEqual(n);
  10282. return Rt.resolve(e.isEqual(s && s.key));
  10283. }
  10284. performConsistencyCheck(t) {
  10285. return this.mutationQueue.length, Rt.resolve();
  10286. }
  10287. /**
  10288. * Finds the index of the given batchId in the mutation queue and asserts that
  10289. * the resulting index is within the bounds of the queue.
  10290. *
  10291. * @param batchId - The batchId to search for
  10292. * @param action - A description of what the caller is doing, phrased in passive
  10293. * form (e.g. "acknowledged" in a routine that acknowledges batches).
  10294. */ Ss(t, e) {
  10295. return this.bs(t);
  10296. }
  10297. /**
  10298. * Finds the index of the given batchId in the mutation queue. This operation
  10299. * is O(1).
  10300. *
  10301. * @returns The computed index of the batch with the given batchId, based on
  10302. * the state of the queue. Note this index can be negative if the requested
  10303. * batchId has already been remvoed from the queue or past the end of the
  10304. * queue if the batchId is larger than the last added batch.
  10305. */ bs(t) {
  10306. if (0 === this.mutationQueue.length)
  10307. // As an index this is past the end of the queue
  10308. return 0;
  10309. // Examine the front of the queue to figure out the difference between the
  10310. // batchId and indexes in the array. Note that since the queue is ordered
  10311. // by batchId, if the first batch has a larger batchId then the requested
  10312. // batchId doesn't exist in the queue.
  10313. return t - this.mutationQueue[0].batchId;
  10314. }
  10315. /**
  10316. * A version of lookupMutationBatch that doesn't return a promise, this makes
  10317. * other functions that uses this code easier to read and more efficent.
  10318. */ Ps(t) {
  10319. const e = this.bs(t);
  10320. if (e < 0 || e >= this.mutationQueue.length) return null;
  10321. return this.mutationQueue[e];
  10322. }
  10323. }
  10324. /**
  10325. * @license
  10326. * Copyright 2017 Google LLC
  10327. *
  10328. * Licensed under the Apache License, Version 2.0 (the "License");
  10329. * you may not use this file except in compliance with the License.
  10330. * You may obtain a copy of the License at
  10331. *
  10332. * http://www.apache.org/licenses/LICENSE-2.0
  10333. *
  10334. * Unless required by applicable law or agreed to in writing, software
  10335. * distributed under the License is distributed on an "AS IS" BASIS,
  10336. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10337. * See the License for the specific language governing permissions and
  10338. * limitations under the License.
  10339. */
  10340. /**
  10341. * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
  10342. * `newMemoryRemoteDocumentCache()`.
  10343. */
  10344. class Lo {
  10345. /**
  10346. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10347. * expected to just return 0 to avoid unnecessarily doing the work of
  10348. * calculating the size.
  10349. */
  10350. constructor(t) {
  10351. this.Ds = t,
  10352. /** Underlying cache of documents and their read times. */
  10353. this.docs = new pe(ht.comparator),
  10354. /** Size of all cached documents. */
  10355. this.size = 0;
  10356. }
  10357. setIndexManager(t) {
  10358. this.indexManager = t;
  10359. }
  10360. /**
  10361. * Adds the supplied entry to the cache and updates the cache size as appropriate.
  10362. *
  10363. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  10364. * returned by `newChangeBuffer()`.
  10365. */ addEntry(t, e) {
  10366. const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Ds(e);
  10367. return this.docs = this.docs.insert(n, {
  10368. document: e.mutableCopy(),
  10369. size: r
  10370. }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());
  10371. }
  10372. /**
  10373. * Removes the specified entry from the cache and updates the cache size as appropriate.
  10374. *
  10375. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  10376. * returned by `newChangeBuffer()`.
  10377. */ removeEntry(t) {
  10378. const e = this.docs.get(t);
  10379. e && (this.docs = this.docs.remove(t), this.size -= e.size);
  10380. }
  10381. getEntry(t, e) {
  10382. const n = this.docs.get(e);
  10383. return Rt.resolve(n ? n.document.mutableCopy() : an.newInvalidDocument(e));
  10384. }
  10385. getEntries(t, e) {
  10386. let n = cs();
  10387. return e.forEach((t => {
  10388. const e = this.docs.get(t);
  10389. n = n.insert(t, e ? e.document.mutableCopy() : an.newInvalidDocument(t));
  10390. })), Rt.resolve(n);
  10391. }
  10392. getDocumentsMatchingQuery(t, e, n, s) {
  10393. let i = cs();
  10394. // Documents are ordered by key, so we can use a prefix scan to narrow down
  10395. // the documents we need to match the query against.
  10396. const r = e.path, o = new ht(r.child("")), u = this.docs.getIteratorFrom(o);
  10397. for (;u.hasNext(); ) {
  10398. const {key: t, value: {document: o}} = u.getNext();
  10399. if (!r.isPrefixOf(t.path)) break;
  10400. t.path.length > r.length + 1 || (Tt(pt(o), n) <= 0 || (s.has(o.key) || ns(e, o)) && (i = i.insert(o.key, o.mutableCopy())));
  10401. }
  10402. return Rt.resolve(i);
  10403. }
  10404. getAllFromCollectionGroup(t, e, n, s) {
  10405. // This method should only be called from the IndexBackfiller if persistence
  10406. // is enabled.
  10407. O();
  10408. }
  10409. Cs(t, e) {
  10410. return Rt.forEach(this.docs, (t => e(t)));
  10411. }
  10412. newChangeBuffer(t) {
  10413. // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
  10414. // a separate changelog and does not need special handling for removals.
  10415. return new qo(this);
  10416. }
  10417. getSize(t) {
  10418. return Rt.resolve(this.size);
  10419. }
  10420. }
  10421. /**
  10422. * Creates a new memory-only RemoteDocumentCache.
  10423. *
  10424. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10425. * expected to just return 0 to avoid unnecessarily doing the work of
  10426. * calculating the size.
  10427. */
  10428. /**
  10429. * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
  10430. */
  10431. class qo extends vo {
  10432. constructor(t) {
  10433. super(), this.os = t;
  10434. }
  10435. applyChanges(t) {
  10436. const e = [];
  10437. return this.changes.forEach(((n, s) => {
  10438. s.isValidDocument() ? e.push(this.os.addEntry(t, s)) : this.os.removeEntry(n);
  10439. })), Rt.waitFor(e);
  10440. }
  10441. getFromCache(t, e) {
  10442. return this.os.getEntry(t, e);
  10443. }
  10444. getAllFromCache(t, e) {
  10445. return this.os.getEntries(t, e);
  10446. }
  10447. }
  10448. /**
  10449. * @license
  10450. * Copyright 2017 Google LLC
  10451. *
  10452. * Licensed under the Apache License, Version 2.0 (the "License");
  10453. * you may not use this file except in compliance with the License.
  10454. * You may obtain a copy of the License at
  10455. *
  10456. * http://www.apache.org/licenses/LICENSE-2.0
  10457. *
  10458. * Unless required by applicable law or agreed to in writing, software
  10459. * distributed under the License is distributed on an "AS IS" BASIS,
  10460. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10461. * See the License for the specific language governing permissions and
  10462. * limitations under the License.
  10463. */ class Uo {
  10464. constructor(t) {
  10465. this.persistence = t,
  10466. /**
  10467. * Maps a target to the data about that target
  10468. */
  10469. this.xs = new os((t => $n(t)), On),
  10470. /** The last received snapshot version. */
  10471. this.lastRemoteSnapshotVersion = rt.min(),
  10472. /** The highest numbered target ID encountered. */
  10473. this.highestTargetId = 0,
  10474. /** The highest sequence number encountered. */
  10475. this.Ns = 0,
  10476. /**
  10477. * A ordered bidirectional mapping between documents and the remote target
  10478. * IDs.
  10479. */
  10480. this.ks = new Oo, this.targetCount = 0, this.Ms = lo.kn();
  10481. }
  10482. forEachTarget(t, e) {
  10483. return this.xs.forEach(((t, n) => e(n))), Rt.resolve();
  10484. }
  10485. getLastRemoteSnapshotVersion(t) {
  10486. return Rt.resolve(this.lastRemoteSnapshotVersion);
  10487. }
  10488. getHighestSequenceNumber(t) {
  10489. return Rt.resolve(this.Ns);
  10490. }
  10491. allocateTargetId(t) {
  10492. return this.highestTargetId = this.Ms.next(), Rt.resolve(this.highestTargetId);
  10493. }
  10494. setTargetsMetadata(t, e, n) {
  10495. return n && (this.lastRemoteSnapshotVersion = n), e > this.Ns && (this.Ns = e),
  10496. Rt.resolve();
  10497. }
  10498. Fn(t) {
  10499. this.xs.set(t.target, t);
  10500. const e = t.targetId;
  10501. e > this.highestTargetId && (this.Ms = new lo(e), this.highestTargetId = e), t.sequenceNumber > this.Ns && (this.Ns = t.sequenceNumber);
  10502. }
  10503. addTargetData(t, e) {
  10504. return this.Fn(e), this.targetCount += 1, Rt.resolve();
  10505. }
  10506. updateTargetData(t, e) {
  10507. return this.Fn(e), Rt.resolve();
  10508. }
  10509. removeTargetData(t, e) {
  10510. return this.xs.delete(e.target), this.ks.Is(e.targetId), this.targetCount -= 1,
  10511. Rt.resolve();
  10512. }
  10513. removeTargets(t, e, n) {
  10514. let s = 0;
  10515. const i = [];
  10516. return this.xs.forEach(((r, o) => {
  10517. o.sequenceNumber <= e && null === n.get(o.targetId) && (this.xs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)),
  10518. s++);
  10519. })), Rt.waitFor(i).next((() => s));
  10520. }
  10521. getTargetCount(t) {
  10522. return Rt.resolve(this.targetCount);
  10523. }
  10524. getTargetData(t, e) {
  10525. const n = this.xs.get(e) || null;
  10526. return Rt.resolve(n);
  10527. }
  10528. addMatchingKeys(t, e, n) {
  10529. return this.ks.gs(e, n), Rt.resolve();
  10530. }
  10531. removeMatchingKeys(t, e, n) {
  10532. this.ks.ps(e, n);
  10533. const s = this.persistence.referenceDelegate, i = [];
  10534. return s && e.forEach((e => {
  10535. i.push(s.markPotentiallyOrphaned(t, e));
  10536. })), Rt.waitFor(i);
  10537. }
  10538. removeMatchingKeysForTargetId(t, e) {
  10539. return this.ks.Is(e), Rt.resolve();
  10540. }
  10541. getMatchingKeysForTargetId(t, e) {
  10542. const n = this.ks.Es(e);
  10543. return Rt.resolve(n);
  10544. }
  10545. containsKey(t, e) {
  10546. return Rt.resolve(this.ks.containsKey(e));
  10547. }
  10548. }
  10549. /**
  10550. * @license
  10551. * Copyright 2017 Google LLC
  10552. *
  10553. * Licensed under the Apache License, Version 2.0 (the "License");
  10554. * you may not use this file except in compliance with the License.
  10555. * You may obtain a copy of the License at
  10556. *
  10557. * http://www.apache.org/licenses/LICENSE-2.0
  10558. *
  10559. * Unless required by applicable law or agreed to in writing, software
  10560. * distributed under the License is distributed on an "AS IS" BASIS,
  10561. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10562. * See the License for the specific language governing permissions and
  10563. * limitations under the License.
  10564. */
  10565. /**
  10566. * A memory-backed instance of Persistence. Data is stored only in RAM and
  10567. * not persisted across sessions.
  10568. */
  10569. class Ko {
  10570. /**
  10571. * The constructor accepts a factory for creating a reference delegate. This
  10572. * allows both the delegate and this instance to have strong references to
  10573. * each other without having nullable fields that would then need to be
  10574. * checked or asserted on every access.
  10575. */
  10576. constructor(t, e) {
  10577. this.$s = {}, this.overlays = {}, this.Os = new Ot(0), this.Fs = !1, this.Fs = !0,
  10578. this.referenceDelegate = t(this), this.Bs = new Uo(this);
  10579. this.indexManager = new zr, this.remoteDocumentCache = function(t) {
  10580. return new Lo(t);
  10581. }((t => this.referenceDelegate.Ls(t))), this.serializer = new ar(e), this.qs = new Mo(this.serializer);
  10582. }
  10583. start() {
  10584. return Promise.resolve();
  10585. }
  10586. shutdown() {
  10587. // No durable state to ensure is closed on shutdown.
  10588. return this.Fs = !1, Promise.resolve();
  10589. }
  10590. get started() {
  10591. return this.Fs;
  10592. }
  10593. setDatabaseDeletedListener() {
  10594. // No op.
  10595. }
  10596. setNetworkEnabled() {
  10597. // No op.
  10598. }
  10599. getIndexManager(t) {
  10600. // We do not currently support indices for memory persistence, so we can
  10601. // return the same shared instance of the memory index manager.
  10602. return this.indexManager;
  10603. }
  10604. getDocumentOverlayCache(t) {
  10605. let e = this.overlays[t.toKey()];
  10606. return e || (e = new $o, this.overlays[t.toKey()] = e), e;
  10607. }
  10608. getMutationQueue(t, e) {
  10609. let n = this.$s[t.toKey()];
  10610. return n || (n = new Bo(e, this.referenceDelegate), this.$s[t.toKey()] = n), n;
  10611. }
  10612. getTargetCache() {
  10613. return this.Bs;
  10614. }
  10615. getRemoteDocumentCache() {
  10616. return this.remoteDocumentCache;
  10617. }
  10618. getBundleCache() {
  10619. return this.qs;
  10620. }
  10621. runTransaction(t, e, n) {
  10622. N("MemoryPersistence", "Starting transaction:", t);
  10623. const s = new Go(this.Os.next());
  10624. return this.referenceDelegate.Us(), n(s).next((t => this.referenceDelegate.Ks(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(),
  10625. t)));
  10626. }
  10627. Gs(t, e) {
  10628. return Rt.or(Object.values(this.$s).map((n => () => n.containsKey(t, e))));
  10629. }
  10630. }
  10631. /**
  10632. * Memory persistence is not actually transactional, but future implementations
  10633. * may have transaction-scoped state.
  10634. */ class Go extends At {
  10635. constructor(t) {
  10636. super(), this.currentSequenceNumber = t;
  10637. }
  10638. }
  10639. class Qo {
  10640. constructor(t) {
  10641. this.persistence = t,
  10642. /** Tracks all documents that are active in Query views. */
  10643. this.Qs = new Oo,
  10644. /** The list of documents that are potentially GCed after each transaction. */
  10645. this.js = null;
  10646. }
  10647. static zs(t) {
  10648. return new Qo(t);
  10649. }
  10650. get Ws() {
  10651. if (this.js) return this.js;
  10652. throw O();
  10653. }
  10654. addReference(t, e, n) {
  10655. return this.Qs.addReference(n, e), this.Ws.delete(n.toString()), Rt.resolve();
  10656. }
  10657. removeReference(t, e, n) {
  10658. return this.Qs.removeReference(n, e), this.Ws.add(n.toString()), Rt.resolve();
  10659. }
  10660. markPotentiallyOrphaned(t, e) {
  10661. return this.Ws.add(e.toString()), Rt.resolve();
  10662. }
  10663. removeTarget(t, e) {
  10664. this.Qs.Is(e.targetId).forEach((t => this.Ws.add(t.toString())));
  10665. const n = this.persistence.getTargetCache();
  10666. return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  10667. t.forEach((t => this.Ws.add(t.toString())));
  10668. })).next((() => n.removeTargetData(t, e)));
  10669. }
  10670. Us() {
  10671. this.js = new Set;
  10672. }
  10673. Ks(t) {
  10674. // Remove newly orphaned documents.
  10675. const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();
  10676. return Rt.forEach(this.Ws, (n => {
  10677. const s = ht.fromPath(n);
  10678. return this.Hs(t, s).next((t => {
  10679. t || e.removeEntry(s, rt.min());
  10680. }));
  10681. })).next((() => (this.js = null, e.apply(t))));
  10682. }
  10683. updateLimboDocument(t, e) {
  10684. return this.Hs(t, e).next((t => {
  10685. t ? this.Ws.delete(e.toString()) : this.Ws.add(e.toString());
  10686. }));
  10687. }
  10688. Ls(t) {
  10689. // For eager GC, we don't care about the document size, there are no size thresholds.
  10690. return 0;
  10691. }
  10692. Hs(t, e) {
  10693. return Rt.or([ () => Rt.resolve(this.Qs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Gs(t, e) ]);
  10694. }
  10695. }
  10696. class jo {
  10697. constructor(t, e) {
  10698. this.persistence = t, this.Js = new os((t => qt(t.path)), ((t, e) => t.isEqual(e))),
  10699. this.garbageCollector = To(this, e);
  10700. }
  10701. static zs(t, e) {
  10702. return new jo(t, e);
  10703. }
  10704. // No-ops, present so memory persistence doesn't have to care which delegate
  10705. // it has.
  10706. Us() {}
  10707. Ks(t) {
  10708. return Rt.resolve();
  10709. }
  10710. forEachTarget(t, e) {
  10711. return this.persistence.getTargetCache().forEachTarget(t, e);
  10712. }
  10713. zn(t) {
  10714. const e = this.Jn(t);
  10715. return this.persistence.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  10716. }
  10717. Jn(t) {
  10718. let e = 0;
  10719. return this.Wn(t, (t => {
  10720. e++;
  10721. })).next((() => e));
  10722. }
  10723. Wn(t, e) {
  10724. return Rt.forEach(this.Js, ((n, s) => this.Xn(t, n, s).next((t => t ? Rt.resolve() : e(s)))));
  10725. }
  10726. removeTargets(t, e, n) {
  10727. return this.persistence.getTargetCache().removeTargets(t, e, n);
  10728. }
  10729. removeOrphanedDocuments(t, e) {
  10730. let n = 0;
  10731. const s = this.persistence.getRemoteDocumentCache(), i = s.newChangeBuffer();
  10732. return s.Cs(t, (s => this.Xn(t, s, e).next((t => {
  10733. t || (n++, i.removeEntry(s, rt.min()));
  10734. })))).next((() => i.apply(t))).next((() => n));
  10735. }
  10736. markPotentiallyOrphaned(t, e) {
  10737. return this.Js.set(e, t.currentSequenceNumber), Rt.resolve();
  10738. }
  10739. removeTarget(t, e) {
  10740. const n = e.withSequenceNumber(t.currentSequenceNumber);
  10741. return this.persistence.getTargetCache().updateTargetData(t, n);
  10742. }
  10743. addReference(t, e, n) {
  10744. return this.Js.set(n, t.currentSequenceNumber), Rt.resolve();
  10745. }
  10746. removeReference(t, e, n) {
  10747. return this.Js.set(n, t.currentSequenceNumber), Rt.resolve();
  10748. }
  10749. updateLimboDocument(t, e) {
  10750. return this.Js.set(e, t.currentSequenceNumber), Rt.resolve();
  10751. }
  10752. Ls(t) {
  10753. let e = t.key.toString().length;
  10754. return t.isFoundDocument() && (e += ze(t.data.value)), e;
  10755. }
  10756. Xn(t, e, n) {
  10757. return Rt.or([ () => this.persistence.Gs(t, e), () => this.persistence.getTargetCache().containsKey(t, e), () => {
  10758. const t = this.Js.get(e);
  10759. return Rt.resolve(void 0 !== t && t > n);
  10760. } ]);
  10761. }
  10762. getCacheSize(t) {
  10763. return this.persistence.getRemoteDocumentCache().getSize(t);
  10764. }
  10765. }
  10766. /**
  10767. * @license
  10768. * Copyright 2020 Google LLC
  10769. *
  10770. * Licensed under the Apache License, Version 2.0 (the "License");
  10771. * you may not use this file except in compliance with the License.
  10772. * You may obtain a copy of the License at
  10773. *
  10774. * http://www.apache.org/licenses/LICENSE-2.0
  10775. *
  10776. * Unless required by applicable law or agreed to in writing, software
  10777. * distributed under the License is distributed on an "AS IS" BASIS,
  10778. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10779. * See the License for the specific language governing permissions and
  10780. * limitations under the License.
  10781. */
  10782. /** Performs database creation and schema upgrades. */ class zo {
  10783. constructor(t) {
  10784. this.serializer = t;
  10785. }
  10786. /**
  10787. * Performs database creation and schema upgrades.
  10788. *
  10789. * Note that in production, this method is only ever used to upgrade the schema
  10790. * to SCHEMA_VERSION. Different values of toVersion are only used for testing
  10791. * and local feature development.
  10792. */ O(t, e, n, s) {
  10793. const i = new Pt("createOrUpgrade", e);
  10794. n < 1 && s >= 1 && (function(t) {
  10795. t.createObjectStore("owner");
  10796. }(t), function(t) {
  10797. t.createObjectStore("mutationQueues", {
  10798. keyPath: "userId"
  10799. });
  10800. t.createObjectStore("mutations", {
  10801. keyPath: "batchId",
  10802. autoIncrement: !0
  10803. }).createIndex("userMutationsIndex", Qt, {
  10804. unique: !0
  10805. }), t.createObjectStore("documentMutations");
  10806. }
  10807. /**
  10808. * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
  10809. * and rewrites all data.
  10810. */ (t), Wo(t), function(t) {
  10811. t.createObjectStore("remoteDocuments");
  10812. }(t));
  10813. // Migration 2 to populate the targetGlobal object no longer needed since
  10814. // migration 3 unconditionally clears it.
  10815. let r = Rt.resolve();
  10816. return n < 3 && s >= 3 && (
  10817. // Brand new clients don't need to drop and recreate--only clients that
  10818. // potentially have corrupt data.
  10819. 0 !== n && (!function(t) {
  10820. t.deleteObjectStore("targetDocuments"), t.deleteObjectStore("targets"), t.deleteObjectStore("targetGlobal");
  10821. }(t), Wo(t)), r = r.next((() =>
  10822. /**
  10823. * Creates the target global singleton row.
  10824. *
  10825. * @param txn - The version upgrade transaction for indexeddb
  10826. */
  10827. function(t) {
  10828. const e = t.store("targetGlobal"), n = {
  10829. highestTargetId: 0,
  10830. highestListenSequenceNumber: 0,
  10831. lastRemoteSnapshotVersion: rt.min().toTimestamp(),
  10832. targetCount: 0
  10833. };
  10834. return e.put("targetGlobalKey", n);
  10835. }(i)))), n < 4 && s >= 4 && (0 !== n && (
  10836. // Schema version 3 uses auto-generated keys to generate globally unique
  10837. // mutation batch IDs (this was previously ensured internally by the
  10838. // client). To migrate to the new schema, we have to read all mutations
  10839. // and write them back out. We preserve the existing batch IDs to guarantee
  10840. // consistency with other object stores. Any further mutation batch IDs will
  10841. // be auto-generated.
  10842. r = r.next((() => function(t, e) {
  10843. return e.store("mutations").j().next((n => {
  10844. t.deleteObjectStore("mutations");
  10845. t.createObjectStore("mutations", {
  10846. keyPath: "batchId",
  10847. autoIncrement: !0
  10848. }).createIndex("userMutationsIndex", Qt, {
  10849. unique: !0
  10850. });
  10851. const s = e.store("mutations"), i = n.map((t => s.put(t)));
  10852. return Rt.waitFor(i);
  10853. }));
  10854. }(t, i)))), r = r.next((() => {
  10855. !function(t) {
  10856. t.createObjectStore("clientMetadata", {
  10857. keyPath: "clientId"
  10858. });
  10859. }(t);
  10860. }))), n < 5 && s >= 5 && (r = r.next((() => this.Ys(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {
  10861. t.createObjectStore("remoteDocumentGlobal");
  10862. }(t), this.Xs(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Zs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.ti(t, i)))),
  10863. n < 9 && s >= 9 && (r = r.next((() => {
  10864. // Multi-Tab used to manage its own changelog, but this has been moved
  10865. // to the DbRemoteDocument object store itself. Since the previous change
  10866. // log only contained transient data, we can drop its object store.
  10867. !function(t) {
  10868. t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
  10869. }(t);
  10870. // Note: Schema version 9 used to create a read time index for the
  10871. // RemoteDocumentCache. This is now done with schema version 13.
  10872. }))), n < 10 && s >= 10 && (r = r.next((() => this.ei(i)))), n < 11 && s >= 11 && (r = r.next((() => {
  10873. !function(t) {
  10874. t.createObjectStore("bundles", {
  10875. keyPath: "bundleId"
  10876. });
  10877. }(t), function(t) {
  10878. t.createObjectStore("namedQueries", {
  10879. keyPath: "name"
  10880. });
  10881. }(t);
  10882. }))), n < 12 && s >= 12 && (r = r.next((() => {
  10883. !function(t) {
  10884. const e = t.createObjectStore("documentOverlays", {
  10885. keyPath: oe
  10886. });
  10887. e.createIndex("collectionPathOverlayIndex", ue, {
  10888. unique: !1
  10889. }), e.createIndex("collectionGroupOverlayIndex", ce, {
  10890. unique: !1
  10891. });
  10892. }(t);
  10893. }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {
  10894. const e = t.createObjectStore("remoteDocumentsV14", {
  10895. keyPath: Ht
  10896. });
  10897. e.createIndex("documentKeyIndex", Jt), e.createIndex("collectionGroupIndex", Yt);
  10898. }(t))).next((() => this.ni(t, i))).next((() => t.deleteObjectStore("remoteDocuments")))),
  10899. n < 14 && s >= 14 && (r = r.next((() => this.si(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {
  10900. t.createObjectStore("indexConfiguration", {
  10901. keyPath: "indexId",
  10902. autoIncrement: !0
  10903. }).createIndex("collectionGroupIndex", "collectionGroup", {
  10904. unique: !1
  10905. });
  10906. t.createObjectStore("indexState", {
  10907. keyPath: ne
  10908. }).createIndex("sequenceNumberIndex", se, {
  10909. unique: !1
  10910. });
  10911. t.createObjectStore("indexEntries", {
  10912. keyPath: ie
  10913. }).createIndex("documentKeyIndex", re, {
  10914. unique: !1
  10915. });
  10916. }(t)))), r;
  10917. }
  10918. Xs(t) {
  10919. let e = 0;
  10920. return t.store("remoteDocuments").X(((t, n) => {
  10921. e += ro(n);
  10922. })).next((() => {
  10923. const n = {
  10924. byteSize: e
  10925. };
  10926. return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey", n);
  10927. }));
  10928. }
  10929. Ys(t) {
  10930. const e = t.store("mutationQueues"), n = t.store("mutations");
  10931. return e.j().next((e => Rt.forEach(e, (e => {
  10932. const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
  10933. return n.j("userMutationsIndex", s).next((n => Rt.forEach(n, (n => {
  10934. F(n.userId === e.userId);
  10935. const s = _r(this.serializer, n);
  10936. return io(t, e.userId, s).next((() => {}));
  10937. }))));
  10938. }))));
  10939. }
  10940. /**
  10941. * Ensures that every document in the remote document cache has a corresponding sentinel row
  10942. * with a sequence number. Missing rows are given the most recently used sequence number.
  10943. */ Zs(t) {
  10944. const e = t.store("targetDocuments"), n = t.store("remoteDocuments");
  10945. return t.store("targetGlobal").get("targetGlobalKey").next((t => {
  10946. const s = [];
  10947. return n.X(((n, i) => {
  10948. const r = new ut(n), o = function(t) {
  10949. return [ 0, qt(t) ];
  10950. }(r);
  10951. s.push(e.get(o).next((n => n ? Rt.resolve() : (n => e.put({
  10952. targetId: 0,
  10953. path: qt(n),
  10954. sequenceNumber: t.highestListenSequenceNumber
  10955. }))(r))));
  10956. })).next((() => Rt.waitFor(s)));
  10957. }));
  10958. }
  10959. ti(t, e) {
  10960. // Create the index.
  10961. t.createObjectStore("collectionParents", {
  10962. keyPath: ee
  10963. });
  10964. const n = e.store("collectionParents"), s = new Wr, i = t => {
  10965. if (s.add(t)) {
  10966. const e = t.lastSegment(), s = t.popLast();
  10967. return n.put({
  10968. collectionId: e,
  10969. parent: qt(s)
  10970. });
  10971. }
  10972. };
  10973. // Helper to add an index entry iff we haven't already written it.
  10974. // Index existing remote documents.
  10975. return e.store("remoteDocuments").X({
  10976. Y: !0
  10977. }, ((t, e) => {
  10978. const n = new ut(t);
  10979. return i(n.popLast());
  10980. })).next((() => e.store("documentMutations").X({
  10981. Y: !0
  10982. }, (([t, e, n], s) => {
  10983. const r = Gt(e);
  10984. return i(r.popLast());
  10985. }))));
  10986. }
  10987. ei(t) {
  10988. const e = t.store("targets");
  10989. return e.X(((t, n) => {
  10990. const s = mr(n), i = gr(this.serializer, s);
  10991. return e.put(i);
  10992. }));
  10993. }
  10994. ni(t, e) {
  10995. const n = e.store("remoteDocuments"), s = [];
  10996. return n.X(((t, n) => {
  10997. const i = e.store("remoteDocumentsV14"), r = (o = n, o.document ? new ht(ut.fromString(o.document.name).popFirst(5)) : o.noDocument ? ht.fromSegments(o.noDocument.path) : o.unknownDocument ? ht.fromSegments(o.unknownDocument.path) : O()).path.toArray();
  10998. var o;
  10999. /**
  11000. * @license
  11001. * Copyright 2017 Google LLC
  11002. *
  11003. * Licensed under the Apache License, Version 2.0 (the "License");
  11004. * you may not use this file except in compliance with the License.
  11005. * You may obtain a copy of the License at
  11006. *
  11007. * http://www.apache.org/licenses/LICENSE-2.0
  11008. *
  11009. * Unless required by applicable law or agreed to in writing, software
  11010. * distributed under the License is distributed on an "AS IS" BASIS,
  11011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11012. * See the License for the specific language governing permissions and
  11013. * limitations under the License.
  11014. */ const u = {
  11015. prefixPath: r.slice(0, r.length - 2),
  11016. collectionGroup: r[r.length - 2],
  11017. documentId: r[r.length - 1],
  11018. readTime: n.readTime || [ 0, 0 ],
  11019. unknownDocument: n.unknownDocument,
  11020. noDocument: n.noDocument,
  11021. document: n.document,
  11022. hasCommittedMutations: !!n.hasCommittedMutations
  11023. };
  11024. s.push(i.put(u));
  11025. })).next((() => Rt.waitFor(s)));
  11026. }
  11027. si(t, e) {
  11028. const n = e.store("mutations"), s = Po(this.serializer), i = new Ko(Qo.zs, this.serializer.fe);
  11029. return n.j().next((t => {
  11030. const n = new Map;
  11031. return t.forEach((t => {
  11032. var e;
  11033. let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : gs();
  11034. _r(this.serializer, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);
  11035. })), Rt.forEach(n, ((t, n) => {
  11036. const r = new V(n), o = Rr.de(this.serializer, r), u = i.getIndexManager(r), c = oo.de(r, this.serializer, u, i.referenceDelegate);
  11037. return new ko(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new we(e, Ot.ct), t).next();
  11038. }));
  11039. }));
  11040. }
  11041. }
  11042. function Wo(t) {
  11043. t.createObjectStore("targetDocuments", {
  11044. keyPath: Zt
  11045. }).createIndex("documentTargetsIndex", te, {
  11046. unique: !0
  11047. });
  11048. // NOTE: This is unique only because the TargetId is the suffix.
  11049. t.createObjectStore("targets", {
  11050. keyPath: "targetId"
  11051. }).createIndex("queryTargetsIndex", Xt, {
  11052. unique: !0
  11053. }), t.createObjectStore("targetGlobal");
  11054. }
  11055. const Ho = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";
  11056. /**
  11057. * Oldest acceptable age in milliseconds for client metadata before the client
  11058. * is considered inactive and its associated data is garbage collected.
  11059. */
  11060. /**
  11061. * An IndexedDB-backed instance of Persistence. Data is stored persistently
  11062. * across sessions.
  11063. *
  11064. * On Web only, the Firestore SDKs support shared access to its persistence
  11065. * layer. This allows multiple browser tabs to read and write to IndexedDb and
  11066. * to synchronize state even without network connectivity. Shared access is
  11067. * currently optional and not enabled unless all clients invoke
  11068. * `enablePersistence()` with `{synchronizeTabs:true}`.
  11069. *
  11070. * In multi-tab mode, if multiple clients are active at the same time, the SDK
  11071. * will designate one client as the “primary client”. An effort is made to pick
  11072. * a visible, network-connected and active client, and this client is
  11073. * responsible for letting other clients know about its presence. The primary
  11074. * client writes a unique client-generated identifier (the client ID) to
  11075. * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to
  11076. * update this entry, another client can acquire the lease and take over as
  11077. * primary.
  11078. *
  11079. * Some persistence operations in the SDK are designated as primary-client only
  11080. * operations. This includes the acknowledgment of mutations and all updates of
  11081. * remote documents. The effects of these operations are written to persistence
  11082. * and then broadcast to other tabs via LocalStorage (see
  11083. * `WebStorageSharedClientState`), which then refresh their state from
  11084. * persistence.
  11085. *
  11086. * Similarly, the primary client listens to notifications sent by secondary
  11087. * clients to discover persistence changes written by secondary clients, such as
  11088. * the addition of new mutations and query targets.
  11089. *
  11090. * If multi-tab is not enabled and another tab already obtained the primary
  11091. * lease, IndexedDbPersistence enters a failed state and all subsequent
  11092. * operations will automatically fail.
  11093. *
  11094. * Additionally, there is an optimization so that when a tab is closed, the
  11095. * primary lease is released immediately (this is especially important to make
  11096. * sure that a refreshed tab is able to immediately re-acquire the primary
  11097. * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
  11098. * since it is an asynchronous API. So in addition to attempting to give up the
  11099. * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
  11100. * LocalStorage which acts as an indicator that another tab should go ahead and
  11101. * take the primary lease immediately regardless of the current lease timestamp.
  11102. *
  11103. * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
  11104. * longer optional.
  11105. */
  11106. class Jo {
  11107. constructor(
  11108. /**
  11109. * Whether to synchronize the in-memory state of multiple tabs and share
  11110. * access to local persistence.
  11111. */
  11112. t, e, n, s, i, r, o, u, c,
  11113. /**
  11114. * If set to true, forcefully obtains database access. Existing tabs will
  11115. * no longer be able to access IndexedDB.
  11116. */
  11117. a, h = 15) {
  11118. if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n,
  11119. this.ii = i, this.window = r, this.document = o, this.ri = c, this.oi = a, this.ui = h,
  11120. this.Os = null, this.Fs = !1, this.isPrimary = !1, this.networkEnabled = !0,
  11121. /** Our window.unload handler, if registered. */
  11122. this.ci = null, this.inForeground = !1,
  11123. /** Our 'visibilitychange' listener if registered. */
  11124. this.ai = null,
  11125. /** The client metadata refresh task. */
  11126. this.hi = null,
  11127. /** The last time we garbage collected the client metadata object store. */
  11128. this.li = Number.NEGATIVE_INFINITY,
  11129. /** A listener to notify on primary state changes. */
  11130. this.fi = t => Promise.resolve(), !Jo.D()) throw new U(q.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
  11131. this.referenceDelegate = new Eo(this, s), this.di = e + "main", this.serializer = new ar(u),
  11132. this.wi = new bt(this.di, this.ui, new zo(this.serializer)), this.Bs = new fo(this.referenceDelegate, this.serializer),
  11133. this.remoteDocumentCache = Po(this.serializer), this.qs = new Er, this.window && this.window.localStorage ? this._i = this.window.localStorage : (this._i = null,
  11134. !1 === a && k("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  11135. }
  11136. /**
  11137. * Attempt to start IndexedDb persistence.
  11138. *
  11139. * @returns Whether persistence was enabled.
  11140. */ start() {
  11141. // NOTE: This is expected to fail sometimes (in the case of another tab
  11142. // already having the persistence lock), so it's the first thing we should
  11143. // do.
  11144. return this.mi().then((() => {
  11145. if (!this.isPrimary && !this.allowTabSynchronization)
  11146. // Fail `start()` if `synchronizeTabs` is disabled and we cannot
  11147. // obtain the primary lease.
  11148. throw new U(q.FAILED_PRECONDITION, Ho);
  11149. return this.gi(), this.yi(), this.pi(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (t => this.Bs.getHighestSequenceNumber(t)));
  11150. })).then((t => {
  11151. this.Os = new Ot(t, this.ri);
  11152. })).then((() => {
  11153. this.Fs = !0;
  11154. })).catch((t => (this.wi && this.wi.close(), Promise.reject(t))));
  11155. }
  11156. /**
  11157. * Registers a listener that gets called when the primary state of the
  11158. * instance changes. Upon registering, this listener is invoked immediately
  11159. * with the current primary state.
  11160. *
  11161. * PORTING NOTE: This is only used for Web multi-tab.
  11162. */ Ii(t) {
  11163. return this.fi = async e => {
  11164. if (this.started) return t(e);
  11165. }, t(this.isPrimary);
  11166. }
  11167. /**
  11168. * Registers a listener that gets called when the database receives a
  11169. * version change event indicating that it has deleted.
  11170. *
  11171. * PORTING NOTE: This is only used for Web multi-tab.
  11172. */ setDatabaseDeletedListener(t) {
  11173. this.wi.B((async e => {
  11174. // Check if an attempt is made to delete IndexedDB.
  11175. null === e.newVersion && await t();
  11176. }));
  11177. }
  11178. /**
  11179. * Adjusts the current network state in the client's metadata, potentially
  11180. * affecting the primary lease.
  11181. *
  11182. * PORTING NOTE: This is only used for Web multi-tab.
  11183. */ setNetworkEnabled(t) {
  11184. this.networkEnabled !== t && (this.networkEnabled = t,
  11185. // Schedule a primary lease refresh for immediate execution. The eventual
  11186. // lease update will be propagated via `primaryStateListener`.
  11187. this.ii.enqueueAndForget((async () => {
  11188. this.started && await this.mi();
  11189. })));
  11190. }
  11191. /**
  11192. * Updates the client metadata in IndexedDb and attempts to either obtain or
  11193. * extend the primary lease for the local client. Asynchronously notifies the
  11194. * primary state listener if the client either newly obtained or released its
  11195. * primary lease.
  11196. */ mi() {
  11197. return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (t => Xo(t).put({
  11198. clientId: this.clientId,
  11199. updateTimeMs: Date.now(),
  11200. networkEnabled: this.networkEnabled,
  11201. inForeground: this.inForeground
  11202. }).next((() => {
  11203. if (this.isPrimary) return this.Ti(t).next((t => {
  11204. t || (this.isPrimary = !1, this.ii.enqueueRetryable((() => this.fi(!1))));
  11205. }));
  11206. })).next((() => this.Ei(t))).next((e => this.isPrimary && !e ? this.Ai(t).next((() => !1)) : !!e && this.vi(t).next((() => !0)))))).catch((t => {
  11207. if (Dt(t))
  11208. // Proceed with the existing state. Any subsequent access to
  11209. // IndexedDB will verify the lease.
  11210. return N("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
  11211. if (!this.allowTabSynchronization) throw t;
  11212. return N("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t),
  11213. /* isPrimary= */ !1;
  11214. })).then((t => {
  11215. this.isPrimary !== t && this.ii.enqueueRetryable((() => this.fi(t))), this.isPrimary = t;
  11216. }));
  11217. }
  11218. Ti(t) {
  11219. return Yo(t).get("owner").next((t => Rt.resolve(this.Ri(t))));
  11220. }
  11221. Pi(t) {
  11222. return Xo(t).delete(this.clientId);
  11223. }
  11224. /**
  11225. * If the garbage collection threshold has passed, prunes the
  11226. * RemoteDocumentChanges and the ClientMetadata store based on the last update
  11227. * time of all clients.
  11228. */ async bi() {
  11229. if (this.isPrimary && !this.Vi(this.li, 18e5)) {
  11230. this.li = Date.now();
  11231. const t = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (t => {
  11232. const e = _e(t, "clientMetadata");
  11233. return e.j().next((t => {
  11234. const n = this.Si(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));
  11235. // Delete metadata for clients that are no longer considered active.
  11236. return Rt.forEach(s, (t => e.delete(t.clientId))).next((() => s));
  11237. }));
  11238. })).catch((() => []));
  11239. // Delete potential leftover entries that may continue to mark the
  11240. // inactive clients as zombied in LocalStorage.
  11241. // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
  11242. // the client atomically, but we can't. So we opt to delete the IndexedDb
  11243. // entries first to avoid potentially reviving a zombied client.
  11244. if (this._i) for (const e of t) this._i.removeItem(this.Di(e.clientId));
  11245. }
  11246. }
  11247. /**
  11248. * Schedules a recurring timer to update the client metadata and to either
  11249. * extend or acquire the primary lease if the client is eligible.
  11250. */ pi() {
  11251. this.hi = this.ii.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.mi().then((() => this.bi())).then((() => this.pi()))));
  11252. }
  11253. /** Checks whether `client` is the local client. */ Ri(t) {
  11254. return !!t && t.ownerId === this.clientId;
  11255. }
  11256. /**
  11257. * Evaluate the state of all active clients and determine whether the local
  11258. * client is or can act as the holder of the primary lease. Returns whether
  11259. * the client is eligible for the lease, but does not actually acquire it.
  11260. * May return 'false' even if there is no active leaseholder and another
  11261. * (foreground) client should become leaseholder instead.
  11262. */ Ei(t) {
  11263. if (this.oi) return Rt.resolve(!0);
  11264. return Yo(t).get("owner").next((e => {
  11265. // A client is eligible for the primary lease if:
  11266. // - its network is enabled and the client's tab is in the foreground.
  11267. // - its network is enabled and no other client's tab is in the
  11268. // foreground.
  11269. // - every clients network is disabled and the client's tab is in the
  11270. // foreground.
  11271. // - every clients network is disabled and no other client's tab is in
  11272. // the foreground.
  11273. // - the `forceOwningTab` setting was passed in.
  11274. if (null !== e && this.Vi(e.leaseTimestampMs, 5e3) && !this.Ci(e.ownerId)) {
  11275. if (this.Ri(e) && this.networkEnabled) return !0;
  11276. if (!this.Ri(e)) {
  11277. if (!e.allowTabSynchronization)
  11278. // Fail the `canActAsPrimary` check if the current leaseholder has
  11279. // not opted into multi-tab synchronization. If this happens at
  11280. // client startup, we reject the Promise returned by
  11281. // `enablePersistence()` and the user can continue to use Firestore
  11282. // with in-memory persistence.
  11283. // If this fails during a lease refresh, we will instead block the
  11284. // AsyncQueue from executing further operations. Note that this is
  11285. // acceptable since mixing & matching different `synchronizeTabs`
  11286. // settings is not supported.
  11287. // TODO(b/114226234): Remove this check when `synchronizeTabs` can
  11288. // no longer be turned off.
  11289. throw new U(q.FAILED_PRECONDITION, Ho);
  11290. return !1;
  11291. }
  11292. }
  11293. return !(!this.networkEnabled || !this.inForeground) || Xo(t).j().next((t => void 0 === this.Si(t, 5e3).find((t => {
  11294. if (this.clientId !== t.clientId) {
  11295. const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;
  11296. if (e || n && s) return !0;
  11297. }
  11298. return !1;
  11299. }))));
  11300. })).next((t => (this.isPrimary !== t && N("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`),
  11301. t)));
  11302. }
  11303. async shutdown() {
  11304. // The shutdown() operations are idempotent and can be called even when
  11305. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  11306. this.Fs = !1, this.xi(), this.hi && (this.hi.cancel(), this.hi = null), this.Ni(),
  11307. this.ki(),
  11308. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  11309. // has obtained the primary lease.
  11310. await this.wi.runTransaction("shutdown", "readwrite", [ "owner", "clientMetadata" ], (t => {
  11311. const e = new we(t, Ot.ct);
  11312. return this.Ai(e).next((() => this.Pi(e)));
  11313. })), this.wi.close(),
  11314. // Remove the entry marking the client as zombied from LocalStorage since
  11315. // we successfully deleted its metadata from IndexedDb.
  11316. this.Mi();
  11317. }
  11318. /**
  11319. * Returns clients that are not zombied and have an updateTime within the
  11320. * provided threshold.
  11321. */ Si(t, e) {
  11322. return t.filter((t => this.Vi(t.updateTimeMs, e) && !this.Ci(t.clientId)));
  11323. }
  11324. /**
  11325. * Returns the IDs of the clients that are currently active. If multi-tab
  11326. * is not supported, returns an array that only contains the local client's
  11327. * ID.
  11328. *
  11329. * PORTING NOTE: This is only used for Web multi-tab.
  11330. */ $i() {
  11331. return this.runTransaction("getActiveClients", "readonly", (t => Xo(t).j().next((t => this.Si(t, 18e5).map((t => t.clientId))))));
  11332. }
  11333. get started() {
  11334. return this.Fs;
  11335. }
  11336. getMutationQueue(t, e) {
  11337. return oo.de(t, this.serializer, e, this.referenceDelegate);
  11338. }
  11339. getTargetCache() {
  11340. return this.Bs;
  11341. }
  11342. getRemoteDocumentCache() {
  11343. return this.remoteDocumentCache;
  11344. }
  11345. getIndexManager(t) {
  11346. return new Jr(t, this.serializer.fe.databaseId);
  11347. }
  11348. getDocumentOverlayCache(t) {
  11349. return Rr.de(this.serializer, t);
  11350. }
  11351. getBundleCache() {
  11352. return this.qs;
  11353. }
  11354. runTransaction(t, e, n) {
  11355. N("IndexedDbPersistence", "Starting transaction:", t);
  11356. const s = "readonly" === e ? "readonly" : "readwrite", i = 15 === (r = this.ui) ? de : 14 === r ? fe : 13 === r ? le : 12 === r ? he : 11 === r ? ae : void O();
  11357. /** Returns the object stores for the provided schema. */
  11358. var r;
  11359. let o;
  11360. // Do all transactions as readwrite against all object stores, since we
  11361. // are the only reader/writer.
  11362. return this.wi.runTransaction(t, s, i, (s => (o = new we(s, this.Os ? this.Os.next() : Ot.ct),
  11363. "readwrite-primary" === e ? this.Ti(o).next((t => !!t || this.Ei(o))).next((e => {
  11364. if (!e) throw k(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1,
  11365. this.ii.enqueueRetryable((() => this.fi(!1))), new U(q.FAILED_PRECONDITION, Et);
  11366. return n(o);
  11367. })).next((t => this.vi(o).next((() => t)))) : this.Oi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(),
  11368. t)));
  11369. }
  11370. /**
  11371. * Verifies that the current tab is the primary leaseholder or alternatively
  11372. * that the leaseholder has opted into multi-tab synchronization.
  11373. */
  11374. // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  11375. // be turned off.
  11376. Oi(t) {
  11377. return Yo(t).get("owner").next((t => {
  11378. if (null !== t && this.Vi(t.leaseTimestampMs, 5e3) && !this.Ci(t.ownerId) && !this.Ri(t) && !(this.oi || this.allowTabSynchronization && t.allowTabSynchronization)) throw new U(q.FAILED_PRECONDITION, Ho);
  11379. }));
  11380. }
  11381. /**
  11382. * Obtains or extends the new primary lease for the local client. This
  11383. * method does not verify that the client is eligible for this lease.
  11384. */ vi(t) {
  11385. const e = {
  11386. ownerId: this.clientId,
  11387. allowTabSynchronization: this.allowTabSynchronization,
  11388. leaseTimestampMs: Date.now()
  11389. };
  11390. return Yo(t).put("owner", e);
  11391. }
  11392. static D() {
  11393. return bt.D();
  11394. }
  11395. /** Checks the primary lease and removes it if we are the current primary. */ Ai(t) {
  11396. const e = Yo(t);
  11397. return e.get("owner").next((t => this.Ri(t) ? (N("IndexedDbPersistence", "Releasing primary lease."),
  11398. e.delete("owner")) : Rt.resolve()));
  11399. }
  11400. /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ Vi(t, e) {
  11401. const n = Date.now();
  11402. return !(t < n - e) && (!(t > n) || (k(`Detected an update time that is in the future: ${t} > ${n}`),
  11403. !1));
  11404. }
  11405. gi() {
  11406. null !== this.document && "function" == typeof this.document.addEventListener && (this.ai = () => {
  11407. this.ii.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState,
  11408. this.mi())));
  11409. }, this.document.addEventListener("visibilitychange", this.ai), this.inForeground = "visible" === this.document.visibilityState);
  11410. }
  11411. Ni() {
  11412. this.ai && (this.document.removeEventListener("visibilitychange", this.ai), this.ai = null);
  11413. }
  11414. /**
  11415. * Attaches a window.unload handler that will synchronously write our
  11416. * clientId to a "zombie client id" location in LocalStorage. This can be used
  11417. * by tabs trying to acquire the primary lease to determine that the lease
  11418. * is no longer valid even if the timestamp is recent. This is particularly
  11419. * important for the refresh case (so the tab correctly re-acquires the
  11420. * primary lease). LocalStorage is used for this rather than IndexedDb because
  11421. * it is a synchronous API and so can be used reliably from an unload
  11422. * handler.
  11423. */ yi() {
  11424. var t;
  11425. "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.ci = () => {
  11426. // Note: In theory, this should be scheduled on the AsyncQueue since it
  11427. // accesses internal state. We execute this code directly during shutdown
  11428. // to make sure it gets a chance to run.
  11429. this.xi();
  11430. const t = /(?:Version|Mobile)\/1[456]/;
  11431. isSafari() && (navigator.appVersion.match(t) || navigator.userAgent.match(t)) &&
  11432. // On Safari 14, 15, and 16, we do not run any cleanup actions as it might
  11433. // trigger a bug that prevents Safari from re-opening IndexedDB during
  11434. // the next page load.
  11435. // See https://bugs.webkit.org/show_bug.cgi?id=226547
  11436. this.ii.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.ii.enqueueAndForget((() => this.shutdown()));
  11437. }, this.window.addEventListener("pagehide", this.ci));
  11438. }
  11439. ki() {
  11440. this.ci && (this.window.removeEventListener("pagehide", this.ci), this.ci = null);
  11441. }
  11442. /**
  11443. * Returns whether a client is "zombied" based on its LocalStorage entry.
  11444. * Clients become zombied when their tab closes without running all of the
  11445. * cleanup logic in `shutdown()`.
  11446. */ Ci(t) {
  11447. var e;
  11448. try {
  11449. const n = null !== (null === (e = this._i) || void 0 === e ? void 0 : e.getItem(this.Di(t)));
  11450. return N("IndexedDbPersistence", `Client '${t}' ${n ? "is" : "is not"} zombied in LocalStorage`),
  11451. n;
  11452. } catch (t) {
  11453. // Gracefully handle if LocalStorage isn't working.
  11454. return k("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
  11455. }
  11456. }
  11457. /**
  11458. * Record client as zombied (a client that had its tab closed). Zombied
  11459. * clients are ignored during primary tab selection.
  11460. */ xi() {
  11461. if (this._i) try {
  11462. this._i.setItem(this.Di(this.clientId), String(Date.now()));
  11463. } catch (t) {
  11464. // Gracefully handle if LocalStorage isn't available / working.
  11465. k("Failed to set zombie client id.", t);
  11466. }
  11467. }
  11468. /** Removes the zombied client entry if it exists. */ Mi() {
  11469. if (this._i) try {
  11470. this._i.removeItem(this.Di(this.clientId));
  11471. } catch (t) {
  11472. // Ignore
  11473. }
  11474. }
  11475. Di(t) {
  11476. return `firestore_zombie_${this.persistenceKey}_${t}`;
  11477. }
  11478. }
  11479. /**
  11480. * Helper to get a typed SimpleDbStore for the primary client object store.
  11481. */ function Yo(t) {
  11482. return _e(t, "owner");
  11483. }
  11484. /**
  11485. * Helper to get a typed SimpleDbStore for the client metadata object store.
  11486. */ function Xo(t) {
  11487. return _e(t, "clientMetadata");
  11488. }
  11489. /**
  11490. * Generates a string used as a prefix when storing data in IndexedDB and
  11491. * LocalStorage.
  11492. */ function Zo(t, e) {
  11493. // Use two different prefix formats:
  11494. // * firestore / persistenceKey / projectID . databaseID / ...
  11495. // * firestore / persistenceKey / projectID / ...
  11496. // projectIDs are DNS-compatible names and cannot contain dots
  11497. // so there's no danger of collisions.
  11498. let n = t.projectId;
  11499. return t.isDefaultDatabase || (n += "." + t.database), "firestore/" + e + "/" + n + "/";
  11500. }
  11501. /**
  11502. * @license
  11503. * Copyright 2017 Google LLC
  11504. *
  11505. * Licensed under the Apache License, Version 2.0 (the "License");
  11506. * you may not use this file except in compliance with the License.
  11507. * You may obtain a copy of the License at
  11508. *
  11509. * http://www.apache.org/licenses/LICENSE-2.0
  11510. *
  11511. * Unless required by applicable law or agreed to in writing, software
  11512. * distributed under the License is distributed on an "AS IS" BASIS,
  11513. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11514. * See the License for the specific language governing permissions and
  11515. * limitations under the License.
  11516. */
  11517. /**
  11518. * A set of changes to what documents are currently in view and out of view for
  11519. * a given query. These changes are sent to the LocalStore by the View (via
  11520. * the SyncEngine) and are used to pin / unpin documents as appropriate.
  11521. */
  11522. class tu {
  11523. constructor(t, e, n, s) {
  11524. this.targetId = t, this.fromCache = e, this.Fi = n, this.Bi = s;
  11525. }
  11526. static Li(t, e) {
  11527. let n = gs(), s = gs();
  11528. for (const t of e.docChanges) switch (t.type) {
  11529. case 0 /* ChangeType.Added */ :
  11530. n = n.add(t.doc.key);
  11531. break;
  11532. case 1 /* ChangeType.Removed */ :
  11533. s = s.add(t.doc.key);
  11534. // do nothing
  11535. }
  11536. return new tu(t, e.fromCache, n, s);
  11537. }
  11538. }
  11539. /**
  11540. * @license
  11541. * Copyright 2019 Google LLC
  11542. *
  11543. * Licensed under the Apache License, Version 2.0 (the "License");
  11544. * you may not use this file except in compliance with the License.
  11545. * You may obtain a copy of the License at
  11546. *
  11547. * http://www.apache.org/licenses/LICENSE-2.0
  11548. *
  11549. * Unless required by applicable law or agreed to in writing, software
  11550. * distributed under the License is distributed on an "AS IS" BASIS,
  11551. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11552. * See the License for the specific language governing permissions and
  11553. * limitations under the License.
  11554. */
  11555. /**
  11556. * The Firestore query engine.
  11557. *
  11558. * Firestore queries can be executed in three modes. The Query Engine determines
  11559. * what mode to use based on what data is persisted. The mode only determines
  11560. * the runtime complexity of the query - the result set is equivalent across all
  11561. * implementations.
  11562. *
  11563. * The Query engine will use indexed-based execution if a user has configured
  11564. * any index that can be used to execute query (via `setIndexConfiguration()`).
  11565. * Otherwise, the engine will try to optimize the query by re-using a previously
  11566. * persisted query result. If that is not possible, the query will be executed
  11567. * via a full collection scan.
  11568. *
  11569. * Index-based execution is the default when available. The query engine
  11570. * supports partial indexed execution and merges the result from the index
  11571. * lookup with documents that have not yet been indexed. The index evaluation
  11572. * matches the backend's format and as such, the SDK can use indexing for all
  11573. * queries that the backend supports.
  11574. *
  11575. * If no index exists, the query engine tries to take advantage of the target
  11576. * document mapping in the TargetCache. These mappings exists for all queries
  11577. * that have been synced with the backend at least once and allow the query
  11578. * engine to only read documents that previously matched a query plus any
  11579. * documents that were edited after the query was last listened to.
  11580. *
  11581. * There are some cases when this optimization is not guaranteed to produce
  11582. * the same results as full collection scans. In these cases, query
  11583. * processing falls back to full scans. These cases are:
  11584. *
  11585. * - Limit queries where a document that matched the query previously no longer
  11586. * matches the query.
  11587. *
  11588. * - Limit queries where a document edit may cause the document to sort below
  11589. * another document that is in the local cache.
  11590. *
  11591. * - Queries that have never been CURRENT or free of limbo documents.
  11592. */ class eu {
  11593. constructor() {
  11594. this.qi = !1;
  11595. }
  11596. /** Sets the document view to query against. */ initialize(t, e) {
  11597. this.Ui = t, this.indexManager = e, this.qi = !0;
  11598. }
  11599. /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {
  11600. return this.Ki(t, e).next((i => i || this.Gi(t, e, s, n))).next((n => n || this.Qi(t, e)));
  11601. }
  11602. /**
  11603. * Performs an indexed query that evaluates the query based on a collection's
  11604. * persisted index values. Returns `null` if an index is not available.
  11605. */ Ki(t, e) {
  11606. if (Qn(e))
  11607. // Queries that match all documents don't benefit from using
  11608. // key-based lookups. It is more efficient to scan all documents in a
  11609. // collection, rather than to perform individual lookups.
  11610. return Rt.resolve(null);
  11611. let n = Jn(e);
  11612. return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (
  11613. // We cannot apply a limit for targets that are served using a partial
  11614. // index. If a partial index will be used to serve the target, the
  11615. // query may return a superset of documents that match the target
  11616. // (e.g. if the index doesn't include all the target's filters), or
  11617. // may return the correct set of documents in the wrong order (e.g. if
  11618. // the index doesn't include a segment for one of the orderBys).
  11619. // Therefore, a limit should not be applied in such cases.
  11620. e = Xn(e, null, "F" /* LimitType.First */), n = Jn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {
  11621. const i = gs(...s);
  11622. return this.Ui.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {
  11623. const r = this.ji(e, s);
  11624. return this.zi(e, r, i, n.readTime) ? this.Ki(t, Xn(e, null, "F" /* LimitType.First */)) : this.Wi(t, r, e, n);
  11625. }))));
  11626. })))));
  11627. }
  11628. /**
  11629. * Performs a query based on the target's persisted query mapping. Returns
  11630. * `null` if the mapping is not available or cannot be used.
  11631. */ Gi(t, e, n, s) {
  11632. return Qn(e) || s.isEqual(rt.min()) ? this.Qi(t, e) : this.Ui.getDocuments(t, n).next((i => {
  11633. const r = this.ji(e, i);
  11634. return this.zi(e, r, n, s) ? this.Qi(t, e) : (C() <= LogLevel.DEBUG && N("QueryEngine", "Re-using previous result from %s to execute query: %s", s.toString(), es(e)),
  11635. this.Wi(t, r, e, yt(s, -1)));
  11636. }));
  11637. // Queries that have never seen a snapshot without limbo free documents
  11638. // should also be run as a full collection scan.
  11639. }
  11640. /** Applies the query filter and sorting to the provided documents. */ ji(t, e) {
  11641. // Sort the documents and re-apply the query filter since previously
  11642. // matching documents do not necessarily still match the query.
  11643. let n = new Ee(is(t));
  11644. return e.forEach(((e, s) => {
  11645. ns(t, s) && (n = n.add(s));
  11646. })), n;
  11647. }
  11648. /**
  11649. * Determines if a limit query needs to be refilled from cache, making it
  11650. * ineligible for index-free execution.
  11651. *
  11652. * @param query - The query.
  11653. * @param sortedPreviousResults - The documents that matched the query when it
  11654. * was last synchronized, sorted by the query's comparator.
  11655. * @param remoteKeys - The document keys that matched the query at the last
  11656. * snapshot.
  11657. * @param limboFreeSnapshotVersion - The version of the snapshot when the
  11658. * query was last synchronized.
  11659. */ zi(t, e, n, s) {
  11660. if (null === t.limit)
  11661. // Queries without limits do not need to be refilled.
  11662. return !1;
  11663. if (n.size !== e.size)
  11664. // The query needs to be refilled if a previously matching document no
  11665. // longer matches.
  11666. return !0;
  11667. // Limit queries are not eligible for index-free query execution if there is
  11668. // a potential that an older document from cache now sorts before a document
  11669. // that was previously part of the limit. This, however, can only happen if
  11670. // the document at the edge of the limit goes out of limit.
  11671. // If a document that is not the limit boundary sorts differently,
  11672. // the boundary of the limit itself did not change and documents from cache
  11673. // will continue to be "rejected" by this boundary. Therefore, we can ignore
  11674. // any modifications that don't affect the last document.
  11675. const i = "F" /* LimitType.First */ === t.limitType ? e.last() : e.first();
  11676. return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);
  11677. }
  11678. Qi(t, e) {
  11679. return C() <= LogLevel.DEBUG && N("QueryEngine", "Using full collection scan to execute query:", es(e)),
  11680. this.Ui.getDocumentsMatchingQuery(t, e, It.min());
  11681. }
  11682. /**
  11683. * Combines the results from an indexed execution with the remaining documents
  11684. * that have not yet been indexed.
  11685. */ Wi(t, e, n, s) {
  11686. // Retrieve all results for documents that were updated since the offset.
  11687. return this.Ui.getDocumentsMatchingQuery(t, n, s).next((t => (
  11688. // Merge with existing results
  11689. e.forEach((e => {
  11690. t = t.insert(e.key, e);
  11691. })), t)));
  11692. }
  11693. }
  11694. /**
  11695. * @license
  11696. * Copyright 2020 Google LLC
  11697. *
  11698. * Licensed under the Apache License, Version 2.0 (the "License");
  11699. * you may not use this file except in compliance with the License.
  11700. * You may obtain a copy of the License at
  11701. *
  11702. * http://www.apache.org/licenses/LICENSE-2.0
  11703. *
  11704. * Unless required by applicable law or agreed to in writing, software
  11705. * distributed under the License is distributed on an "AS IS" BASIS,
  11706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11707. * See the License for the specific language governing permissions and
  11708. * limitations under the License.
  11709. */
  11710. /**
  11711. * Implements `LocalStore` interface.
  11712. *
  11713. * Note: some field defined in this class might have public access level, but
  11714. * the class is not exported so they are only accessible from this module.
  11715. * This is useful to implement optional features (like bundles) in free
  11716. * functions, such that they are tree-shakeable.
  11717. */
  11718. class nu {
  11719. constructor(
  11720. /** Manages our in-memory or durable persistence. */
  11721. t, e, n, s) {
  11722. this.persistence = t, this.Hi = e, this.serializer = s,
  11723. /**
  11724. * Maps a targetID to data about its target.
  11725. *
  11726. * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
  11727. * of `applyRemoteEvent()` idempotent.
  11728. */
  11729. this.Ji = new pe(et),
  11730. /** Maps a target to its targetID. */
  11731. // TODO(wuandy): Evaluate if TargetId can be part of Target.
  11732. this.Yi = new os((t => $n(t)), On),
  11733. /**
  11734. * A per collection group index of the last read time processed by
  11735. * `getNewDocumentChanges()`.
  11736. *
  11737. * PORTING NOTE: This is only used for multi-tab synchronization.
  11738. */
  11739. this.Xi = new Map, this.Zi = t.getRemoteDocumentCache(), this.Bs = t.getTargetCache(),
  11740. this.qs = t.getBundleCache(), this.tr(n);
  11741. }
  11742. tr(t) {
  11743. // TODO(indexing): Add spec tests that test these components change after a
  11744. // user change
  11745. this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t),
  11746. this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new ko(this.Zi, this.mutationQueue, this.documentOverlayCache, this.indexManager),
  11747. this.Zi.setIndexManager(this.indexManager), this.Hi.initialize(this.localDocuments, this.indexManager);
  11748. }
  11749. collectGarbage(t) {
  11750. return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (e => t.collect(e, this.Ji)));
  11751. }
  11752. }
  11753. function su(
  11754. /** Manages our in-memory or durable persistence. */
  11755. t, e, n, s) {
  11756. return new nu(t, e, n, s);
  11757. }
  11758. /**
  11759. * Tells the LocalStore that the currently authenticated user has changed.
  11760. *
  11761. * In response the local store switches the mutation queue to the new user and
  11762. * returns any resulting document changes.
  11763. */
  11764. // PORTING NOTE: Android and iOS only return the documents affected by the
  11765. // change.
  11766. async function iu(t, e) {
  11767. const n = L(t);
  11768. return await n.persistence.runTransaction("Handle user change", "readonly", (t => {
  11769. // Swap out the mutation queue, grabbing the pending mutation batches
  11770. // before and after.
  11771. let s;
  11772. return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.tr(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {
  11773. const i = [], r = [];
  11774. // Union the old/new changed keys.
  11775. let o = gs();
  11776. for (const t of s) {
  11777. i.push(t.batchId);
  11778. for (const e of t.mutations) o = o.add(e.key);
  11779. }
  11780. for (const t of e) {
  11781. r.push(t.batchId);
  11782. for (const e of t.mutations) o = o.add(e.key);
  11783. }
  11784. // Return the set of all (potentially) changed documents and the list
  11785. // of mutation batch IDs that were affected by change.
  11786. return n.localDocuments.getDocuments(t, o).next((t => ({
  11787. er: t,
  11788. removedBatchIds: i,
  11789. addedBatchIds: r
  11790. })));
  11791. }));
  11792. }));
  11793. }
  11794. /* Accepts locally generated Mutations and commit them to storage. */
  11795. /**
  11796. * Acknowledges the given batch.
  11797. *
  11798. * On the happy path when a batch is acknowledged, the local store will
  11799. *
  11800. * + remove the batch from the mutation queue;
  11801. * + apply the changes to the remote document cache;
  11802. * + recalculate the latency compensated view implied by those changes (there
  11803. * may be mutations in the queue that affect the documents but haven't been
  11804. * acknowledged yet); and
  11805. * + give the changed documents back the sync engine
  11806. *
  11807. * @returns The resulting (modified) documents.
  11808. */
  11809. function ru(t, e) {
  11810. const n = L(t);
  11811. return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (t => {
  11812. const s = e.batch.keys(), i = n.Zi.newChangeBuffer({
  11813. trackRemovals: !0
  11814. });
  11815. return function(t, e, n, s) {
  11816. const i = n.batch, r = i.keys();
  11817. let o = Rt.resolve();
  11818. return r.forEach((t => {
  11819. o = o.next((() => s.getEntry(e, t))).next((e => {
  11820. const r = n.docVersions.get(t);
  11821. F(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (
  11822. // We use the commitVersion as the readTime rather than the
  11823. // document's updateTime since the updateTime is not advanced
  11824. // for updates that do not modify the underlying document.
  11825. e.setReadTime(n.commitVersion), s.addEntry(e)));
  11826. }));
  11827. })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));
  11828. }
  11829. /** Returns the local view of the documents affected by a mutation batch. */
  11830. // PORTING NOTE: Multi-Tab only.
  11831. (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {
  11832. let e = gs();
  11833. for (let n = 0; n < t.mutationResults.length; ++n) {
  11834. t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));
  11835. }
  11836. return e;
  11837. }
  11838. /**
  11839. * Removes mutations from the MutationQueue for the specified batch;
  11840. * LocalDocuments will be recalculated.
  11841. *
  11842. * @returns The resulting modified documents.
  11843. */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));
  11844. }));
  11845. }
  11846. /**
  11847. * Returns the last consistent snapshot processed (used by the RemoteStore to
  11848. * determine whether to buffer incoming snapshots from the backend).
  11849. */
  11850. function ou(t) {
  11851. const e = L(t);
  11852. return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (t => e.Bs.getLastRemoteSnapshotVersion(t)));
  11853. }
  11854. /**
  11855. * Updates the "ground-state" (remote) documents. We assume that the remote
  11856. * event reflects any write batches that have been acknowledged or rejected
  11857. * (i.e. we do not re-apply local mutations to updates from this event).
  11858. *
  11859. * LocalDocuments are re-calculated if there are remaining mutations in the
  11860. * queue.
  11861. */ function uu(t, e) {
  11862. const n = L(t), s = e.snapshotVersion;
  11863. let i = n.Ji;
  11864. return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (t => {
  11865. const r = n.Zi.newChangeBuffer({
  11866. trackRemovals: !0
  11867. });
  11868. // Reset newTargetDataByTargetMap in case this transaction gets re-run.
  11869. i = n.Ji;
  11870. const o = [];
  11871. e.targetChanges.forEach(((r, u) => {
  11872. const c = i.get(u);
  11873. if (!c) return;
  11874. // Only update the remote keys if the target is still active. This
  11875. // ensures that we can persist the updated target data along with
  11876. // the updated assignment.
  11877. o.push(n.Bs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Bs.addMatchingKeys(t, r.addedDocuments, u))));
  11878. let a = c.withSequenceNumber(t.currentSequenceNumber);
  11879. null !== e.targetMismatches.get(u) ? a = a.withResumeToken(Ve.EMPTY_BYTE_STRING, rt.min()).withLastLimboFreeSnapshotVersion(rt.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)),
  11880. i = i.insert(u, a),
  11881. // Update the target data if there are target changes (or if
  11882. // sufficient time has passed since the last update).
  11883. /**
  11884. * Returns true if the newTargetData should be persisted during an update of
  11885. * an active target. TargetData should always be persisted when a target is
  11886. * being released and should not call this function.
  11887. *
  11888. * While the target is active, TargetData updates can be omitted when nothing
  11889. * about the target has changed except metadata like the resume token or
  11890. * snapshot version. Occasionally it's worth the extra write to prevent these
  11891. * values from getting too stale after a crash, but this doesn't have to be
  11892. * too frequent.
  11893. */
  11894. function(t, e, n) {
  11895. // Always persist target data if we don't already have a resume token.
  11896. if (0 === t.resumeToken.approximateByteSize()) return !0;
  11897. // Don't allow resume token changes to be buffered indefinitely. This
  11898. // allows us to be reasonably up-to-date after a crash and avoids needing
  11899. // to loop over all active queries on shutdown. Especially in the browser
  11900. // we may not get time to do anything interesting while the current tab is
  11901. // closing.
  11902. if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;
  11903. // Otherwise if the only thing that has changed about a target is its resume
  11904. // token it's not worth persisting. Note that the RemoteStore keeps an
  11905. // in-memory view of the currently active targets which includes the current
  11906. // resume token, so stream failure or user changes will still use an
  11907. // up-to-date resume token regardless of what we do here.
  11908. return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;
  11909. }
  11910. /**
  11911. * Notifies local store of the changed views to locally pin documents.
  11912. */ (c, a, r) && o.push(n.Bs.updateTargetData(t, a));
  11913. }));
  11914. let u = cs(), c = gs();
  11915. // HACK: The only reason we allow a null snapshot version is so that we
  11916. // can synthesize remote events when we get permission denied errors while
  11917. // trying to resolve the state of a locally cached document that is in
  11918. // limbo.
  11919. if (e.documentUpdates.forEach((s => {
  11920. e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));
  11921. })),
  11922. // Each loop iteration only affects its "own" doc, so it's safe to get all
  11923. // the remote documents in advance in a single call.
  11924. o.push(cu(t, r, e.documentUpdates).next((t => {
  11925. u = t.nr, c = t.sr;
  11926. }))), !s.isEqual(rt.min())) {
  11927. const e = n.Bs.getLastRemoteSnapshotVersion(t).next((e => n.Bs.setTargetsMetadata(t, t.currentSequenceNumber, s)));
  11928. o.push(e);
  11929. }
  11930. return Rt.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));
  11931. })).then((t => (n.Ji = i, t)));
  11932. }
  11933. /**
  11934. * Populates document change buffer with documents from backend or a bundle.
  11935. * Returns the document changes resulting from applying those documents, and
  11936. * also a set of documents whose existence state are changed as a result.
  11937. *
  11938. * @param txn - Transaction to use to read existing documents from storage.
  11939. * @param documentBuffer - Document buffer to collect the resulted changes to be
  11940. * applied to storage.
  11941. * @param documents - Documents to be applied.
  11942. */ function cu(t, e, n) {
  11943. let s = gs(), i = gs();
  11944. return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {
  11945. let s = cs();
  11946. return n.forEach(((n, r) => {
  11947. const o = t.get(n);
  11948. // Check if see if there is a existence state change for this document.
  11949. r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)),
  11950. // Note: The order of the steps below is important, since we want
  11951. // to ensure that rejected limbo resolutions (which fabricate
  11952. // NoDocuments with SnapshotVersion.min()) never add documents to
  11953. // cache.
  11954. r.isNoDocument() && r.version.isEqual(rt.min()) ? (
  11955. // NoDocuments with SnapshotVersion.min() are used in manufactured
  11956. // events. We remove these documents from cache since we lost
  11957. // access.
  11958. e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r),
  11959. s = s.insert(n, r)) : N("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", r.version);
  11960. })), {
  11961. nr: s,
  11962. sr: i
  11963. };
  11964. }));
  11965. }
  11966. /**
  11967. * Gets the mutation batch after the passed in batchId in the mutation queue
  11968. * or null if empty.
  11969. * @param afterBatchId - If provided, the batch to search after.
  11970. * @returns The next mutation or null if there wasn't one.
  11971. */
  11972. function au(t, e) {
  11973. const n = L(t);
  11974. return n.persistence.runTransaction("Get next mutation batch", "readonly", (t => (void 0 === e && (e = -1),
  11975. n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));
  11976. }
  11977. /**
  11978. * Reads the current value of a Document with a given key or null if not
  11979. * found - used for testing.
  11980. */
  11981. /**
  11982. * Assigns the given target an internal ID so that its results can be pinned so
  11983. * they don't get GC'd. A target must be allocated in the local store before
  11984. * the store can be used to manage its view.
  11985. *
  11986. * Allocating an already allocated `Target` will return the existing `TargetData`
  11987. * for that `Target`.
  11988. */
  11989. function hu(t, e) {
  11990. const n = L(t);
  11991. return n.persistence.runTransaction("Allocate target", "readwrite", (t => {
  11992. let s;
  11993. return n.Bs.getTargetData(t, e).next((i => i ? (
  11994. // This target has been listened to previously, so reuse the
  11995. // previous targetID.
  11996. // TODO(mcg): freshen last accessed date?
  11997. s = i, Rt.resolve(s)) : n.Bs.allocateTargetId(t).next((i => (s = new cr(e, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.currentSequenceNumber),
  11998. n.Bs.addTargetData(t, s).next((() => s)))))));
  11999. })).then((t => {
  12000. // If Multi-Tab is enabled, the existing target data may be newer than
  12001. // the in-memory data
  12002. const s = n.Ji.get(t.targetId);
  12003. return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.Ji = n.Ji.insert(t.targetId, t),
  12004. n.Yi.set(e, t.targetId)), t;
  12005. }));
  12006. }
  12007. /**
  12008. * Returns the TargetData as seen by the LocalStore, including updates that may
  12009. * have not yet been persisted to the TargetCache.
  12010. */
  12011. // Visible for testing.
  12012. /**
  12013. * Unpins all the documents associated with the given target. If
  12014. * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
  12015. * directly removes the associated target data from the target cache.
  12016. *
  12017. * Releasing a non-existing `Target` is a no-op.
  12018. */
  12019. // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
  12020. async function lu(t, e, n) {
  12021. const s = L(t), i = s.Ji.get(e), r = n ? "readwrite" : "readwrite-primary";
  12022. try {
  12023. n || await s.persistence.runTransaction("Release target", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));
  12024. } catch (t) {
  12025. if (!Dt(t)) throw t;
  12026. // All `releaseTarget` does is record the final metadata state for the
  12027. // target, but we've been recording this periodically during target
  12028. // activity. If we lose this write this could cause a very slight
  12029. // difference in the order of target deletion during GC, but we
  12030. // don't define exact LRU semantics so this is acceptable.
  12031. N("LocalStore", `Failed to update sequence numbers for target ${e}: ${t}`);
  12032. }
  12033. s.Ji = s.Ji.remove(e), s.Yi.delete(i.target);
  12034. }
  12035. /**
  12036. * Runs the specified query against the local store and returns the results,
  12037. * potentially taking advantage of query data from previous executions (such
  12038. * as the set of remote keys).
  12039. *
  12040. * @param usePreviousResults - Whether results from previous executions can
  12041. * be used to optimize this query execution.
  12042. */ function fu(t, e, n) {
  12043. const s = L(t);
  12044. let i = rt.min(), r = gs();
  12045. return s.persistence.runTransaction("Execute query", "readonly", (t => function(t, e, n) {
  12046. const s = L(t), i = s.Yi.get(n);
  12047. return void 0 !== i ? Rt.resolve(s.Ji.get(i)) : s.Bs.getTargetData(e, n);
  12048. }(s, t, Jn(e)).next((e => {
  12049. if (e) return i = e.lastLimboFreeSnapshotVersion, s.Bs.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  12050. r = t;
  12051. }));
  12052. })).next((() => s.Hi.getDocumentsMatchingQuery(t, e, n ? i : rt.min(), n ? r : gs()))).next((t => (_u(s, ss(e), t),
  12053. {
  12054. documents: t,
  12055. ir: r
  12056. })))));
  12057. }
  12058. // PORTING NOTE: Multi-Tab only.
  12059. function du(t, e) {
  12060. const n = L(t), s = L(n.Bs), i = n.Ji.get(e);
  12061. return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (t => s.le(t, e).next((t => t ? t.target : null))));
  12062. }
  12063. /**
  12064. * Returns the set of documents that have been updated since the last call.
  12065. * If this is the first call, returns the set of changes since client
  12066. * initialization. Further invocations will return document that have changed
  12067. * since the prior call.
  12068. */
  12069. // PORTING NOTE: Multi-Tab only.
  12070. function wu(t, e) {
  12071. const n = L(t), s = n.Xi.get(e) || rt.min();
  12072. // Get the current maximum read time for the collection. This should always
  12073. // exist, but to reduce the chance for regressions we default to
  12074. // SnapshotVersion.Min()
  12075. // TODO(indexing): Consider removing the default value.
  12076. return n.persistence.runTransaction("Get new document changes", "readonly", (t => n.Zi.getAllFromCollectionGroup(t, e, yt(s, -1),
  12077. /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (_u(n, e, t), t)));
  12078. }
  12079. /** Sets the collection group's maximum read time from the given documents. */
  12080. // PORTING NOTE: Multi-Tab only.
  12081. function _u(t, e, n) {
  12082. let s = t.Xi.get(e) || rt.min();
  12083. n.forEach(((t, e) => {
  12084. e.readTime.compareTo(s) > 0 && (s = e.readTime);
  12085. })), t.Xi.set(e, s);
  12086. }
  12087. /**
  12088. * Creates a new target using the given bundle name, which will be used to
  12089. * hold the keys of all documents from the bundle in query-document mappings.
  12090. * This ensures that the loaded documents do not get garbage collected
  12091. * right away.
  12092. */
  12093. /**
  12094. * Applies the documents from a bundle to the "ground-state" (remote)
  12095. * documents.
  12096. *
  12097. * LocalDocuments are re-calculated if there are remaining mutations in the
  12098. * queue.
  12099. */
  12100. async function mu(t, e, n, s) {
  12101. const i = L(t);
  12102. let r = gs(), o = cs();
  12103. for (const t of n) {
  12104. const n = e.rr(t.metadata.name);
  12105. t.document && (r = r.add(n));
  12106. const s = e.ur(t);
  12107. s.setReadTime(e.cr(t.metadata.readTime)), o = o.insert(n, s);
  12108. }
  12109. const u = i.Zi.newChangeBuffer({
  12110. trackRemovals: !0
  12111. }), c = await hu(i, function(t) {
  12112. // It is OK that the path used for the query is not valid, because this will
  12113. // not be read and queried.
  12114. return Jn(Gn(ut.fromString(`__bundle__/docs/${t}`)));
  12115. }(s));
  12116. // Allocates a target to hold all document keys from the bundle, such that
  12117. // they will not get garbage collected right away.
  12118. return i.persistence.runTransaction("Apply bundle documents", "readwrite", (t => cu(t, u, o).next((e => (u.apply(t),
  12119. e))).next((e => i.Bs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Bs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.nr, e.sr))).next((() => e.nr))))));
  12120. }
  12121. /**
  12122. * Returns a promise of a boolean to indicate if the given bundle has already
  12123. * been loaded and the create time is newer than the current loading bundle.
  12124. */
  12125. /**
  12126. * Saves the given `NamedQuery` to local persistence.
  12127. */
  12128. async function gu(t, e, n = gs()) {
  12129. // Allocate a target for the named query such that it can be resumed
  12130. // from associated read time if users use it to listen.
  12131. // NOTE: this also means if no corresponding target exists, the new target
  12132. // will remain active and will not get collected, unless users happen to
  12133. // unlisten the query somehow.
  12134. const s = await hu(t, Jn(yr(e.bundledQuery))), i = L(t);
  12135. return i.persistence.runTransaction("Save named query", "readwrite", (t => {
  12136. const r = Ni(e.readTime);
  12137. // Simply save the query itself if it is older than what the SDK already
  12138. // has.
  12139. if (s.snapshotVersion.compareTo(r) >= 0) return i.qs.saveNamedQuery(t, e);
  12140. // Update existing target data because the query from the bundle is newer.
  12141. const o = s.withResumeToken(Ve.EMPTY_BYTE_STRING, r);
  12142. return i.Ji = i.Ji.insert(o.targetId, o), i.Bs.updateTargetData(t, o).next((() => i.Bs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Bs.addMatchingKeys(t, n, s.targetId))).next((() => i.qs.saveNamedQuery(t, e)));
  12143. }));
  12144. }
  12145. /** Assembles the key for a client state in WebStorage */
  12146. function yu(t, e) {
  12147. return `firestore_clients_${t}_${e}`;
  12148. }
  12149. // The format of the WebStorage key that stores the mutation state is:
  12150. // firestore_mutations_<persistence_prefix>_<batch_id>
  12151. // (for unauthenticated users)
  12152. // or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>
  12153. // 'user_uid' is last to avoid needing to escape '_' characters that it might
  12154. // contain.
  12155. /** Assembles the key for a mutation batch in WebStorage */
  12156. function pu(t, e, n) {
  12157. let s = `firestore_mutations_${t}_${n}`;
  12158. return e.isAuthenticated() && (s += `_${e.uid}`), s;
  12159. }
  12160. // The format of the WebStorage key that stores a query target's metadata is:
  12161. // firestore_targets_<persistence_prefix>_<target_id>
  12162. /** Assembles the key for a query state in WebStorage */
  12163. function Iu(t, e) {
  12164. return `firestore_targets_${t}_${e}`;
  12165. }
  12166. // The WebStorage prefix that stores the primary tab's online state. The
  12167. // format of the key is:
  12168. // firestore_online_state_<persistence_prefix>
  12169. /**
  12170. * Holds the state of a mutation batch, including its user ID, batch ID and
  12171. * whether the batch is 'pending', 'acknowledged' or 'rejected'.
  12172. */
  12173. // Visible for testing
  12174. class Tu {
  12175. constructor(t, e, n, s) {
  12176. this.user = t, this.batchId = e, this.state = n, this.error = s;
  12177. }
  12178. /**
  12179. * Parses a MutationMetadata from its JSON representation in WebStorage.
  12180. * Logs a warning and returns null if the format of the data is not valid.
  12181. */ static ar(t, e, n) {
  12182. const s = JSON.parse(n);
  12183. let i, r = "object" == typeof s && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error);
  12184. return r && s.error && (r = "string" == typeof s.error.message && "string" == typeof s.error.code,
  12185. r && (i = new U(s.error.code, s.error.message))), r ? new Tu(t, e, s.state, i) : (k("SharedClientState", `Failed to parse mutation state for ID '${e}': ${n}`),
  12186. null);
  12187. }
  12188. hr() {
  12189. const t = {
  12190. state: this.state,
  12191. updateTimeMs: Date.now()
  12192. };
  12193. return this.error && (t.error = {
  12194. code: this.error.code,
  12195. message: this.error.message
  12196. }), JSON.stringify(t);
  12197. }
  12198. }
  12199. /**
  12200. * Holds the state of a query target, including its target ID and whether the
  12201. * target is 'not-current', 'current' or 'rejected'.
  12202. */
  12203. // Visible for testing
  12204. class Eu {
  12205. constructor(t, e, n) {
  12206. this.targetId = t, this.state = e, this.error = n;
  12207. }
  12208. /**
  12209. * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
  12210. * Logs a warning and returns null if the format of the data is not valid.
  12211. */ static ar(t, e) {
  12212. const n = JSON.parse(e);
  12213. let s, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error);
  12214. return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code,
  12215. i && (s = new U(n.error.code, n.error.message))), i ? new Eu(t, n.state, s) : (k("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`),
  12216. null);
  12217. }
  12218. hr() {
  12219. const t = {
  12220. state: this.state,
  12221. updateTimeMs: Date.now()
  12222. };
  12223. return this.error && (t.error = {
  12224. code: this.error.code,
  12225. message: this.error.message
  12226. }), JSON.stringify(t);
  12227. }
  12228. }
  12229. /**
  12230. * This class represents the immutable ClientState for a client read from
  12231. * WebStorage, containing the list of active query targets.
  12232. */ class Au {
  12233. constructor(t, e) {
  12234. this.clientId = t, this.activeTargetIds = e;
  12235. }
  12236. /**
  12237. * Parses a RemoteClientState from the JSON representation in WebStorage.
  12238. * Logs a warning and returns null if the format of the data is not valid.
  12239. */ static ar(t, e) {
  12240. const n = JSON.parse(e);
  12241. let s = "object" == typeof n && n.activeTargetIds instanceof Array, i = ps();
  12242. for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Lt(n.activeTargetIds[t]),
  12243. i = i.add(n.activeTargetIds[t]);
  12244. return s ? new Au(t, i) : (k("SharedClientState", `Failed to parse client data for instance '${t}': ${e}`),
  12245. null);
  12246. }
  12247. }
  12248. /**
  12249. * This class represents the online state for all clients participating in
  12250. * multi-tab. The online state is only written to by the primary client, and
  12251. * used in secondary clients to update their query views.
  12252. */ class vu {
  12253. constructor(t, e) {
  12254. this.clientId = t, this.onlineState = e;
  12255. }
  12256. /**
  12257. * Parses a SharedOnlineState from its JSON representation in WebStorage.
  12258. * Logs a warning and returns null if the format of the data is not valid.
  12259. */ static ar(t) {
  12260. const e = JSON.parse(t);
  12261. return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new vu(e.clientId, e.onlineState) : (k("SharedClientState", `Failed to parse online state: ${t}`),
  12262. null);
  12263. }
  12264. }
  12265. /**
  12266. * Metadata state of the local client. Unlike `RemoteClientState`, this class is
  12267. * mutable and keeps track of all pending mutations, which allows us to
  12268. * update the range of pending mutation batch IDs as new mutations are added or
  12269. * removed.
  12270. *
  12271. * The data in `LocalClientState` is not read from WebStorage and instead
  12272. * updated via its instance methods. The updated state can be serialized via
  12273. * `toWebStorageJSON()`.
  12274. */
  12275. // Visible for testing.
  12276. class Ru {
  12277. constructor() {
  12278. this.activeTargetIds = ps();
  12279. }
  12280. lr(t) {
  12281. this.activeTargetIds = this.activeTargetIds.add(t);
  12282. }
  12283. dr(t) {
  12284. this.activeTargetIds = this.activeTargetIds.delete(t);
  12285. }
  12286. /**
  12287. * Converts this entry into a JSON-encoded format we can use for WebStorage.
  12288. * Does not encode `clientId` as it is part of the key in WebStorage.
  12289. */ hr() {
  12290. const t = {
  12291. activeTargetIds: this.activeTargetIds.toArray(),
  12292. updateTimeMs: Date.now()
  12293. };
  12294. return JSON.stringify(t);
  12295. }
  12296. }
  12297. /**
  12298. * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the
  12299. * backing store for the SharedClientState. It keeps track of all active
  12300. * clients and supports modifications of the local client's data.
  12301. */ class Pu {
  12302. constructor(t, e, n, s, i) {
  12303. this.window = t, this.ii = e, this.persistenceKey = n, this.wr = s, this.syncEngine = null,
  12304. this.onlineStateHandler = null, this.sequenceNumberHandler = null, this._r = this.mr.bind(this),
  12305. this.gr = new pe(et), this.started = !1,
  12306. /**
  12307. * Captures WebStorage events that occur before `start()` is called. These
  12308. * events are replayed once `WebStorageSharedClientState` is started.
  12309. */
  12310. this.yr = [];
  12311. // Escape the special characters mentioned here:
  12312. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  12313. const r = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  12314. this.storage = this.window.localStorage, this.currentUser = i, this.pr = yu(this.persistenceKey, this.wr),
  12315. this.Ir =
  12316. /** Assembles the key for the current sequence number. */
  12317. function(t) {
  12318. return `firestore_sequence_number_${t}`;
  12319. }
  12320. /**
  12321. * @license
  12322. * Copyright 2018 Google LLC
  12323. *
  12324. * Licensed under the Apache License, Version 2.0 (the "License");
  12325. * you may not use this file except in compliance with the License.
  12326. * You may obtain a copy of the License at
  12327. *
  12328. * http://www.apache.org/licenses/LICENSE-2.0
  12329. *
  12330. * Unless required by applicable law or agreed to in writing, software
  12331. * distributed under the License is distributed on an "AS IS" BASIS,
  12332. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12333. * See the License for the specific language governing permissions and
  12334. * limitations under the License.
  12335. */ (this.persistenceKey), this.gr = this.gr.insert(this.wr, new Ru), this.Tr = new RegExp(`^firestore_clients_${r}_([^_]*)$`),
  12336. this.Er = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this.Ar = new RegExp(`^firestore_targets_${r}_(\\d+)$`),
  12337. this.vr =
  12338. /** Assembles the key for the online state of the primary tab. */
  12339. function(t) {
  12340. return `firestore_online_state_${t}`;
  12341. }
  12342. // The WebStorage prefix that plays as a event to indicate the remote documents
  12343. // might have changed due to some secondary tabs loading a bundle.
  12344. // format of the key is:
  12345. // firestore_bundle_loaded_v2_<persistenceKey>
  12346. // The version ending with "v2" stores the list of modified collection groups.
  12347. (this.persistenceKey), this.Rr = function(t) {
  12348. return `firestore_bundle_loaded_v2_${t}`;
  12349. }
  12350. // The WebStorage key prefix for the key that stores the last sequence number allocated. The key
  12351. // looks like 'firestore_sequence_number_<persistence_prefix>'.
  12352. (this.persistenceKey),
  12353. // Rather than adding the storage observer during start(), we add the
  12354. // storage observer during initialization. This ensures that we collect
  12355. // events before other components populate their initial state (during their
  12356. // respective start() calls). Otherwise, we might for example miss a
  12357. // mutation that is added after LocalStore's start() processed the existing
  12358. // mutations but before we observe WebStorage events.
  12359. this.window.addEventListener("storage", this._r);
  12360. }
  12361. /** Returns 'true' if WebStorage is available in the current environment. */ static D(t) {
  12362. return !(!t || !t.localStorage);
  12363. }
  12364. async start() {
  12365. // Retrieve the list of existing clients to backfill the data in
  12366. // SharedClientState.
  12367. const t = await this.syncEngine.$i();
  12368. for (const e of t) {
  12369. if (e === this.wr) continue;
  12370. const t = this.getItem(yu(this.persistenceKey, e));
  12371. if (t) {
  12372. const n = Au.ar(e, t);
  12373. n && (this.gr = this.gr.insert(n.clientId, n));
  12374. }
  12375. }
  12376. this.Pr();
  12377. // Check if there is an existing online state and call the callback handler
  12378. // if applicable.
  12379. const e = this.storage.getItem(this.vr);
  12380. if (e) {
  12381. const t = this.br(e);
  12382. t && this.Vr(t);
  12383. }
  12384. for (const t of this.yr) this.mr(t);
  12385. this.yr = [],
  12386. // Register a window unload hook to remove the client metadata entry from
  12387. // WebStorage even if `shutdown()` was not called.
  12388. this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0;
  12389. }
  12390. writeSequenceNumber(t) {
  12391. this.setItem(this.Ir, JSON.stringify(t));
  12392. }
  12393. getAllActiveQueryTargets() {
  12394. return this.Sr(this.gr);
  12395. }
  12396. isActiveQueryTarget(t) {
  12397. let e = !1;
  12398. return this.gr.forEach(((n, s) => {
  12399. s.activeTargetIds.has(t) && (e = !0);
  12400. })), e;
  12401. }
  12402. addPendingMutation(t) {
  12403. this.Dr(t, "pending");
  12404. }
  12405. updateMutationState(t, e, n) {
  12406. this.Dr(t, e, n),
  12407. // Once a final mutation result is observed by other clients, they no longer
  12408. // access the mutation's metadata entry. Since WebStorage replays events
  12409. // in order, it is safe to delete the entry right after updating it.
  12410. this.Cr(t);
  12411. }
  12412. addLocalQueryTarget(t) {
  12413. let e = "not-current";
  12414. // Lookup an existing query state if the target ID was already registered
  12415. // by another tab
  12416. if (this.isActiveQueryTarget(t)) {
  12417. const n = this.storage.getItem(Iu(this.persistenceKey, t));
  12418. if (n) {
  12419. const s = Eu.ar(t, n);
  12420. s && (e = s.state);
  12421. }
  12422. }
  12423. return this.Nr.lr(t), this.Pr(), e;
  12424. }
  12425. removeLocalQueryTarget(t) {
  12426. this.Nr.dr(t), this.Pr();
  12427. }
  12428. isLocalQueryTarget(t) {
  12429. return this.Nr.activeTargetIds.has(t);
  12430. }
  12431. clearQueryState(t) {
  12432. this.removeItem(Iu(this.persistenceKey, t));
  12433. }
  12434. updateQueryState(t, e, n) {
  12435. this.kr(t, e, n);
  12436. }
  12437. handleUserChange(t, e, n) {
  12438. e.forEach((t => {
  12439. this.Cr(t);
  12440. })), this.currentUser = t, n.forEach((t => {
  12441. this.addPendingMutation(t);
  12442. }));
  12443. }
  12444. setOnlineState(t) {
  12445. this.Mr(t);
  12446. }
  12447. notifyBundleLoaded(t) {
  12448. this.$r(t);
  12449. }
  12450. shutdown() {
  12451. this.started && (this.window.removeEventListener("storage", this._r), this.removeItem(this.pr),
  12452. this.started = !1);
  12453. }
  12454. getItem(t) {
  12455. const e = this.storage.getItem(t);
  12456. return N("SharedClientState", "READ", t, e), e;
  12457. }
  12458. setItem(t, e) {
  12459. N("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
  12460. }
  12461. removeItem(t) {
  12462. N("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
  12463. }
  12464. mr(t) {
  12465. // Note: The function is typed to take Event to be interface-compatible with
  12466. // `Window.addEventListener`.
  12467. const e = t;
  12468. if (e.storageArea === this.storage) {
  12469. if (N("SharedClientState", "EVENT", e.key, e.newValue), e.key === this.pr) return void k("Received WebStorage notification for local change. Another client might have garbage-collected our state");
  12470. this.ii.enqueueRetryable((async () => {
  12471. if (this.started) {
  12472. if (null !== e.key) if (this.Tr.test(e.key)) {
  12473. if (null == e.newValue) {
  12474. const t = this.Or(e.key);
  12475. return this.Fr(t, null);
  12476. }
  12477. {
  12478. const t = this.Br(e.key, e.newValue);
  12479. if (t) return this.Fr(t.clientId, t);
  12480. }
  12481. } else if (this.Er.test(e.key)) {
  12482. if (null !== e.newValue) {
  12483. const t = this.Lr(e.key, e.newValue);
  12484. if (t) return this.qr(t);
  12485. }
  12486. } else if (this.Ar.test(e.key)) {
  12487. if (null !== e.newValue) {
  12488. const t = this.Ur(e.key, e.newValue);
  12489. if (t) return this.Kr(t);
  12490. }
  12491. } else if (e.key === this.vr) {
  12492. if (null !== e.newValue) {
  12493. const t = this.br(e.newValue);
  12494. if (t) return this.Vr(t);
  12495. }
  12496. } else if (e.key === this.Ir) {
  12497. const t = function(t) {
  12498. let e = Ot.ct;
  12499. if (null != t) try {
  12500. const n = JSON.parse(t);
  12501. F("number" == typeof n), e = n;
  12502. } catch (t) {
  12503. k("SharedClientState", "Failed to read sequence number from WebStorage", t);
  12504. }
  12505. return e;
  12506. }
  12507. /**
  12508. * `MemorySharedClientState` is a simple implementation of SharedClientState for
  12509. * clients using memory persistence. The state in this class remains fully
  12510. * isolated and no synchronization is performed.
  12511. */ (e.newValue);
  12512. t !== Ot.ct && this.sequenceNumberHandler(t);
  12513. } else if (e.key === this.Rr) {
  12514. const t = this.Gr(e.newValue);
  12515. await Promise.all(t.map((t => this.syncEngine.Qr(t))));
  12516. }
  12517. } else this.yr.push(e);
  12518. }));
  12519. }
  12520. }
  12521. get Nr() {
  12522. return this.gr.get(this.wr);
  12523. }
  12524. Pr() {
  12525. this.setItem(this.pr, this.Nr.hr());
  12526. }
  12527. Dr(t, e, n) {
  12528. const s = new Tu(this.currentUser, t, e, n), i = pu(this.persistenceKey, this.currentUser, t);
  12529. this.setItem(i, s.hr());
  12530. }
  12531. Cr(t) {
  12532. const e = pu(this.persistenceKey, this.currentUser, t);
  12533. this.removeItem(e);
  12534. }
  12535. Mr(t) {
  12536. const e = {
  12537. clientId: this.wr,
  12538. onlineState: t
  12539. };
  12540. this.storage.setItem(this.vr, JSON.stringify(e));
  12541. }
  12542. kr(t, e, n) {
  12543. const s = Iu(this.persistenceKey, t), i = new Eu(t, e, n);
  12544. this.setItem(s, i.hr());
  12545. }
  12546. $r(t) {
  12547. const e = JSON.stringify(Array.from(t));
  12548. this.setItem(this.Rr, e);
  12549. }
  12550. /**
  12551. * Parses a client state key in WebStorage. Returns null if the key does not
  12552. * match the expected key format.
  12553. */ Or(t) {
  12554. const e = this.Tr.exec(t);
  12555. return e ? e[1] : null;
  12556. }
  12557. /**
  12558. * Parses a client state in WebStorage. Returns 'null' if the value could not
  12559. * be parsed.
  12560. */ Br(t, e) {
  12561. const n = this.Or(t);
  12562. return Au.ar(n, e);
  12563. }
  12564. /**
  12565. * Parses a mutation batch state in WebStorage. Returns 'null' if the value
  12566. * could not be parsed.
  12567. */ Lr(t, e) {
  12568. const n = this.Er.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
  12569. return Tu.ar(new V(i), s, e);
  12570. }
  12571. /**
  12572. * Parses a query target state from WebStorage. Returns 'null' if the value
  12573. * could not be parsed.
  12574. */ Ur(t, e) {
  12575. const n = this.Ar.exec(t), s = Number(n[1]);
  12576. return Eu.ar(s, e);
  12577. }
  12578. /**
  12579. * Parses an online state from WebStorage. Returns 'null' if the value
  12580. * could not be parsed.
  12581. */ br(t) {
  12582. return vu.ar(t);
  12583. }
  12584. Gr(t) {
  12585. return JSON.parse(t);
  12586. }
  12587. async qr(t) {
  12588. if (t.user.uid === this.currentUser.uid) return this.syncEngine.jr(t.batchId, t.state, t.error);
  12589. N("SharedClientState", `Ignoring mutation for non-active user ${t.user.uid}`);
  12590. }
  12591. Kr(t) {
  12592. return this.syncEngine.zr(t.targetId, t.state, t.error);
  12593. }
  12594. Fr(t, e) {
  12595. const n = e ? this.gr.insert(t, e) : this.gr.remove(t), s = this.Sr(this.gr), i = this.Sr(n), r = [], o = [];
  12596. return i.forEach((t => {
  12597. s.has(t) || r.push(t);
  12598. })), s.forEach((t => {
  12599. i.has(t) || o.push(t);
  12600. })), this.syncEngine.Wr(r, o).then((() => {
  12601. this.gr = n;
  12602. }));
  12603. }
  12604. Vr(t) {
  12605. // We check whether the client that wrote this online state is still active
  12606. // by comparing its client ID to the list of clients kept active in
  12607. // IndexedDb. If a client does not update their IndexedDb client state
  12608. // within 5 seconds, it is considered inactive and we don't emit an online
  12609. // state event.
  12610. this.gr.get(t.clientId) && this.onlineStateHandler(t.onlineState);
  12611. }
  12612. Sr(t) {
  12613. let e = ps();
  12614. return t.forEach(((t, n) => {
  12615. e = e.unionWith(n.activeTargetIds);
  12616. })), e;
  12617. }
  12618. }
  12619. class bu {
  12620. constructor() {
  12621. this.Hr = new Ru, this.Jr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  12622. }
  12623. addPendingMutation(t) {
  12624. // No op.
  12625. }
  12626. updateMutationState(t, e, n) {
  12627. // No op.
  12628. }
  12629. addLocalQueryTarget(t) {
  12630. return this.Hr.lr(t), this.Jr[t] || "not-current";
  12631. }
  12632. updateQueryState(t, e, n) {
  12633. this.Jr[t] = e;
  12634. }
  12635. removeLocalQueryTarget(t) {
  12636. this.Hr.dr(t);
  12637. }
  12638. isLocalQueryTarget(t) {
  12639. return this.Hr.activeTargetIds.has(t);
  12640. }
  12641. clearQueryState(t) {
  12642. delete this.Jr[t];
  12643. }
  12644. getAllActiveQueryTargets() {
  12645. return this.Hr.activeTargetIds;
  12646. }
  12647. isActiveQueryTarget(t) {
  12648. return this.Hr.activeTargetIds.has(t);
  12649. }
  12650. start() {
  12651. return this.Hr = new Ru, Promise.resolve();
  12652. }
  12653. handleUserChange(t, e, n) {
  12654. // No op.
  12655. }
  12656. setOnlineState(t) {
  12657. // No op.
  12658. }
  12659. shutdown() {}
  12660. writeSequenceNumber(t) {}
  12661. notifyBundleLoaded(t) {
  12662. // No op.
  12663. }
  12664. }
  12665. /**
  12666. * @license
  12667. * Copyright 2019 Google LLC
  12668. *
  12669. * Licensed under the Apache License, Version 2.0 (the "License");
  12670. * you may not use this file except in compliance with the License.
  12671. * You may obtain a copy of the License at
  12672. *
  12673. * http://www.apache.org/licenses/LICENSE-2.0
  12674. *
  12675. * Unless required by applicable law or agreed to in writing, software
  12676. * distributed under the License is distributed on an "AS IS" BASIS,
  12677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12678. * See the License for the specific language governing permissions and
  12679. * limitations under the License.
  12680. */ class Vu {
  12681. Yr(t) {
  12682. // No-op.
  12683. }
  12684. shutdown() {
  12685. // No-op.
  12686. }
  12687. }
  12688. /**
  12689. * @license
  12690. * Copyright 2019 Google LLC
  12691. *
  12692. * Licensed under the Apache License, Version 2.0 (the "License");
  12693. * you may not use this file except in compliance with the License.
  12694. * You may obtain a copy of the License at
  12695. *
  12696. * http://www.apache.org/licenses/LICENSE-2.0
  12697. *
  12698. * Unless required by applicable law or agreed to in writing, software
  12699. * distributed under the License is distributed on an "AS IS" BASIS,
  12700. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12701. * See the License for the specific language governing permissions and
  12702. * limitations under the License.
  12703. */
  12704. // References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
  12705. /* eslint-disable no-restricted-globals */
  12706. /**
  12707. * Browser implementation of ConnectivityMonitor.
  12708. */
  12709. class Su {
  12710. constructor() {
  12711. this.Xr = () => this.Zr(), this.eo = () => this.no(), this.so = [], this.io();
  12712. }
  12713. Yr(t) {
  12714. this.so.push(t);
  12715. }
  12716. shutdown() {
  12717. window.removeEventListener("online", this.Xr), window.removeEventListener("offline", this.eo);
  12718. }
  12719. io() {
  12720. window.addEventListener("online", this.Xr), window.addEventListener("offline", this.eo);
  12721. }
  12722. Zr() {
  12723. N("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
  12724. for (const t of this.so) t(0 /* NetworkStatus.AVAILABLE */);
  12725. }
  12726. no() {
  12727. N("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
  12728. for (const t of this.so) t(1 /* NetworkStatus.UNAVAILABLE */);
  12729. }
  12730. // TODO(chenbrian): Consider passing in window either into this component or
  12731. // here for testing via FakeWindow.
  12732. /** Checks that all used attributes of window are available. */
  12733. static D() {
  12734. return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  12735. }
  12736. }
  12737. /**
  12738. * @license
  12739. * Copyright 2023 Google LLC
  12740. *
  12741. * Licensed under the Apache License, Version 2.0 (the "License");
  12742. * you may not use this file except in compliance with the License.
  12743. * You may obtain a copy of the License at
  12744. *
  12745. * http://www.apache.org/licenses/LICENSE-2.0
  12746. *
  12747. * Unless required by applicable law or agreed to in writing, software
  12748. * distributed under the License is distributed on an "AS IS" BASIS,
  12749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12750. * See the License for the specific language governing permissions and
  12751. * limitations under the License.
  12752. */
  12753. /**
  12754. * The value returned from the most recent invocation of
  12755. * `generateUniqueDebugId()`, or null if it has never been invoked.
  12756. */ let Du = null;
  12757. /**
  12758. * Generates and returns an initial value for `lastUniqueDebugId`.
  12759. *
  12760. * The returned value is randomly selected from a range of integers that are
  12761. * represented as 8 hexadecimal digits. This means that (within reason) any
  12762. * numbers generated by incrementing the returned number by 1 will also be
  12763. * represented by 8 hexadecimal digits. This leads to all "IDs" having the same
  12764. * length when converted to a hexadecimal string, making reading logs containing
  12765. * these IDs easier to follow. And since the return value is randomly selected
  12766. * it will help to differentiate between logs from different executions.
  12767. */
  12768. /**
  12769. * Generates and returns a unique ID as a hexadecimal string.
  12770. *
  12771. * The returned ID is intended to be used in debug logging messages to help
  12772. * correlate log messages that may be spatially separated in the logs, but
  12773. * logically related. For example, a network connection could include the same
  12774. * "debug ID" string in all of its log messages to help trace a specific
  12775. * connection over time.
  12776. *
  12777. * @return the 10-character generated ID (e.g. "0xa1b2c3d4").
  12778. */
  12779. function Cu() {
  12780. return null === Du ? Du = 268435456 + Math.round(2147483648 * Math.random()) : Du++,
  12781. "0x" + Du.toString(16);
  12782. }
  12783. /**
  12784. * @license
  12785. * Copyright 2020 Google LLC
  12786. *
  12787. * Licensed under the Apache License, Version 2.0 (the "License");
  12788. * you may not use this file except in compliance with the License.
  12789. * You may obtain a copy of the License at
  12790. *
  12791. * http://www.apache.org/licenses/LICENSE-2.0
  12792. *
  12793. * Unless required by applicable law or agreed to in writing, software
  12794. * distributed under the License is distributed on an "AS IS" BASIS,
  12795. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12796. * See the License for the specific language governing permissions and
  12797. * limitations under the License.
  12798. */ const xu = {
  12799. BatchGetDocuments: "batchGet",
  12800. Commit: "commit",
  12801. RunQuery: "runQuery",
  12802. RunAggregationQuery: "runAggregationQuery"
  12803. };
  12804. /**
  12805. * Maps RPC names to the corresponding REST endpoint name.
  12806. *
  12807. * We use array notation to avoid mangling.
  12808. */
  12809. /**
  12810. * @license
  12811. * Copyright 2017 Google LLC
  12812. *
  12813. * Licensed under the Apache License, Version 2.0 (the "License");
  12814. * you may not use this file except in compliance with the License.
  12815. * You may obtain a copy of the License at
  12816. *
  12817. * http://www.apache.org/licenses/LICENSE-2.0
  12818. *
  12819. * Unless required by applicable law or agreed to in writing, software
  12820. * distributed under the License is distributed on an "AS IS" BASIS,
  12821. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12822. * See the License for the specific language governing permissions and
  12823. * limitations under the License.
  12824. */
  12825. /**
  12826. * Provides a simple helper class that implements the Stream interface to
  12827. * bridge to other implementations that are streams but do not implement the
  12828. * interface. The stream callbacks are invoked with the callOn... methods.
  12829. */
  12830. class Nu {
  12831. constructor(t) {
  12832. this.ro = t.ro, this.oo = t.oo;
  12833. }
  12834. uo(t) {
  12835. this.co = t;
  12836. }
  12837. ao(t) {
  12838. this.ho = t;
  12839. }
  12840. onMessage(t) {
  12841. this.lo = t;
  12842. }
  12843. close() {
  12844. this.oo();
  12845. }
  12846. send(t) {
  12847. this.ro(t);
  12848. }
  12849. fo() {
  12850. this.co();
  12851. }
  12852. wo(t) {
  12853. this.ho(t);
  12854. }
  12855. _o(t) {
  12856. this.lo(t);
  12857. }
  12858. }
  12859. /**
  12860. * @license
  12861. * Copyright 2017 Google LLC
  12862. *
  12863. * Licensed under the Apache License, Version 2.0 (the "License");
  12864. * you may not use this file except in compliance with the License.
  12865. * You may obtain a copy of the License at
  12866. *
  12867. * http://www.apache.org/licenses/LICENSE-2.0
  12868. *
  12869. * Unless required by applicable law or agreed to in writing, software
  12870. * distributed under the License is distributed on an "AS IS" BASIS,
  12871. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12872. * See the License for the specific language governing permissions and
  12873. * limitations under the License.
  12874. */ const ku = "WebChannelConnection";
  12875. class Mu extends
  12876. /**
  12877. * Base class for all Rest-based connections to the backend (WebChannel and
  12878. * HTTP).
  12879. */
  12880. class {
  12881. constructor(t) {
  12882. this.databaseInfo = t, this.databaseId = t.databaseId;
  12883. const e = t.ssl ? "https" : "http";
  12884. this.mo = e + "://" + t.host, this.yo = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  12885. }
  12886. get po() {
  12887. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  12888. // where to run the query, and expect the `request` to NOT specify the "path".
  12889. return !1;
  12890. }
  12891. Io(t, e, n, s, i) {
  12892. const r = Cu(), o = this.To(t, e);
  12893. N("RestConnection", `Sending RPC '${t}' ${r}:`, o, n);
  12894. const u = {};
  12895. return this.Eo(u, s, i), this.Ao(t, o, u, n).then((e => (N("RestConnection", `Received RPC '${t}' ${r}: `, e),
  12896. e)), (e => {
  12897. throw M("RestConnection", `RPC '${t}' ${r} failed with error: `, e, "url: ", o, "request:", n),
  12898. e;
  12899. }));
  12900. }
  12901. vo(t, e, n, s, i, r) {
  12902. // The REST API automatically aggregates all of the streamed results, so we
  12903. // can just use the normal invoke() method.
  12904. return this.Io(t, e, n, s, i);
  12905. }
  12906. /**
  12907. * Modifies the headers for a request, adding any authorization token if
  12908. * present and any additional headers for the request.
  12909. */ Eo(t, e, n) {
  12910. t["X-Goog-Api-Client"] = "gl-js/ fire/" + S,
  12911. // Content-Type: text/plain will avoid preflight requests which might
  12912. // mess with CORS and redirects by proxies. If we add custom headers
  12913. // we will need to change this code to potentially use the $httpOverwrite
  12914. // parameter supported by ESF to avoid triggering preflight requests.
  12915. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  12916. e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));
  12917. }
  12918. To(t, e) {
  12919. const n = xu[t];
  12920. return `${this.mo}/v1/${e}:${n}`;
  12921. }
  12922. } {
  12923. constructor(t) {
  12924. super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling,
  12925. this.useFetchStreams = t.useFetchStreams, this.longPollingOptions = t.longPollingOptions;
  12926. }
  12927. Ao(t, e, n, s) {
  12928. const i = Cu();
  12929. return new Promise(((r, o) => {
  12930. const u = new XhrIo;
  12931. u.setWithCredentials(!0), u.listenOnce(EventType.COMPLETE, (() => {
  12932. try {
  12933. switch (u.getLastErrorCode()) {
  12934. case ErrorCode.NO_ERROR:
  12935. const e = u.getResponseJson();
  12936. N(ku, `XHR for RPC '${t}' ${i} received:`, JSON.stringify(e)), r(e);
  12937. break;
  12938. case ErrorCode.TIMEOUT:
  12939. N(ku, `RPC '${t}' ${i} timed out`), o(new U(q.DEADLINE_EXCEEDED, "Request time out"));
  12940. break;
  12941. case ErrorCode.HTTP_ERROR:
  12942. const n = u.getStatus();
  12943. if (N(ku, `RPC '${t}' ${i} failed with status:`, n, "response text:", u.getResponseText()),
  12944. n > 0) {
  12945. let t = u.getResponseJson();
  12946. Array.isArray(t) && (t = t[0]);
  12947. const e = null == t ? void 0 : t.error;
  12948. if (e && e.status && e.message) {
  12949. const t = function(t) {
  12950. const e = t.toLowerCase().replace(/_/g, "-");
  12951. return Object.values(q).indexOf(e) >= 0 ? e : q.UNKNOWN;
  12952. }(e.status);
  12953. o(new U(t, e.message));
  12954. } else o(new U(q.UNKNOWN, "Server responded with status " + u.getStatus()));
  12955. } else
  12956. // If we received an HTTP_ERROR but there's no status code,
  12957. // it's most probably a connection issue
  12958. o(new U(q.UNAVAILABLE, "Connection failed."));
  12959. break;
  12960. default:
  12961. O();
  12962. }
  12963. } finally {
  12964. N(ku, `RPC '${t}' ${i} completed.`);
  12965. }
  12966. }));
  12967. const c = JSON.stringify(s);
  12968. N(ku, `RPC '${t}' ${i} sending request:`, s), u.send(e, "POST", c, n, 15);
  12969. }));
  12970. }
  12971. Ro(t, e, n) {
  12972. const s = Cu(), i = [ this.mo, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], r = createWebChannelTransport(), o = getStatEventTarget(), u = {
  12973. // Required for backend stickiness, routing behavior is based on this
  12974. // parameter.
  12975. httpSessionIdParam: "gsessionid",
  12976. initMessageHeaders: {},
  12977. messageUrlParams: {
  12978. // This param is used to improve routing and project isolation by the
  12979. // backend and must be included in every request.
  12980. database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
  12981. },
  12982. sendRawJson: !0,
  12983. supportsCrossDomainXhr: !0,
  12984. internalChannelParams: {
  12985. // Override the default timeout (randomized between 10-20 seconds) since
  12986. // a large write batch on a slow internet connection may take a long
  12987. // time to send to the backend. Rather than have WebChannel impose a
  12988. // tight timeout which could lead to infinite timeouts and retries, we
  12989. // set it very large (5-10 minutes) and rely on the browser's builtin
  12990. // timeouts to kick in if the request isn't working.
  12991. forwardChannelRequestTimeoutMs: 6e5
  12992. },
  12993. forceLongPolling: this.forceLongPolling,
  12994. detectBufferingProxy: this.autoDetectLongPolling
  12995. }, c = this.longPollingOptions.timeoutSeconds;
  12996. void 0 !== c && (u.longPollingTimeout = Math.round(1e3 * c)), this.useFetchStreams && (u.xmlHttpFactory = new FetchXmlHttpFactory({})),
  12997. this.Eo(u.initMessageHeaders, e, n),
  12998. // Sending the custom headers we just added to request.initMessageHeaders
  12999. // (Authorization, etc.) will trigger the browser to make a CORS preflight
  13000. // request because the XHR will no longer meet the criteria for a "simple"
  13001. // CORS request:
  13002. // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
  13003. // Therefore to avoid the CORS preflight request (an extra network
  13004. // roundtrip), we use the encodeInitMessageHeaders option to specify that
  13005. // the headers should instead be encoded in the request's POST payload,
  13006. // which is recognized by the webchannel backend.
  13007. u.encodeInitMessageHeaders = !0;
  13008. const a = i.join("");
  13009. N(ku, `Creating RPC '${t}' stream ${s}: ${a}`, u);
  13010. const h = r.createWebChannel(a, u);
  13011. // WebChannel supports sending the first message with the handshake - saving
  13012. // a network round trip. However, it will have to call send in the same
  13013. // JS event loop as open. In order to enforce this, we delay actually
  13014. // opening the WebChannel until send is called. Whether we have called
  13015. // open is tracked with this variable.
  13016. let l = !1, f = !1;
  13017. // A flag to determine whether the stream was closed (by us or through an
  13018. // error/close event) to avoid delivering multiple close events or sending
  13019. // on a closed stream
  13020. const d = new Nu({
  13021. ro: e => {
  13022. f ? N(ku, `Not sending because RPC '${t}' stream ${s} is closed:`, e) : (l || (N(ku, `Opening RPC '${t}' stream ${s} transport.`),
  13023. h.open(), l = !0), N(ku, `RPC '${t}' stream ${s} sending:`, e), h.send(e));
  13024. },
  13025. oo: () => h.close()
  13026. }), w = (t, e, n) => {
  13027. // TODO(dimond): closure typing seems broken because WebChannel does
  13028. // not implement goog.events.Listenable
  13029. t.listen(e, (t => {
  13030. try {
  13031. n(t);
  13032. } catch (t) {
  13033. setTimeout((() => {
  13034. throw t;
  13035. }), 0);
  13036. }
  13037. }));
  13038. };
  13039. // Closure events are guarded and exceptions are swallowed, so catch any
  13040. // exception and rethrow using a setTimeout so they become visible again.
  13041. // Note that eventually this function could go away if we are confident
  13042. // enough the code is exception free.
  13043. return w(h, WebChannel.EventType.OPEN, (() => {
  13044. f || N(ku, `RPC '${t}' stream ${s} transport opened.`);
  13045. })), w(h, WebChannel.EventType.CLOSE, (() => {
  13046. f || (f = !0, N(ku, `RPC '${t}' stream ${s} transport closed`), d.wo());
  13047. })), w(h, WebChannel.EventType.ERROR, (e => {
  13048. f || (f = !0, M(ku, `RPC '${t}' stream ${s} transport errored:`, e), d.wo(new U(q.UNAVAILABLE, "The operation could not be completed")));
  13049. })), w(h, WebChannel.EventType.MESSAGE, (e => {
  13050. var n;
  13051. if (!f) {
  13052. const i = e.data[0];
  13053. F(!!i);
  13054. // TODO(b/35143891): There is a bug in One Platform that caused errors
  13055. // (and only errors) to be wrapped in an extra array. To be forward
  13056. // compatible with the bug we need to check either condition. The latter
  13057. // can be removed once the fix has been rolled out.
  13058. // Use any because msgData.error is not typed.
  13059. const r = i, o = r.error || (null === (n = r[0]) || void 0 === n ? void 0 : n.error);
  13060. if (o) {
  13061. N(ku, `RPC '${t}' stream ${s} received error:`, o);
  13062. // error.status will be a string like 'OK' or 'NOT_FOUND'.
  13063. const e = o.status;
  13064. let n =
  13065. /**
  13066. * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
  13067. *
  13068. * @returns The Code equivalent to the given status string or undefined if
  13069. * there is no match.
  13070. */
  13071. function(t) {
  13072. // lookup by string
  13073. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13074. const e = ii[t];
  13075. if (void 0 !== e) return ui(e);
  13076. }(e), i = o.message;
  13077. void 0 === n && (n = q.INTERNAL, i = "Unknown error status: " + e + " with message " + o.message),
  13078. // Mark closed so no further events are propagated
  13079. f = !0, d.wo(new U(n, i)), h.close();
  13080. } else N(ku, `RPC '${t}' stream ${s} received:`, i), d._o(i);
  13081. }
  13082. })), w(o, Event.STAT_EVENT, (e => {
  13083. e.stat === Stat.PROXY ? N(ku, `RPC '${t}' stream ${s} detected buffering proxy`) : e.stat === Stat.NOPROXY && N(ku, `RPC '${t}' stream ${s} detected no buffering proxy`);
  13084. })), setTimeout((() => {
  13085. // Technically we could/should wait for the WebChannel opened event,
  13086. // but because we want to send the first message with the WebChannel
  13087. // handshake we pretend the channel opened here (asynchronously), and
  13088. // then delay the actual open until the first message is sent.
  13089. d.fo();
  13090. }), 0), d;
  13091. }
  13092. }
  13093. /**
  13094. * @license
  13095. * Copyright 2020 Google LLC
  13096. *
  13097. * Licensed under the Apache License, Version 2.0 (the "License");
  13098. * you may not use this file except in compliance with the License.
  13099. * You may obtain a copy of the License at
  13100. *
  13101. * http://www.apache.org/licenses/LICENSE-2.0
  13102. *
  13103. * Unless required by applicable law or agreed to in writing, software
  13104. * distributed under the License is distributed on an "AS IS" BASIS,
  13105. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13106. * See the License for the specific language governing permissions and
  13107. * limitations under the License.
  13108. */
  13109. /** Initializes the WebChannelConnection for the browser. */
  13110. /**
  13111. * @license
  13112. * Copyright 2020 Google LLC
  13113. *
  13114. * Licensed under the Apache License, Version 2.0 (the "License");
  13115. * you may not use this file except in compliance with the License.
  13116. * You may obtain a copy of the License at
  13117. *
  13118. * http://www.apache.org/licenses/LICENSE-2.0
  13119. *
  13120. * Unless required by applicable law or agreed to in writing, software
  13121. * distributed under the License is distributed on an "AS IS" BASIS,
  13122. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13123. * See the License for the specific language governing permissions and
  13124. * limitations under the License.
  13125. */
  13126. /** The Platform's 'window' implementation or null if not available. */
  13127. function $u() {
  13128. // `window` is not always available, e.g. in ReactNative and WebWorkers.
  13129. // eslint-disable-next-line no-restricted-globals
  13130. return "undefined" != typeof window ? window : null;
  13131. }
  13132. /** The Platform's 'document' implementation or null if not available. */ function Ou() {
  13133. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  13134. // eslint-disable-next-line no-restricted-globals
  13135. return "undefined" != typeof document ? document : null;
  13136. }
  13137. /**
  13138. * @license
  13139. * Copyright 2020 Google LLC
  13140. *
  13141. * Licensed under the Apache License, Version 2.0 (the "License");
  13142. * you may not use this file except in compliance with the License.
  13143. * You may obtain a copy of the License at
  13144. *
  13145. * http://www.apache.org/licenses/LICENSE-2.0
  13146. *
  13147. * Unless required by applicable law or agreed to in writing, software
  13148. * distributed under the License is distributed on an "AS IS" BASIS,
  13149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13150. * See the License for the specific language governing permissions and
  13151. * limitations under the License.
  13152. */ function Fu(t) {
  13153. return new Vi(t, /* useProto3Json= */ !0);
  13154. }
  13155. /**
  13156. * @license
  13157. * Copyright 2017 Google LLC
  13158. *
  13159. * Licensed under the Apache License, Version 2.0 (the "License");
  13160. * you may not use this file except in compliance with the License.
  13161. * You may obtain a copy of the License at
  13162. *
  13163. * http://www.apache.org/licenses/LICENSE-2.0
  13164. *
  13165. * Unless required by applicable law or agreed to in writing, software
  13166. * distributed under the License is distributed on an "AS IS" BASIS,
  13167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13168. * See the License for the specific language governing permissions and
  13169. * limitations under the License.
  13170. */
  13171. /**
  13172. * A helper for running delayed tasks following an exponential backoff curve
  13173. * between attempts.
  13174. *
  13175. * Each delay is made up of a "base" delay which follows the exponential
  13176. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  13177. * base delay. This prevents clients from accidentally synchronizing their
  13178. * delays causing spikes of load to the backend.
  13179. */
  13180. class Bu {
  13181. constructor(
  13182. /**
  13183. * The AsyncQueue to run backoff operations on.
  13184. */
  13185. t,
  13186. /**
  13187. * The ID to use when scheduling backoff operations on the AsyncQueue.
  13188. */
  13189. e,
  13190. /**
  13191. * The initial delay (used as the base delay on the first retry attempt).
  13192. * Note that jitter will still be applied, so the actual delay could be as
  13193. * little as 0.5*initialDelayMs.
  13194. */
  13195. n = 1e3
  13196. /**
  13197. * The multiplier to use to determine the extended base delay after each
  13198. * attempt.
  13199. */ , s = 1.5
  13200. /**
  13201. * The maximum base delay after which no further backoff is performed.
  13202. * Note that jitter will still be applied, so the actual delay could be as
  13203. * much as 1.5*maxDelayMs.
  13204. */ , i = 6e4) {
  13205. this.ii = t, this.timerId = e, this.Po = n, this.bo = s, this.Vo = i, this.So = 0,
  13206. this.Do = null,
  13207. /** The last backoff attempt, as epoch milliseconds. */
  13208. this.Co = Date.now(), this.reset();
  13209. }
  13210. /**
  13211. * Resets the backoff delay.
  13212. *
  13213. * The very next backoffAndWait() will have no delay. If it is called again
  13214. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  13215. * subsequent ones will increase according to the backoffFactor.
  13216. */ reset() {
  13217. this.So = 0;
  13218. }
  13219. /**
  13220. * Resets the backoff delay to the maximum delay (e.g. for use after a
  13221. * RESOURCE_EXHAUSTED error).
  13222. */ xo() {
  13223. this.So = this.Vo;
  13224. }
  13225. /**
  13226. * Returns a promise that resolves after currentDelayMs, and increases the
  13227. * delay for any subsequent attempts. If there was a pending backoff operation
  13228. * already, it will be canceled.
  13229. */ No(t) {
  13230. // Cancel any pending backoff operation.
  13231. this.cancel();
  13232. // First schedule using the current base (which may be 0 and should be
  13233. // honored as such).
  13234. const e = Math.floor(this.So + this.ko()), n = Math.max(0, Date.now() - this.Co), s = Math.max(0, e - n);
  13235. // Guard against lastAttemptTime being in the future due to a clock change.
  13236. s > 0 && N("ExponentialBackoff", `Backing off for ${s} ms (base delay: ${this.So} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),
  13237. this.Do = this.ii.enqueueAfterDelay(this.timerId, s, (() => (this.Co = Date.now(),
  13238. t()))),
  13239. // Apply backoff factor to determine next delay and ensure it is within
  13240. // bounds.
  13241. this.So *= this.bo, this.So < this.Po && (this.So = this.Po), this.So > this.Vo && (this.So = this.Vo);
  13242. }
  13243. Mo() {
  13244. null !== this.Do && (this.Do.skipDelay(), this.Do = null);
  13245. }
  13246. cancel() {
  13247. null !== this.Do && (this.Do.cancel(), this.Do = null);
  13248. }
  13249. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ ko() {
  13250. return (Math.random() - .5) * this.So;
  13251. }
  13252. }
  13253. /**
  13254. * @license
  13255. * Copyright 2017 Google LLC
  13256. *
  13257. * Licensed under the Apache License, Version 2.0 (the "License");
  13258. * you may not use this file except in compliance with the License.
  13259. * You may obtain a copy of the License at
  13260. *
  13261. * http://www.apache.org/licenses/LICENSE-2.0
  13262. *
  13263. * Unless required by applicable law or agreed to in writing, software
  13264. * distributed under the License is distributed on an "AS IS" BASIS,
  13265. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13266. * See the License for the specific language governing permissions and
  13267. * limitations under the License.
  13268. */
  13269. /**
  13270. * A PersistentStream is an abstract base class that represents a streaming RPC
  13271. * to the Firestore backend. It's built on top of the connections own support
  13272. * for streaming RPCs, and adds several critical features for our clients:
  13273. *
  13274. * - Exponential backoff on failure
  13275. * - Authentication via CredentialsProvider
  13276. * - Dispatching all callbacks into the shared worker queue
  13277. * - Closing idle streams after 60 seconds of inactivity
  13278. *
  13279. * Subclasses of PersistentStream implement serialization of models to and
  13280. * from the JSON representation of the protocol buffers for a specific
  13281. * streaming RPC.
  13282. *
  13283. * ## Starting and Stopping
  13284. *
  13285. * Streaming RPCs are stateful and need to be start()ed before messages can
  13286. * be sent and received. The PersistentStream will call the onOpen() function
  13287. * of the listener once the stream is ready to accept requests.
  13288. *
  13289. * Should a start() fail, PersistentStream will call the registered onClose()
  13290. * listener with a FirestoreError indicating what went wrong.
  13291. *
  13292. * A PersistentStream can be started and stopped repeatedly.
  13293. *
  13294. * Generic types:
  13295. * SendType: The type of the outgoing message of the underlying
  13296. * connection stream
  13297. * ReceiveType: The type of the incoming message of the underlying
  13298. * connection stream
  13299. * ListenerType: The type of the listener that will be used for callbacks
  13300. */
  13301. class Lu {
  13302. constructor(t, e, n, s, i, r, o, u) {
  13303. this.ii = t, this.$o = n, this.Oo = s, this.connection = i, this.authCredentialsProvider = r,
  13304. this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ ,
  13305. /**
  13306. * A close count that's incremented every time the stream is closed; used by
  13307. * getCloseGuardedDispatcher() to invalidate callbacks that happen after
  13308. * close.
  13309. */
  13310. this.Fo = 0, this.Bo = null, this.Lo = null, this.stream = null, this.qo = new Bu(t, e);
  13311. }
  13312. /**
  13313. * Returns true if start() has been called and no error has occurred. True
  13314. * indicates the stream is open or in the process of opening (which
  13315. * encompasses respecting backoff, getting auth tokens, and starting the
  13316. * actual RPC). Use isOpen() to determine if the stream is open and ready for
  13317. * outbound requests.
  13318. */ Uo() {
  13319. return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Ko();
  13320. }
  13321. /**
  13322. * Returns true if the underlying RPC is open (the onOpen() listener has been
  13323. * called) and the stream is ready for outbound requests.
  13324. */ Ko() {
  13325. return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
  13326. }
  13327. /**
  13328. * Starts the RPC. Only allowed if isStarted() returns false. The stream is
  13329. * not immediately ready for use: onOpen() will be invoked when the RPC is
  13330. * ready for outbound requests, at which point isOpen() will return true.
  13331. *
  13332. * When start returns, isStarted() will return true.
  13333. */ start() {
  13334. 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Go();
  13335. }
  13336. /**
  13337. * Stops the RPC. This call is idempotent and allowed regardless of the
  13338. * current isStarted() state.
  13339. *
  13340. * When stop returns, isStarted() and isOpen() will both return false.
  13341. */ async stop() {
  13342. this.Uo() && await this.close(0 /* PersistentStreamState.Initial */);
  13343. }
  13344. /**
  13345. * After an error the stream will usually back off on the next attempt to
  13346. * start it. If the error warrants an immediate restart of the stream, the
  13347. * sender can use this to indicate that the receiver should not back off.
  13348. *
  13349. * Each error will call the onClose() listener. That function can decide to
  13350. * inhibit backoff if required.
  13351. */ Qo() {
  13352. this.state = 0 /* PersistentStreamState.Initial */ , this.qo.reset();
  13353. }
  13354. /**
  13355. * Marks this stream as idle. If no further actions are performed on the
  13356. * stream for one minute, the stream will automatically close itself and
  13357. * notify the stream's onClose() handler with Status.OK. The stream will then
  13358. * be in a !isStarted() state, requiring the caller to start the stream again
  13359. * before further use.
  13360. *
  13361. * Only streams that are in state 'Open' can be marked idle, as all other
  13362. * states imply pending network operations.
  13363. */ jo() {
  13364. // Starts the idle time if we are in state 'Open' and are not yet already
  13365. // running a timer (in which case the previous idle timeout still applies).
  13366. this.Ko() && null === this.Bo && (this.Bo = this.ii.enqueueAfterDelay(this.$o, 6e4, (() => this.zo())));
  13367. }
  13368. /** Sends a message to the underlying stream. */ Wo(t) {
  13369. this.Ho(), this.stream.send(t);
  13370. }
  13371. /** Called by the idle timer when the stream should close due to inactivity. */ async zo() {
  13372. if (this.Ko())
  13373. // When timing out an idle stream there's no reason to force the stream into backoff when
  13374. // it restarts so set the stream state to Initial instead of Error.
  13375. return this.close(0 /* PersistentStreamState.Initial */);
  13376. }
  13377. /** Marks the stream as active again. */ Ho() {
  13378. this.Bo && (this.Bo.cancel(), this.Bo = null);
  13379. }
  13380. /** Cancels the health check delayed operation. */ Jo() {
  13381. this.Lo && (this.Lo.cancel(), this.Lo = null);
  13382. }
  13383. /**
  13384. * Closes the stream and cleans up as necessary:
  13385. *
  13386. * * closes the underlying GRPC stream;
  13387. * * calls the onClose handler with the given 'error';
  13388. * * sets internal stream state to 'finalState';
  13389. * * adjusts the backoff timer based on the error
  13390. *
  13391. * A new stream can be opened by calling start().
  13392. *
  13393. * @param finalState - the intended state of the stream after closing.
  13394. * @param error - the error the connection was closed with.
  13395. */ async close(t, e) {
  13396. // Cancel any outstanding timers (they're guaranteed not to execute).
  13397. this.Ho(), this.Jo(), this.qo.cancel(),
  13398. // Invalidates any stream-related callbacks (e.g. from auth or the
  13399. // underlying stream), guaranteeing they won't execute.
  13400. this.Fo++, 4 /* PersistentStreamState.Error */ !== t ?
  13401. // If this is an intentional close ensure we don't delay our next connection attempt.
  13402. this.qo.reset() : e && e.code === q.RESOURCE_EXHAUSTED ? (
  13403. // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
  13404. k(e.toString()), k("Using maximum backoff delay to prevent overloading the backend."),
  13405. this.qo.xo()) : e && e.code === q.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
  13406. // "unauthenticated" error means the token was rejected. This should rarely
  13407. // happen since both Auth and AppCheck ensure a sufficient TTL when we
  13408. // request a token. If a user manually resets their system clock this can
  13409. // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
  13410. // before we received the first message and we need to invalidate the token
  13411. // to ensure that we fetch a new token.
  13412. this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()),
  13413. // Clean up the underlying stream because we are no longer interested in events.
  13414. null !== this.stream && (this.Yo(), this.stream.close(), this.stream = null),
  13415. // This state must be assigned before calling onClose() to allow the callback to
  13416. // inhibit backoff or otherwise manipulate the state in its non-started state.
  13417. this.state = t,
  13418. // Notify the listener that the stream closed.
  13419. await this.listener.ao(e);
  13420. }
  13421. /**
  13422. * Can be overridden to perform additional cleanup before the stream is closed.
  13423. * Calling super.tearDown() is not required.
  13424. */ Yo() {}
  13425. auth() {
  13426. this.state = 1 /* PersistentStreamState.Starting */;
  13427. const t = this.Xo(this.Fo), e = this.Fo;
  13428. // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
  13429. Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {
  13430. // Stream can be stopped while waiting for authentication.
  13431. // TODO(mikelehen): We really should just use dispatchIfNotClosed
  13432. // and let this dispatch onto the queue, but that opened a spec test can
  13433. // of worms that I don't want to deal with in this PR.
  13434. this.Fo === e &&
  13435. // Normally we'd have to schedule the callback on the AsyncQueue.
  13436. // However, the following calls are safe to be called outside the
  13437. // AsyncQueue since they don't chain asynchronous calls
  13438. this.Zo(t, n);
  13439. }), (e => {
  13440. t((() => {
  13441. const t = new U(q.UNKNOWN, "Fetching auth token failed: " + e.message);
  13442. return this.tu(t);
  13443. }));
  13444. }));
  13445. }
  13446. Zo(t, e) {
  13447. const n = this.Xo(this.Fo);
  13448. this.stream = this.eu(t, e), this.stream.uo((() => {
  13449. n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Lo = this.ii.enqueueAfterDelay(this.Oo, 1e4, (() => (this.Ko() && (this.state = 3 /* PersistentStreamState.Healthy */),
  13450. Promise.resolve()))), this.listener.uo())));
  13451. })), this.stream.ao((t => {
  13452. n((() => this.tu(t)));
  13453. })), this.stream.onMessage((t => {
  13454. n((() => this.onMessage(t)));
  13455. }));
  13456. }
  13457. Go() {
  13458. this.state = 5 /* PersistentStreamState.Backoff */ , this.qo.No((async () => {
  13459. this.state = 0 /* PersistentStreamState.Initial */ , this.start();
  13460. }));
  13461. }
  13462. // Visible for tests
  13463. tu(t) {
  13464. // In theory the stream could close cleanly, however, in our current model
  13465. // we never expect this to happen because if we stop a stream ourselves,
  13466. // this callback will never be called. To prevent cases where we retry
  13467. // without a backoff accidentally, we set the stream to error in all cases.
  13468. return N("PersistentStream", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);
  13469. }
  13470. /**
  13471. * Returns a "dispatcher" function that dispatches operations onto the
  13472. * AsyncQueue but only runs them if closeCount remains unchanged. This allows
  13473. * us to turn auth / stream callbacks into no-ops if the stream is closed /
  13474. * re-opened, etc.
  13475. */ Xo(t) {
  13476. return e => {
  13477. this.ii.enqueueAndForget((() => this.Fo === t ? e() : (N("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."),
  13478. Promise.resolve())));
  13479. };
  13480. }
  13481. }
  13482. /**
  13483. * A PersistentStream that implements the Listen RPC.
  13484. *
  13485. * Once the Listen stream has called the onOpen() listener, any number of
  13486. * listen() and unlisten() calls can be made to control what changes will be
  13487. * sent from the server for ListenResponses.
  13488. */ class qu extends Lu {
  13489. constructor(t, e, n, s, i, r) {
  13490. super(t, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13491. this.serializer = i;
  13492. }
  13493. eu(t, e) {
  13494. return this.connection.Ro("Listen", t, e);
  13495. }
  13496. onMessage(t) {
  13497. // A successful response means the stream is healthy
  13498. this.qo.reset();
  13499. const e = Qi(this.serializer, t), n = function(t) {
  13500. // We have only reached a consistent snapshot for the entire stream if there
  13501. // is a read_time set and it applies to all targets (i.e. the list of
  13502. // targets is empty). The backend is guaranteed to send such responses.
  13503. if (!("targetChange" in t)) return rt.min();
  13504. const e = t.targetChange;
  13505. return e.targetIds && e.targetIds.length ? rt.min() : e.readTime ? Ni(e.readTime) : rt.min();
  13506. }(t);
  13507. return this.listener.nu(e, n);
  13508. }
  13509. /**
  13510. * Registers interest in the results of the given target. If the target
  13511. * includes a resumeToken it will be included in the request. Results that
  13512. * affect the target will be streamed back as WatchChange messages that
  13513. * reference the targetId.
  13514. */ su(t) {
  13515. const e = {};
  13516. e.database = Li(this.serializer), e.addTarget = function(t, e) {
  13517. let n;
  13518. const s = e.target;
  13519. if (n = Fn(s) ? {
  13520. documents: Hi(t, s)
  13521. } : {
  13522. query: Ji(t, s)
  13523. }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0) {
  13524. n.resumeToken = Ci(t, e.resumeToken);
  13525. const s = Si(t, e.expectedCount);
  13526. null !== s && (n.expectedCount = s);
  13527. } else if (e.snapshotVersion.compareTo(rt.min()) > 0) {
  13528. // TODO(wuandy): Consider removing above check because it is most likely true.
  13529. // Right now, many tests depend on this behaviour though (leaving min() out
  13530. // of serialization).
  13531. n.readTime = Di(t, e.snapshotVersion.toTimestamp());
  13532. const s = Si(t, e.expectedCount);
  13533. null !== s && (n.expectedCount = s);
  13534. }
  13535. return n;
  13536. }(this.serializer, t);
  13537. const n = Xi(this.serializer, t);
  13538. n && (e.labels = n), this.Wo(e);
  13539. }
  13540. /**
  13541. * Unregisters interest in the results of the target associated with the
  13542. * given targetId.
  13543. */ iu(t) {
  13544. const e = {};
  13545. e.database = Li(this.serializer), e.removeTarget = t, this.Wo(e);
  13546. }
  13547. }
  13548. /**
  13549. * A Stream that implements the Write RPC.
  13550. *
  13551. * The Write RPC requires the caller to maintain special streamToken
  13552. * state in between calls, to help the server understand which responses the
  13553. * client has processed by the time the next request is made. Every response
  13554. * will contain a streamToken; this value must be passed to the next
  13555. * request.
  13556. *
  13557. * After calling start() on this stream, the next request must be a handshake,
  13558. * containing whatever streamToken is on hand. Once a response to this
  13559. * request is received, all pending mutations may be submitted. When
  13560. * submitting multiple batches of mutations at the same time, it's
  13561. * okay to use the same streamToken for the calls to writeMutations.
  13562. *
  13563. * TODO(b/33271235): Use proto types
  13564. */ class Uu extends Lu {
  13565. constructor(t, e, n, s, i, r) {
  13566. super(t, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13567. this.serializer = i, this.ru = !1;
  13568. }
  13569. /**
  13570. * Tracks whether or not a handshake has been successfully exchanged and
  13571. * the stream is ready to accept mutations.
  13572. */ get ou() {
  13573. return this.ru;
  13574. }
  13575. // Override of PersistentStream.start
  13576. start() {
  13577. this.ru = !1, this.lastStreamToken = void 0, super.start();
  13578. }
  13579. Yo() {
  13580. this.ru && this.uu([]);
  13581. }
  13582. eu(t, e) {
  13583. return this.connection.Ro("Write", t, e);
  13584. }
  13585. onMessage(t) {
  13586. if (
  13587. // Always capture the last stream token.
  13588. F(!!t.streamToken), this.lastStreamToken = t.streamToken, this.ru) {
  13589. // A successful first write response means the stream is healthy,
  13590. // Note, that we could consider a successful handshake healthy, however,
  13591. // the write itself might be causing an error we want to back off from.
  13592. this.qo.reset();
  13593. const e = Wi(t.writeResults, t.commitTime), n = Ni(t.commitTime);
  13594. return this.listener.cu(n, e);
  13595. }
  13596. // The first response is always the handshake response
  13597. return F(!t.writeResults || 0 === t.writeResults.length), this.ru = !0, this.listener.au();
  13598. }
  13599. /**
  13600. * Sends an initial streamToken to the server, performing the handshake
  13601. * required to make the StreamingWrite RPC work. Subsequent
  13602. * calls should wait until onHandshakeComplete was called.
  13603. */ hu() {
  13604. // TODO(dimond): Support stream resumption. We intentionally do not set the
  13605. // stream token on the handshake, ignoring any stream token we might have.
  13606. const t = {};
  13607. t.database = Li(this.serializer), this.Wo(t);
  13608. }
  13609. /** Sends a group of mutations to the Firestore backend to apply. */ uu(t) {
  13610. const e = {
  13611. streamToken: this.lastStreamToken,
  13612. writes: t.map((t => ji(this.serializer, t)))
  13613. };
  13614. this.Wo(e);
  13615. }
  13616. }
  13617. /**
  13618. * @license
  13619. * Copyright 2017 Google LLC
  13620. *
  13621. * Licensed under the Apache License, Version 2.0 (the "License");
  13622. * you may not use this file except in compliance with the License.
  13623. * You may obtain a copy of the License at
  13624. *
  13625. * http://www.apache.org/licenses/LICENSE-2.0
  13626. *
  13627. * Unless required by applicable law or agreed to in writing, software
  13628. * distributed under the License is distributed on an "AS IS" BASIS,
  13629. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13630. * See the License for the specific language governing permissions and
  13631. * limitations under the License.
  13632. */
  13633. /**
  13634. * Datastore and its related methods are a wrapper around the external Google
  13635. * Cloud Datastore grpc API, which provides an interface that is more convenient
  13636. * for the rest of the client SDK architecture to consume.
  13637. */
  13638. /**
  13639. * An implementation of Datastore that exposes additional state for internal
  13640. * consumption.
  13641. */
  13642. class Ku extends class {} {
  13643. constructor(t, e, n, s) {
  13644. super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n,
  13645. this.serializer = s, this.lu = !1;
  13646. }
  13647. fu() {
  13648. if (this.lu) throw new U(q.FAILED_PRECONDITION, "The client has already been terminated.");
  13649. }
  13650. /** Invokes the provided RPC with auth and AppCheck tokens. */ Io(t, e, n) {
  13651. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.Io(t, e, n, s, i))).catch((t => {
  13652. throw "FirebaseError" === t.name ? (t.code === q.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13653. this.appCheckCredentials.invalidateToken()), t) : new U(q.UNKNOWN, t.toString());
  13654. }));
  13655. }
  13656. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ vo(t, e, n, s) {
  13657. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection.vo(t, e, n, i, r, s))).catch((t => {
  13658. throw "FirebaseError" === t.name ? (t.code === q.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13659. this.appCheckCredentials.invalidateToken()), t) : new U(q.UNKNOWN, t.toString());
  13660. }));
  13661. }
  13662. terminate() {
  13663. this.lu = !0;
  13664. }
  13665. }
  13666. // TODO(firestorexp): Make sure there is only one Datastore instance per
  13667. // firestore-exp client.
  13668. async function Gu(t, e, n) {
  13669. var s;
  13670. const i = L(t), {request: r, du: o} = function(t, e, n) {
  13671. const s = Ji(t, e), i = {}, r = [];
  13672. let o = 0;
  13673. return n.forEach((t => {
  13674. // Map all client-side aliases to a unique short-form
  13675. // alias. This avoids issues with client-side aliases that
  13676. // exceed the 1500-byte string size limit.
  13677. const e = "aggregate_" + o++;
  13678. i[e] = t.alias, "count" === t.yt ? r.push({
  13679. alias: e,
  13680. count: {}
  13681. }) : "avg" === t.yt ? r.push({
  13682. alias: e,
  13683. avg: {
  13684. field: sr(t.fieldPath)
  13685. }
  13686. }) : "sum" === t.yt && r.push({
  13687. alias: e,
  13688. sum: {
  13689. field: sr(t.fieldPath)
  13690. }
  13691. });
  13692. })), {
  13693. request: {
  13694. structuredAggregationQuery: {
  13695. aggregations: r,
  13696. structuredQuery: s.structuredQuery
  13697. },
  13698. parent: s.parent
  13699. },
  13700. du: i
  13701. };
  13702. }(i.serializer, Jn(e), n), u = r.parent;
  13703. i.connection.po || delete r.parent;
  13704. const c = (await i.vo("RunAggregationQuery", u, r, /*expectedResponseCount=*/ 1)).filter((t => !!t.result));
  13705. // Omit RunAggregationQueryResponse that only contain readTimes.
  13706. F(1 === c.length);
  13707. // Remap the short-form aliases that were sent to the server
  13708. // to the client-side aliases. Users will access the results
  13709. // using the client-side alias.
  13710. const a = null === (s = c[0].result) || void 0 === s ? void 0 : s.aggregateFields;
  13711. return Object.keys(a).reduce(((t, e) => (t[o[e]] = a[e], t)), {});
  13712. }
  13713. /**
  13714. * A component used by the RemoteStore to track the OnlineState (that is,
  13715. * whether or not the client as a whole should be considered to be online or
  13716. * offline), implementing the appropriate heuristics.
  13717. *
  13718. * In particular, when the client is trying to connect to the backend, we
  13719. * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
  13720. * a connection to succeed. If we have too many failures or the timeout elapses,
  13721. * then we set the OnlineState to Offline, and the client will behave as if
  13722. * it is offline (get()s will return cached data, etc.).
  13723. */
  13724. class Qu {
  13725. constructor(t, e) {
  13726. this.asyncQueue = t, this.onlineStateHandler = e,
  13727. /** The current OnlineState. */
  13728. this.state = "Unknown" /* OnlineState.Unknown */ ,
  13729. /**
  13730. * A count of consecutive failures to open the stream. If it reaches the
  13731. * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
  13732. * Offline.
  13733. */
  13734. this.wu = 0,
  13735. /**
  13736. * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
  13737. * transition from OnlineState.Unknown to OnlineState.Offline without waiting
  13738. * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
  13739. */
  13740. this._u = null,
  13741. /**
  13742. * Whether the client should log a warning message if it fails to connect to
  13743. * the backend (initially true, cleared after a successful stream, or if we've
  13744. * logged the message already).
  13745. */
  13746. this.mu = !0;
  13747. }
  13748. /**
  13749. * Called by RemoteStore when a watch stream is started (including on each
  13750. * backoff attempt).
  13751. *
  13752. * If this is the first attempt, it sets the OnlineState to Unknown and starts
  13753. * the onlineStateTimer.
  13754. */ gu() {
  13755. 0 === this.wu && (this.yu("Unknown" /* OnlineState.Unknown */), this._u = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this._u = null,
  13756. this.pu("Backend didn't respond within 10 seconds."), this.yu("Offline" /* OnlineState.Offline */),
  13757. Promise.resolve()))));
  13758. }
  13759. /**
  13760. * Updates our OnlineState as appropriate after the watch stream reports a
  13761. * failure. The first failure moves us to the 'Unknown' state. We then may
  13762. * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
  13763. * actually transition to the 'Offline' state.
  13764. */ Iu(t) {
  13765. "Online" /* OnlineState.Online */ === this.state ? this.yu("Unknown" /* OnlineState.Unknown */) : (this.wu++,
  13766. this.wu >= 1 && (this.Tu(), this.pu(`Connection failed 1 times. Most recent error: ${t.toString()}`),
  13767. this.yu("Offline" /* OnlineState.Offline */)));
  13768. }
  13769. /**
  13770. * Explicitly sets the OnlineState to the specified state.
  13771. *
  13772. * Note that this resets our timers / failure counters, etc. used by our
  13773. * Offline heuristics, so must not be used in place of
  13774. * handleWatchStreamStart() and handleWatchStreamFailure().
  13775. */ set(t) {
  13776. this.Tu(), this.wu = 0, "Online" /* OnlineState.Online */ === t && (
  13777. // We've connected to watch at least once. Don't warn the developer
  13778. // about being offline going forward.
  13779. this.mu = !1), this.yu(t);
  13780. }
  13781. yu(t) {
  13782. t !== this.state && (this.state = t, this.onlineStateHandler(t));
  13783. }
  13784. pu(t) {
  13785. const e = `Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
  13786. this.mu ? (k(e), this.mu = !1) : N("OnlineStateTracker", e);
  13787. }
  13788. Tu() {
  13789. null !== this._u && (this._u.cancel(), this._u = null);
  13790. }
  13791. }
  13792. /**
  13793. * @license
  13794. * Copyright 2017 Google LLC
  13795. *
  13796. * Licensed under the Apache License, Version 2.0 (the "License");
  13797. * you may not use this file except in compliance with the License.
  13798. * You may obtain a copy of the License at
  13799. *
  13800. * http://www.apache.org/licenses/LICENSE-2.0
  13801. *
  13802. * Unless required by applicable law or agreed to in writing, software
  13803. * distributed under the License is distributed on an "AS IS" BASIS,
  13804. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13805. * See the License for the specific language governing permissions and
  13806. * limitations under the License.
  13807. */ class ju {
  13808. constructor(
  13809. /**
  13810. * The local store, used to fill the write pipeline with outbound mutations.
  13811. */
  13812. t,
  13813. /** The client-side proxy for interacting with the backend. */
  13814. e, n, s, i) {
  13815. this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {},
  13816. /**
  13817. * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
  13818. * LocalStore via fillWritePipeline() and have or will send to the write
  13819. * stream.
  13820. *
  13821. * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
  13822. * restart the write stream. When the stream is established the writes in the
  13823. * pipeline will be sent in order.
  13824. *
  13825. * Writes remain in writePipeline until they are acknowledged by the backend
  13826. * and thus will automatically be re-sent if the stream is interrupted /
  13827. * restarted before they're acknowledged.
  13828. *
  13829. * Write responses from the backend are linked to their originating request
  13830. * purely based on order, and so we can just shift() writes from the front of
  13831. * the writePipeline as we receive responses.
  13832. */
  13833. this.Eu = [],
  13834. /**
  13835. * A mapping of watched targets that the client cares about tracking and the
  13836. * user has explicitly called a 'listen' for this target.
  13837. *
  13838. * These targets may or may not have been sent to or acknowledged by the
  13839. * server. On re-establishing the listen stream, these targets should be sent
  13840. * to the server. The targets removed with unlistens are removed eagerly
  13841. * without waiting for confirmation from the listen stream.
  13842. */
  13843. this.Au = new Map,
  13844. /**
  13845. * A set of reasons for why the RemoteStore may be offline. If empty, the
  13846. * RemoteStore may start its network connections.
  13847. */
  13848. this.vu = new Set,
  13849. /**
  13850. * Event handlers that get called when the network is disabled or enabled.
  13851. *
  13852. * PORTING NOTE: These functions are used on the Web client to create the
  13853. * underlying streams (to support tree-shakeable streams). On Android and iOS,
  13854. * the streams are created during construction of RemoteStore.
  13855. */
  13856. this.Ru = [], this.Pu = i, this.Pu.Yr((t => {
  13857. n.enqueueAndForget((async () => {
  13858. // Porting Note: Unlike iOS, `restartNetwork()` is called even when the
  13859. // network becomes unreachable as we don't have any other way to tear
  13860. // down our streams.
  13861. ec(this) && (N("RemoteStore", "Restarting streams for network reachability change."),
  13862. await async function(t) {
  13863. const e = L(t);
  13864. e.vu.add(4 /* OfflineCause.ConnectivityChange */), await Wu(e), e.bu.set("Unknown" /* OnlineState.Unknown */),
  13865. e.vu.delete(4 /* OfflineCause.ConnectivityChange */), await zu(e);
  13866. }(this));
  13867. }));
  13868. })), this.bu = new Qu(n, s);
  13869. }
  13870. }
  13871. async function zu(t) {
  13872. if (ec(t)) for (const e of t.Ru) await e(/* enabled= */ !0);
  13873. }
  13874. /**
  13875. * Temporarily disables the network. The network can be re-enabled using
  13876. * enableNetwork().
  13877. */ async function Wu(t) {
  13878. for (const e of t.Ru) await e(/* enabled= */ !1);
  13879. }
  13880. /**
  13881. * Starts new listen for the given target. Uses resume token if provided. It
  13882. * is a no-op if the target of given `TargetData` is already being listened to.
  13883. */
  13884. function Hu(t, e) {
  13885. const n = L(t);
  13886. n.Au.has(e.targetId) || (
  13887. // Mark this as something the client is currently listening for.
  13888. n.Au.set(e.targetId, e), tc(n) ?
  13889. // The listen will be sent in onWatchStreamOpen
  13890. Zu(n) : pc(n).Ko() && Yu(n, e));
  13891. }
  13892. /**
  13893. * Removes the listen from server. It is a no-op if the given target id is
  13894. * not being listened to.
  13895. */ function Ju(t, e) {
  13896. const n = L(t), s = pc(n);
  13897. n.Au.delete(e), s.Ko() && Xu(n, e), 0 === n.Au.size && (s.Ko() ? s.jo() : ec(n) &&
  13898. // Revert to OnlineState.Unknown if the watch stream is not open and we
  13899. // have no listeners, since without any listens to send we cannot
  13900. // confirm if the stream is healthy and upgrade to OnlineState.Online.
  13901. n.bu.set("Unknown" /* OnlineState.Unknown */));
  13902. }
  13903. /**
  13904. * We need to increment the the expected number of pending responses we're due
  13905. * from watch so we wait for the ack to process any messages from this target.
  13906. */ function Yu(t, e) {
  13907. if (t.Vu.qt(e.targetId), e.resumeToken.approximateByteSize() > 0 || e.snapshotVersion.compareTo(rt.min()) > 0) {
  13908. const n = t.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;
  13909. e = e.withExpectedCount(n);
  13910. }
  13911. pc(t).su(e);
  13912. }
  13913. /**
  13914. * We need to increment the expected number of pending responses we're due
  13915. * from watch so we wait for the removal on the server before we process any
  13916. * messages from this target.
  13917. */ function Xu(t, e) {
  13918. t.Vu.qt(e), pc(t).iu(e);
  13919. }
  13920. function Zu(t) {
  13921. t.Vu = new Ei({
  13922. getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),
  13923. le: e => t.Au.get(e) || null,
  13924. ue: () => t.datastore.serializer.databaseId
  13925. }), pc(t).start(), t.bu.gu();
  13926. }
  13927. /**
  13928. * Returns whether the watch stream should be started because it's necessary
  13929. * and has not yet been started.
  13930. */ function tc(t) {
  13931. return ec(t) && !pc(t).Uo() && t.Au.size > 0;
  13932. }
  13933. function ec(t) {
  13934. return 0 === L(t).vu.size;
  13935. }
  13936. function nc(t) {
  13937. t.Vu = void 0;
  13938. }
  13939. async function sc(t) {
  13940. t.Au.forEach(((e, n) => {
  13941. Yu(t, e);
  13942. }));
  13943. }
  13944. async function ic(t, e) {
  13945. nc(t),
  13946. // If we still need the watch stream, retry the connection.
  13947. tc(t) ? (t.bu.Iu(e), Zu(t)) :
  13948. // No need to restart watch stream because there are no active targets.
  13949. // The online state is set to unknown because there is no active attempt
  13950. // at establishing a connection
  13951. t.bu.set("Unknown" /* OnlineState.Unknown */);
  13952. }
  13953. async function rc(t, e, n) {
  13954. if (
  13955. // Mark the client as online since we got a message from the server
  13956. t.bu.set("Online" /* OnlineState.Online */), e instanceof Ii && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause)
  13957. // There was an error on a target, don't wait for a consistent snapshot
  13958. // to raise events
  13959. try {
  13960. await
  13961. /** Handles an error on a target */
  13962. async function(t, e) {
  13963. const n = e.cause;
  13964. for (const s of e.targetIds)
  13965. // A watched target might have been removed already.
  13966. t.Au.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.Au.delete(s), t.Vu.removeTarget(s));
  13967. }
  13968. /**
  13969. * Attempts to fill our write pipeline with writes from the LocalStore.
  13970. *
  13971. * Called internally to bootstrap or refill the write pipeline and by
  13972. * SyncEngine whenever there are new mutations to process.
  13973. *
  13974. * Starts the write stream if necessary.
  13975. */ (t, e);
  13976. } catch (n) {
  13977. N("RemoteStore", "Failed to remove targets %s: %s ", e.targetIds.join(","), n),
  13978. await oc(t, n);
  13979. } else if (e instanceof yi ? t.Vu.Ht(e) : e instanceof pi ? t.Vu.ne(e) : t.Vu.Xt(e),
  13980. !n.isEqual(rt.min())) try {
  13981. const e = await ou(t.localStore);
  13982. n.compareTo(e) >= 0 &&
  13983. // We have received a target change with a global snapshot if the snapshot
  13984. // version is not equal to SnapshotVersion.min().
  13985. await
  13986. /**
  13987. * Takes a batch of changes from the Datastore, repackages them as a
  13988. * RemoteEvent, and passes that on to the listener, which is typically the
  13989. * SyncEngine.
  13990. */
  13991. function(t, e) {
  13992. const n = t.Vu.ce(e);
  13993. // Update in-memory resume tokens. LocalStore will update the
  13994. // persistent view of these when applying the completed RemoteEvent.
  13995. return n.targetChanges.forEach(((n, s) => {
  13996. if (n.resumeToken.approximateByteSize() > 0) {
  13997. const i = t.Au.get(s);
  13998. // A watched target might have been removed already.
  13999. i && t.Au.set(s, i.withResumeToken(n.resumeToken, e));
  14000. }
  14001. })),
  14002. // Re-establish listens for the targets that have been invalidated by
  14003. // existence filter mismatches.
  14004. n.targetMismatches.forEach(((e, n) => {
  14005. const s = t.Au.get(e);
  14006. if (!s)
  14007. // A watched target might have been removed already.
  14008. return;
  14009. // Clear the resume token for the target, since we're in a known mismatch
  14010. // state.
  14011. t.Au.set(e, s.withResumeToken(Ve.EMPTY_BYTE_STRING, s.snapshotVersion)),
  14012. // Cause a hard reset by unwatching and rewatching immediately, but
  14013. // deliberately don't send a resume token so that we get a full update.
  14014. Xu(t, e);
  14015. // Mark the target we send as being on behalf of an existence filter
  14016. // mismatch, but don't actually retain that in listenTargets. This ensures
  14017. // that we flag the first re-listen this way without impacting future
  14018. // listens of this target (that might happen e.g. on reconnect).
  14019. const i = new cr(s.target, e, n, s.sequenceNumber);
  14020. Yu(t, i);
  14021. })), t.remoteSyncer.applyRemoteEvent(n);
  14022. }(t, n);
  14023. } catch (e) {
  14024. N("RemoteStore", "Failed to raise snapshot:", e), await oc(t, e);
  14025. }
  14026. }
  14027. /**
  14028. * Recovery logic for IndexedDB errors that takes the network offline until
  14029. * `op` succeeds. Retries are scheduled with backoff using
  14030. * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
  14031. * validated via a generic operation.
  14032. *
  14033. * The returned Promise is resolved once the network is disabled and before
  14034. * any retry attempt.
  14035. */ async function oc(t, e, n) {
  14036. if (!Dt(e)) throw e;
  14037. t.vu.add(1 /* OfflineCause.IndexedDbFailed */),
  14038. // Disable network and raise offline snapshots
  14039. await Wu(t), t.bu.set("Offline" /* OnlineState.Offline */), n || (
  14040. // Use a simple read operation to determine if IndexedDB recovered.
  14041. // Ideally, we would expose a health check directly on SimpleDb, but
  14042. // RemoteStore only has access to persistence through LocalStore.
  14043. n = () => ou(t.localStore)),
  14044. // Probe IndexedDB periodically and re-enable network
  14045. t.asyncQueue.enqueueRetryable((async () => {
  14046. N("RemoteStore", "Retrying IndexedDB access"), await n(), t.vu.delete(1 /* OfflineCause.IndexedDbFailed */),
  14047. await zu(t);
  14048. }));
  14049. }
  14050. /**
  14051. * Executes `op`. If `op` fails, takes the network offline until `op`
  14052. * succeeds. Returns after the first attempt.
  14053. */ function uc(t, e) {
  14054. return e().catch((n => oc(t, n, e)));
  14055. }
  14056. async function cc(t) {
  14057. const e = L(t), n = Ic(e);
  14058. let s = e.Eu.length > 0 ? e.Eu[e.Eu.length - 1].batchId : -1;
  14059. for (;ac(e); ) try {
  14060. const t = await au(e.localStore, s);
  14061. if (null === t) {
  14062. 0 === e.Eu.length && n.jo();
  14063. break;
  14064. }
  14065. s = t.batchId, hc(e, t);
  14066. } catch (t) {
  14067. await oc(e, t);
  14068. }
  14069. lc(e) && fc(e);
  14070. }
  14071. /**
  14072. * Returns true if we can add to the write pipeline (i.e. the network is
  14073. * enabled and the write pipeline is not full).
  14074. */ function ac(t) {
  14075. return ec(t) && t.Eu.length < 10;
  14076. }
  14077. /**
  14078. * Queues additional writes to be sent to the write stream, sending them
  14079. * immediately if the write stream is established.
  14080. */ function hc(t, e) {
  14081. t.Eu.push(e);
  14082. const n = Ic(t);
  14083. n.Ko() && n.ou && n.uu(e.mutations);
  14084. }
  14085. function lc(t) {
  14086. return ec(t) && !Ic(t).Uo() && t.Eu.length > 0;
  14087. }
  14088. function fc(t) {
  14089. Ic(t).start();
  14090. }
  14091. async function dc(t) {
  14092. Ic(t).hu();
  14093. }
  14094. async function wc(t) {
  14095. const e = Ic(t);
  14096. // Send the write pipeline now that the stream is established.
  14097. for (const n of t.Eu) e.uu(n.mutations);
  14098. }
  14099. async function _c(t, e, n) {
  14100. const s = t.Eu.shift(), i = ti.from(s, e, n);
  14101. await uc(t, (() => t.remoteSyncer.applySuccessfulWrite(i))),
  14102. // It's possible that with the completion of this mutation another
  14103. // slot has freed up.
  14104. await cc(t);
  14105. }
  14106. async function mc(t, e) {
  14107. // If the write stream closed after the write handshake completes, a write
  14108. // operation failed and we fail the pending operation.
  14109. e && Ic(t).ou &&
  14110. // This error affects the actual write.
  14111. await async function(t, e) {
  14112. // Only handle permanent errors here. If it's transient, just let the retry
  14113. // logic kick in.
  14114. if (n = e.code, oi(n) && n !== q.ABORTED) {
  14115. // This was a permanent error, the request itself was the problem
  14116. // so it's not going to succeed if we resend it.
  14117. const n = t.Eu.shift();
  14118. // In this case it's also unlikely that the server itself is melting
  14119. // down -- this was just a bad request so inhibit backoff on the next
  14120. // restart.
  14121. Ic(t).Qo(), await uc(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))),
  14122. // It's possible that with the completion of this mutation
  14123. // another slot has freed up.
  14124. await cc(t);
  14125. }
  14126. var n;
  14127. }(t, e),
  14128. // The write stream might have been started by refilling the write
  14129. // pipeline for failed writes
  14130. lc(t) && fc(t);
  14131. }
  14132. async function gc(t, e) {
  14133. const n = L(t);
  14134. n.asyncQueue.verifyOperationInProgress(), N("RemoteStore", "RemoteStore received new credentials");
  14135. const s = ec(n);
  14136. // Tear down and re-create our network streams. This will ensure we get a
  14137. // fresh auth token for the new user and re-fill the write pipeline with
  14138. // new mutations from the LocalStore (since mutations are per-user).
  14139. n.vu.add(3 /* OfflineCause.CredentialChange */), await Wu(n), s &&
  14140. // Don't set the network status to Unknown if we are offline.
  14141. n.bu.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e),
  14142. n.vu.delete(3 /* OfflineCause.CredentialChange */), await zu(n);
  14143. }
  14144. /**
  14145. * Toggles the network state when the client gains or loses its primary lease.
  14146. */ async function yc(t, e) {
  14147. const n = L(t);
  14148. e ? (n.vu.delete(2 /* OfflineCause.IsSecondary */), await zu(n)) : e || (n.vu.add(2 /* OfflineCause.IsSecondary */),
  14149. await Wu(n), n.bu.set("Unknown" /* OnlineState.Unknown */));
  14150. }
  14151. /**
  14152. * If not yet initialized, registers the WatchStream and its network state
  14153. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14154. * already available.
  14155. *
  14156. * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
  14157. * This is not done on Web to allow it to be tree-shaken.
  14158. */ function pc(t) {
  14159. return t.Su || (
  14160. // Create stream (but note that it is not started yet).
  14161. t.Su = function(t, e, n) {
  14162. const s = L(t);
  14163. return s.fu(), new qu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);
  14164. }
  14165. /**
  14166. * @license
  14167. * Copyright 2018 Google LLC
  14168. *
  14169. * Licensed under the Apache License, Version 2.0 (the "License");
  14170. * you may not use this file except in compliance with the License.
  14171. * You may obtain a copy of the License at
  14172. *
  14173. * http://www.apache.org/licenses/LICENSE-2.0
  14174. *
  14175. * Unless required by applicable law or agreed to in writing, software
  14176. * distributed under the License is distributed on an "AS IS" BASIS,
  14177. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14178. * See the License for the specific language governing permissions and
  14179. * limitations under the License.
  14180. */ (t.datastore, t.asyncQueue, {
  14181. uo: sc.bind(null, t),
  14182. ao: ic.bind(null, t),
  14183. nu: rc.bind(null, t)
  14184. }), t.Ru.push((async e => {
  14185. e ? (t.Su.Qo(), tc(t) ? Zu(t) : t.bu.set("Unknown" /* OnlineState.Unknown */)) : (await t.Su.stop(),
  14186. nc(t));
  14187. }))), t.Su;
  14188. }
  14189. /**
  14190. * If not yet initialized, registers the WriteStream and its network state
  14191. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14192. * already available.
  14193. *
  14194. * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
  14195. * This is not done on Web to allow it to be tree-shaken.
  14196. */ function Ic(t) {
  14197. return t.Du || (
  14198. // Create stream (but note that it is not started yet).
  14199. t.Du = function(t, e, n) {
  14200. const s = L(t);
  14201. return s.fu(), new Uu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);
  14202. }(t.datastore, t.asyncQueue, {
  14203. uo: dc.bind(null, t),
  14204. ao: mc.bind(null, t),
  14205. au: wc.bind(null, t),
  14206. cu: _c.bind(null, t)
  14207. }), t.Ru.push((async e => {
  14208. e ? (t.Du.Qo(),
  14209. // This will start the write stream if necessary.
  14210. await cc(t)) : (await t.Du.stop(), t.Eu.length > 0 && (N("RemoteStore", `Stopping write stream with ${t.Eu.length} pending writes`),
  14211. t.Eu = []));
  14212. }))), t.Du;
  14213. }
  14214. /**
  14215. * @license
  14216. * Copyright 2017 Google LLC
  14217. *
  14218. * Licensed under the Apache License, Version 2.0 (the "License");
  14219. * you may not use this file except in compliance with the License.
  14220. * You may obtain a copy of the License at
  14221. *
  14222. * http://www.apache.org/licenses/LICENSE-2.0
  14223. *
  14224. * Unless required by applicable law or agreed to in writing, software
  14225. * distributed under the License is distributed on an "AS IS" BASIS,
  14226. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14227. * See the License for the specific language governing permissions and
  14228. * limitations under the License.
  14229. */
  14230. /**
  14231. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  14232. *
  14233. * It is created via DelayedOperation.createAndSchedule().
  14234. *
  14235. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  14236. *
  14237. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  14238. * in newer versions of TypeScript defines `finally`, which is not available in
  14239. * IE.
  14240. */
  14241. class Tc {
  14242. constructor(t, e, n, s, i) {
  14243. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i,
  14244. this.deferred = new K, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  14245. // It's normal for the deferred promise to be canceled (due to cancellation)
  14246. // and so we attach a dummy catch callback to avoid
  14247. // 'UnhandledPromiseRejectionWarning' log spam.
  14248. this.deferred.promise.catch((t => {}));
  14249. }
  14250. /**
  14251. * Creates and returns a DelayedOperation that has been scheduled to be
  14252. * executed on the provided asyncQueue after the provided delayMs.
  14253. *
  14254. * @param asyncQueue - The queue to schedule the operation on.
  14255. * @param id - A Timer ID identifying the type of operation this is.
  14256. * @param delayMs - The delay (ms) before the operation should be scheduled.
  14257. * @param op - The operation to run.
  14258. * @param removalCallback - A callback to be called synchronously once the
  14259. * operation is executed or canceled, notifying the AsyncQueue to remove it
  14260. * from its delayedOperations list.
  14261. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  14262. * the DelayedOperation class public.
  14263. */ static createAndSchedule(t, e, n, s, i) {
  14264. const r = Date.now() + n, o = new Tc(t, e, r, s, i);
  14265. return o.start(n), o;
  14266. }
  14267. /**
  14268. * Starts the timer. This is called immediately after construction by
  14269. * createAndSchedule().
  14270. */ start(t) {
  14271. this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);
  14272. }
  14273. /**
  14274. * Queues the operation to run immediately (if it hasn't already been run or
  14275. * canceled).
  14276. */ skipDelay() {
  14277. return this.handleDelayElapsed();
  14278. }
  14279. /**
  14280. * Cancels the operation if it hasn't already been executed or canceled. The
  14281. * promise will be rejected.
  14282. *
  14283. * As long as the operation has not yet been run, calling cancel() provides a
  14284. * guarantee that the operation will not be run.
  14285. */ cancel(t) {
  14286. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new U(q.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
  14287. }
  14288. handleDelayElapsed() {
  14289. this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(),
  14290. this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));
  14291. }
  14292. clearTimeout() {
  14293. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  14294. this.timerHandle = null);
  14295. }
  14296. }
  14297. /**
  14298. * Returns a FirestoreError that can be surfaced to the user if the provided
  14299. * error is an IndexedDbTransactionError. Re-throws the error otherwise.
  14300. */ function Ec(t, e) {
  14301. if (k("AsyncQueue", `${e}: ${t}`), Dt(t)) return new U(q.UNAVAILABLE, `${e}: ${t}`);
  14302. throw t;
  14303. }
  14304. /**
  14305. * @license
  14306. * Copyright 2017 Google LLC
  14307. *
  14308. * Licensed under the Apache License, Version 2.0 (the "License");
  14309. * you may not use this file except in compliance with the License.
  14310. * You may obtain a copy of the License at
  14311. *
  14312. * http://www.apache.org/licenses/LICENSE-2.0
  14313. *
  14314. * Unless required by applicable law or agreed to in writing, software
  14315. * distributed under the License is distributed on an "AS IS" BASIS,
  14316. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14317. * See the License for the specific language governing permissions and
  14318. * limitations under the License.
  14319. */
  14320. /**
  14321. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  14322. * in order specified by the provided comparator. We always add a document key
  14323. * comparator on top of what is provided to guarantee document equality based on
  14324. * the key.
  14325. */ class Ac {
  14326. /** The default ordering is by key if the comparator is omitted */
  14327. constructor(t) {
  14328. // We are adding document key comparator to the end as it's the only
  14329. // guaranteed unique property of a document.
  14330. this.comparator = t ? (e, n) => t(e, n) || ht.comparator(e.key, n.key) : (t, e) => ht.comparator(t.key, e.key),
  14331. this.keyedMap = hs(), this.sortedSet = new pe(this.comparator);
  14332. }
  14333. /**
  14334. * Returns an empty copy of the existing DocumentSet, using the same
  14335. * comparator.
  14336. */ static emptySet(t) {
  14337. return new Ac(t.comparator);
  14338. }
  14339. has(t) {
  14340. return null != this.keyedMap.get(t);
  14341. }
  14342. get(t) {
  14343. return this.keyedMap.get(t);
  14344. }
  14345. first() {
  14346. return this.sortedSet.minKey();
  14347. }
  14348. last() {
  14349. return this.sortedSet.maxKey();
  14350. }
  14351. isEmpty() {
  14352. return this.sortedSet.isEmpty();
  14353. }
  14354. /**
  14355. * Returns the index of the provided key in the document set, or -1 if the
  14356. * document key is not present in the set;
  14357. */ indexOf(t) {
  14358. const e = this.keyedMap.get(t);
  14359. return e ? this.sortedSet.indexOf(e) : -1;
  14360. }
  14361. get size() {
  14362. return this.sortedSet.size;
  14363. }
  14364. /** Iterates documents in order defined by "comparator" */ forEach(t) {
  14365. this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));
  14366. }
  14367. /** Inserts or updates a document with the same key */ add(t) {
  14368. // First remove the element if we have it.
  14369. const e = this.delete(t.key);
  14370. return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
  14371. }
  14372. /** Deletes a document with a given key */ delete(t) {
  14373. const e = this.get(t);
  14374. return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
  14375. }
  14376. isEqual(t) {
  14377. if (!(t instanceof Ac)) return !1;
  14378. if (this.size !== t.size) return !1;
  14379. const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();
  14380. for (;e.hasNext(); ) {
  14381. const t = e.getNext().key, s = n.getNext().key;
  14382. if (!t.isEqual(s)) return !1;
  14383. }
  14384. return !0;
  14385. }
  14386. toString() {
  14387. const t = [];
  14388. return this.forEach((e => {
  14389. t.push(e.toString());
  14390. })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
  14391. }
  14392. copy(t, e) {
  14393. const n = new Ac;
  14394. return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;
  14395. }
  14396. }
  14397. /**
  14398. * @license
  14399. * Copyright 2017 Google LLC
  14400. *
  14401. * Licensed under the Apache License, Version 2.0 (the "License");
  14402. * you may not use this file except in compliance with the License.
  14403. * You may obtain a copy of the License at
  14404. *
  14405. * http://www.apache.org/licenses/LICENSE-2.0
  14406. *
  14407. * Unless required by applicable law or agreed to in writing, software
  14408. * distributed under the License is distributed on an "AS IS" BASIS,
  14409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14410. * See the License for the specific language governing permissions and
  14411. * limitations under the License.
  14412. */
  14413. /**
  14414. * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
  14415. * duplicate events for the same doc.
  14416. */ class vc {
  14417. constructor() {
  14418. this.Cu = new pe(ht.comparator);
  14419. }
  14420. track(t) {
  14421. const e = t.doc.key, n = this.Cu.get(e);
  14422. n ?
  14423. // Merge the new change with the existing change.
  14424. 0 /* ChangeType.Added */ !== t.type && 3 /* ChangeType.Metadata */ === n.type ? this.Cu = this.Cu.insert(e, t) : 3 /* ChangeType.Metadata */ === t.type && 1 /* ChangeType.Removed */ !== n.type ? this.Cu = this.Cu.insert(e, {
  14425. type: n.type,
  14426. doc: t.doc
  14427. }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {
  14428. type: 2 /* ChangeType.Modified */ ,
  14429. doc: t.doc
  14430. }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.insert(e, {
  14431. type: 0 /* ChangeType.Added */ ,
  14432. doc: t.doc
  14433. }) : 1 /* ChangeType.Removed */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.remove(e) : 1 /* ChangeType.Removed */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {
  14434. type: 1 /* ChangeType.Removed */ ,
  14435. doc: n.doc
  14436. }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Cu = this.Cu.insert(e, {
  14437. type: 2 /* ChangeType.Modified */ ,
  14438. doc: t.doc
  14439. }) :
  14440. // This includes these cases, which don't make sense:
  14441. // Added->Added
  14442. // Removed->Removed
  14443. // Modified->Added
  14444. // Removed->Modified
  14445. // Metadata->Added
  14446. // Removed->Metadata
  14447. O() : this.Cu = this.Cu.insert(e, t);
  14448. }
  14449. xu() {
  14450. const t = [];
  14451. return this.Cu.inorderTraversal(((e, n) => {
  14452. t.push(n);
  14453. })), t;
  14454. }
  14455. }
  14456. class Rc {
  14457. constructor(t, e, n, s, i, r, o, u, c) {
  14458. this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i,
  14459. this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u,
  14460. this.hasCachedResults = c;
  14461. }
  14462. /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {
  14463. const r = [];
  14464. return e.forEach((t => {
  14465. r.push({
  14466. type: 0 /* ChangeType.Added */ ,
  14467. doc: t
  14468. });
  14469. })), new Rc(t, e, Ac.emptySet(e), r, n, s,
  14470. /* syncStateChanged= */ !0,
  14471. /* excludesMetadataChanges= */ !1, i);
  14472. }
  14473. get hasPendingWrites() {
  14474. return !this.mutatedKeys.isEmpty();
  14475. }
  14476. isEqual(t) {
  14477. if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && Zn(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
  14478. const e = this.docChanges, n = t.docChanges;
  14479. if (e.length !== n.length) return !1;
  14480. for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;
  14481. return !0;
  14482. }
  14483. }
  14484. /**
  14485. * @license
  14486. * Copyright 2017 Google LLC
  14487. *
  14488. * Licensed under the Apache License, Version 2.0 (the "License");
  14489. * you may not use this file except in compliance with the License.
  14490. * You may obtain a copy of the License at
  14491. *
  14492. * http://www.apache.org/licenses/LICENSE-2.0
  14493. *
  14494. * Unless required by applicable law or agreed to in writing, software
  14495. * distributed under the License is distributed on an "AS IS" BASIS,
  14496. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14497. * See the License for the specific language governing permissions and
  14498. * limitations under the License.
  14499. */
  14500. /**
  14501. * Holds the listeners and the last received ViewSnapshot for a query being
  14502. * tracked by EventManager.
  14503. */ class Pc {
  14504. constructor() {
  14505. this.Nu = void 0, this.listeners = [];
  14506. }
  14507. }
  14508. class bc {
  14509. constructor() {
  14510. this.queries = new os((t => ts(t)), Zn), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14511. this.ku = new Set;
  14512. }
  14513. }
  14514. async function Vc(t, e) {
  14515. const n = L(t), s = e.query;
  14516. let i = !1, r = n.queries.get(s);
  14517. if (r || (i = !0, r = new Pc), i) try {
  14518. r.Nu = await n.onListen(s);
  14519. } catch (t) {
  14520. const n = Ec(t, `Initialization of query '${es(e.query)}' failed`);
  14521. return void e.onError(n);
  14522. }
  14523. if (n.queries.set(s, r), r.listeners.push(e),
  14524. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14525. e.Mu(n.onlineState), r.Nu) {
  14526. e.$u(r.Nu) && xc(n);
  14527. }
  14528. }
  14529. async function Sc(t, e) {
  14530. const n = L(t), s = e.query;
  14531. let i = !1;
  14532. const r = n.queries.get(s);
  14533. if (r) {
  14534. const t = r.listeners.indexOf(e);
  14535. t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);
  14536. }
  14537. if (i) return n.queries.delete(s), n.onUnlisten(s);
  14538. }
  14539. function Dc(t, e) {
  14540. const n = L(t);
  14541. let s = !1;
  14542. for (const t of e) {
  14543. const e = t.query, i = n.queries.get(e);
  14544. if (i) {
  14545. for (const e of i.listeners) e.$u(t) && (s = !0);
  14546. i.Nu = t;
  14547. }
  14548. }
  14549. s && xc(n);
  14550. }
  14551. function Cc(t, e, n) {
  14552. const s = L(t), i = s.queries.get(e);
  14553. if (i) for (const t of i.listeners) t.onError(n);
  14554. // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
  14555. // after an error.
  14556. s.queries.delete(e);
  14557. }
  14558. // Call all global snapshot listeners that have been set.
  14559. function xc(t) {
  14560. t.ku.forEach((t => {
  14561. t.next();
  14562. }));
  14563. }
  14564. /**
  14565. * QueryListener takes a series of internal view snapshots and determines
  14566. * when to raise the event.
  14567. *
  14568. * It uses an Observer to dispatch events.
  14569. */ class Nc {
  14570. constructor(t, e, n) {
  14571. this.query = t, this.Ou = e,
  14572. /**
  14573. * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
  14574. * observer. This flag is set to true once we've actually raised an event.
  14575. */
  14576. this.Fu = !1, this.Bu = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14577. this.options = n || {};
  14578. }
  14579. /**
  14580. * Applies the new ViewSnapshot to this listener, raising a user-facing event
  14581. * if applicable (depending on what changed, whether the user has opted into
  14582. * metadata-only changes, etc.). Returns true if a user-facing event was
  14583. * indeed raised.
  14584. */ $u(t) {
  14585. if (!this.options.includeMetadataChanges) {
  14586. // Remove the metadata only changes.
  14587. const e = [];
  14588. for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);
  14589. t = new Rc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged,
  14590. /* excludesMetadataChanges= */ !0, t.hasCachedResults);
  14591. }
  14592. let e = !1;
  14593. return this.Fu ? this.Lu(t) && (this.Ou.next(t), e = !0) : this.qu(t, this.onlineState) && (this.Uu(t),
  14594. e = !0), this.Bu = t, e;
  14595. }
  14596. onError(t) {
  14597. this.Ou.error(t);
  14598. }
  14599. /** Returns whether a snapshot was raised. */ Mu(t) {
  14600. this.onlineState = t;
  14601. let e = !1;
  14602. return this.Bu && !this.Fu && this.qu(this.Bu, t) && (this.Uu(this.Bu), e = !0),
  14603. e;
  14604. }
  14605. qu(t, e) {
  14606. // Always raise the first event when we're synced
  14607. if (!t.fromCache) return !0;
  14608. // NOTE: We consider OnlineState.Unknown as online (it should become Offline
  14609. // or Online if we wait long enough).
  14610. const n = "Offline" /* OnlineState.Offline */ !== e;
  14611. // Don't raise the event if we're online, aren't synced yet (checked
  14612. // above) and are waiting for a sync.
  14613. return (!this.options.Ku || !n) && (!t.docs.isEmpty() || t.hasCachedResults || "Offline" /* OnlineState.Offline */ === e);
  14614. // Raise data from cache if we have any documents, have cached results before,
  14615. // or we are offline.
  14616. }
  14617. Lu(t) {
  14618. // We don't need to handle includeDocumentMetadataChanges here because
  14619. // the Metadata only changes have already been stripped out if needed.
  14620. // At this point the only changes we will see are the ones we should
  14621. // propagate.
  14622. if (t.docChanges.length > 0) return !0;
  14623. const e = this.Bu && this.Bu.hasPendingWrites !== t.hasPendingWrites;
  14624. return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
  14625. // Generally we should have hit one of the cases above, but it's possible
  14626. // to get here if there were only metadata docChanges and they got
  14627. // stripped out.
  14628. }
  14629. Uu(t) {
  14630. t = Rc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults),
  14631. this.Fu = !0, this.Ou.next(t);
  14632. }
  14633. }
  14634. /**
  14635. * @license
  14636. * Copyright 2020 Google LLC
  14637. *
  14638. * Licensed under the Apache License, Version 2.0 (the "License");
  14639. * you may not use this file except in compliance with the License.
  14640. * You may obtain a copy of the License at
  14641. *
  14642. * http://www.apache.org/licenses/LICENSE-2.0
  14643. *
  14644. * Unless required by applicable law or agreed to in writing, software
  14645. * distributed under the License is distributed on an "AS IS" BASIS,
  14646. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14647. * See the License for the specific language governing permissions and
  14648. * limitations under the License.
  14649. */
  14650. /**
  14651. * A complete element in the bundle stream, together with the byte length it
  14652. * occupies in the stream.
  14653. */ class kc {
  14654. constructor(t,
  14655. // How many bytes this element takes to store in the bundle.
  14656. e) {
  14657. this.Gu = t, this.byteLength = e;
  14658. }
  14659. Qu() {
  14660. return "metadata" in this.Gu;
  14661. }
  14662. }
  14663. /**
  14664. * @license
  14665. * Copyright 2020 Google LLC
  14666. *
  14667. * Licensed under the Apache License, Version 2.0 (the "License");
  14668. * you may not use this file except in compliance with the License.
  14669. * You may obtain a copy of the License at
  14670. *
  14671. * http://www.apache.org/licenses/LICENSE-2.0
  14672. *
  14673. * Unless required by applicable law or agreed to in writing, software
  14674. * distributed under the License is distributed on an "AS IS" BASIS,
  14675. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14676. * See the License for the specific language governing permissions and
  14677. * limitations under the License.
  14678. */
  14679. /**
  14680. * Helper to convert objects from bundles to model objects in the SDK.
  14681. */ class Mc {
  14682. constructor(t) {
  14683. this.serializer = t;
  14684. }
  14685. rr(t) {
  14686. return Oi(this.serializer, t);
  14687. }
  14688. /**
  14689. * Converts a BundleDocument to a MutableDocument.
  14690. */ ur(t) {
  14691. return t.metadata.exists ? Ki(this.serializer, t.document, !1) : an.newNoDocument(this.rr(t.metadata.name), this.cr(t.metadata.readTime));
  14692. }
  14693. cr(t) {
  14694. return Ni(t);
  14695. }
  14696. }
  14697. /**
  14698. * A class to process the elements from a bundle, load them into local
  14699. * storage and provide progress update while loading.
  14700. */ class $c {
  14701. constructor(t, e, n) {
  14702. this.ju = t, this.localStore = e, this.serializer = n,
  14703. /** Batched queries to be saved into storage */
  14704. this.queries = [],
  14705. /** Batched documents to be saved into storage */
  14706. this.documents = [],
  14707. /** The collection groups affected by this bundle. */
  14708. this.collectionGroups = new Set, this.progress = Oc(t);
  14709. }
  14710. /**
  14711. * Adds an element from the bundle to the loader.
  14712. *
  14713. * Returns a new progress if adding the element leads to a new progress,
  14714. * otherwise returns null.
  14715. */ zu(t) {
  14716. this.progress.bytesLoaded += t.byteLength;
  14717. let e = this.progress.documentsLoaded;
  14718. if (t.Gu.namedQuery) this.queries.push(t.Gu.namedQuery); else if (t.Gu.documentMetadata) {
  14719. this.documents.push({
  14720. metadata: t.Gu.documentMetadata
  14721. }), t.Gu.documentMetadata.exists || ++e;
  14722. const n = ut.fromString(t.Gu.documentMetadata.name);
  14723. this.collectionGroups.add(n.get(n.length - 2));
  14724. } else t.Gu.document && (this.documents[this.documents.length - 1].document = t.Gu.document,
  14725. ++e);
  14726. return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e,
  14727. Object.assign({}, this.progress)) : null;
  14728. }
  14729. Wu(t) {
  14730. const e = new Map, n = new Mc(this.serializer);
  14731. for (const s of t) if (s.metadata.queries) {
  14732. const t = n.rr(s.metadata.name);
  14733. for (const n of s.metadata.queries) {
  14734. const s = (e.get(n) || gs()).add(t);
  14735. e.set(n, s);
  14736. }
  14737. }
  14738. return e;
  14739. }
  14740. /**
  14741. * Update the progress to 'Success' and return the updated progress.
  14742. */ async complete() {
  14743. const t = await mu(this.localStore, new Mc(this.serializer), this.documents, this.ju.id), e = this.Wu(this.documents);
  14744. for (const t of this.queries) await gu(this.localStore, t, e.get(t.name));
  14745. return this.progress.taskState = "Success", {
  14746. progress: this.progress,
  14747. Hu: this.collectionGroups,
  14748. Ju: t
  14749. };
  14750. }
  14751. }
  14752. /**
  14753. * Returns a `LoadBundleTaskProgress` representing the initial progress of
  14754. * loading a bundle.
  14755. */ function Oc(t) {
  14756. return {
  14757. taskState: "Running",
  14758. documentsLoaded: 0,
  14759. bytesLoaded: 0,
  14760. totalDocuments: t.totalDocuments,
  14761. totalBytes: t.totalBytes
  14762. };
  14763. }
  14764. /**
  14765. * Returns a `LoadBundleTaskProgress` representing the progress that the loading
  14766. * has succeeded.
  14767. */
  14768. /**
  14769. * @license
  14770. * Copyright 2017 Google LLC
  14771. *
  14772. * Licensed under the Apache License, Version 2.0 (the "License");
  14773. * you may not use this file except in compliance with the License.
  14774. * You may obtain a copy of the License at
  14775. *
  14776. * http://www.apache.org/licenses/LICENSE-2.0
  14777. *
  14778. * Unless required by applicable law or agreed to in writing, software
  14779. * distributed under the License is distributed on an "AS IS" BASIS,
  14780. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14781. * See the License for the specific language governing permissions and
  14782. * limitations under the License.
  14783. */
  14784. class Fc {
  14785. constructor(t) {
  14786. this.key = t;
  14787. }
  14788. }
  14789. class Bc {
  14790. constructor(t) {
  14791. this.key = t;
  14792. }
  14793. }
  14794. /**
  14795. * View is responsible for computing the final merged truth of what docs are in
  14796. * a query. It gets notified of local and remote changes to docs, and applies
  14797. * the query filters and limits to determine the most correct possible results.
  14798. */ class Lc {
  14799. constructor(t,
  14800. /** Documents included in the remote target */
  14801. e) {
  14802. this.query = t, this.Yu = e, this.Xu = null, this.hasCachedResults = !1,
  14803. /**
  14804. * A flag whether the view is current with the backend. A view is considered
  14805. * current after it has seen the current flag from the backend and did not
  14806. * lose consistency within the watch stream (e.g. because of an existence
  14807. * filter mismatch).
  14808. */
  14809. this.current = !1,
  14810. /** Documents in the view but not in the remote target */
  14811. this.Zu = gs(),
  14812. /** Document Keys that have local changes */
  14813. this.mutatedKeys = gs(), this.tc = is(t), this.ec = new Ac(this.tc);
  14814. }
  14815. /**
  14816. * The set of remote documents that the server has told us belongs to the target associated with
  14817. * this view.
  14818. */ get nc() {
  14819. return this.Yu;
  14820. }
  14821. /**
  14822. * Iterates over a set of doc changes, applies the query limit, and computes
  14823. * what the new results should be, what the changes were, and whether we may
  14824. * need to go back to the local cache for more results. Does not make any
  14825. * changes to the view.
  14826. * @param docChanges - The doc changes to apply to this view.
  14827. * @param previousChanges - If this is being called with a refill, then start
  14828. * with this set of docs and changes instead of the current view.
  14829. * @returns a new set of docs, changes, and refill flag.
  14830. */ sc(t, e) {
  14831. const n = e ? e.ic : new vc, s = e ? e.ec : this.ec;
  14832. let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;
  14833. // Track the last doc in a (full) limit. This is necessary, because some
  14834. // update (a delete, or an update moving a doc past the old limit) might
  14835. // mean there is some other document in the local cache that either should
  14836. // come (1) between the old last limit doc and the new last document, in the
  14837. // case of updates, or (2) after the new last document, in the case of
  14838. // deletes. So we keep this doc at the old limit to compare the updates to.
  14839. // Note that this should never get used in a refill (when previousChanges is
  14840. // set), because there will only be adds -- no deletes or updates.
  14841. const u = "F" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = "L" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;
  14842. // Drop documents out to meet limit/limitToLast requirement.
  14843. if (t.inorderTraversal(((t, e) => {
  14844. const a = s.get(t), h = ns(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations ||
  14845. // We only consider committed mutations for documents that were
  14846. // mutated during the lifetime of the view.
  14847. this.mutatedKeys.has(h.key) && h.hasCommittedMutations);
  14848. let d = !1;
  14849. // Calculate change
  14850. if (a && h) {
  14851. a.data.isEqual(h.data) ? l !== f && (n.track({
  14852. type: 3 /* ChangeType.Metadata */ ,
  14853. doc: h
  14854. }), d = !0) : this.rc(a, h) || (n.track({
  14855. type: 2 /* ChangeType.Modified */ ,
  14856. doc: h
  14857. }), d = !0, (u && this.tc(h, u) > 0 || c && this.tc(h, c) < 0) && (
  14858. // This doc moved from inside the limit to outside the limit.
  14859. // That means there may be some other doc in the local cache
  14860. // that should be included instead.
  14861. o = !0));
  14862. } else !a && h ? (n.track({
  14863. type: 0 /* ChangeType.Added */ ,
  14864. doc: h
  14865. }), d = !0) : a && !h && (n.track({
  14866. type: 1 /* ChangeType.Removed */ ,
  14867. doc: a
  14868. }), d = !0, (u || c) && (
  14869. // A doc was removed from a full limit query. We'll need to
  14870. // requery from the local cache to see if we know about some other
  14871. // doc that should be in the results.
  14872. o = !0));
  14873. d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));
  14874. })), null !== this.query.limit) for (;r.size > this.query.limit; ) {
  14875. const t = "F" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();
  14876. r = r.delete(t.key), i = i.delete(t.key), n.track({
  14877. type: 1 /* ChangeType.Removed */ ,
  14878. doc: t
  14879. });
  14880. }
  14881. return {
  14882. ec: r,
  14883. ic: n,
  14884. zi: o,
  14885. mutatedKeys: i
  14886. };
  14887. }
  14888. rc(t, e) {
  14889. // We suppress the initial change event for documents that were modified as
  14890. // part of a write acknowledgment (e.g. when the value of a server transform
  14891. // is applied) as Watch will send us the same document again.
  14892. // By suppressing the event, we only raise two user visible events (one with
  14893. // `hasPendingWrites` and the final state of the document) instead of three
  14894. // (one with `hasPendingWrites`, the modified document with
  14895. // `hasPendingWrites` and the final state of the document).
  14896. return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
  14897. }
  14898. /**
  14899. * Updates the view with the given ViewDocumentChanges and optionally updates
  14900. * limbo docs and sync state from the provided target change.
  14901. * @param docChanges - The set of changes to make to the view's docs.
  14902. * @param updateLimboDocuments - Whether to update limbo documents based on
  14903. * this change.
  14904. * @param targetChange - A target change to apply for computing limbo docs and
  14905. * sync state.
  14906. * @returns A new ViewChange with the given docs, changes, and sync state.
  14907. */
  14908. // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  14909. applyChanges(t, e, n) {
  14910. const s = this.ec;
  14911. this.ec = t.ec, this.mutatedKeys = t.mutatedKeys;
  14912. // Sort changes based on type and query comparator
  14913. const i = t.ic.xu();
  14914. i.sort(((t, e) => function(t, e) {
  14915. const n = t => {
  14916. switch (t) {
  14917. case 0 /* ChangeType.Added */ :
  14918. return 1;
  14919. case 2 /* ChangeType.Modified */ :
  14920. case 3 /* ChangeType.Metadata */ :
  14921. // A metadata change is converted to a modified change at the public
  14922. // api layer. Since we sort by document key and then change type,
  14923. // metadata and modified changes must be sorted equivalently.
  14924. return 2;
  14925. case 1 /* ChangeType.Removed */ :
  14926. return 0;
  14927. default:
  14928. return O();
  14929. }
  14930. };
  14931. return n(t) - n(e);
  14932. }
  14933. /**
  14934. * @license
  14935. * Copyright 2020 Google LLC
  14936. *
  14937. * Licensed under the Apache License, Version 2.0 (the "License");
  14938. * you may not use this file except in compliance with the License.
  14939. * You may obtain a copy of the License at
  14940. *
  14941. * http://www.apache.org/licenses/LICENSE-2.0
  14942. *
  14943. * Unless required by applicable law or agreed to in writing, software
  14944. * distributed under the License is distributed on an "AS IS" BASIS,
  14945. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14946. * See the License for the specific language governing permissions and
  14947. * limitations under the License.
  14948. */ (t.type, e.type) || this.tc(t.doc, e.doc))), this.oc(n);
  14949. const r = e ? this.uc() : [], o = 0 === this.Zu.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Xu;
  14950. if (this.Xu = o, 0 !== i.length || u) {
  14951. return {
  14952. snapshot: new Rc(this.query, t.ec, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u,
  14953. /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),
  14954. cc: r
  14955. };
  14956. }
  14957. // no changes
  14958. return {
  14959. cc: r
  14960. };
  14961. }
  14962. /**
  14963. * Applies an OnlineState change to the view, potentially generating a
  14964. * ViewChange if the view's syncState changes as a result.
  14965. */ Mu(t) {
  14966. return this.current && "Offline" /* OnlineState.Offline */ === t ? (
  14967. // If we're offline, set `current` to false and then call applyChanges()
  14968. // to refresh our syncState and generate a ViewChange as appropriate. We
  14969. // are guaranteed to get a new TargetChange that sets `current` back to
  14970. // true once the client is back online.
  14971. this.current = !1, this.applyChanges({
  14972. ec: this.ec,
  14973. ic: new vc,
  14974. mutatedKeys: this.mutatedKeys,
  14975. zi: !1
  14976. },
  14977. /* updateLimboDocuments= */ !1)) : {
  14978. cc: []
  14979. };
  14980. }
  14981. /**
  14982. * Returns whether the doc for the given key should be in limbo.
  14983. */ ac(t) {
  14984. // If the remote end says it's part of this query, it's not in limbo.
  14985. return !this.Yu.has(t) && (
  14986. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  14987. !!this.ec.has(t) && !this.ec.get(t).hasLocalMutations);
  14988. }
  14989. /**
  14990. * Updates syncedDocuments, current, and limbo docs based on the given change.
  14991. * Returns the list of changes to which docs are in limbo.
  14992. */ oc(t) {
  14993. t && (t.addedDocuments.forEach((t => this.Yu = this.Yu.add(t))), t.modifiedDocuments.forEach((t => {})),
  14994. t.removedDocuments.forEach((t => this.Yu = this.Yu.delete(t))), this.current = t.current);
  14995. }
  14996. uc() {
  14997. // We can only determine limbo documents when we're in-sync with the server.
  14998. if (!this.current) return [];
  14999. // TODO(klimt): Do this incrementally so that it's not quadratic when
  15000. // updating many documents.
  15001. const t = this.Zu;
  15002. this.Zu = gs(), this.ec.forEach((t => {
  15003. this.ac(t.key) && (this.Zu = this.Zu.add(t.key));
  15004. }));
  15005. // Diff the new limbo docs with the old limbo docs.
  15006. const e = [];
  15007. return t.forEach((t => {
  15008. this.Zu.has(t) || e.push(new Bc(t));
  15009. })), this.Zu.forEach((n => {
  15010. t.has(n) || e.push(new Fc(n));
  15011. })), e;
  15012. }
  15013. /**
  15014. * Update the in-memory state of the current view with the state read from
  15015. * persistence.
  15016. *
  15017. * We update the query view whenever a client's primary status changes:
  15018. * - When a client transitions from primary to secondary, it can miss
  15019. * LocalStorage updates and its query views may temporarily not be
  15020. * synchronized with the state on disk.
  15021. * - For secondary to primary transitions, the client needs to update the list
  15022. * of `syncedDocuments` since secondary clients update their query views
  15023. * based purely on synthesized RemoteEvents.
  15024. *
  15025. * @param queryResult.documents - The documents that match the query according
  15026. * to the LocalStore.
  15027. * @param queryResult.remoteKeys - The keys of the documents that match the
  15028. * query according to the backend.
  15029. *
  15030. * @returns The ViewChange that resulted from this synchronization.
  15031. */
  15032. // PORTING NOTE: Multi-tab only.
  15033. hc(t) {
  15034. this.Yu = t.ir, this.Zu = gs();
  15035. const e = this.sc(t.documents);
  15036. return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
  15037. }
  15038. /**
  15039. * Returns a view snapshot as if this query was just listened to. Contains
  15040. * a document add for every existing document and the `fromCache` and
  15041. * `hasPendingWrites` status of the already established view.
  15042. */
  15043. // PORTING NOTE: Multi-tab only.
  15044. lc() {
  15045. return Rc.fromInitialDocuments(this.query, this.ec, this.mutatedKeys, 0 /* SyncState.Local */ === this.Xu, this.hasCachedResults);
  15046. }
  15047. }
  15048. /**
  15049. * QueryView contains all of the data that SyncEngine needs to keep track of for
  15050. * a particular query.
  15051. */
  15052. class qc {
  15053. constructor(
  15054. /**
  15055. * The query itself.
  15056. */
  15057. t,
  15058. /**
  15059. * The target number created by the client that is used in the watch
  15060. * stream to identify this query.
  15061. */
  15062. e,
  15063. /**
  15064. * The view is responsible for computing the final merged truth of what
  15065. * docs are in the query. It gets notified of local and remote changes,
  15066. * and applies the query filters and limits to determine the most correct
  15067. * possible results.
  15068. */
  15069. n) {
  15070. this.query = t, this.targetId = e, this.view = n;
  15071. }
  15072. }
  15073. /** Tracks a limbo resolution. */ class Uc {
  15074. constructor(t) {
  15075. this.key = t,
  15076. /**
  15077. * Set to true once we've received a document. This is used in
  15078. * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
  15079. * decide whether it needs to manufacture a delete event for the target once
  15080. * the target is CURRENT.
  15081. */
  15082. this.fc = !1;
  15083. }
  15084. }
  15085. /**
  15086. * An implementation of `SyncEngine` coordinating with other parts of SDK.
  15087. *
  15088. * The parts of SyncEngine that act as a callback to RemoteStore need to be
  15089. * registered individually. This is done in `syncEngineWrite()` and
  15090. * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
  15091. * serve as entry points to RemoteStore's functionality.
  15092. *
  15093. * Note: some field defined in this class might have public access level, but
  15094. * the class is not exported so they are only accessible from this module.
  15095. * This is useful to implement optional features (like bundles) in free
  15096. * functions, such that they are tree-shakeable.
  15097. */ class Kc {
  15098. constructor(t, e, n,
  15099. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15100. s, i, r) {
  15101. this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s,
  15102. this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.dc = {}, this.wc = new os((t => ts(t)), Zn),
  15103. this._c = new Map,
  15104. /**
  15105. * The keys of documents that are in limbo for which we haven't yet started a
  15106. * limbo resolution query. The strings in this set are the result of calling
  15107. * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
  15108. *
  15109. * The `Set` type was chosen because it provides efficient lookup and removal
  15110. * of arbitrary elements and it also maintains insertion order, providing the
  15111. * desired queue-like FIFO semantics.
  15112. */
  15113. this.mc = new Set,
  15114. /**
  15115. * Keeps track of the target ID for each document that is in limbo with an
  15116. * active target.
  15117. */
  15118. this.gc = new pe(ht.comparator),
  15119. /**
  15120. * Keeps track of the information about an active limbo resolution for each
  15121. * active target ID that was started for the purpose of limbo resolution.
  15122. */
  15123. this.yc = new Map, this.Ic = new Oo,
  15124. /** Stores user completion handlers, indexed by User and BatchId. */
  15125. this.Tc = {},
  15126. /** Stores user callbacks waiting for all pending writes to be acknowledged. */
  15127. this.Ec = new Map, this.Ac = lo.Mn(), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  15128. // The primary state is set to `true` or `false` immediately after Firestore
  15129. // startup. In the interim, a client should only be considered primary if
  15130. // `isPrimary` is true.
  15131. this.vc = void 0;
  15132. }
  15133. get isPrimaryClient() {
  15134. return !0 === this.vc;
  15135. }
  15136. }
  15137. /**
  15138. * Initiates the new listen, resolves promise when listen enqueued to the
  15139. * server. All the subsequent view snapshots or errors are sent to the
  15140. * subscribed handlers. Returns the initial snapshot.
  15141. */
  15142. async function Gc(t, e) {
  15143. const n = pa(t);
  15144. let s, i;
  15145. const r = n.wc.get(e);
  15146. if (r)
  15147. // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
  15148. // already exists when EventManager calls us for the first time. This
  15149. // happens when the primary tab is already listening to this query on
  15150. // behalf of another tab and the user of the primary also starts listening
  15151. // to the query. EventManager will not have an assigned target ID in this
  15152. // case and calls `listen` to obtain this ID.
  15153. s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.lc(); else {
  15154. const t = await hu(n.localStore, Jn(e)), r = n.sharedClientState.addLocalQueryTarget(t.targetId);
  15155. s = t.targetId, i = await Qc(n, e, s, "current" === r, t.resumeToken), n.isPrimaryClient && Hu(n.remoteStore, t);
  15156. }
  15157. return i;
  15158. }
  15159. /**
  15160. * Registers a view for a previously unknown query and computes its initial
  15161. * snapshot.
  15162. */ async function Qc(t, e, n, s, i) {
  15163. // PORTING NOTE: On Web only, we inject the code that registers new Limbo
  15164. // targets based on view changes. This allows us to only depend on Limbo
  15165. // changes when user code includes queries.
  15166. t.Rc = (e, n, s) => async function(t, e, n, s) {
  15167. let i = e.view.sc(n);
  15168. i.zi && (
  15169. // The query has a limit and some docs were removed, so we need
  15170. // to re-run the query against the local store to make sure we
  15171. // didn't lose any good docs that had been past the limit.
  15172. i = await fu(t.localStore, e.query,
  15173. /* usePreviousResults= */ !1).then((({documents: t}) => e.view.sc(t, i))));
  15174. const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i,
  15175. /* updateLimboDocuments= */ t.isPrimaryClient, r);
  15176. return ia(t, e.targetId, o.cc), o.snapshot;
  15177. }(t, e, n, s);
  15178. const r = await fu(t.localStore, e,
  15179. /* usePreviousResults= */ !0), o = new Lc(e, r.ir), u = o.sc(r.documents), c = gi.createSynthesizedTargetChangeForCurrentChange(n, s && "Offline" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u,
  15180. /* updateLimboDocuments= */ t.isPrimaryClient, c);
  15181. ia(t, n, a.cc);
  15182. const h = new qc(e, n, o);
  15183. return t.wc.set(e, h), t._c.has(n) ? t._c.get(n).push(e) : t._c.set(n, [ e ]), a.snapshot;
  15184. }
  15185. /** Stops listening to the query. */ async function jc(t, e) {
  15186. const n = L(t), s = n.wc.get(e), i = n._c.get(s.targetId);
  15187. if (i.length > 1) return n._c.set(s.targetId, i.filter((t => !Zn(t, e)))), void n.wc.delete(e);
  15188. // No other queries are mapped to the target, clean up the query and the target.
  15189. if (n.isPrimaryClient) {
  15190. // We need to remove the local query target first to allow us to verify
  15191. // whether any other client is still interested in this target.
  15192. n.sharedClientState.removeLocalQueryTarget(s.targetId);
  15193. n.sharedClientState.isActiveQueryTarget(s.targetId) || await lu(n.localStore, s.targetId,
  15194. /*keepPersistedTargetData=*/ !1).then((() => {
  15195. n.sharedClientState.clearQueryState(s.targetId), Ju(n.remoteStore, s.targetId),
  15196. na(n, s.targetId);
  15197. })).catch(vt);
  15198. } else na(n, s.targetId), await lu(n.localStore, s.targetId,
  15199. /*keepPersistedTargetData=*/ !0);
  15200. }
  15201. /**
  15202. * Initiates the write of local mutation batch which involves adding the
  15203. * writes to the mutation queue, notifying the remote store about new
  15204. * mutations and raising events for any changes this write caused.
  15205. *
  15206. * The promise returned by this call is resolved when the above steps
  15207. * have completed, *not* when the write was acked by the backend. The
  15208. * userCallback is resolved once the write was acked/rejected by the
  15209. * backend (or failed locally for any other reason).
  15210. */ async function zc(t, e, n) {
  15211. const s = Ia(t);
  15212. try {
  15213. const t = await function(t, e) {
  15214. const n = L(t), s = it.now(), i = e.reduce(((t, e) => t.add(e.key)), gs());
  15215. let r, o;
  15216. return n.persistence.runTransaction("Locally write mutations", "readwrite", (t => {
  15217. // Figure out which keys do not have a remote version in the cache, this
  15218. // is needed to create the right overlay mutation: if no remote version
  15219. // presents, we do not need to create overlays as patch mutations.
  15220. // TODO(Overlay): Is there a better way to determine this? Using the
  15221. // document version does not work because local mutations set them back
  15222. // to 0.
  15223. let u = cs(), c = gs();
  15224. return n.Zi.getEntries(t, i).next((t => {
  15225. u = t, u.forEach(((t, e) => {
  15226. e.isValidDocument() || (c = c.add(t));
  15227. }));
  15228. })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {
  15229. r = i;
  15230. // For non-idempotent mutations (such as `FieldValue.increment()`),
  15231. // we record the base state in a separate patch mutation. This is
  15232. // later used to guarantee consistent values and prevents flicker
  15233. // even if the backend sends us an update that already includes our
  15234. // transform.
  15235. const o = [];
  15236. for (const t of e) {
  15237. const e = Gs(t, r.get(t.key).overlayedDocument);
  15238. null != e &&
  15239. // NOTE: The base state should only be applied if there's some
  15240. // existing document to override, so use a Precondition of
  15241. // exists=true
  15242. o.push(new zs(t.key, e, cn(e.value.mapValue), Fs.exists(!0)));
  15243. }
  15244. return n.mutationQueue.addMutationBatch(t, s, o, e);
  15245. })).next((e => {
  15246. o = e;
  15247. const s = e.applyToLocalDocumentSet(r, c);
  15248. return n.documentOverlayCache.saveOverlays(t, e.batchId, s);
  15249. }));
  15250. })).then((() => ({
  15251. batchId: o.batchId,
  15252. changes: ls(r)
  15253. })));
  15254. }(s.localStore, e);
  15255. s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {
  15256. let s = t.Tc[t.currentUser.toKey()];
  15257. s || (s = new pe(et));
  15258. s = s.insert(e, n), t.Tc[t.currentUser.toKey()] = s;
  15259. }
  15260. /**
  15261. * Resolves or rejects the user callback for the given batch and then discards
  15262. * it.
  15263. */ (s, t.batchId, n), await ua(s, t.changes), await cc(s.remoteStore);
  15264. } catch (t) {
  15265. // If we can't persist the mutation, we reject the user callback and
  15266. // don't send the mutation. The user can then retry the write.
  15267. const e = Ec(t, "Failed to persist write");
  15268. n.reject(e);
  15269. }
  15270. }
  15271. /**
  15272. * Applies one remote event to the sync engine, notifying any views of the
  15273. * changes, and releasing any pending mutation batches that would become
  15274. * visible because of the snapshot version the remote event contains.
  15275. */ async function Wc(t, e) {
  15276. const n = L(t);
  15277. try {
  15278. const t = await uu(n.localStore, e);
  15279. // Update `receivedDocument` as appropriate for any limbo targets.
  15280. e.targetChanges.forEach(((t, e) => {
  15281. const s = n.yc.get(e);
  15282. s && (
  15283. // Since this is a limbo resolution lookup, it's for a single document
  15284. // and it could be added, modified, or removed, but not a combination.
  15285. F(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1),
  15286. t.addedDocuments.size > 0 ? s.fc = !0 : t.modifiedDocuments.size > 0 ? F(s.fc) : t.removedDocuments.size > 0 && (F(s.fc),
  15287. s.fc = !1));
  15288. })), await ua(n, t, e);
  15289. } catch (t) {
  15290. await vt(t);
  15291. }
  15292. }
  15293. /**
  15294. * Applies an OnlineState change to the sync engine and notifies any views of
  15295. * the change.
  15296. */ function Hc(t, e, n) {
  15297. const s = L(t);
  15298. // If we are the secondary client, we explicitly ignore the remote store's
  15299. // online state (the local client may go offline, even though the primary
  15300. // tab remains online) and only apply the primary tab's online state from
  15301. // SharedClientState.
  15302. if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
  15303. const t = [];
  15304. s.wc.forEach(((n, s) => {
  15305. const i = s.view.Mu(e);
  15306. i.snapshot && t.push(i.snapshot);
  15307. })), function(t, e) {
  15308. const n = L(t);
  15309. n.onlineState = e;
  15310. let s = !1;
  15311. n.queries.forEach(((t, n) => {
  15312. for (const t of n.listeners)
  15313. // Run global snapshot listeners if a consistent snapshot has been emitted.
  15314. t.Mu(e) && (s = !0);
  15315. })), s && xc(n);
  15316. }(s.eventManager, e), t.length && s.dc.nu(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);
  15317. }
  15318. }
  15319. /**
  15320. * Rejects the listen for the given targetID. This can be triggered by the
  15321. * backend for any active target.
  15322. *
  15323. * @param syncEngine - The sync engine implementation.
  15324. * @param targetId - The targetID corresponds to one previously initiated by the
  15325. * user as part of TargetData passed to listen() on RemoteStore.
  15326. * @param err - A description of the condition that has forced the rejection.
  15327. * Nearly always this will be an indication that the user is no longer
  15328. * authorized to see the data matching the target.
  15329. */ async function Jc(t, e, n) {
  15330. const s = L(t);
  15331. // PORTING NOTE: Multi-tab only.
  15332. s.sharedClientState.updateQueryState(e, "rejected", n);
  15333. const i = s.yc.get(e), r = i && i.key;
  15334. if (r) {
  15335. // TODO(klimt): We really only should do the following on permission
  15336. // denied errors, but we don't have the cause code here.
  15337. // It's a limbo doc. Create a synthetic event saying it was deleted.
  15338. // This is kind of a hack. Ideally, we would have a method in the local
  15339. // store to purge a document. However, it would be tricky to keep all of
  15340. // the local store's invariants with another method.
  15341. let t = new pe(ht.comparator);
  15342. // TODO(b/217189216): This limbo document should ideally have a read time,
  15343. // so that it is picked up by any read-time based scans. The backend,
  15344. // however, does not send a read time for target removals.
  15345. t = t.insert(r, an.newNoDocument(r, rt.min()));
  15346. const n = gs().add(r), i = new mi(rt.min(),
  15347. /* targetChanges= */ new Map,
  15348. /* targetMismatches= */ new pe(et), t, n);
  15349. await Wc(s, i),
  15350. // Since this query failed, we won't want to manually unlisten to it.
  15351. // We only remove it from bookkeeping after we successfully applied the
  15352. // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
  15353. // this query when the RemoteStore restarts the Watch stream, which should
  15354. // re-trigger the target failure.
  15355. s.gc = s.gc.remove(r), s.yc.delete(e), oa(s);
  15356. } else await lu(s.localStore, e,
  15357. /* keepPersistedTargetData */ !1).then((() => na(s, e, n))).catch(vt);
  15358. }
  15359. async function Yc(t, e) {
  15360. const n = L(t), s = e.batch.batchId;
  15361. try {
  15362. const t = await ru(n.localStore, e);
  15363. // The local store may or may not be able to apply the write result and
  15364. // raise events immediately (depending on whether the watcher is caught
  15365. // up), so we raise user callbacks first so that they consistently happen
  15366. // before listen events.
  15367. ea(n, s, /*error=*/ null), ta(n, s), n.sharedClientState.updateMutationState(s, "acknowledged"),
  15368. await ua(n, t);
  15369. } catch (t) {
  15370. await vt(t);
  15371. }
  15372. }
  15373. async function Xc(t, e, n) {
  15374. const s = L(t);
  15375. try {
  15376. const t = await function(t, e) {
  15377. const n = L(t);
  15378. return n.persistence.runTransaction("Reject batch", "readwrite-primary", (t => {
  15379. let s;
  15380. return n.mutationQueue.lookupMutationBatch(t, e).next((e => (F(null !== e), s = e.keys(),
  15381. n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));
  15382. }));
  15383. }
  15384. /**
  15385. * Returns the largest (latest) batch id in mutation queue that is pending
  15386. * server response.
  15387. *
  15388. * Returns `BATCHID_UNKNOWN` if the queue is empty.
  15389. */ (s.localStore, e);
  15390. // The local store may or may not be able to apply the write result and
  15391. // raise events immediately (depending on whether the watcher is caught up),
  15392. // so we raise user callbacks first so that they consistently happen before
  15393. // listen events.
  15394. ea(s, e, n), ta(s, e), s.sharedClientState.updateMutationState(e, "rejected", n),
  15395. await ua(s, t);
  15396. } catch (n) {
  15397. await vt(n);
  15398. }
  15399. }
  15400. /**
  15401. * Registers a user callback that resolves when all pending mutations at the moment of calling
  15402. * are acknowledged .
  15403. */ async function Zc(t, e) {
  15404. const n = L(t);
  15405. ec(n.remoteStore) || N("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
  15406. try {
  15407. const t = await function(t) {
  15408. const e = L(t);
  15409. return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));
  15410. }(n.localStore);
  15411. if (-1 === t)
  15412. // Trigger the callback right away if there is no pending writes at the moment.
  15413. return void e.resolve();
  15414. const s = n.Ec.get(t) || [];
  15415. s.push(e), n.Ec.set(t, s);
  15416. } catch (t) {
  15417. const n = Ec(t, "Initialization of waitForPendingWrites() operation failed");
  15418. e.reject(n);
  15419. }
  15420. }
  15421. /**
  15422. * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
  15423. * if there are any.
  15424. */ function ta(t, e) {
  15425. (t.Ec.get(e) || []).forEach((t => {
  15426. t.resolve();
  15427. })), t.Ec.delete(e);
  15428. }
  15429. /** Reject all outstanding callbacks waiting for pending writes to complete. */ function ea(t, e, n) {
  15430. const s = L(t);
  15431. let i = s.Tc[s.currentUser.toKey()];
  15432. // NOTE: Mutations restored from persistence won't have callbacks, so it's
  15433. // okay for there to be no callback for this ID.
  15434. if (i) {
  15435. const t = i.get(e);
  15436. t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.Tc[s.currentUser.toKey()] = i;
  15437. }
  15438. }
  15439. function na(t, e, n = null) {
  15440. t.sharedClientState.removeLocalQueryTarget(e);
  15441. for (const s of t._c.get(e)) t.wc.delete(s), n && t.dc.Pc(s, n);
  15442. if (t._c.delete(e), t.isPrimaryClient) {
  15443. t.Ic.Is(e).forEach((e => {
  15444. t.Ic.containsKey(e) ||
  15445. // We removed the last reference for this key
  15446. sa(t, e);
  15447. }));
  15448. }
  15449. }
  15450. function sa(t, e) {
  15451. t.mc.delete(e.path.canonicalString());
  15452. // It's possible that the target already got removed because the query failed. In that case,
  15453. // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
  15454. const n = t.gc.get(e);
  15455. null !== n && (Ju(t.remoteStore, n), t.gc = t.gc.remove(e), t.yc.delete(n), oa(t));
  15456. }
  15457. function ia(t, e, n) {
  15458. for (const s of n) if (s instanceof Fc) t.Ic.addReference(s.key, e), ra(t, s); else if (s instanceof Bc) {
  15459. N("SyncEngine", "Document no longer in limbo: " + s.key), t.Ic.removeReference(s.key, e);
  15460. t.Ic.containsKey(s.key) ||
  15461. // We removed the last reference for this key
  15462. sa(t, s.key);
  15463. } else O();
  15464. }
  15465. function ra(t, e) {
  15466. const n = e.key, s = n.path.canonicalString();
  15467. t.gc.get(n) || t.mc.has(s) || (N("SyncEngine", "New document in limbo: " + n), t.mc.add(s),
  15468. oa(t));
  15469. }
  15470. /**
  15471. * Starts listens for documents in limbo that are enqueued for resolution,
  15472. * subject to a maximum number of concurrent resolutions.
  15473. *
  15474. * Without bounding the number of concurrent resolutions, the server can fail
  15475. * with "resource exhausted" errors which can lead to pathological client
  15476. * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
  15477. */ function oa(t) {
  15478. for (;t.mc.size > 0 && t.gc.size < t.maxConcurrentLimboResolutions; ) {
  15479. const e = t.mc.values().next().value;
  15480. t.mc.delete(e);
  15481. const n = new ht(ut.fromString(e)), s = t.Ac.next();
  15482. t.yc.set(s, new Uc(n)), t.gc = t.gc.insert(n, s), Hu(t.remoteStore, new cr(Jn(Gn(n.path)), s, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , Ot.ct));
  15483. }
  15484. }
  15485. async function ua(t, e, n) {
  15486. const s = L(t), i = [], r = [], o = [];
  15487. s.wc.isEmpty() || (s.wc.forEach(((t, u) => {
  15488. o.push(s.Rc(u, e, n).then((t => {
  15489. // Update views if there are actual changes.
  15490. if (
  15491. // If there are changes, or we are handling a global snapshot, notify
  15492. // secondary clients to update query state.
  15493. (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? "not-current" : "current"),
  15494. t) {
  15495. i.push(t);
  15496. const e = tu.Li(u.targetId, t);
  15497. r.push(e);
  15498. }
  15499. })));
  15500. })), await Promise.all(o), s.dc.nu(i), await async function(t, e) {
  15501. const n = L(t);
  15502. try {
  15503. await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (t => Rt.forEach(e, (e => Rt.forEach(e.Fi, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => Rt.forEach(e.Bi, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));
  15504. } catch (t) {
  15505. if (!Dt(t)) throw t;
  15506. // If `notifyLocalViewChanges` fails, we did not advance the sequence
  15507. // number for the documents that were included in this transaction.
  15508. // This might trigger them to be deleted earlier than they otherwise
  15509. // would have, but it should not invalidate the integrity of the data.
  15510. N("LocalStore", "Failed to update sequence numbers: " + t);
  15511. }
  15512. for (const t of e) {
  15513. const e = t.targetId;
  15514. if (!t.fromCache) {
  15515. const t = n.Ji.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);
  15516. // Advance the last limbo free snapshot version
  15517. n.Ji = n.Ji.insert(e, i);
  15518. }
  15519. }
  15520. }(s.localStore, r));
  15521. }
  15522. async function ca(t, e) {
  15523. const n = L(t);
  15524. if (!n.currentUser.isEqual(e)) {
  15525. N("SyncEngine", "User change. New user:", e.toKey());
  15526. const t = await iu(n.localStore, e);
  15527. n.currentUser = e,
  15528. // Fails tasks waiting for pending writes requested by previous user.
  15529. function(t, e) {
  15530. t.Ec.forEach((t => {
  15531. t.forEach((t => {
  15532. t.reject(new U(q.CANCELLED, e));
  15533. }));
  15534. })), t.Ec.clear();
  15535. }(n, "'waitForPendingWrites' promise is rejected due to a user change."),
  15536. // TODO(b/114226417): Consider calling this only in the primary tab.
  15537. n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await ua(n, t.er);
  15538. }
  15539. }
  15540. function aa(t, e) {
  15541. const n = L(t), s = n.yc.get(e);
  15542. if (s && s.fc) return gs().add(s.key);
  15543. {
  15544. let t = gs();
  15545. const s = n._c.get(e);
  15546. if (!s) return t;
  15547. for (const e of s) {
  15548. const s = n.wc.get(e);
  15549. t = t.unionWith(s.view.nc);
  15550. }
  15551. return t;
  15552. }
  15553. }
  15554. /**
  15555. * Reconcile the list of synced documents in an existing view with those
  15556. * from persistence.
  15557. */ async function ha(t, e) {
  15558. const n = L(t), s = await fu(n.localStore, e.query,
  15559. /* usePreviousResults= */ !0), i = e.view.hc(s);
  15560. return n.isPrimaryClient && ia(n, e.targetId, i.cc), i;
  15561. }
  15562. /**
  15563. * Retrieves newly changed documents from remote document cache and raises
  15564. * snapshots if needed.
  15565. */
  15566. // PORTING NOTE: Multi-Tab only.
  15567. async function la(t, e) {
  15568. const n = L(t);
  15569. return wu(n.localStore, e).then((t => ua(n, t)));
  15570. }
  15571. /** Applies a mutation state to an existing batch. */
  15572. // PORTING NOTE: Multi-Tab only.
  15573. async function fa(t, e, n, s) {
  15574. const i = L(t), r = await function(t, e) {
  15575. const n = L(t), s = L(n.mutationQueue);
  15576. return n.persistence.runTransaction("Lookup mutation documents", "readonly", (t => s.Sn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : Rt.resolve(null)))));
  15577. }
  15578. // PORTING NOTE: Multi-Tab only.
  15579. (i.localStore, e);
  15580. null !== r ? ("pending" === n ?
  15581. // If we are the primary client, we need to send this write to the
  15582. // backend. Secondary clients will ignore these writes since their remote
  15583. // connection is disabled.
  15584. await cc(i.remoteStore) : "acknowledged" === n || "rejected" === n ? (
  15585. // NOTE: Both these methods are no-ops for batches that originated from
  15586. // other clients.
  15587. ea(i, e, s || null), ta(i, e), function(t, e) {
  15588. L(L(t).mutationQueue).Cn(e);
  15589. }
  15590. // PORTING NOTE: Multi-Tab only.
  15591. (i.localStore, e)) : O(), await ua(i, r)) :
  15592. // A throttled tab may not have seen the mutation before it was completed
  15593. // and removed from the mutation queue, in which case we won't have cached
  15594. // the affected documents. In this case we can safely ignore the update
  15595. // since that means we didn't apply the mutation locally at all (if we
  15596. // had, we would have cached the affected documents), and so we will just
  15597. // see any resulting document changes via normal remote document updates
  15598. // as applicable.
  15599. N("SyncEngine", "Cannot apply mutation batch with id: " + e);
  15600. }
  15601. /** Applies a query target change from a different tab. */
  15602. // PORTING NOTE: Multi-Tab only.
  15603. async function da(t, e) {
  15604. const n = L(t);
  15605. if (pa(n), Ia(n), !0 === e && !0 !== n.vc) {
  15606. // Secondary tabs only maintain Views for their local listeners and the
  15607. // Views internal state may not be 100% populated (in particular
  15608. // secondary tabs don't track syncedDocuments, the set of documents the
  15609. // server considers to be in the target). So when a secondary becomes
  15610. // primary, we need to need to make sure that all views for all targets
  15611. // match the state on disk.
  15612. const t = n.sharedClientState.getAllActiveQueryTargets(), e = await wa(n, t.toArray());
  15613. n.vc = !0, await yc(n.remoteStore, !0);
  15614. for (const t of e) Hu(n.remoteStore, t);
  15615. } else if (!1 === e && !1 !== n.vc) {
  15616. const t = [];
  15617. let e = Promise.resolve();
  15618. n._c.forEach(((s, i) => {
  15619. n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (na(n, i),
  15620. lu(n.localStore, i,
  15621. /*keepPersistedTargetData=*/ !0)))), Ju(n.remoteStore, i);
  15622. })), await e, await wa(n, t),
  15623. // PORTING NOTE: Multi-Tab only.
  15624. function(t) {
  15625. const e = L(t);
  15626. e.yc.forEach(((t, n) => {
  15627. Ju(e.remoteStore, n);
  15628. })), e.Ic.Ts(), e.yc = new Map, e.gc = new pe(ht.comparator);
  15629. }
  15630. /**
  15631. * Reconcile the query views of the provided query targets with the state from
  15632. * persistence. Raises snapshots for any changes that affect the local
  15633. * client and returns the updated state of all target's query data.
  15634. *
  15635. * @param syncEngine - The sync engine implementation
  15636. * @param targets - the list of targets with views that need to be recomputed
  15637. * @param transitionToPrimary - `true` iff the tab transitions from a secondary
  15638. * tab to a primary tab
  15639. */
  15640. // PORTING NOTE: Multi-Tab only.
  15641. (n), n.vc = !1, await yc(n.remoteStore, !1);
  15642. }
  15643. }
  15644. async function wa(t, e, n) {
  15645. const s = L(t), i = [], r = [];
  15646. for (const t of e) {
  15647. let e;
  15648. const n = s._c.get(t);
  15649. if (n && 0 !== n.length) {
  15650. // For queries that have a local View, we fetch their current state
  15651. // from LocalStore (as the resume token and the snapshot version
  15652. // might have changed) and reconcile their views with the persisted
  15653. // state (the list of syncedDocuments may have gotten out of sync).
  15654. e = await hu(s.localStore, Jn(n[0]));
  15655. for (const t of n) {
  15656. const e = s.wc.get(t), n = await ha(s, e);
  15657. n.snapshot && r.push(n.snapshot);
  15658. }
  15659. } else {
  15660. // For queries that never executed on this client, we need to
  15661. // allocate the target in LocalStore and initialize a new View.
  15662. const n = await du(s.localStore, t);
  15663. e = await hu(s.localStore, n), await Qc(s, _a(n), t,
  15664. /*current=*/ !1, e.resumeToken);
  15665. }
  15666. i.push(e);
  15667. }
  15668. return s.dc.nu(r), i;
  15669. }
  15670. /**
  15671. * Creates a `Query` object from the specified `Target`. There is no way to
  15672. * obtain the original `Query`, so we synthesize a `Query` from the `Target`
  15673. * object.
  15674. *
  15675. * The synthesized result might be different from the original `Query`, but
  15676. * since the synthesized `Query` should return the same results as the
  15677. * original one (only the presentation of results might differ), the potential
  15678. * difference will not cause issues.
  15679. */
  15680. // PORTING NOTE: Multi-Tab only.
  15681. function _a(t) {
  15682. return Kn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* LimitType.First */ , t.startAt, t.endAt);
  15683. }
  15684. /** Returns the IDs of the clients that are currently active. */
  15685. // PORTING NOTE: Multi-Tab only.
  15686. function ma(t) {
  15687. const e = L(t);
  15688. return L(L(e.localStore).persistence).$i();
  15689. }
  15690. /** Applies a query target change from a different tab. */
  15691. // PORTING NOTE: Multi-Tab only.
  15692. async function ga(t, e, n, s) {
  15693. const i = L(t);
  15694. if (i.vc)
  15695. // If we receive a target state notification via WebStorage, we are
  15696. // either already secondary or another tab has taken the primary lease.
  15697. return void N("SyncEngine", "Ignoring unexpected query state notification.");
  15698. const r = i._c.get(e);
  15699. if (r && r.length > 0) switch (n) {
  15700. case "current":
  15701. case "not-current":
  15702. {
  15703. const t = await wu(i.localStore, ss(r[0])), s = mi.createSynthesizedRemoteEventForCurrentChange(e, "current" === n, Ve.EMPTY_BYTE_STRING);
  15704. await ua(i, t, s);
  15705. break;
  15706. }
  15707. case "rejected":
  15708. await lu(i.localStore, e,
  15709. /* keepPersistedTargetData */ !0), na(i, e, s);
  15710. break;
  15711. default:
  15712. O();
  15713. }
  15714. }
  15715. /** Adds or removes Watch targets for queries from different tabs. */ async function ya(t, e, n) {
  15716. const s = pa(t);
  15717. if (s.vc) {
  15718. for (const t of e) {
  15719. if (s._c.has(t)) {
  15720. // A target might have been added in a previous attempt
  15721. N("SyncEngine", "Adding an already active target " + t);
  15722. continue;
  15723. }
  15724. const e = await du(s.localStore, t), n = await hu(s.localStore, e);
  15725. await Qc(s, _a(e), n.targetId,
  15726. /*current=*/ !1, n.resumeToken), Hu(s.remoteStore, n);
  15727. }
  15728. for (const t of n)
  15729. // Check that the target is still active since the target might have been
  15730. // removed if it has been rejected by the backend.
  15731. s._c.has(t) &&
  15732. // Release queries that are still active.
  15733. await lu(s.localStore, t,
  15734. /* keepPersistedTargetData */ !1).then((() => {
  15735. Ju(s.remoteStore, t), na(s, t);
  15736. })).catch(vt);
  15737. }
  15738. }
  15739. function pa(t) {
  15740. const e = L(t);
  15741. return e.remoteStore.remoteSyncer.applyRemoteEvent = Wc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = aa.bind(null, e),
  15742. e.remoteStore.remoteSyncer.rejectListen = Jc.bind(null, e), e.dc.nu = Dc.bind(null, e.eventManager),
  15743. e.dc.Pc = Cc.bind(null, e.eventManager), e;
  15744. }
  15745. function Ia(t) {
  15746. const e = L(t);
  15747. return e.remoteStore.remoteSyncer.applySuccessfulWrite = Yc.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Xc.bind(null, e),
  15748. e;
  15749. }
  15750. /**
  15751. * Loads a Firestore bundle into the SDK. The returned promise resolves when
  15752. * the bundle finished loading.
  15753. *
  15754. * @param syncEngine - SyncEngine to use.
  15755. * @param bundleReader - Bundle to load into the SDK.
  15756. * @param task - LoadBundleTask used to update the loading progress to public API.
  15757. */ function Ta(t, e, n) {
  15758. const s = L(t);
  15759. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  15760. (
  15761. /** Loads a bundle and returns the list of affected collection groups. */
  15762. async function(t, e, n) {
  15763. try {
  15764. const s = await e.getMetadata();
  15765. if (await function(t, e) {
  15766. const n = L(t), s = Ni(e.createTime);
  15767. return n.persistence.runTransaction("hasNewerBundle", "readonly", (t => n.qs.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));
  15768. }
  15769. /**
  15770. * Saves the given `BundleMetadata` to local persistence.
  15771. */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {
  15772. return {
  15773. taskState: "Success",
  15774. documentsLoaded: t.totalDocuments,
  15775. bytesLoaded: t.totalBytes,
  15776. totalDocuments: t.totalDocuments,
  15777. totalBytes: t.totalBytes
  15778. };
  15779. }(s)), Promise.resolve(new Set);
  15780. n._updateProgress(Oc(s));
  15781. const i = new $c(s, t.localStore, e.serializer);
  15782. let r = await e.bc();
  15783. for (;r; ) {
  15784. const t = await i.zu(r);
  15785. t && n._updateProgress(t), r = await e.bc();
  15786. }
  15787. const o = await i.complete();
  15788. return await ua(t, o.Ju,
  15789. /* remoteEvent */ void 0),
  15790. // Save metadata, so loading the same bundle will skip.
  15791. await function(t, e) {
  15792. const n = L(t);
  15793. return n.persistence.runTransaction("Save bundle", "readwrite", (t => n.qs.saveBundleMetadata(t, e)));
  15794. }
  15795. /**
  15796. * Returns a promise of a `NamedQuery` associated with given query name. Promise
  15797. * resolves to undefined if no persisted data can be found.
  15798. */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Hu);
  15799. } catch (t) {
  15800. return M("SyncEngine", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);
  15801. }
  15802. }
  15803. /**
  15804. * @license
  15805. * Copyright 2020 Google LLC
  15806. *
  15807. * Licensed under the Apache License, Version 2.0 (the "License");
  15808. * you may not use this file except in compliance with the License.
  15809. * You may obtain a copy of the License at
  15810. *
  15811. * http://www.apache.org/licenses/LICENSE-2.0
  15812. *
  15813. * Unless required by applicable law or agreed to in writing, software
  15814. * distributed under the License is distributed on an "AS IS" BASIS,
  15815. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15816. * See the License for the specific language governing permissions and
  15817. * limitations under the License.
  15818. */
  15819. /**
  15820. * Provides all components needed for Firestore with in-memory persistence.
  15821. * Uses EagerGC garbage collection.
  15822. */)(s, e, n).then((t => {
  15823. s.sharedClientState.notifyBundleLoaded(t);
  15824. }));
  15825. }
  15826. class Ea {
  15827. constructor() {
  15828. this.synchronizeTabs = !1;
  15829. }
  15830. async initialize(t) {
  15831. this.serializer = Fu(t.databaseInfo.databaseId), this.sharedClientState = this.createSharedClientState(t),
  15832. this.persistence = this.createPersistence(t), await this.persistence.start(), this.localStore = this.createLocalStore(t),
  15833. this.gcScheduler = this.createGarbageCollectionScheduler(t, this.localStore), this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(t, this.localStore);
  15834. }
  15835. createGarbageCollectionScheduler(t, e) {
  15836. return null;
  15837. }
  15838. createIndexBackfillerScheduler(t, e) {
  15839. return null;
  15840. }
  15841. createLocalStore(t) {
  15842. return su(this.persistence, new eu, t.initialUser, this.serializer);
  15843. }
  15844. createPersistence(t) {
  15845. return new Ko(Qo.zs, this.serializer);
  15846. }
  15847. createSharedClientState(t) {
  15848. return new bu;
  15849. }
  15850. async terminate() {
  15851. this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(),
  15852. await this.persistence.shutdown();
  15853. }
  15854. }
  15855. class Aa extends Ea {
  15856. constructor(t) {
  15857. super(), this.cacheSizeBytes = t;
  15858. }
  15859. createGarbageCollectionScheduler(t, e) {
  15860. F(this.persistence.referenceDelegate instanceof jo);
  15861. const n = this.persistence.referenceDelegate.garbageCollector;
  15862. return new po(n, t.asyncQueue, e);
  15863. }
  15864. createPersistence(t) {
  15865. const e = void 0 !== this.cacheSizeBytes ? so.withCacheSize(this.cacheSizeBytes) : so.DEFAULT;
  15866. return new Ko((t => jo.zs(t, e)), this.serializer);
  15867. }
  15868. }
  15869. /**
  15870. * Provides all components needed for Firestore with IndexedDB persistence.
  15871. */ class va extends Ea {
  15872. constructor(t, e, n) {
  15873. super(), this.Vc = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;
  15874. }
  15875. async initialize(t) {
  15876. await super.initialize(t), await this.Vc.initialize(this, t),
  15877. // Enqueue writes from a previous session
  15878. await Ia(this.Vc.syncEngine), await cc(this.Vc.remoteStore),
  15879. // NOTE: This will immediately call the listener, so we make sure to
  15880. // set it after localStore / remoteStore are started.
  15881. await this.persistence.Ii((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(),
  15882. this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(),
  15883. Promise.resolve())));
  15884. }
  15885. createLocalStore(t) {
  15886. return su(this.persistence, new eu, t.initialUser, this.serializer);
  15887. }
  15888. createGarbageCollectionScheduler(t, e) {
  15889. const n = this.persistence.referenceDelegate.garbageCollector;
  15890. return new po(n, t.asyncQueue, e);
  15891. }
  15892. createIndexBackfillerScheduler(t, e) {
  15893. const n = new $t(e, this.persistence);
  15894. return new Mt(t.asyncQueue, n);
  15895. }
  15896. createPersistence(t) {
  15897. const e = Zo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? so.withCacheSize(this.cacheSizeBytes) : so.DEFAULT;
  15898. return new Jo(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, $u(), Ou(), this.serializer, this.sharedClientState, !!this.forceOwnership);
  15899. }
  15900. createSharedClientState(t) {
  15901. return new bu;
  15902. }
  15903. }
  15904. /**
  15905. * Provides all components needed for Firestore with multi-tab IndexedDB
  15906. * persistence.
  15907. *
  15908. * In the legacy client, this provider is used to provide both multi-tab and
  15909. * non-multi-tab persistence since we cannot tell at build time whether
  15910. * `synchronizeTabs` will be enabled.
  15911. */ class Ra extends va {
  15912. constructor(t, e) {
  15913. super(t, e, /* forceOwnership= */ !1), this.Vc = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;
  15914. }
  15915. async initialize(t) {
  15916. await super.initialize(t);
  15917. const e = this.Vc.syncEngine;
  15918. this.sharedClientState instanceof Pu && (this.sharedClientState.syncEngine = {
  15919. jr: fa.bind(null, e),
  15920. zr: ga.bind(null, e),
  15921. Wr: ya.bind(null, e),
  15922. $i: ma.bind(null, e),
  15923. Qr: la.bind(null, e)
  15924. }, await this.sharedClientState.start()),
  15925. // NOTE: This will immediately call the listener, so we make sure to
  15926. // set it after localStore / remoteStore are started.
  15927. await this.persistence.Ii((async t => {
  15928. await da(this.Vc.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()),
  15929. this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());
  15930. }));
  15931. }
  15932. createSharedClientState(t) {
  15933. const e = $u();
  15934. if (!Pu.D(e)) throw new U(q.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
  15935. const n = Zo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);
  15936. return new Pu(e, t.asyncQueue, n, t.clientId, t.initialUser);
  15937. }
  15938. }
  15939. /**
  15940. * Initializes and wires the components that are needed to interface with the
  15941. * network.
  15942. */ class Pa {
  15943. async initialize(t, e) {
  15944. this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState,
  15945. this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e),
  15946. this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e,
  15947. /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => Hc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */),
  15948. this.remoteStore.remoteSyncer.handleCredentialChange = ca.bind(null, this.syncEngine),
  15949. await yc(this.remoteStore, this.syncEngine.isPrimaryClient));
  15950. }
  15951. createEventManager(t) {
  15952. return new bc;
  15953. }
  15954. createDatastore(t) {
  15955. const e = Fu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new Mu(s));
  15956. var s;
  15957. /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {
  15958. return new Ku(t, e, n, s);
  15959. }(t.authCredentials, t.appCheckCredentials, n, e);
  15960. }
  15961. createRemoteStore(t) {
  15962. return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => Hc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */),
  15963. r = Su.D() ? new Su : new Vu, new ju(e, n, s, i, r);
  15964. var e, n, s, i, r;
  15965. /** Re-enables the network. Idempotent. */ }
  15966. createSyncEngine(t, e) {
  15967. return function(t, e, n,
  15968. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15969. s, i, r, o) {
  15970. const u = new Kc(t, e, n, s, i, r);
  15971. return o && (u.vc = !0), u;
  15972. }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
  15973. }
  15974. terminate() {
  15975. return async function(t) {
  15976. const e = L(t);
  15977. N("RemoteStore", "RemoteStore shutting down."), e.vu.add(5 /* OfflineCause.Shutdown */),
  15978. await Wu(e), e.Pu.shutdown(),
  15979. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
  15980. // triggering spurious listener events with cached data, etc.
  15981. e.bu.set("Unknown" /* OnlineState.Unknown */);
  15982. }(this.remoteStore);
  15983. }
  15984. }
  15985. /**
  15986. * @license
  15987. * Copyright 2020 Google LLC
  15988. *
  15989. * Licensed under the Apache License, Version 2.0 (the "License");
  15990. * you may not use this file except in compliance with the License.
  15991. * You may obtain a copy of the License at
  15992. *
  15993. * http://www.apache.org/licenses/LICENSE-2.0
  15994. *
  15995. * Unless required by applicable law or agreed to in writing, software
  15996. * distributed under the License is distributed on an "AS IS" BASIS,
  15997. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15998. * See the License for the specific language governing permissions and
  15999. * limitations under the License.
  16000. */
  16001. /**
  16002. * How many bytes to read each time when `ReadableStreamReader.read()` is
  16003. * called. Only applicable for byte streams that we control (e.g. those backed
  16004. * by an UInt8Array).
  16005. */
  16006. /**
  16007. * Builds a `ByteStreamReader` from a UInt8Array.
  16008. * @param source - The data source to use.
  16009. * @param bytesPerRead - How many bytes each `read()` from the returned reader
  16010. * will read.
  16011. */
  16012. function ba(t, e = 10240) {
  16013. let n = 0;
  16014. // The TypeScript definition for ReadableStreamReader changed. We use
  16015. // `any` here to allow this code to compile with different versions.
  16016. // See https://github.com/microsoft/TypeScript/issues/42970
  16017. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16018. return {
  16019. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16020. async read() {
  16021. if (n < t.byteLength) {
  16022. const s = {
  16023. value: t.slice(n, n + e),
  16024. done: !1
  16025. };
  16026. return n += e, s;
  16027. }
  16028. return {
  16029. done: !0
  16030. };
  16031. },
  16032. async cancel() {},
  16033. releaseLock() {},
  16034. closed: Promise.resolve()
  16035. };
  16036. }
  16037. /**
  16038. * @license
  16039. * Copyright 2020 Google LLC
  16040. *
  16041. * Licensed under the Apache License, Version 2.0 (the "License");
  16042. * you may not use this file except in compliance with the License.
  16043. * You may obtain a copy of the License at
  16044. *
  16045. * http://www.apache.org/licenses/LICENSE-2.0
  16046. *
  16047. * Unless required by applicable law or agreed to in writing, software
  16048. * distributed under the License is distributed on an "AS IS" BASIS,
  16049. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16050. * See the License for the specific language governing permissions and
  16051. * limitations under the License.
  16052. */
  16053. /**
  16054. * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
  16055. */
  16056. /**
  16057. * @license
  16058. * Copyright 2017 Google LLC
  16059. *
  16060. * Licensed under the Apache License, Version 2.0 (the "License");
  16061. * you may not use this file except in compliance with the License.
  16062. * You may obtain a copy of the License at
  16063. *
  16064. * http://www.apache.org/licenses/LICENSE-2.0
  16065. *
  16066. * Unless required by applicable law or agreed to in writing, software
  16067. * distributed under the License is distributed on an "AS IS" BASIS,
  16068. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16069. * See the License for the specific language governing permissions and
  16070. * limitations under the License.
  16071. */
  16072. /*
  16073. * A wrapper implementation of Observer<T> that will dispatch events
  16074. * asynchronously. To allow immediate silencing, a mute call is added which
  16075. * causes events scheduled to no longer be raised.
  16076. */
  16077. class Va {
  16078. constructor(t) {
  16079. this.observer = t,
  16080. /**
  16081. * When set to true, will not raise future events. Necessary to deal with
  16082. * async detachment of listener.
  16083. */
  16084. this.muted = !1;
  16085. }
  16086. next(t) {
  16087. this.observer.next && this.Sc(this.observer.next, t);
  16088. }
  16089. error(t) {
  16090. this.observer.error ? this.Sc(this.observer.error, t) : k("Uncaught Error in snapshot listener:", t.toString());
  16091. }
  16092. Dc() {
  16093. this.muted = !0;
  16094. }
  16095. Sc(t, e) {
  16096. this.muted || setTimeout((() => {
  16097. this.muted || t(e);
  16098. }), 0);
  16099. }
  16100. }
  16101. /**
  16102. * @license
  16103. * Copyright 2020 Google LLC
  16104. *
  16105. * Licensed under the Apache License, Version 2.0 (the "License");
  16106. * you may not use this file except in compliance with the License.
  16107. * You may obtain a copy of the License at
  16108. *
  16109. * http://www.apache.org/licenses/LICENSE-2.0
  16110. *
  16111. * Unless required by applicable law or agreed to in writing, software
  16112. * distributed under the License is distributed on an "AS IS" BASIS,
  16113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16114. * See the License for the specific language governing permissions and
  16115. * limitations under the License.
  16116. */
  16117. /**
  16118. * A class representing a bundle.
  16119. *
  16120. * Takes a bundle stream or buffer, and presents abstractions to read bundled
  16121. * elements out of the underlying content.
  16122. */ class Sa {
  16123. constructor(
  16124. /** The reader to read from underlying binary bundle data source. */
  16125. t, e) {
  16126. this.Cc = t, this.serializer = e,
  16127. /** Cached bundle metadata. */
  16128. this.metadata = new K,
  16129. /**
  16130. * Internal buffer to hold bundle content, accumulating incomplete element
  16131. * content.
  16132. */
  16133. this.buffer = new Uint8Array, this.xc = new TextDecoder("utf-8"),
  16134. // Read the metadata (which is the first element).
  16135. this.Nc().then((t => {
  16136. t && t.Qu() ? this.metadata.resolve(t.Gu.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null == t ? void 0 : t.Gu)}`));
  16137. }), (t => this.metadata.reject(t)));
  16138. }
  16139. close() {
  16140. return this.Cc.cancel();
  16141. }
  16142. async getMetadata() {
  16143. return this.metadata.promise;
  16144. }
  16145. async bc() {
  16146. // Makes sure metadata is read before proceeding.
  16147. return await this.getMetadata(), this.Nc();
  16148. }
  16149. /**
  16150. * Reads from the head of internal buffer, and pulling more data from
  16151. * underlying stream if a complete element cannot be found, until an
  16152. * element(including the prefixed length and the JSON string) is found.
  16153. *
  16154. * Once a complete element is read, it is dropped from internal buffer.
  16155. *
  16156. * Returns either the bundled element, or null if we have reached the end of
  16157. * the stream.
  16158. */ async Nc() {
  16159. const t = await this.kc();
  16160. if (null === t) return null;
  16161. const e = this.xc.decode(t), n = Number(e);
  16162. isNaN(n) && this.Mc(`length string (${e}) is not valid number`);
  16163. const s = await this.$c(n);
  16164. return new kc(JSON.parse(s), t.length + n);
  16165. }
  16166. /** First index of '{' from the underlying buffer. */ Oc() {
  16167. return this.buffer.findIndex((t => t === "{".charCodeAt(0)));
  16168. }
  16169. /**
  16170. * Reads from the beginning of the internal buffer, until the first '{', and
  16171. * return the content.
  16172. *
  16173. * If reached end of the stream, returns a null.
  16174. */ async kc() {
  16175. for (;this.Oc() < 0; ) {
  16176. if (await this.Fc()) break;
  16177. }
  16178. // Broke out of the loop because underlying stream is closed, and there
  16179. // happens to be no more data to process.
  16180. if (0 === this.buffer.length) return null;
  16181. const t = this.Oc();
  16182. // Broke out of the loop because underlying stream is closed, but still
  16183. // cannot find an open bracket.
  16184. t < 0 && this.Mc("Reached the end of bundle when a length string is expected.");
  16185. const e = this.buffer.slice(0, t);
  16186. // Update the internal buffer to drop the read length.
  16187. return this.buffer = this.buffer.slice(t), e;
  16188. }
  16189. /**
  16190. * Reads from a specified position from the internal buffer, for a specified
  16191. * number of bytes, pulling more data from the underlying stream if needed.
  16192. *
  16193. * Returns a string decoded from the read bytes.
  16194. */ async $c(t) {
  16195. for (;this.buffer.length < t; ) {
  16196. await this.Fc() && this.Mc("Reached the end of bundle when more is expected.");
  16197. }
  16198. const e = this.xc.decode(this.buffer.slice(0, t));
  16199. // Update the internal buffer to drop the read json string.
  16200. return this.buffer = this.buffer.slice(t), e;
  16201. }
  16202. Mc(t) {
  16203. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16204. throw this.Cc.cancel(), new Error(`Invalid bundle format: ${t}`);
  16205. }
  16206. /**
  16207. * Pulls more data from underlying stream to internal buffer.
  16208. * Returns a boolean indicating whether the stream is finished.
  16209. */ async Fc() {
  16210. const t = await this.Cc.read();
  16211. if (!t.done) {
  16212. const e = new Uint8Array(this.buffer.length + t.value.length);
  16213. e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;
  16214. }
  16215. return t.done;
  16216. }
  16217. }
  16218. /**
  16219. * @license
  16220. * Copyright 2017 Google LLC
  16221. *
  16222. * Licensed under the Apache License, Version 2.0 (the "License");
  16223. * you may not use this file except in compliance with the License.
  16224. * You may obtain a copy of the License at
  16225. *
  16226. * http://www.apache.org/licenses/LICENSE-2.0
  16227. *
  16228. * Unless required by applicable law or agreed to in writing, software
  16229. * distributed under the License is distributed on an "AS IS" BASIS,
  16230. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16231. * See the License for the specific language governing permissions and
  16232. * limitations under the License.
  16233. */
  16234. /**
  16235. * Internal transaction object responsible for accumulating the mutations to
  16236. * perform and the base versions for any documents read.
  16237. */
  16238. class Da {
  16239. constructor(t) {
  16240. this.datastore = t,
  16241. // The version of each document that was read during this transaction.
  16242. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  16243. /**
  16244. * A deferred usage error that occurred previously in this transaction that
  16245. * will cause the transaction to fail once it actually commits.
  16246. */
  16247. this.lastWriteError = null,
  16248. /**
  16249. * Set of documents that have been written in the transaction.
  16250. *
  16251. * When there's more than one write to the same key in a transaction, any
  16252. * writes after the first are handled differently.
  16253. */
  16254. this.writtenDocs = new Set;
  16255. }
  16256. async lookup(t) {
  16257. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new U(q.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
  16258. const e = await async function(t, e) {
  16259. const n = L(t), s = Li(n.serializer) + "/documents", i = {
  16260. documents: e.map((t => $i(n.serializer, t)))
  16261. }, r = await n.vo("BatchGetDocuments", s, i, e.length), o = new Map;
  16262. r.forEach((t => {
  16263. const e = Gi(n.serializer, t);
  16264. o.set(e.key.toString(), e);
  16265. }));
  16266. const u = [];
  16267. return e.forEach((t => {
  16268. const e = o.get(t.toString());
  16269. F(!!e), u.push(e);
  16270. })), u;
  16271. }(this.datastore, t);
  16272. return e.forEach((t => this.recordVersion(t))), e;
  16273. }
  16274. set(t, e) {
  16275. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16276. }
  16277. update(t, e) {
  16278. try {
  16279. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  16280. } catch (t) {
  16281. this.lastWriteError = t;
  16282. }
  16283. this.writtenDocs.add(t.toString());
  16284. }
  16285. delete(t) {
  16286. this.write(new Ys(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16287. }
  16288. async commit() {
  16289. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  16290. const t = this.readVersions;
  16291. // For each mutation, note that the doc was written.
  16292. this.mutations.forEach((e => {
  16293. t.delete(e.key.toString());
  16294. })),
  16295. // For each document that was read but not written to, we want to perform
  16296. // a `verify` operation.
  16297. t.forEach(((t, e) => {
  16298. const n = ht.fromPath(e);
  16299. this.mutations.push(new Xs(n, this.precondition(n)));
  16300. })), await async function(t, e) {
  16301. const n = L(t), s = Li(n.serializer) + "/documents", i = {
  16302. writes: e.map((t => ji(n.serializer, t)))
  16303. };
  16304. await n.Io("Commit", s, i);
  16305. }(this.datastore, this.mutations), this.committed = !0;
  16306. }
  16307. recordVersion(t) {
  16308. let e;
  16309. if (t.isFoundDocument()) e = t.version; else {
  16310. if (!t.isNoDocument()) throw O();
  16311. // Represent a deleted doc using SnapshotVersion.min().
  16312. e = rt.min();
  16313. }
  16314. const n = this.readVersions.get(t.key.toString());
  16315. if (n) {
  16316. if (!e.isEqual(n))
  16317. // This transaction will fail no matter what.
  16318. throw new U(q.ABORTED, "Document version changed between two reads.");
  16319. } else this.readVersions.set(t.key.toString(), e);
  16320. }
  16321. /**
  16322. * Returns the version of this document when it was read in this transaction,
  16323. * as a precondition, or no precondition if it was not read.
  16324. */ precondition(t) {
  16325. const e = this.readVersions.get(t.toString());
  16326. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(rt.min()) ? Fs.exists(!1) : Fs.updateTime(e) : Fs.none();
  16327. }
  16328. /**
  16329. * Returns the precondition for a document if the operation is an update.
  16330. */ preconditionForUpdate(t) {
  16331. const e = this.readVersions.get(t.toString());
  16332. // The first time a document is written, we want to take into account the
  16333. // read time and existence
  16334. if (!this.writtenDocs.has(t.toString()) && e) {
  16335. if (e.isEqual(rt.min()))
  16336. // The document doesn't exist, so fail the transaction.
  16337. // This has to be validated locally because you can't send a
  16338. // precondition that a document does not exist without changing the
  16339. // semantics of the backend write to be an insert. This is the reverse
  16340. // of what we want, since we want to assert that the document doesn't
  16341. // exist but then send the update and have it fail. Since we can't
  16342. // express that to the backend, we have to validate locally.
  16343. // Note: this can change once we can send separate verify writes in the
  16344. // transaction.
  16345. throw new U(q.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  16346. // Document exists, base precondition on document update time.
  16347. return Fs.updateTime(e);
  16348. }
  16349. // Document was not read, so we just use the preconditions for a blind
  16350. // update.
  16351. return Fs.exists(!0);
  16352. }
  16353. write(t) {
  16354. this.ensureCommitNotCalled(), this.mutations.push(t);
  16355. }
  16356. ensureCommitNotCalled() {}
  16357. }
  16358. /**
  16359. * @license
  16360. * Copyright 2019 Google LLC
  16361. *
  16362. * Licensed under the Apache License, Version 2.0 (the "License");
  16363. * you may not use this file except in compliance with the License.
  16364. * You may obtain a copy of the License at
  16365. *
  16366. * http://www.apache.org/licenses/LICENSE-2.0
  16367. *
  16368. * Unless required by applicable law or agreed to in writing, software
  16369. * distributed under the License is distributed on an "AS IS" BASIS,
  16370. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16371. * See the License for the specific language governing permissions and
  16372. * limitations under the License.
  16373. */
  16374. /**
  16375. * TransactionRunner encapsulates the logic needed to run and retry transactions
  16376. * with backoff.
  16377. */ class Ca {
  16378. constructor(t, e, n, s, i) {
  16379. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s,
  16380. this.deferred = i, this.Bc = n.maxAttempts, this.qo = new Bu(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  16381. }
  16382. /** Runs the transaction and sets the result on deferred. */ run() {
  16383. this.Bc -= 1, this.Lc();
  16384. }
  16385. Lc() {
  16386. this.qo.No((async () => {
  16387. const t = new Da(this.datastore), e = this.qc(t);
  16388. e && e.then((e => {
  16389. this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {
  16390. this.deferred.resolve(e);
  16391. })).catch((t => {
  16392. this.Uc(t);
  16393. }))));
  16394. })).catch((t => {
  16395. this.Uc(t);
  16396. }));
  16397. }));
  16398. }
  16399. qc(t) {
  16400. try {
  16401. const e = this.updateFunction(t);
  16402. return !Ft(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  16403. null);
  16404. } catch (t) {
  16405. // Do not retry errors thrown by user provided updateFunction.
  16406. return this.deferred.reject(t), null;
  16407. }
  16408. }
  16409. Uc(t) {
  16410. this.Bc > 0 && this.Kc(t) ? (this.Bc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Lc(),
  16411. Promise.resolve())))) : this.deferred.reject(t);
  16412. }
  16413. Kc(t) {
  16414. if ("FirebaseError" === t.name) {
  16415. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  16416. // non-matching document versions with ABORTED. These errors should be retried.
  16417. const e = t.code;
  16418. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !oi(e);
  16419. }
  16420. return !1;
  16421. }
  16422. }
  16423. /**
  16424. * @license
  16425. * Copyright 2017 Google LLC
  16426. *
  16427. * Licensed under the Apache License, Version 2.0 (the "License");
  16428. * you may not use this file except in compliance with the License.
  16429. * You may obtain a copy of the License at
  16430. *
  16431. * http://www.apache.org/licenses/LICENSE-2.0
  16432. *
  16433. * Unless required by applicable law or agreed to in writing, software
  16434. * distributed under the License is distributed on an "AS IS" BASIS,
  16435. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16436. * See the License for the specific language governing permissions and
  16437. * limitations under the License.
  16438. */
  16439. /**
  16440. * FirestoreClient is a top-level class that constructs and owns all of the //
  16441. * pieces of the client SDK architecture. It is responsible for creating the //
  16442. * async queue that is shared by all of the other components in the system. //
  16443. */
  16444. class xa {
  16445. constructor(t, e,
  16446. /**
  16447. * Asynchronous queue responsible for all of our internal processing. When
  16448. * we get incoming work from the user (via public API) or the network
  16449. * (incoming GRPC messages), we should always schedule onto this queue.
  16450. * This ensures all of our work is properly serialized (e.g. we don't
  16451. * start processing a new operation while the previous one is waiting for
  16452. * an async I/O to complete).
  16453. */
  16454. n, s) {
  16455. this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s,
  16456. this.user = V.UNAUTHENTICATED, this.clientId = tt.A(), this.authCredentialListener = () => Promise.resolve(),
  16457. this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {
  16458. N("FirestoreClient", "Received user=", t.uid), await this.authCredentialListener(t),
  16459. this.user = t;
  16460. })), this.appCheckCredentials.start(n, (t => (N("FirestoreClient", "Received new app check token=", t),
  16461. this.appCheckCredentialListener(t, this.user))));
  16462. }
  16463. async getConfiguration() {
  16464. return {
  16465. asyncQueue: this.asyncQueue,
  16466. databaseInfo: this.databaseInfo,
  16467. clientId: this.clientId,
  16468. authCredentials: this.authCredentials,
  16469. appCheckCredentials: this.appCheckCredentials,
  16470. initialUser: this.user,
  16471. maxConcurrentLimboResolutions: 100
  16472. };
  16473. }
  16474. setCredentialChangeListener(t) {
  16475. this.authCredentialListener = t;
  16476. }
  16477. setAppCheckTokenChangeListener(t) {
  16478. this.appCheckCredentialListener = t;
  16479. }
  16480. /**
  16481. * Checks that the client has not been terminated. Ensures that other methods on //
  16482. * this class cannot be called after the client is terminated. //
  16483. */ verifyNotTerminated() {
  16484. if (this.asyncQueue.isShuttingDown) throw new U(q.FAILED_PRECONDITION, "The client has already been terminated.");
  16485. }
  16486. terminate() {
  16487. this.asyncQueue.enterRestrictedMode();
  16488. const t = new K;
  16489. return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {
  16490. try {
  16491. this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(),
  16492. // The credentials provider must be terminated after shutting down the
  16493. // RemoteStore as it will prevent the RemoteStore from retrieving auth
  16494. // tokens.
  16495. this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();
  16496. } catch (e) {
  16497. const n = Ec(e, "Failed to shutdown persistence");
  16498. t.reject(n);
  16499. }
  16500. })), t.promise;
  16501. }
  16502. }
  16503. async function Na(t, e) {
  16504. t.asyncQueue.verifyOperationInProgress(), N("FirestoreClient", "Initializing OfflineComponentProvider");
  16505. const n = await t.getConfiguration();
  16506. await e.initialize(n);
  16507. let s = n.initialUser;
  16508. t.setCredentialChangeListener((async t => {
  16509. s.isEqual(t) || (await iu(e.localStore, t), s = t);
  16510. })),
  16511. // When a user calls clearPersistence() in one client, all other clients
  16512. // need to be terminated to allow the delete to succeed.
  16513. e.persistence.setDatabaseDeletedListener((() => t.terminate())), t._offlineComponents = e;
  16514. }
  16515. async function ka(t, e) {
  16516. t.asyncQueue.verifyOperationInProgress();
  16517. const n = await $a(t);
  16518. N("FirestoreClient", "Initializing OnlineComponentProvider");
  16519. const s = await t.getConfiguration();
  16520. await e.initialize(n, s),
  16521. // The CredentialChangeListener of the online component provider takes
  16522. // precedence over the offline component provider.
  16523. t.setCredentialChangeListener((t => gc(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => gc(e.remoteStore, n))),
  16524. t._onlineComponents = e;
  16525. }
  16526. /**
  16527. * Decides whether the provided error allows us to gracefully disable
  16528. * persistence (as opposed to crashing the client).
  16529. */ function Ma(t) {
  16530. return "FirebaseError" === t.name ? t.code === q.FAILED_PRECONDITION || t.code === q.UNIMPLEMENTED : !("undefined" != typeof DOMException && t instanceof DOMException) || (
  16531. // When the browser is out of quota we could get either quota exceeded
  16532. // or an aborted error depending on whether the error happened during
  16533. // schema migration.
  16534. 22 === t.code || 20 === t.code ||
  16535. // Firefox Private Browsing mode disables IndexedDb and returns
  16536. // INVALID_STATE for any usage.
  16537. 11 === t.code);
  16538. }
  16539. async function $a(t) {
  16540. if (!t._offlineComponents) if (t._uninitializedComponentsProvider) {
  16541. N("FirestoreClient", "Using user provided OfflineComponentProvider");
  16542. try {
  16543. await Na(t, t._uninitializedComponentsProvider._offline);
  16544. } catch (e) {
  16545. const n = e;
  16546. if (!Ma(n)) throw n;
  16547. M("Error using user provided cache. Falling back to memory cache: " + n), await Na(t, new Ea);
  16548. }
  16549. } else N("FirestoreClient", "Using default OfflineComponentProvider"), await Na(t, new Ea);
  16550. return t._offlineComponents;
  16551. }
  16552. async function Oa(t) {
  16553. return t._onlineComponents || (t._uninitializedComponentsProvider ? (N("FirestoreClient", "Using user provided OnlineComponentProvider"),
  16554. await ka(t, t._uninitializedComponentsProvider._online)) : (N("FirestoreClient", "Using default OnlineComponentProvider"),
  16555. await ka(t, new Pa))), t._onlineComponents;
  16556. }
  16557. function Fa(t) {
  16558. return $a(t).then((t => t.persistence));
  16559. }
  16560. function Ba(t) {
  16561. return $a(t).then((t => t.localStore));
  16562. }
  16563. function La(t) {
  16564. return Oa(t).then((t => t.remoteStore));
  16565. }
  16566. function qa(t) {
  16567. return Oa(t).then((t => t.syncEngine));
  16568. }
  16569. function Ua(t) {
  16570. return Oa(t).then((t => t.datastore));
  16571. }
  16572. async function Ka(t) {
  16573. const e = await Oa(t), n = e.eventManager;
  16574. return n.onListen = Gc.bind(null, e.syncEngine), n.onUnlisten = jc.bind(null, e.syncEngine),
  16575. n;
  16576. }
  16577. /** Enables the network connection and re-enqueues all pending operations. */ function Ga(t) {
  16578. return t.asyncQueue.enqueue((async () => {
  16579. const e = await Fa(t), n = await La(t);
  16580. return e.setNetworkEnabled(!0), function(t) {
  16581. const e = L(t);
  16582. return e.vu.delete(0 /* OfflineCause.UserDisabled */), zu(e);
  16583. }(n);
  16584. }));
  16585. }
  16586. /** Disables the network connection. Pending operations will not complete. */ function Qa(t) {
  16587. return t.asyncQueue.enqueue((async () => {
  16588. const e = await Fa(t), n = await La(t);
  16589. return e.setNetworkEnabled(!1), async function(t) {
  16590. const e = L(t);
  16591. e.vu.add(0 /* OfflineCause.UserDisabled */), await Wu(e),
  16592. // Set the OnlineState to Offline so get()s return from cache, etc.
  16593. e.bu.set("Offline" /* OnlineState.Offline */);
  16594. }(n);
  16595. }));
  16596. }
  16597. /**
  16598. * Returns a Promise that resolves when all writes that were pending at the time
  16599. * this method was called received server acknowledgement. An acknowledgement
  16600. * can be either acceptance or rejection.
  16601. */ function ja(t, e) {
  16602. const n = new K;
  16603. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16604. try {
  16605. const s = await function(t, e) {
  16606. const n = L(t);
  16607. return n.persistence.runTransaction("read document", "readonly", (t => n.localDocuments.getDocument(t, e)));
  16608. }(t, e);
  16609. s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new U(q.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"));
  16610. } catch (t) {
  16611. const s = Ec(t, `Failed to get document '${e} from cache`);
  16612. n.reject(s);
  16613. }
  16614. }
  16615. /**
  16616. * Retrieves a latency-compensated document from the backend via a
  16617. * SnapshotListener.
  16618. */ (await Ba(t), e, n))), n.promise;
  16619. }
  16620. function za(t, e, n = {}) {
  16621. const s = new K;
  16622. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16623. const r = new Va({
  16624. next: r => {
  16625. // Remove query first before passing event to user to avoid
  16626. // user actions affecting the now stale query.
  16627. e.enqueueAndForget((() => Sc(t, o)));
  16628. const u = r.docs.has(n);
  16629. !u && r.fromCache ?
  16630. // TODO(dimond): If we're online and the document doesn't
  16631. // exist then we resolve with a doc.exists set to false. If
  16632. // we're offline however, we reject the Promise in this
  16633. // case. Two options: 1) Cache the negative response from
  16634. // the server so we can deliver that even when you're
  16635. // offline 2) Actually reject the Promise in the online case
  16636. // if the document doesn't exist.
  16637. i.reject(new U(q.UNAVAILABLE, "Failed to get document because the client is offline.")) : u && r.fromCache && s && "server" === s.source ? i.reject(new U(q.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(r);
  16638. },
  16639. error: t => i.reject(t)
  16640. }), o = new Nc(Gn(n.path), r, {
  16641. includeMetadataChanges: !0,
  16642. Ku: !0
  16643. });
  16644. return Vc(t, o);
  16645. }(await Ka(t), t.asyncQueue, e, n, s))), s.promise;
  16646. }
  16647. function Wa(t, e) {
  16648. const n = new K;
  16649. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16650. try {
  16651. const s = await fu(t, e,
  16652. /* usePreviousResults= */ !0), i = new Lc(e, s.ir), r = i.sc(s.documents), o = i.applyChanges(r,
  16653. /* updateLimboDocuments= */ !1);
  16654. n.resolve(o.snapshot);
  16655. } catch (t) {
  16656. const s = Ec(t, `Failed to execute query '${e} against cache`);
  16657. n.reject(s);
  16658. }
  16659. }
  16660. /**
  16661. * Retrieves a latency-compensated query snapshot from the backend via a
  16662. * SnapshotListener.
  16663. */ (await Ba(t), e, n))), n.promise;
  16664. }
  16665. function Ha(t, e, n = {}) {
  16666. const s = new K;
  16667. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16668. const r = new Va({
  16669. next: n => {
  16670. // Remove query first before passing event to user to avoid
  16671. // user actions affecting the now stale query.
  16672. e.enqueueAndForget((() => Sc(t, o))), n.fromCache && "server" === s.source ? i.reject(new U(q.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n);
  16673. },
  16674. error: t => i.reject(t)
  16675. }), o = new Nc(n, r, {
  16676. includeMetadataChanges: !0,
  16677. Ku: !0
  16678. });
  16679. return Vc(t, o);
  16680. }(await Ka(t), t.asyncQueue, e, n, s))), s.promise;
  16681. }
  16682. function Ja(t, e) {
  16683. const n = new Va(e);
  16684. return t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16685. L(t).ku.add(e),
  16686. // Immediately fire an initial event, indicating all existing listeners
  16687. // are in-sync.
  16688. e.next();
  16689. }(await Ka(t), n))), () => {
  16690. n.Dc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16691. L(t).ku.delete(e);
  16692. }(await Ka(t), n)));
  16693. };
  16694. }
  16695. /**
  16696. * Takes an updateFunction in which a set of reads and writes can be performed
  16697. * atomically. In the updateFunction, the client can read and write values
  16698. * using the supplied transaction object. After the updateFunction, all
  16699. * changes will be committed. If a retryable error occurs (ex: some other
  16700. * client has changed any of the data referenced), then the updateFunction
  16701. * will be called again after a backoff. If the updateFunction still fails
  16702. * after all retries, then the transaction will be rejected.
  16703. *
  16704. * The transaction object passed to the updateFunction contains methods for
  16705. * accessing documents and collections. Unlike other datastore access, data
  16706. * accessed with the transaction will not reflect local changes that have not
  16707. * been committed. For this reason, it is required that all reads are
  16708. * performed before any writes. Transactions must be performed while online.
  16709. */ function Ya(t, e, n, s) {
  16710. const i = function(t, e) {
  16711. let n;
  16712. n = "string" == typeof t ? hi().encode(t) : t;
  16713. return function(t, e) {
  16714. return new Sa(t, e);
  16715. }(function(t, e) {
  16716. if (t instanceof Uint8Array) return ba(t, e);
  16717. if (t instanceof ArrayBuffer) return ba(new Uint8Array(t), e);
  16718. if (t instanceof ReadableStream) return t.getReader();
  16719. throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
  16720. }(n), e);
  16721. }(n, Fu(e));
  16722. t.asyncQueue.enqueueAndForget((async () => {
  16723. Ta(await qa(t), i, s);
  16724. }));
  16725. }
  16726. function Xa(t, e) {
  16727. return t.asyncQueue.enqueue((async () => function(t, e) {
  16728. const n = L(t);
  16729. return n.persistence.runTransaction("Get named query", "readonly", (t => n.qs.getNamedQuery(t, e)));
  16730. }(await Ba(t), e)));
  16731. }
  16732. function Za(t, e) {
  16733. return t.asyncQueue.enqueue((async () => async function(t, e) {
  16734. const n = L(t), s = n.indexManager, i = [];
  16735. return n.persistence.runTransaction("Configure indexes", "readwrite", (t => s.getFieldIndexes(t).next((n =>
  16736. /**
  16737. * @license
  16738. * Copyright 2017 Google LLC
  16739. *
  16740. * Licensed under the Apache License, Version 2.0 (the "License");
  16741. * you may not use this file except in compliance with the License.
  16742. * You may obtain a copy of the License at
  16743. *
  16744. * http://www.apache.org/licenses/LICENSE-2.0
  16745. *
  16746. * Unless required by applicable law or agreed to in writing, software
  16747. * distributed under the License is distributed on an "AS IS" BASIS,
  16748. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16749. * See the License for the specific language governing permissions and
  16750. * limitations under the License.
  16751. */
  16752. /**
  16753. * Compares two array for equality using comparator. The method computes the
  16754. * intersection and invokes `onAdd` for every element that is in `after` but not
  16755. * `before`. `onRemove` is invoked for every element in `before` but missing
  16756. * from `after`.
  16757. *
  16758. * The method creates a copy of both `before` and `after` and runs in O(n log
  16759. * n), where n is the size of the two lists.
  16760. *
  16761. * @param before - The elements that exist in the original array.
  16762. * @param after - The elements to diff against the original array.
  16763. * @param comparator - The comparator for the elements in before and after.
  16764. * @param onAdd - A function to invoke for every element that is part of `
  16765. * after` but not `before`.
  16766. * @param onRemove - A function to invoke for every element that is part of
  16767. * `before` but not `after`.
  16768. */
  16769. function(t, e, n, s, i) {
  16770. t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);
  16771. const r = t.length, o = e.length;
  16772. let u = 0, c = 0;
  16773. for (;u < o && c < r; ) {
  16774. const r = n(t[c], e[u]);
  16775. r < 0 ?
  16776. // The element was removed if the next element in our ordered
  16777. // walkthrough is only in `before`.
  16778. i(t[c++]) : r > 0 ?
  16779. // The element was added if the next element in our ordered walkthrough
  16780. // is only in `after`.
  16781. s(e[u++]) : (u++, c++);
  16782. }
  16783. for (;u < o; ) s(e[u++]);
  16784. for (;c < r; ) i(t[c++]);
  16785. }(n, e, wt, (e => {
  16786. i.push(s.addFieldIndex(t, e));
  16787. }), (e => {
  16788. i.push(s.deleteFieldIndex(t, e));
  16789. })))).next((() => Rt.waitFor(i)))));
  16790. }
  16791. /**
  16792. * @license
  16793. * Copyright 2019 Google LLC
  16794. *
  16795. * Licensed under the Apache License, Version 2.0 (the "License");
  16796. * you may not use this file except in compliance with the License.
  16797. * You may obtain a copy of the License at
  16798. *
  16799. * http://www.apache.org/licenses/LICENSE-2.0
  16800. *
  16801. * Unless required by applicable law or agreed to in writing, software
  16802. * distributed under the License is distributed on an "AS IS" BASIS,
  16803. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16804. * See the License for the specific language governing permissions and
  16805. * limitations under the License.
  16806. */
  16807. // The format of the LocalStorage key that stores the client state is:
  16808. // firestore_clients_<persistence_prefix>_<instance_key>
  16809. (await Ba(t), e)));
  16810. }
  16811. /**
  16812. * @license
  16813. * Copyright 2023 Google LLC
  16814. *
  16815. * Licensed under the Apache License, Version 2.0 (the "License");
  16816. * you may not use this file except in compliance with the License.
  16817. * You may obtain a copy of the License at
  16818. *
  16819. * http://www.apache.org/licenses/LICENSE-2.0
  16820. *
  16821. * Unless required by applicable law or agreed to in writing, software
  16822. * distributed under the License is distributed on an "AS IS" BASIS,
  16823. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16824. * See the License for the specific language governing permissions and
  16825. * limitations under the License.
  16826. */
  16827. /**
  16828. * Compares two `ExperimentalLongPollingOptions` objects for equality.
  16829. */
  16830. /**
  16831. * Creates and returns a new `ExperimentalLongPollingOptions` with the same
  16832. * option values as the given instance.
  16833. */
  16834. function th(t) {
  16835. const e = {};
  16836. return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e;
  16837. }
  16838. /**
  16839. * @license
  16840. * Copyright 2020 Google LLC
  16841. *
  16842. * Licensed under the Apache License, Version 2.0 (the "License");
  16843. * you may not use this file except in compliance with the License.
  16844. * You may obtain a copy of the License at
  16845. *
  16846. * http://www.apache.org/licenses/LICENSE-2.0
  16847. *
  16848. * Unless required by applicable law or agreed to in writing, software
  16849. * distributed under the License is distributed on an "AS IS" BASIS,
  16850. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16851. * See the License for the specific language governing permissions and
  16852. * limitations under the License.
  16853. */ const eh = new Map;
  16854. /**
  16855. * An instance map that ensures only one Datastore exists per Firestore
  16856. * instance.
  16857. */
  16858. /**
  16859. * @license
  16860. * Copyright 2017 Google LLC
  16861. *
  16862. * Licensed under the Apache License, Version 2.0 (the "License");
  16863. * you may not use this file except in compliance with the License.
  16864. * You may obtain a copy of the License at
  16865. *
  16866. * http://www.apache.org/licenses/LICENSE-2.0
  16867. *
  16868. * Unless required by applicable law or agreed to in writing, software
  16869. * distributed under the License is distributed on an "AS IS" BASIS,
  16870. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16871. * See the License for the specific language governing permissions and
  16872. * limitations under the License.
  16873. */
  16874. function nh(t, e, n) {
  16875. if (!n) throw new U(q.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);
  16876. }
  16877. /**
  16878. * Validates that two boolean options are not set at the same time.
  16879. * @internal
  16880. */ function sh(t, e, n, s) {
  16881. if (!0 === e && !0 === s) throw new U(q.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);
  16882. }
  16883. /**
  16884. * Validates that `path` refers to a document (indicated by the fact it contains
  16885. * an even numbers of segments).
  16886. */ function ih(t) {
  16887. if (!ht.isDocumentKey(t)) throw new U(q.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
  16888. }
  16889. /**
  16890. * Validates that `path` refers to a collection (indicated by the fact it
  16891. * contains an odd numbers of segments).
  16892. */ function rh(t) {
  16893. if (ht.isDocumentKey(t)) throw new U(q.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
  16894. }
  16895. /**
  16896. * Returns true if it's a non-null object without a custom prototype
  16897. * (i.e. excludes Array, Date, etc.).
  16898. */
  16899. /** Returns a string describing the type / value of the provided input. */
  16900. function oh(t) {
  16901. if (void 0 === t) return "undefined";
  16902. if (null === t) return "null";
  16903. if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`),
  16904. JSON.stringify(t);
  16905. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  16906. if ("object" == typeof t) {
  16907. if (t instanceof Array) return "an array";
  16908. {
  16909. const e =
  16910. /** try to get the constructor name for an object. */
  16911. function(t) {
  16912. if (t.constructor) return t.constructor.name;
  16913. return null;
  16914. }
  16915. /**
  16916. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  16917. * underlying instance. Throws if `obj` is not an instance of `T`.
  16918. *
  16919. * This cast is used in the Lite and Full SDK to verify instance types for
  16920. * arguments passed to the public API.
  16921. * @internal
  16922. */ (t);
  16923. return e ? `a custom ${e} object` : "an object";
  16924. }
  16925. }
  16926. return "function" == typeof t ? "a function" : O();
  16927. }
  16928. function uh(t,
  16929. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16930. e) {
  16931. if ("_delegate" in t && (
  16932. // Unwrap Compat types
  16933. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16934. t = t._delegate), !(t instanceof e)) {
  16935. if (e.name === t.constructor.name) throw new U(q.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  16936. {
  16937. const n = oh(t);
  16938. throw new U(q.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);
  16939. }
  16940. }
  16941. return t;
  16942. }
  16943. function ch(t, e) {
  16944. if (e <= 0) throw new U(q.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);
  16945. }
  16946. /**
  16947. * @license
  16948. * Copyright 2020 Google LLC
  16949. *
  16950. * Licensed under the Apache License, Version 2.0 (the "License");
  16951. * you may not use this file except in compliance with the License.
  16952. * You may obtain a copy of the License at
  16953. *
  16954. * http://www.apache.org/licenses/LICENSE-2.0
  16955. *
  16956. * Unless required by applicable law or agreed to in writing, software
  16957. * distributed under the License is distributed on an "AS IS" BASIS,
  16958. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16959. * See the License for the specific language governing permissions and
  16960. * limitations under the License.
  16961. */
  16962. // settings() defaults:
  16963. /**
  16964. * A concrete type describing all the values that can be applied via a
  16965. * user-supplied `FirestoreSettings` object. This is a separate type so that
  16966. * defaults can be supplied and the value can be checked for equality.
  16967. */
  16968. class ah {
  16969. constructor(t) {
  16970. var e, n;
  16971. if (void 0 === t.host) {
  16972. if (void 0 !== t.ssl) throw new U(q.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  16973. this.host = "firestore.googleapis.com", this.ssl = true;
  16974. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  16975. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  16976. this.cache = t.localCache, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  16977. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new U(q.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  16978. this.cacheSizeBytes = t.cacheSizeBytes;
  16979. }
  16980. sh("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling),
  16981. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true :
  16982. // For backwards compatibility, coerce the value to boolean even though
  16983. // the TypeScript compiler has narrowed the type to boolean already.
  16984. // noinspection PointlessBooleanExpressionJS
  16985. this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  16986. this.experimentalLongPollingOptions = th(null !== (n = t.experimentalLongPollingOptions) && void 0 !== n ? n : {}),
  16987. function(t) {
  16988. if (void 0 !== t.timeoutSeconds) {
  16989. if (isNaN(t.timeoutSeconds)) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`);
  16990. if (t.timeoutSeconds < 5) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`);
  16991. if (t.timeoutSeconds > 30) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`);
  16992. }
  16993. }
  16994. /**
  16995. * @license
  16996. * Copyright 2020 Google LLC
  16997. *
  16998. * Licensed under the Apache License, Version 2.0 (the "License");
  16999. * you may not use this file except in compliance with the License.
  17000. * You may obtain a copy of the License at
  17001. *
  17002. * http://www.apache.org/licenses/LICENSE-2.0
  17003. *
  17004. * Unless required by applicable law or agreed to in writing, software
  17005. * distributed under the License is distributed on an "AS IS" BASIS,
  17006. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17007. * See the License for the specific language governing permissions and
  17008. * limitations under the License.
  17009. */
  17010. /**
  17011. * The Cloud Firestore service interface.
  17012. *
  17013. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  17014. */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams;
  17015. }
  17016. isEqual(t) {
  17017. return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && (e = this.experimentalLongPollingOptions,
  17018. n = t.experimentalLongPollingOptions, e.timeoutSeconds === n.timeoutSeconds) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  17019. var e, n;
  17020. }
  17021. }
  17022. class hh {
  17023. /** @hideconstructor */
  17024. constructor(t, e, n, s) {
  17025. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  17026. this._app = s,
  17027. /**
  17028. * Whether it's a Firestore or Firestore Lite instance.
  17029. */
  17030. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new ah({}),
  17031. this._settingsFrozen = !1;
  17032. }
  17033. /**
  17034. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  17035. * instance.
  17036. */ get app() {
  17037. if (!this._app) throw new U(q.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  17038. return this._app;
  17039. }
  17040. get _initialized() {
  17041. return this._settingsFrozen;
  17042. }
  17043. get _terminated() {
  17044. return void 0 !== this._terminateTask;
  17045. }
  17046. _setSettings(t) {
  17047. if (this._settingsFrozen) throw new U(q.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
  17048. this._settings = new ah(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  17049. if (!t) return new Q;
  17050. switch (t.type) {
  17051. case "firstParty":
  17052. return new H(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  17053. case "provider":
  17054. return t.client;
  17055. default:
  17056. throw new U(q.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
  17057. }
  17058. }(t.credentials));
  17059. }
  17060. _getSettings() {
  17061. return this._settings;
  17062. }
  17063. _freezeSettings() {
  17064. return this._settingsFrozen = !0, this._settings;
  17065. }
  17066. _delete() {
  17067. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  17068. }
  17069. /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
  17070. return {
  17071. app: this._app,
  17072. databaseId: this._databaseId,
  17073. settings: this._settings
  17074. };
  17075. }
  17076. /**
  17077. * Terminates all components used by this client. Subclasses can override
  17078. * this method to clean up their own dependencies, but must also call this
  17079. * method.
  17080. *
  17081. * Only ever called once.
  17082. */ _terminate() {
  17083. /**
  17084. * Removes all components associated with the provided instance. Must be called
  17085. * when the `Firestore` instance is terminated.
  17086. */
  17087. return function(t) {
  17088. const e = eh.get(t);
  17089. e && (N("ComponentProvider", "Removing Datastore"), eh.delete(t), e.terminate());
  17090. }(this), Promise.resolve();
  17091. }
  17092. }
  17093. /**
  17094. * Modify this instance to communicate with the Cloud Firestore emulator.
  17095. *
  17096. * Note: This must be called before this instance has been used to do any
  17097. * operations.
  17098. *
  17099. * @param firestore - The `Firestore` instance to configure to connect to the
  17100. * emulator.
  17101. * @param host - the emulator host (ex: localhost).
  17102. * @param port - the emulator port (ex: 9000).
  17103. * @param options.mockUserToken - the mock auth token to use for unit testing
  17104. * Security Rules.
  17105. */ function lh(t, e, n, s = {}) {
  17106. var i;
  17107. const r = (t = uh(t, hh))._getSettings(), o = `${e}:${n}`;
  17108. if ("firestore.googleapis.com" !== r.host && r.host !== o && M("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),
  17109. t._setSettings(Object.assign(Object.assign({}, r), {
  17110. host: o,
  17111. ssl: !1
  17112. })), s.mockUserToken) {
  17113. let e, n;
  17114. if ("string" == typeof s.mockUserToken) e = s.mockUserToken, n = V.MOCK_USER; else {
  17115. // Let createMockUserToken validate first (catches common mistakes like
  17116. // invalid field "uid" and missing field "sub" / "user_id".)
  17117. e = createMockUserToken(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);
  17118. const r = s.mockUserToken.sub || s.mockUserToken.user_id;
  17119. if (!r) throw new U(q.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  17120. n = new V(r);
  17121. }
  17122. t._authCredentials = new j(new G(e, n));
  17123. }
  17124. }
  17125. /**
  17126. * @license
  17127. * Copyright 2020 Google LLC
  17128. *
  17129. * Licensed under the Apache License, Version 2.0 (the "License");
  17130. * you may not use this file except in compliance with the License.
  17131. * You may obtain a copy of the License at
  17132. *
  17133. * http://www.apache.org/licenses/LICENSE-2.0
  17134. *
  17135. * Unless required by applicable law or agreed to in writing, software
  17136. * distributed under the License is distributed on an "AS IS" BASIS,
  17137. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17138. * See the License for the specific language governing permissions and
  17139. * limitations under the License.
  17140. */
  17141. /**
  17142. * A `DocumentReference` refers to a document location in a Firestore database
  17143. * and can be used to write, read, or listen to the location. The document at
  17144. * the referenced location may or may not exist.
  17145. */ class fh {
  17146. /** @hideconstructor */
  17147. constructor(t,
  17148. /**
  17149. * If provided, the `FirestoreDataConverter` associated with this instance.
  17150. */
  17151. e, n) {
  17152. this.converter = e, this._key = n,
  17153. /** The type of this Firestore reference. */
  17154. this.type = "document", this.firestore = t;
  17155. }
  17156. get _path() {
  17157. return this._key.path;
  17158. }
  17159. /**
  17160. * The document's identifier within its collection.
  17161. */ get id() {
  17162. return this._key.path.lastSegment();
  17163. }
  17164. /**
  17165. * A string representing the path of the referenced document (relative
  17166. * to the root of the database).
  17167. */ get path() {
  17168. return this._key.path.canonicalString();
  17169. }
  17170. /**
  17171. * The collection this `DocumentReference` belongs to.
  17172. */ get parent() {
  17173. return new wh(this.firestore, this.converter, this._key.path.popLast());
  17174. }
  17175. withConverter(t) {
  17176. return new fh(this.firestore, t, this._key);
  17177. }
  17178. }
  17179. /**
  17180. * A `Query` refers to a query which you can read or listen to. You can also
  17181. * construct refined `Query` objects by adding filters and ordering.
  17182. */ class dh {
  17183. // This is the lite version of the Query class in the main SDK.
  17184. /** @hideconstructor protected */
  17185. constructor(t,
  17186. /**
  17187. * If provided, the `FirestoreDataConverter` associated with this instance.
  17188. */
  17189. e, n) {
  17190. this.converter = e, this._query = n,
  17191. /** The type of this Firestore reference. */
  17192. this.type = "query", this.firestore = t;
  17193. }
  17194. withConverter(t) {
  17195. return new dh(this.firestore, t, this._query);
  17196. }
  17197. }
  17198. /**
  17199. * A `CollectionReference` object can be used for adding documents, getting
  17200. * document references, and querying for documents (using {@link (query:1)}).
  17201. */ class wh extends dh {
  17202. /** @hideconstructor */
  17203. constructor(t, e, n) {
  17204. super(t, e, Gn(n)), this._path = n,
  17205. /** The type of this Firestore reference. */
  17206. this.type = "collection";
  17207. }
  17208. /** The collection's identifier. */ get id() {
  17209. return this._query.path.lastSegment();
  17210. }
  17211. /**
  17212. * A string representing the path of the referenced collection (relative
  17213. * to the root of the database).
  17214. */ get path() {
  17215. return this._query.path.canonicalString();
  17216. }
  17217. /**
  17218. * A reference to the containing `DocumentReference` if this is a
  17219. * subcollection. If this isn't a subcollection, the reference is null.
  17220. */ get parent() {
  17221. const t = this._path.popLast();
  17222. return t.isEmpty() ? null : new fh(this.firestore,
  17223. /* converter= */ null, new ht(t));
  17224. }
  17225. withConverter(t) {
  17226. return new wh(this.firestore, t, this._path);
  17227. }
  17228. }
  17229. function _h(t, e, ...n) {
  17230. if (t = getModularInstance(t), nh("collection", "path", e), t instanceof hh) {
  17231. const s = ut.fromString(e, ...n);
  17232. return rh(s), new wh(t, /* converter= */ null, s);
  17233. }
  17234. {
  17235. if (!(t instanceof fh || t instanceof wh)) throw new U(q.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17236. const s = t._path.child(ut.fromString(e, ...n));
  17237. return rh(s), new wh(t.firestore,
  17238. /* converter= */ null, s);
  17239. }
  17240. }
  17241. // TODO(firestorelite): Consider using ErrorFactory -
  17242. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  17243. /**
  17244. * Creates and returns a new `Query` instance that includes all documents in the
  17245. * database that are contained in a collection or subcollection with the
  17246. * given `collectionId`.
  17247. *
  17248. * @param firestore - A reference to the root `Firestore` instance.
  17249. * @param collectionId - Identifies the collections to query over. Every
  17250. * collection or subcollection with this ID as the last segment of its path
  17251. * will be included. Cannot contain a slash.
  17252. * @returns The created `Query`.
  17253. */ function mh(t, e) {
  17254. if (t = uh(t, hh), nh("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new U(q.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  17255. return new dh(t,
  17256. /* converter= */ null, function(t) {
  17257. return new Un(ut.emptyPath(), t);
  17258. }(e));
  17259. }
  17260. function gh(t, e, ...n) {
  17261. if (t = getModularInstance(t),
  17262. // We allow omission of 'pathString' but explicitly prohibit passing in both
  17263. // 'undefined' and 'null'.
  17264. 1 === arguments.length && (e = tt.A()), nh("doc", "path", e), t instanceof hh) {
  17265. const s = ut.fromString(e, ...n);
  17266. return ih(s), new fh(t,
  17267. /* converter= */ null, new ht(s));
  17268. }
  17269. {
  17270. if (!(t instanceof fh || t instanceof wh)) throw new U(q.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17271. const s = t._path.child(ut.fromString(e, ...n));
  17272. return ih(s), new fh(t.firestore, t instanceof wh ? t.converter : null, new ht(s));
  17273. }
  17274. }
  17275. /**
  17276. * Returns true if the provided references are equal.
  17277. *
  17278. * @param left - A reference to compare.
  17279. * @param right - A reference to compare.
  17280. * @returns true if the references point to the same location in the same
  17281. * Firestore database.
  17282. */ function yh(t, e) {
  17283. return t = getModularInstance(t), e = getModularInstance(e), (t instanceof fh || t instanceof wh) && (e instanceof fh || e instanceof wh) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);
  17284. }
  17285. /**
  17286. * Returns true if the provided queries point to the same collection and apply
  17287. * the same constraints.
  17288. *
  17289. * @param left - A `Query` to compare.
  17290. * @param right - A `Query` to compare.
  17291. * @returns true if the references point to the same location in the same
  17292. * Firestore database.
  17293. */ function ph(t, e) {
  17294. return t = getModularInstance(t), e = getModularInstance(e), t instanceof dh && e instanceof dh && (t.firestore === e.firestore && Zn(t._query, e._query) && t.converter === e.converter);
  17295. }
  17296. /**
  17297. * @license
  17298. * Copyright 2020 Google LLC
  17299. *
  17300. * Licensed under the Apache License, Version 2.0 (the "License");
  17301. * you may not use this file except in compliance with the License.
  17302. * You may obtain a copy of the License at
  17303. *
  17304. * http://www.apache.org/licenses/LICENSE-2.0
  17305. *
  17306. * Unless required by applicable law or agreed to in writing, software
  17307. * distributed under the License is distributed on an "AS IS" BASIS,
  17308. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17309. * See the License for the specific language governing permissions and
  17310. * limitations under the License.
  17311. */ class Ih {
  17312. constructor() {
  17313. // The last promise in the queue.
  17314. this.Gc = Promise.resolve(),
  17315. // A list of retryable operations. Retryable operations are run in order and
  17316. // retried with backoff.
  17317. this.Qc = [],
  17318. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  17319. // be changed again.
  17320. this.jc = !1,
  17321. // Operations scheduled to be queued in the future. Operations are
  17322. // automatically removed after they are run or canceled.
  17323. this.zc = [],
  17324. // visible for testing
  17325. this.Wc = null,
  17326. // Flag set while there's an outstanding AsyncQueue operation, used for
  17327. // assertion sanity-checks.
  17328. this.Hc = !1,
  17329. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  17330. this.Jc = !1,
  17331. // List of TimerIds to fast-forward delays for.
  17332. this.Yc = [],
  17333. // Backoff timer used to schedule retries for retryable operations
  17334. this.qo = new Bu(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  17335. // Visibility handler that triggers an immediate retry of all retryable
  17336. // operations. Meant to speed up recovery when we regain file system access
  17337. // after page comes into foreground.
  17338. this.Xc = () => {
  17339. const t = Ou();
  17340. t && N("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.qo.Mo();
  17341. };
  17342. const t = Ou();
  17343. t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Xc);
  17344. }
  17345. get isShuttingDown() {
  17346. return this.jc;
  17347. }
  17348. /**
  17349. * Adds a new operation to the queue without waiting for it to complete (i.e.
  17350. * we ignore the Promise result).
  17351. */ enqueueAndForget(t) {
  17352. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17353. this.enqueue(t);
  17354. }
  17355. enqueueAndForgetEvenWhileRestricted(t) {
  17356. this.Zc(),
  17357. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17358. this.ta(t);
  17359. }
  17360. enterRestrictedMode(t) {
  17361. if (!this.jc) {
  17362. this.jc = !0, this.Jc = t || !1;
  17363. const e = Ou();
  17364. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Xc);
  17365. }
  17366. }
  17367. enqueue(t) {
  17368. if (this.Zc(), this.jc)
  17369. // Return a Promise which never resolves.
  17370. return new Promise((() => {}));
  17371. // Create a deferred Promise that we can return to the callee. This
  17372. // allows us to return a "hanging Promise" only to the callee and still
  17373. // advance the queue even when the operation is not run.
  17374. const e = new K;
  17375. return this.ta((() => this.jc && this.Jc ? Promise.resolve() : (t().then(e.resolve, e.reject),
  17376. e.promise))).then((() => e.promise));
  17377. }
  17378. enqueueRetryable(t) {
  17379. this.enqueueAndForget((() => (this.Qc.push(t), this.ea())));
  17380. }
  17381. /**
  17382. * Runs the next operation from the retryable queue. If the operation fails,
  17383. * reschedules with backoff.
  17384. */ async ea() {
  17385. if (0 !== this.Qc.length) {
  17386. try {
  17387. await this.Qc[0](), this.Qc.shift(), this.qo.reset();
  17388. } catch (t) {
  17389. if (!Dt(t)) throw t;
  17390. // Failure will be handled by AsyncQueue
  17391. N("AsyncQueue", "Operation failed with retryable error: " + t);
  17392. }
  17393. this.Qc.length > 0 &&
  17394. // If there are additional operations, we re-schedule `retryNextOp()`.
  17395. // This is necessary to run retryable operations that failed during
  17396. // their initial attempt since we don't know whether they are already
  17397. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  17398. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  17399. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  17400. // call scheduled here.
  17401. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  17402. // new backoff on every call, there is only ever a single additional
  17403. // operation in the queue.
  17404. this.qo.No((() => this.ea()));
  17405. }
  17406. }
  17407. ta(t) {
  17408. const e = this.Gc.then((() => (this.Hc = !0, t().catch((t => {
  17409. this.Wc = t, this.Hc = !1;
  17410. const e =
  17411. /**
  17412. * Chrome includes Error.message in Error.stack. Other browsers do not.
  17413. * This returns expected output of message + stack when available.
  17414. * @param error - Error or FirestoreError
  17415. */
  17416. function(t) {
  17417. let e = t.message || "";
  17418. t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
  17419. return e;
  17420. }
  17421. /**
  17422. * @license
  17423. * Copyright 2017 Google LLC
  17424. *
  17425. * Licensed under the Apache License, Version 2.0 (the "License");
  17426. * you may not use this file except in compliance with the License.
  17427. * You may obtain a copy of the License at
  17428. *
  17429. * http://www.apache.org/licenses/LICENSE-2.0
  17430. *
  17431. * Unless required by applicable law or agreed to in writing, software
  17432. * distributed under the License is distributed on an "AS IS" BASIS,
  17433. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17434. * See the License for the specific language governing permissions and
  17435. * limitations under the License.
  17436. */ (t);
  17437. // Re-throw the error so that this.tail becomes a rejected Promise and
  17438. // all further attempts to chain (via .then) will just short-circuit
  17439. // and return the rejected Promise.
  17440. throw k("INTERNAL UNHANDLED ERROR: ", e), t;
  17441. })).then((t => (this.Hc = !1, t))))));
  17442. return this.Gc = e, e;
  17443. }
  17444. enqueueAfterDelay(t, e, n) {
  17445. this.Zc(),
  17446. // Fast-forward delays for timerIds that have been overriden.
  17447. this.Yc.indexOf(t) > -1 && (e = 0);
  17448. const s = Tc.createAndSchedule(this, t, e, n, (t => this.na(t)));
  17449. return this.zc.push(s), s;
  17450. }
  17451. Zc() {
  17452. this.Wc && O();
  17453. }
  17454. verifyOperationInProgress() {}
  17455. /**
  17456. * Waits until all currently queued tasks are finished executing. Delayed
  17457. * operations are not run.
  17458. */ async sa() {
  17459. // Operations in the queue prior to draining may have enqueued additional
  17460. // operations. Keep draining the queue until the tail is no longer advanced,
  17461. // which indicates that no more new operations were enqueued and that all
  17462. // operations were executed.
  17463. let t;
  17464. do {
  17465. t = this.Gc, await t;
  17466. } while (t !== this.Gc);
  17467. }
  17468. /**
  17469. * For Tests: Determine if a delayed operation with a particular TimerId
  17470. * exists.
  17471. */ ia(t) {
  17472. for (const e of this.zc) if (e.timerId === t) return !0;
  17473. return !1;
  17474. }
  17475. /**
  17476. * For Tests: Runs some or all delayed operations early.
  17477. *
  17478. * @param lastTimerId - Delayed operations up to and including this TimerId
  17479. * will be drained. Pass TimerId.All to run all delayed operations.
  17480. * @returns a Promise that resolves once all operations have been run.
  17481. */ ra(t) {
  17482. // Note that draining may generate more delayed ops, so we do that first.
  17483. return this.sa().then((() => {
  17484. // Run ops in the same order they'd run if they ran naturally.
  17485. this.zc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));
  17486. for (const e of this.zc) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break;
  17487. return this.sa();
  17488. }));
  17489. }
  17490. /**
  17491. * For Tests: Skip all subsequent delays for a timer id.
  17492. */ oa(t) {
  17493. this.Yc.push(t);
  17494. }
  17495. /** Called once a DelayedOperation is run or canceled. */ na(t) {
  17496. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  17497. const e = this.zc.indexOf(t);
  17498. this.zc.splice(e, 1);
  17499. }
  17500. }
  17501. function Th(t) {
  17502. /**
  17503. * Returns true if obj is an object and contains at least one of the specified
  17504. * methods.
  17505. */
  17506. return function(t, e) {
  17507. if ("object" != typeof t || null === t) return !1;
  17508. const n = t;
  17509. for (const t of e) if (t in n && "function" == typeof n[t]) return !0;
  17510. return !1;
  17511. }
  17512. /**
  17513. * @license
  17514. * Copyright 2020 Google LLC
  17515. *
  17516. * Licensed under the Apache License, Version 2.0 (the "License");
  17517. * you may not use this file except in compliance with the License.
  17518. * You may obtain a copy of the License at
  17519. *
  17520. * http://www.apache.org/licenses/LICENSE-2.0
  17521. *
  17522. * Unless required by applicable law or agreed to in writing, software
  17523. * distributed under the License is distributed on an "AS IS" BASIS,
  17524. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17525. * See the License for the specific language governing permissions and
  17526. * limitations under the License.
  17527. */
  17528. /**
  17529. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  17530. * loading, as well as task completion and error events.
  17531. *
  17532. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  17533. */ (t, [ "next", "error", "complete" ]);
  17534. }
  17535. class Eh {
  17536. constructor() {
  17537. this._progressObserver = {}, this._taskCompletionResolver = new K, this._lastProgress = {
  17538. taskState: "Running",
  17539. totalBytes: 0,
  17540. totalDocuments: 0,
  17541. bytesLoaded: 0,
  17542. documentsLoaded: 0
  17543. };
  17544. }
  17545. /**
  17546. * Registers functions to listen to bundle loading progress events.
  17547. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  17548. * each time a Firestore document is loaded from the bundle.
  17549. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  17550. * error, and there should be no more updates after this.
  17551. * @param complete - Called when the loading task is complete.
  17552. */ onProgress(t, e, n) {
  17553. this._progressObserver = {
  17554. next: t,
  17555. error: e,
  17556. complete: n
  17557. };
  17558. }
  17559. /**
  17560. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  17561. *
  17562. * @param onRejected - Called when an error occurs during bundle loading.
  17563. */ catch(t) {
  17564. return this._taskCompletionResolver.promise.catch(t);
  17565. }
  17566. /**
  17567. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  17568. *
  17569. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  17570. * The update will always have its `taskState` set to `"Success"`.
  17571. * @param onRejected - Called when an error occurs during bundle loading.
  17572. */ then(t, e) {
  17573. return this._taskCompletionResolver.promise.then(t, e);
  17574. }
  17575. /**
  17576. * Notifies all observers that bundle loading has completed, with a provided
  17577. * `LoadBundleTaskProgress` object.
  17578. *
  17579. * @private
  17580. */ _completeWith(t) {
  17581. this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(),
  17582. this._taskCompletionResolver.resolve(t);
  17583. }
  17584. /**
  17585. * Notifies all observers that bundle loading has failed, with a provided
  17586. * `Error` as the reason.
  17587. *
  17588. * @private
  17589. */ _failWith(t) {
  17590. this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress),
  17591. this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);
  17592. }
  17593. /**
  17594. * Notifies a progress update of loading a bundle.
  17595. * @param progress - The new progress.
  17596. *
  17597. * @private
  17598. */ _updateProgress(t) {
  17599. this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);
  17600. }
  17601. }
  17602. /**
  17603. * @license
  17604. * Copyright 2020 Google LLC
  17605. *
  17606. * Licensed under the Apache License, Version 2.0 (the "License");
  17607. * you may not use this file except in compliance with the License.
  17608. * You may obtain a copy of the License at
  17609. *
  17610. * http://www.apache.org/licenses/LICENSE-2.0
  17611. *
  17612. * Unless required by applicable law or agreed to in writing, software
  17613. * distributed under the License is distributed on an "AS IS" BASIS,
  17614. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17615. * See the License for the specific language governing permissions and
  17616. * limitations under the License.
  17617. */
  17618. /**
  17619. * Constant used to indicate the LRU garbage collection should be disabled.
  17620. * Set this value as the `cacheSizeBytes` on the settings passed to the
  17621. * {@link Firestore} instance.
  17622. */ const Ah = -1;
  17623. /**
  17624. * The Cloud Firestore service interface.
  17625. *
  17626. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  17627. */ class vh extends hh {
  17628. /** @hideconstructor */
  17629. constructor(t, e, n, s) {
  17630. super(t, e, n, s),
  17631. /**
  17632. * Whether it's a {@link Firestore} or Firestore Lite instance.
  17633. */
  17634. this.type = "firestore", this._queue = new Ih, this._persistenceKey = (null == s ? void 0 : s.name) || "[DEFAULT]";
  17635. }
  17636. _terminate() {
  17637. return this._firestoreClient ||
  17638. // The client must be initialized to ensure that all subsequent API
  17639. // usage throws an exception.
  17640. Vh(this), this._firestoreClient.terminate();
  17641. }
  17642. }
  17643. /**
  17644. * Initializes a new instance of {@link Firestore} with the provided settings.
  17645. * Can only be called before any other function, including
  17646. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  17647. * equivalent to calling {@link (getFirestore:1)}.
  17648. *
  17649. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  17650. * be associated.
  17651. * @param settings - A settings object to configure the {@link Firestore} instance.
  17652. * @param databaseId - The name of the database.
  17653. * @returns A newly initialized {@link Firestore} instance.
  17654. */ function Rh(t, e, n) {
  17655. n || (n = "(default)");
  17656. const s = _getProvider(t, "firestore");
  17657. if (s.isInitialized(n)) {
  17658. const t = s.getImmediate({
  17659. identifier: n
  17660. }), i = s.getOptions(n);
  17661. if (deepEqual(i, e)) return t;
  17662. throw new U(q.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.");
  17663. }
  17664. if (void 0 !== e.cacheSizeBytes && void 0 !== e.localCache) throw new U(q.INVALID_ARGUMENT, "cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");
  17665. if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new U(q.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17666. return s.initialize({
  17667. options: e,
  17668. instanceIdentifier: n
  17669. });
  17670. }
  17671. function Ph(e, n) {
  17672. const s = "object" == typeof e ? e : getApp(), i = "string" == typeof e ? e : n || "(default)", r = _getProvider(s, "firestore").getImmediate({
  17673. identifier: i
  17674. });
  17675. if (!r._initialized) {
  17676. const t = getDefaultEmulatorHostnameAndPort("firestore");
  17677. t && lh(r, ...t);
  17678. }
  17679. return r;
  17680. }
  17681. /**
  17682. * @internal
  17683. */ function bh(t) {
  17684. return t._firestoreClient || Vh(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;
  17685. }
  17686. function Vh(t) {
  17687. var e, n, s;
  17688. const i = t._freezeSettings(), r = function(t, e, n, s) {
  17689. return new $e(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, th(s.experimentalLongPollingOptions), s.useFetchStreams);
  17690. }(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, i);
  17691. t._firestoreClient = new xa(t._authCredentials, t._appCheckCredentials, t._queue, r),
  17692. (null === (n = i.cache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (s = i.cache) || void 0 === s ? void 0 : s._onlineComponentProvider) && (t._firestoreClient._uninitializedComponentsProvider = {
  17693. _offlineKind: i.cache.kind,
  17694. _offline: i.cache._offlineComponentProvider,
  17695. _online: i.cache._onlineComponentProvider
  17696. });
  17697. }
  17698. /**
  17699. * Attempts to enable persistent storage, if possible.
  17700. *
  17701. * Must be called before any other functions (other than
  17702. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  17703. * {@link clearIndexedDbPersistence}.
  17704. *
  17705. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  17706. * returns. Note that even after this failure, the {@link Firestore} instance will
  17707. * remain usable, however offline persistence will be disabled.
  17708. *
  17709. * There are several reasons why this can fail, which can be identified by
  17710. * the `code` on the error.
  17711. *
  17712. * * failed-precondition: The app is already open in another browser tab.
  17713. * * unimplemented: The browser is incompatible with the offline
  17714. * persistence implementation.
  17715. *
  17716. * Persistence cannot be used in a Node.js environment.
  17717. *
  17718. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17719. * @param persistenceSettings - Optional settings object to configure
  17720. * persistence.
  17721. * @returns A `Promise` that represents successfully enabling persistent storage.
  17722. * @deprecated This function will be removed in a future major release. Instead, set
  17723. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17724. * turn on IndexedDb cache. Calling this function when `FirestoreSettings.cache`
  17725. * is already specified will throw an exception.
  17726. */ function Sh(t, e) {
  17727. Bh(t = uh(t, vh));
  17728. const n = bh(t);
  17729. if (n._uninitializedComponentsProvider) throw new U(q.FAILED_PRECONDITION, "SDK cache is already specified.");
  17730. M("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17731. const s = t._freezeSettings(), i = new Pa;
  17732. return Ch(n, i, new va(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
  17733. }
  17734. /**
  17735. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  17736. * across all tabs, all operations share access to local persistence, including
  17737. * shared execution of queries and latency-compensated local document updates
  17738. * across all connected instances.
  17739. *
  17740. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  17741. * it returns. Note that even after this failure, the {@link Firestore} instance will
  17742. * remain usable, however offline persistence will be disabled.
  17743. *
  17744. * There are several reasons why this can fail, which can be identified by
  17745. * the `code` on the error.
  17746. *
  17747. * * failed-precondition: The app is already open in another browser tab and
  17748. * multi-tab is not enabled.
  17749. * * unimplemented: The browser is incompatible with the offline
  17750. * persistence implementation.
  17751. *
  17752. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17753. * @returns A `Promise` that represents successfully enabling persistent
  17754. * storage.
  17755. * @deprecated This function will be removed in a future major release. Instead, set
  17756. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17757. * turn on indexeddb cache. Calling this function when `FirestoreSettings.cache`
  17758. * is already specified will throw an exception.
  17759. */ function Dh(t) {
  17760. Bh(t = uh(t, vh));
  17761. const e = bh(t);
  17762. if (e._uninitializedComponentsProvider) throw new U(q.FAILED_PRECONDITION, "SDK cache is already specified.");
  17763. M("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17764. const n = t._freezeSettings(), s = new Pa;
  17765. return Ch(e, s, new Ra(s, n.cacheSizeBytes));
  17766. }
  17767. /**
  17768. * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
  17769. * If the operation fails with a recoverable error (see
  17770. * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
  17771. * but the client remains usable.
  17772. */ function Ch(t, e, n) {
  17773. const s = new K;
  17774. return t.asyncQueue.enqueue((async () => {
  17775. try {
  17776. await Na(t, n), await ka(t, e), s.resolve();
  17777. } catch (t) {
  17778. const e = t;
  17779. if (!Ma(e)) throw e;
  17780. M("Error enabling indexeddb cache. Falling back to memory cache: " + e), s.reject(e);
  17781. }
  17782. })).then((() => s.promise));
  17783. }
  17784. /**
  17785. * Clears the persistent storage. This includes pending writes and cached
  17786. * documents.
  17787. *
  17788. * Must be called while the {@link Firestore} instance is not started (after the app is
  17789. * terminated or when the app is first initialized). On startup, this function
  17790. * must be called before other functions (other than {@link
  17791. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  17792. * instance is still running, the promise will be rejected with the error code
  17793. * of `failed-precondition`.
  17794. *
  17795. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  17796. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  17797. * dropping existing data but does not attempt to securely overwrite or
  17798. * otherwise make cached data unrecoverable. For applications that are sensitive
  17799. * to the disclosure of cached data in between user sessions, we strongly
  17800. * recommend not enabling persistence at all.
  17801. *
  17802. * @param firestore - The {@link Firestore} instance to clear persistence for.
  17803. * @returns A `Promise` that is resolved when the persistent storage is
  17804. * cleared. Otherwise, the promise is rejected with an error.
  17805. */ function xh(t) {
  17806. if (t._initialized && !t._terminated) throw new U(q.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  17807. const e = new K;
  17808. return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {
  17809. try {
  17810. await async function(t) {
  17811. if (!bt.D()) return Promise.resolve();
  17812. const e = t + "main";
  17813. await bt.delete(e);
  17814. }(Zo(t._databaseId, t._persistenceKey)), e.resolve();
  17815. } catch (t) {
  17816. e.reject(t);
  17817. }
  17818. })), e.promise;
  17819. }
  17820. /**
  17821. * Waits until all currently pending writes for the active user have been
  17822. * acknowledged by the backend.
  17823. *
  17824. * The returned promise resolves immediately if there are no outstanding writes.
  17825. * Otherwise, the promise waits for all previously issued writes (including
  17826. * those written in a previous app session), but it does not wait for writes
  17827. * that were added after the function is called. If you want to wait for
  17828. * additional writes, call `waitForPendingWrites()` again.
  17829. *
  17830. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  17831. * changes.
  17832. *
  17833. * @returns A `Promise` which resolves when all currently pending writes have been
  17834. * acknowledged by the backend.
  17835. */ function Nh(t) {
  17836. return function(t) {
  17837. const e = new K;
  17838. return t.asyncQueue.enqueueAndForget((async () => Zc(await qa(t), e))), e.promise;
  17839. }(bh(t = uh(t, vh)));
  17840. }
  17841. /**
  17842. * Re-enables use of the network for this {@link Firestore} instance after a prior
  17843. * call to {@link disableNetwork}.
  17844. *
  17845. * @returns A `Promise` that is resolved once the network has been enabled.
  17846. */ function kh(t) {
  17847. return Ga(bh(t = uh(t, vh)));
  17848. }
  17849. /**
  17850. * Disables network usage for this instance. It can be re-enabled via {@link
  17851. * enableNetwork}. While the network is disabled, any snapshot listeners,
  17852. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  17853. * operations will be queued until the network is restored.
  17854. *
  17855. * @returns A `Promise` that is resolved once the network has been disabled.
  17856. */ function Mh(t) {
  17857. return Qa(bh(t = uh(t, vh)));
  17858. }
  17859. /**
  17860. * Terminates the provided {@link Firestore} instance.
  17861. *
  17862. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  17863. * may be used. Any other function will throw a `FirestoreError`.
  17864. *
  17865. * To restart after termination, create a new instance of FirebaseFirestore with
  17866. * {@link (getFirestore:1)}.
  17867. *
  17868. * Termination does not cancel any pending writes, and any promises that are
  17869. * awaiting a response from the server will not be resolved. If you have
  17870. * persistence enabled, the next time you start this instance, it will resume
  17871. * sending these writes to the server.
  17872. *
  17873. * Note: Under normal circumstances, calling `terminate()` is not required. This
  17874. * function is useful only when you want to force this instance to release all
  17875. * of its resources or in combination with `clearIndexedDbPersistence()` to
  17876. * ensure that all local state is destroyed between test runs.
  17877. *
  17878. * @returns A `Promise` that is resolved when the instance has been successfully
  17879. * terminated.
  17880. */ function $h(t) {
  17881. return _removeServiceInstance(t.app, "firestore", t._databaseId.database), t._delete();
  17882. }
  17883. /**
  17884. * Loads a Firestore bundle into the local cache.
  17885. *
  17886. * @param firestore - The {@link Firestore} instance to load bundles for.
  17887. * @param bundleData - An object representing the bundle to be loaded. Valid
  17888. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  17889. *
  17890. * @returns A `LoadBundleTask` object, which notifies callers with progress
  17891. * updates, and completion or error events. It can be used as a
  17892. * `Promise<LoadBundleTaskProgress>`.
  17893. */ function Oh(t, e) {
  17894. const n = bh(t = uh(t, vh)), s = new Eh;
  17895. return Ya(n, t._databaseId, e, s), s;
  17896. }
  17897. /**
  17898. * Reads a Firestore {@link Query} from local cache, identified by the given
  17899. * name.
  17900. *
  17901. * The named queries are packaged into bundles on the server side (along
  17902. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  17903. * in local cache, use this method to extract a {@link Query} by name.
  17904. *
  17905. * @param firestore - The {@link Firestore} instance to read the query from.
  17906. * @param name - The name of the query.
  17907. * @returns A `Promise` that is resolved with the Query or `null`.
  17908. */ function Fh(t, e) {
  17909. return Xa(bh(t = uh(t, vh)), e).then((e => e ? new dh(t, null, e.query) : null));
  17910. }
  17911. function Bh(t) {
  17912. if (t._initialized || t._terminated) throw new U(q.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");
  17913. }
  17914. /**
  17915. * @license
  17916. * Copyright 2020 Google LLC
  17917. *
  17918. * Licensed under the Apache License, Version 2.0 (the "License");
  17919. * you may not use this file except in compliance with the License.
  17920. * You may obtain a copy of the License at
  17921. *
  17922. * http://www.apache.org/licenses/LICENSE-2.0
  17923. *
  17924. * Unless required by applicable law or agreed to in writing, software
  17925. * distributed under the License is distributed on an "AS IS" BASIS,
  17926. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17927. * See the License for the specific language governing permissions and
  17928. * limitations under the License.
  17929. */
  17930. /**
  17931. * @license
  17932. * Copyright 2022 Google LLC
  17933. *
  17934. * Licensed under the Apache License, Version 2.0 (the "License");
  17935. * you may not use this file except in compliance with the License.
  17936. * You may obtain a copy of the License at
  17937. *
  17938. * http://www.apache.org/licenses/LICENSE-2.0
  17939. *
  17940. * Unless required by applicable law or agreed to in writing, software
  17941. * distributed under the License is distributed on an "AS IS" BASIS,
  17942. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17943. * See the License for the specific language governing permissions and
  17944. * limitations under the License.
  17945. */
  17946. /**
  17947. * Represents an aggregation that can be performed by Firestore.
  17948. */
  17949. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  17950. class Lh {
  17951. /**
  17952. * Create a new AggregateField<T>
  17953. * @param _aggregateType Specifies the type of aggregation operation to perform.
  17954. * @param _internalFieldPath Optionally specifies the field that is aggregated.
  17955. * @internal
  17956. */
  17957. constructor(
  17958. // TODO (sum/avg) make aggregateType public when the feature is supported
  17959. t = "count", e) {
  17960. this._aggregateType = t, this._internalFieldPath = e,
  17961. /** A type string to uniquely identify instances of this class. */
  17962. this.type = "AggregateField";
  17963. }
  17964. }
  17965. /**
  17966. * The results of executing an aggregation query.
  17967. */ class qh {
  17968. /** @hideconstructor */
  17969. constructor(t, e, n) {
  17970. this._userDataWriter = e, this._data = n,
  17971. /** A type string to uniquely identify instances of this class. */
  17972. this.type = "AggregateQuerySnapshot", this.query = t;
  17973. }
  17974. /**
  17975. * Returns the results of the aggregations performed over the underlying
  17976. * query.
  17977. *
  17978. * The keys of the returned object will be the same as those of the
  17979. * `AggregateSpec` object specified to the aggregation method, and the values
  17980. * will be the corresponding aggregation result.
  17981. *
  17982. * @returns The results of the aggregations performed over the underlying
  17983. * query.
  17984. */ data() {
  17985. return this._userDataWriter.convertObjectMap(this._data);
  17986. }
  17987. }
  17988. /**
  17989. * @license
  17990. * Copyright 2020 Google LLC
  17991. *
  17992. * Licensed under the Apache License, Version 2.0 (the "License");
  17993. * you may not use this file except in compliance with the License.
  17994. * You may obtain a copy of the License at
  17995. *
  17996. * http://www.apache.org/licenses/LICENSE-2.0
  17997. *
  17998. * Unless required by applicable law or agreed to in writing, software
  17999. * distributed under the License is distributed on an "AS IS" BASIS,
  18000. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18001. * See the License for the specific language governing permissions and
  18002. * limitations under the License.
  18003. */
  18004. /**
  18005. * An immutable object representing an array of bytes.
  18006. */ class Uh {
  18007. /** @hideconstructor */
  18008. constructor(t) {
  18009. this._byteString = t;
  18010. }
  18011. /**
  18012. * Creates a new `Bytes` object from the given Base64 string, converting it to
  18013. * bytes.
  18014. *
  18015. * @param base64 - The Base64 string used to create the `Bytes` object.
  18016. */ static fromBase64String(t) {
  18017. try {
  18018. return new Uh(Ve.fromBase64String(t));
  18019. } catch (t) {
  18020. throw new U(q.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + t);
  18021. }
  18022. }
  18023. /**
  18024. * Creates a new `Bytes` object from the given Uint8Array.
  18025. *
  18026. * @param array - The Uint8Array used to create the `Bytes` object.
  18027. */ static fromUint8Array(t) {
  18028. return new Uh(Ve.fromUint8Array(t));
  18029. }
  18030. /**
  18031. * Returns the underlying bytes as a Base64-encoded string.
  18032. *
  18033. * @returns The Base64-encoded string created from the `Bytes` object.
  18034. */ toBase64() {
  18035. return this._byteString.toBase64();
  18036. }
  18037. /**
  18038. * Returns the underlying bytes in a new `Uint8Array`.
  18039. *
  18040. * @returns The Uint8Array created from the `Bytes` object.
  18041. */ toUint8Array() {
  18042. return this._byteString.toUint8Array();
  18043. }
  18044. /**
  18045. * Returns a string representation of the `Bytes` object.
  18046. *
  18047. * @returns A string representation of the `Bytes` object.
  18048. */ toString() {
  18049. return "Bytes(base64: " + this.toBase64() + ")";
  18050. }
  18051. /**
  18052. * Returns true if this `Bytes` object is equal to the provided one.
  18053. *
  18054. * @param other - The `Bytes` object to compare against.
  18055. * @returns true if this `Bytes` object is equal to the provided one.
  18056. */ isEqual(t) {
  18057. return this._byteString.isEqual(t._byteString);
  18058. }
  18059. }
  18060. /**
  18061. * @license
  18062. * Copyright 2020 Google LLC
  18063. *
  18064. * Licensed under the Apache License, Version 2.0 (the "License");
  18065. * you may not use this file except in compliance with the License.
  18066. * You may obtain a copy of the License at
  18067. *
  18068. * http://www.apache.org/licenses/LICENSE-2.0
  18069. *
  18070. * Unless required by applicable law or agreed to in writing, software
  18071. * distributed under the License is distributed on an "AS IS" BASIS,
  18072. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18073. * See the License for the specific language governing permissions and
  18074. * limitations under the License.
  18075. */
  18076. /**
  18077. * A `FieldPath` refers to a field in a document. The path may consist of a
  18078. * single field name (referring to a top-level field in the document), or a
  18079. * list of field names (referring to a nested field in the document).
  18080. *
  18081. * Create a `FieldPath` by providing field names. If more than one field
  18082. * name is provided, the path will point to a nested field in a document.
  18083. */ class Kh {
  18084. /**
  18085. * Creates a `FieldPath` from the provided field names. If more than one field
  18086. * name is provided, the path will point to a nested field in a document.
  18087. *
  18088. * @param fieldNames - A list of field names.
  18089. */
  18090. constructor(...t) {
  18091. for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new U(q.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  18092. this._internalPath = new at(t);
  18093. }
  18094. /**
  18095. * Returns true if this `FieldPath` is equal to the provided one.
  18096. *
  18097. * @param other - The `FieldPath` to compare against.
  18098. * @returns true if this `FieldPath` is equal to the provided one.
  18099. */ isEqual(t) {
  18100. return this._internalPath.isEqual(t._internalPath);
  18101. }
  18102. }
  18103. /**
  18104. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  18105. * It can be used in queries to sort or filter by the document ID.
  18106. */ function Gh() {
  18107. return new Kh("__name__");
  18108. }
  18109. /**
  18110. * @license
  18111. * Copyright 2020 Google LLC
  18112. *
  18113. * Licensed under the Apache License, Version 2.0 (the "License");
  18114. * you may not use this file except in compliance with the License.
  18115. * You may obtain a copy of the License at
  18116. *
  18117. * http://www.apache.org/licenses/LICENSE-2.0
  18118. *
  18119. * Unless required by applicable law or agreed to in writing, software
  18120. * distributed under the License is distributed on an "AS IS" BASIS,
  18121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18122. * See the License for the specific language governing permissions and
  18123. * limitations under the License.
  18124. */
  18125. /**
  18126. * Sentinel values that can be used when writing document fields with `set()`
  18127. * or `update()`.
  18128. */ class Qh {
  18129. /**
  18130. * @param _methodName - The public API endpoint that returns this class.
  18131. * @hideconstructor
  18132. */
  18133. constructor(t) {
  18134. this._methodName = t;
  18135. }
  18136. }
  18137. /**
  18138. * @license
  18139. * Copyright 2017 Google LLC
  18140. *
  18141. * Licensed under the Apache License, Version 2.0 (the "License");
  18142. * you may not use this file except in compliance with the License.
  18143. * You may obtain a copy of the License at
  18144. *
  18145. * http://www.apache.org/licenses/LICENSE-2.0
  18146. *
  18147. * Unless required by applicable law or agreed to in writing, software
  18148. * distributed under the License is distributed on an "AS IS" BASIS,
  18149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18150. * See the License for the specific language governing permissions and
  18151. * limitations under the License.
  18152. */
  18153. /**
  18154. * An immutable object representing a geographic location in Firestore. The
  18155. * location is represented as latitude/longitude pair.
  18156. *
  18157. * Latitude values are in the range of [-90, 90].
  18158. * Longitude values are in the range of [-180, 180].
  18159. */ class jh {
  18160. /**
  18161. * Creates a new immutable `GeoPoint` object with the provided latitude and
  18162. * longitude values.
  18163. * @param latitude - The latitude as number between -90 and 90.
  18164. * @param longitude - The longitude as number between -180 and 180.
  18165. */
  18166. constructor(t, e) {
  18167. if (!isFinite(t) || t < -90 || t > 90) throw new U(q.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
  18168. if (!isFinite(e) || e < -180 || e > 180) throw new U(q.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
  18169. this._lat = t, this._long = e;
  18170. }
  18171. /**
  18172. * The latitude of this `GeoPoint` instance.
  18173. */ get latitude() {
  18174. return this._lat;
  18175. }
  18176. /**
  18177. * The longitude of this `GeoPoint` instance.
  18178. */ get longitude() {
  18179. return this._long;
  18180. }
  18181. /**
  18182. * Returns true if this `GeoPoint` is equal to the provided one.
  18183. *
  18184. * @param other - The `GeoPoint` to compare against.
  18185. * @returns true if this `GeoPoint` is equal to the provided one.
  18186. */ isEqual(t) {
  18187. return this._lat === t._lat && this._long === t._long;
  18188. }
  18189. /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
  18190. return {
  18191. latitude: this._lat,
  18192. longitude: this._long
  18193. };
  18194. }
  18195. /**
  18196. * Actually private to JS consumers of our API, so this function is prefixed
  18197. * with an underscore.
  18198. */ _compareTo(t) {
  18199. return et(this._lat, t._lat) || et(this._long, t._long);
  18200. }
  18201. }
  18202. /**
  18203. * @license
  18204. * Copyright 2017 Google LLC
  18205. *
  18206. * Licensed under the Apache License, Version 2.0 (the "License");
  18207. * you may not use this file except in compliance with the License.
  18208. * You may obtain a copy of the License at
  18209. *
  18210. * http://www.apache.org/licenses/LICENSE-2.0
  18211. *
  18212. * Unless required by applicable law or agreed to in writing, software
  18213. * distributed under the License is distributed on an "AS IS" BASIS,
  18214. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18215. * See the License for the specific language governing permissions and
  18216. * limitations under the License.
  18217. */ const zh = /^__.*__$/;
  18218. /** The result of parsing document data (e.g. for a setData call). */ class Wh {
  18219. constructor(t, e, n) {
  18220. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18221. }
  18222. toMutation(t, e) {
  18223. return null !== this.fieldMask ? new zs(t, this.data, this.fieldMask, e, this.fieldTransforms) : new js(t, this.data, e, this.fieldTransforms);
  18224. }
  18225. }
  18226. /** The result of parsing "update" data (i.e. for an updateData call). */ class Hh {
  18227. constructor(t,
  18228. // The fieldMask does not include document transforms.
  18229. e, n) {
  18230. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18231. }
  18232. toMutation(t, e) {
  18233. return new zs(t, this.data, this.fieldMask, e, this.fieldTransforms);
  18234. }
  18235. }
  18236. function Jh(t) {
  18237. switch (t) {
  18238. case 0 /* UserDataSource.Set */ :
  18239. // fall through
  18240. case 2 /* UserDataSource.MergeSet */ :
  18241. // fall through
  18242. case 1 /* UserDataSource.Update */ :
  18243. return !0;
  18244. case 3 /* UserDataSource.Argument */ :
  18245. case 4 /* UserDataSource.ArrayArgument */ :
  18246. return !1;
  18247. default:
  18248. throw O();
  18249. }
  18250. }
  18251. /** A "context" object passed around while parsing user data. */ class Yh {
  18252. /**
  18253. * Initializes a ParseContext with the given source and path.
  18254. *
  18255. * @param settings - The settings for the parser.
  18256. * @param databaseId - The database ID of the Firestore instance.
  18257. * @param serializer - The serializer to use to generate the Value proto.
  18258. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  18259. * rather than throw.
  18260. * @param fieldTransforms - A mutable list of field transforms encountered
  18261. * while parsing the data.
  18262. * @param fieldMask - A mutable list of field paths encountered while parsing
  18263. * the data.
  18264. *
  18265. * TODO(b/34871131): We don't support array paths right now, so path can be
  18266. * null to indicate the context represents any location within an array (in
  18267. * which case certain features will not work and errors will be somewhat
  18268. * compromised).
  18269. */
  18270. constructor(t, e, n, s, i, r) {
  18271. this.settings = t, this.databaseId = e, this.serializer = n, this.ignoreUndefinedProperties = s,
  18272. // Minor hack: If fieldTransforms is undefined, we assume this is an
  18273. // external call and we need to validate the entire path.
  18274. void 0 === i && this.ua(), this.fieldTransforms = i || [], this.fieldMask = r || [];
  18275. }
  18276. get path() {
  18277. return this.settings.path;
  18278. }
  18279. get ca() {
  18280. return this.settings.ca;
  18281. }
  18282. /** Returns a new context with the specified settings overwritten. */ aa(t) {
  18283. return new Yh(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  18284. }
  18285. ha(t) {
  18286. var e;
  18287. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({
  18288. path: n,
  18289. la: !1
  18290. });
  18291. return s.fa(t), s;
  18292. }
  18293. da(t) {
  18294. var e;
  18295. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({
  18296. path: n,
  18297. la: !1
  18298. });
  18299. return s.ua(), s;
  18300. }
  18301. wa(t) {
  18302. // TODO(b/34871131): We don't support array paths right now; so make path
  18303. // undefined.
  18304. return this.aa({
  18305. path: void 0,
  18306. la: !0
  18307. });
  18308. }
  18309. _a(t) {
  18310. return gl(t, this.settings.methodName, this.settings.ma || !1, this.path, this.settings.ga);
  18311. }
  18312. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {
  18313. return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));
  18314. }
  18315. ua() {
  18316. // TODO(b/34871131): Remove null check once we have proper paths for fields
  18317. // within arrays.
  18318. if (this.path) for (let t = 0; t < this.path.length; t++) this.fa(this.path.get(t));
  18319. }
  18320. fa(t) {
  18321. if (0 === t.length) throw this._a("Document fields must not be empty");
  18322. if (Jh(this.ca) && zh.test(t)) throw this._a('Document fields cannot begin and end with "__"');
  18323. }
  18324. }
  18325. /**
  18326. * Helper for parsing raw user input (provided via the API) into internal model
  18327. * classes.
  18328. */ class Xh {
  18329. constructor(t, e, n) {
  18330. this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = n || Fu(t);
  18331. }
  18332. /** Creates a new top-level parse context. */ ya(t, e, n, s = !1) {
  18333. return new Yh({
  18334. ca: t,
  18335. methodName: e,
  18336. ga: n,
  18337. path: at.emptyPath(),
  18338. la: !1,
  18339. ma: s
  18340. }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  18341. }
  18342. }
  18343. function Zh(t) {
  18344. const e = t._freezeSettings(), n = Fu(t._databaseId);
  18345. return new Xh(t._databaseId, !!e.ignoreUndefinedProperties, n);
  18346. }
  18347. /** Parse document data from a set() call. */ function tl(t, e, n, s, i, r = {}) {
  18348. const o = t.ya(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);
  18349. dl("Data must be an object, but it was:", o, s);
  18350. const u = ll(s, o);
  18351. let c, a;
  18352. if (r.merge) c = new Re(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {
  18353. const t = [];
  18354. for (const s of r.mergeFields) {
  18355. const i = wl(e, s, n);
  18356. if (!o.contains(i)) throw new U(q.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);
  18357. yl(t, i) || t.push(i);
  18358. }
  18359. c = new Re(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));
  18360. } else c = null, a = o.fieldTransforms;
  18361. return new Wh(new un(u), c, a);
  18362. }
  18363. class el extends Qh {
  18364. _toFieldTransform(t) {
  18365. if (2 /* UserDataSource.MergeSet */ !== t.ca) throw 1 /* UserDataSource.Update */ === t.ca ? t._a(`${this._methodName}() can only appear at the top level of your update data`) : t._a(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
  18366. // No transform to add for a delete, but we need to add it to our
  18367. // fieldMask so it gets deleted.
  18368. return t.fieldMask.push(t.path), null;
  18369. }
  18370. isEqual(t) {
  18371. return t instanceof el;
  18372. }
  18373. }
  18374. /**
  18375. * Creates a child context for parsing SerializableFieldValues.
  18376. *
  18377. * This is different than calling `ParseContext.contextWith` because it keeps
  18378. * the fieldTransforms and fieldMask separate.
  18379. *
  18380. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  18381. * Although these values are used with writes, any elements in these FieldValues
  18382. * are not considered writes since they cannot contain any FieldValue sentinels,
  18383. * etc.
  18384. *
  18385. * @param fieldValue - The sentinel FieldValue for which to create a child
  18386. * context.
  18387. * @param context - The parent context.
  18388. * @param arrayElement - Whether or not the FieldValue has an array.
  18389. */ function nl(t, e, n) {
  18390. return new Yh({
  18391. ca: 3 /* UserDataSource.Argument */ ,
  18392. ga: e.settings.ga,
  18393. methodName: t._methodName,
  18394. la: n
  18395. }, e.databaseId, e.serializer, e.ignoreUndefinedProperties);
  18396. }
  18397. class sl extends Qh {
  18398. _toFieldTransform(t) {
  18399. return new Ms(t.path, new bs);
  18400. }
  18401. isEqual(t) {
  18402. return t instanceof sl;
  18403. }
  18404. }
  18405. class il extends Qh {
  18406. constructor(t, e) {
  18407. super(t), this.pa = e;
  18408. }
  18409. _toFieldTransform(t) {
  18410. const e = nl(this, t,
  18411. /*array=*/ !0), n = this.pa.map((t => hl(t, e))), s = new Vs(n);
  18412. return new Ms(t.path, s);
  18413. }
  18414. isEqual(t) {
  18415. // TODO(mrschmidt): Implement isEquals
  18416. return this === t;
  18417. }
  18418. }
  18419. class rl extends Qh {
  18420. constructor(t, e) {
  18421. super(t), this.pa = e;
  18422. }
  18423. _toFieldTransform(t) {
  18424. const e = nl(this, t,
  18425. /*array=*/ !0), n = this.pa.map((t => hl(t, e))), s = new Ds(n);
  18426. return new Ms(t.path, s);
  18427. }
  18428. isEqual(t) {
  18429. // TODO(mrschmidt): Implement isEquals
  18430. return this === t;
  18431. }
  18432. }
  18433. class ol extends Qh {
  18434. constructor(t, e) {
  18435. super(t), this.Ia = e;
  18436. }
  18437. _toFieldTransform(t) {
  18438. const e = new xs(t.serializer, Es(t.serializer, this.Ia));
  18439. return new Ms(t.path, e);
  18440. }
  18441. isEqual(t) {
  18442. // TODO(mrschmidt): Implement isEquals
  18443. return this === t;
  18444. }
  18445. }
  18446. /** Parse update data from an update() call. */ function ul(t, e, n, s) {
  18447. const i = t.ya(1 /* UserDataSource.Update */ , e, n);
  18448. dl("Data must be an object, but it was:", i, s);
  18449. const r = [], o = un.empty();
  18450. ge(s, ((t, s) => {
  18451. const u = ml(e, t, n);
  18452. // For Compat types, we have to "extract" the underlying types before
  18453. // performing validation.
  18454. s = getModularInstance(s);
  18455. const c = i.da(u);
  18456. if (s instanceof el)
  18457. // Add it to the field mask, but don't add anything to updateData.
  18458. r.push(u); else {
  18459. const t = hl(s, c);
  18460. null != t && (r.push(u), o.set(u, t));
  18461. }
  18462. }));
  18463. const u = new Re(r);
  18464. return new Hh(o, u, i.fieldTransforms);
  18465. }
  18466. /** Parse update data from a list of field/value arguments. */ function cl(t, e, n, s, i, r) {
  18467. const o = t.ya(1 /* UserDataSource.Update */ , e, n), u = [ wl(e, s, n) ], c = [ i ];
  18468. if (r.length % 2 != 0) throw new U(q.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
  18469. for (let t = 0; t < r.length; t += 2) u.push(wl(e, r[t])), c.push(r[t + 1]);
  18470. const a = [], h = un.empty();
  18471. // We iterate in reverse order to pick the last value for a field if the
  18472. // user specified the field multiple times.
  18473. for (let t = u.length - 1; t >= 0; --t) if (!yl(a, u[t])) {
  18474. const e = u[t];
  18475. let n = c[t];
  18476. // For Compat types, we have to "extract" the underlying types before
  18477. // performing validation.
  18478. n = getModularInstance(n);
  18479. const s = o.da(e);
  18480. if (n instanceof el)
  18481. // Add it to the field mask, but don't add anything to updateData.
  18482. a.push(e); else {
  18483. const t = hl(n, s);
  18484. null != t && (a.push(e), h.set(e, t));
  18485. }
  18486. }
  18487. const l = new Re(a);
  18488. return new Hh(h, l, o.fieldTransforms);
  18489. }
  18490. /**
  18491. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  18492. * bound).
  18493. *
  18494. * @param allowArrays - Whether the query value is an array that may directly
  18495. * contain additional arrays (e.g. the operand of an `in` query).
  18496. */ function al(t, e, n, s = !1) {
  18497. return hl(n, t.ya(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  18498. }
  18499. /**
  18500. * Parses user data to Protobuf Values.
  18501. *
  18502. * @param input - Data to be parsed.
  18503. * @param context - A context object representing the current path being parsed,
  18504. * the source of the data being parsed, etc.
  18505. * @returns The parsed value, or null if the value was a FieldValue sentinel
  18506. * that should not be included in the resulting parsed data.
  18507. */ function hl(t, e) {
  18508. if (fl(
  18509. // Unwrap the API type from the Compat SDK. This will return the API type
  18510. // from firestore-exp.
  18511. t = getModularInstance(t))) return dl("Unsupported field value:", e, t), ll(t, e);
  18512. if (t instanceof Qh)
  18513. // FieldValues usually parse into transforms (except deleteField())
  18514. // in which case we do not want to include this field in our parsed data
  18515. // (as doing so will overwrite the field directly prior to the transform
  18516. // trying to transform it). So we don't add this location to
  18517. // context.fieldMask and we return null as our parsing result.
  18518. /**
  18519. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  18520. * context.fieldTransforms.
  18521. */
  18522. return function(t, e) {
  18523. // Sentinels are only supported with writes, and not within arrays.
  18524. if (!Jh(e.ca)) throw e._a(`${t._methodName}() can only be used with update() and set()`);
  18525. if (!e.path) throw e._a(`${t._methodName}() is not currently supported inside arrays`);
  18526. const n = t._toFieldTransform(e);
  18527. n && e.fieldTransforms.push(n);
  18528. }
  18529. /**
  18530. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  18531. *
  18532. * @returns The parsed value
  18533. */ (t, e), null;
  18534. if (void 0 === t && e.ignoreUndefinedProperties)
  18535. // If the input is undefined it can never participate in the fieldMask, so
  18536. // don't handle this below. If `ignoreUndefinedProperties` is false,
  18537. // `parseScalarValue` will reject an undefined value.
  18538. return null;
  18539. if (
  18540. // If context.path is null we are inside an array and we don't support
  18541. // field mask paths more granular than the top-level array.
  18542. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  18543. // TODO(b/34871131): Include the path containing the array in the error
  18544. // message.
  18545. // In the case of IN queries, the parsed data is an array (representing
  18546. // the set of values to be included for the IN query) that may directly
  18547. // contain additional arrays (each representing an individual field
  18548. // value), so we disable this validation.
  18549. if (e.settings.la && 4 /* UserDataSource.ArrayArgument */ !== e.ca) throw e._a("Nested arrays are not supported");
  18550. return function(t, e) {
  18551. const n = [];
  18552. let s = 0;
  18553. for (const i of t) {
  18554. let t = hl(i, e.wa(s));
  18555. null == t && (
  18556. // Just include nulls in the array for fields being replaced with a
  18557. // sentinel.
  18558. t = {
  18559. nullValue: "NULL_VALUE"
  18560. }), n.push(t), s++;
  18561. }
  18562. return {
  18563. arrayValue: {
  18564. values: n
  18565. }
  18566. };
  18567. }(t, e);
  18568. }
  18569. return function(t, e) {
  18570. if (null === (t = getModularInstance(t))) return {
  18571. nullValue: "NULL_VALUE"
  18572. };
  18573. if ("number" == typeof t) return Es(e.serializer, t);
  18574. if ("boolean" == typeof t) return {
  18575. booleanValue: t
  18576. };
  18577. if ("string" == typeof t) return {
  18578. stringValue: t
  18579. };
  18580. if (t instanceof Date) {
  18581. const n = it.fromDate(t);
  18582. return {
  18583. timestampValue: Di(e.serializer, n)
  18584. };
  18585. }
  18586. if (t instanceof it) {
  18587. // Firestore backend truncates precision down to microseconds. To ensure
  18588. // offline mode works the same with regards to truncation, perform the
  18589. // truncation immediately without waiting for the backend to do that.
  18590. const n = new it(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  18591. return {
  18592. timestampValue: Di(e.serializer, n)
  18593. };
  18594. }
  18595. if (t instanceof jh) return {
  18596. geoPointValue: {
  18597. latitude: t.latitude,
  18598. longitude: t.longitude
  18599. }
  18600. };
  18601. if (t instanceof Uh) return {
  18602. bytesValue: Ci(e.serializer, t._byteString)
  18603. };
  18604. if (t instanceof fh) {
  18605. const n = e.databaseId, s = t.firestore._databaseId;
  18606. if (!s.isEqual(n)) throw e._a(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);
  18607. return {
  18608. referenceValue: ki(t.firestore._databaseId || e.databaseId, t._key.path)
  18609. };
  18610. }
  18611. throw e._a(`Unsupported field value: ${oh(t)}`);
  18612. }
  18613. /**
  18614. * Checks whether an object looks like a JSON object that should be converted
  18615. * into a struct. Normal class/prototype instances are considered to look like
  18616. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  18617. * GeoPoints, etc. are not considered to look like JSON objects since they map
  18618. * to specific FieldValue types other than ObjectValue.
  18619. */ (t, e);
  18620. }
  18621. function ll(t, e) {
  18622. const n = {};
  18623. return ye(t) ?
  18624. // If we encounter an empty object, we explicitly add it to the update
  18625. // mask to ensure that the server creates a map entry.
  18626. e.path && e.path.length > 0 && e.fieldMask.push(e.path) : ge(t, ((t, s) => {
  18627. const i = hl(s, e.ha(t));
  18628. null != i && (n[t] = i);
  18629. })), {
  18630. mapValue: {
  18631. fields: n
  18632. }
  18633. };
  18634. }
  18635. function fl(t) {
  18636. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof it || t instanceof jh || t instanceof Uh || t instanceof fh || t instanceof Qh);
  18637. }
  18638. function dl(t, e, n) {
  18639. if (!fl(n) || !function(t) {
  18640. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  18641. }(n)) {
  18642. const s = oh(n);
  18643. throw "an object" === s ? e._a(t + " a custom object") : e._a(t + " " + s);
  18644. }
  18645. }
  18646. /**
  18647. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  18648. */ function wl(t, e, n) {
  18649. if ((
  18650. // If required, replace the FieldPath Compat class with with the firestore-exp
  18651. // FieldPath.
  18652. e = getModularInstance(e)) instanceof Kh) return e._internalPath;
  18653. if ("string" == typeof e) return ml(t, e);
  18654. throw gl("Field path arguments must be of type string or ", t,
  18655. /* hasConverter= */ !1,
  18656. /* path= */ void 0, n);
  18657. }
  18658. /**
  18659. * Matches any characters in a field path string that are reserved.
  18660. */ const _l = new RegExp("[~\\*/\\[\\]]");
  18661. /**
  18662. * Wraps fromDotSeparatedString with an error message about the method that
  18663. * was thrown.
  18664. * @param methodName - The publicly visible method name
  18665. * @param path - The dot-separated string form of a field path which will be
  18666. * split on dots.
  18667. * @param targetDoc - The document against which the field path will be
  18668. * evaluated.
  18669. */ function ml(t, e, n) {
  18670. if (e.search(_l) >= 0) throw gl(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t,
  18671. /* hasConverter= */ !1,
  18672. /* path= */ void 0, n);
  18673. try {
  18674. return new Kh(...e.split("."))._internalPath;
  18675. } catch (s) {
  18676. throw gl(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t,
  18677. /* hasConverter= */ !1,
  18678. /* path= */ void 0, n);
  18679. }
  18680. }
  18681. function gl(t, e, n, s, i) {
  18682. const r = s && !s.isEmpty(), o = void 0 !== i;
  18683. let u = `Function ${e}() called with invalid data`;
  18684. n && (u += " (via `toFirestore()`)"), u += ". ";
  18685. let c = "";
  18686. return (r || o) && (c += " (found", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`),
  18687. c += ")"), new U(q.INVALID_ARGUMENT, u + t + c);
  18688. }
  18689. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function yl(t, e) {
  18690. return t.some((t => t.isEqual(e)));
  18691. }
  18692. /**
  18693. * @license
  18694. * Copyright 2020 Google LLC
  18695. *
  18696. * Licensed under the Apache License, Version 2.0 (the "License");
  18697. * you may not use this file except in compliance with the License.
  18698. * You may obtain a copy of the License at
  18699. *
  18700. * http://www.apache.org/licenses/LICENSE-2.0
  18701. *
  18702. * Unless required by applicable law or agreed to in writing, software
  18703. * distributed under the License is distributed on an "AS IS" BASIS,
  18704. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18705. * See the License for the specific language governing permissions and
  18706. * limitations under the License.
  18707. */
  18708. /**
  18709. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18710. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18711. * get a specific field.
  18712. *
  18713. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18714. * access will return 'undefined'. You can use the `exists()` method to
  18715. * explicitly verify a document's existence.
  18716. */ class pl {
  18717. // Note: This class is stripped down version of the DocumentSnapshot in
  18718. // the legacy SDK. The changes are:
  18719. // - No support for SnapshotMetadata.
  18720. // - No support for SnapshotOptions.
  18721. /** @hideconstructor protected */
  18722. constructor(t, e, n, s, i) {
  18723. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s,
  18724. this._converter = i;
  18725. }
  18726. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
  18727. return this._key.path.lastSegment();
  18728. }
  18729. /**
  18730. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  18731. */ get ref() {
  18732. return new fh(this._firestore, this._converter, this._key);
  18733. }
  18734. /**
  18735. * Signals whether or not the document at the snapshot's location exists.
  18736. *
  18737. * @returns true if the document exists.
  18738. */ exists() {
  18739. return null !== this._document;
  18740. }
  18741. /**
  18742. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18743. * the document doesn't exist.
  18744. *
  18745. * @returns An `Object` containing all fields in the document or `undefined`
  18746. * if the document doesn't exist.
  18747. */ data() {
  18748. if (this._document) {
  18749. if (this._converter) {
  18750. // We only want to use the converter and create a new DocumentSnapshot
  18751. // if a converter has been provided.
  18752. const t = new Il(this._firestore, this._userDataWriter, this._key, this._document,
  18753. /* converter= */ null);
  18754. return this._converter.fromFirestore(t);
  18755. }
  18756. return this._userDataWriter.convertValue(this._document.data.value);
  18757. }
  18758. }
  18759. /**
  18760. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18761. * document or field doesn't exist.
  18762. *
  18763. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18764. * field.
  18765. * @returns The data at the specified field location or undefined if no such
  18766. * field exists in the document.
  18767. */
  18768. // We are using `any` here to avoid an explicit cast by our users.
  18769. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18770. get(t) {
  18771. if (this._document) {
  18772. const e = this._document.data.field(Tl("DocumentSnapshot.get", t));
  18773. if (null !== e) return this._userDataWriter.convertValue(e);
  18774. }
  18775. }
  18776. }
  18777. /**
  18778. * A `QueryDocumentSnapshot` contains data read from a document in your
  18779. * Firestore database as part of a query. The document is guaranteed to exist
  18780. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18781. * specific field.
  18782. *
  18783. * A `QueryDocumentSnapshot` offers the same API surface as a
  18784. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18785. * `exists` property will always be true and `data()` will never return
  18786. * 'undefined'.
  18787. */ class Il extends pl {
  18788. /**
  18789. * Retrieves all fields in the document as an `Object`.
  18790. *
  18791. * @override
  18792. * @returns An `Object` containing all fields in the document.
  18793. */
  18794. data() {
  18795. return super.data();
  18796. }
  18797. }
  18798. /**
  18799. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  18800. */ function Tl(t, e) {
  18801. return "string" == typeof e ? ml(t, e) : e instanceof Kh ? e._internalPath : e._delegate._internalPath;
  18802. }
  18803. /**
  18804. * @license
  18805. * Copyright 2020 Google LLC
  18806. *
  18807. * Licensed under the Apache License, Version 2.0 (the "License");
  18808. * you may not use this file except in compliance with the License.
  18809. * You may obtain a copy of the License at
  18810. *
  18811. * http://www.apache.org/licenses/LICENSE-2.0
  18812. *
  18813. * Unless required by applicable law or agreed to in writing, software
  18814. * distributed under the License is distributed on an "AS IS" BASIS,
  18815. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18816. * See the License for the specific language governing permissions and
  18817. * limitations under the License.
  18818. */ function El(t) {
  18819. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new U(q.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
  18820. }
  18821. /**
  18822. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  18823. * to a Firestore query.
  18824. */ class Al {}
  18825. /**
  18826. * A `QueryConstraint` is used to narrow the set of documents returned by a
  18827. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  18828. * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
  18829. * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and
  18830. * can then be passed to {@link (query:1)} to create a new query instance that
  18831. * also contains this `QueryConstraint`.
  18832. */ class vl extends Al {}
  18833. function Rl(t, e, ...n) {
  18834. let s = [];
  18835. e instanceof Al && s.push(e), s = s.concat(n), function(t) {
  18836. const e = t.filter((t => t instanceof Vl)).length, n = t.filter((t => t instanceof Pl)).length;
  18837. if (e > 1 || e > 0 && n > 0) throw new U(q.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");
  18838. }
  18839. /**
  18840. * @license
  18841. * Copyright 2020 Google LLC
  18842. *
  18843. * Licensed under the Apache License, Version 2.0 (the "License");
  18844. * you may not use this file except in compliance with the License.
  18845. * You may obtain a copy of the License at
  18846. *
  18847. * http://www.apache.org/licenses/LICENSE-2.0
  18848. *
  18849. * Unless required by applicable law or agreed to in writing, software
  18850. * distributed under the License is distributed on an "AS IS" BASIS,
  18851. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18852. * See the License for the specific language governing permissions and
  18853. * limitations under the License.
  18854. */
  18855. /**
  18856. * Converts Firestore's internal types to the JavaScript types that we expose
  18857. * to the user.
  18858. *
  18859. * @internal
  18860. */ (s);
  18861. for (const e of s) t = e._apply(t);
  18862. return t;
  18863. }
  18864. /**
  18865. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  18866. * a Firestore query by filtering on one or more document fields.
  18867. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  18868. * be passed to {@link (query:1)} to create a new query instance that also contains
  18869. * this `QueryFieldFilterConstraint`.
  18870. */ class Pl extends vl {
  18871. /**
  18872. * @internal
  18873. */
  18874. constructor(t, e, n) {
  18875. super(), this._field = t, this._op = e, this._value = n,
  18876. /** The type of this query constraint */
  18877. this.type = "where";
  18878. }
  18879. static _create(t, e, n) {
  18880. return new Pl(t, e, n);
  18881. }
  18882. _apply(t) {
  18883. const e = this._parse(t);
  18884. return Ql(t._query, e), new dh(t.firestore, t.converter, Yn(t._query, e));
  18885. }
  18886. _parse(t) {
  18887. const e = Zh(t.firestore), n = function(t, e, n, s, i, r, o) {
  18888. let u;
  18889. if (i.isKeyField()) {
  18890. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === r || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new U(q.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);
  18891. if ("in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r) {
  18892. Gl(o, r);
  18893. const e = [];
  18894. for (const n of o) e.push(Kl(s, t, n));
  18895. u = {
  18896. arrayValue: {
  18897. values: e
  18898. }
  18899. };
  18900. } else u = Kl(s, t, o);
  18901. } else "in" /* Operator.IN */ !== r && "not-in" /* Operator.NOT_IN */ !== r && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== r || Gl(o, r),
  18902. u = al(n, e, o,
  18903. /* allowArrays= */ "in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r);
  18904. return mn.create(i, r, u);
  18905. }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value);
  18906. return n;
  18907. }
  18908. }
  18909. /**
  18910. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  18911. * must contain the specified field and that the value should satisfy the
  18912. * relation constraint provided.
  18913. *
  18914. * @param fieldPath - The path to compare
  18915. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  18916. * "&lt;=", "!=").
  18917. * @param value - The value for comparison
  18918. * @returns The created {@link QueryFieldFilterConstraint}.
  18919. */ function bl(t, e, n) {
  18920. const s = e, i = Tl("where", t);
  18921. return Pl._create(i, s, n);
  18922. }
  18923. /**
  18924. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  18925. * returned by a Firestore query by performing the logical OR or AND of multiple
  18926. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  18927. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  18928. * {@link and} and can then be passed to {@link (query:1)} to create a new query
  18929. * instance that also contains the `QueryCompositeFilterConstraint`.
  18930. */ class Vl extends Al {
  18931. /**
  18932. * @internal
  18933. */
  18934. constructor(
  18935. /** The type of this query constraint */
  18936. t, e) {
  18937. super(), this.type = t, this._queryConstraints = e;
  18938. }
  18939. static _create(t, e) {
  18940. return new Vl(t, e);
  18941. }
  18942. _parse(t) {
  18943. const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));
  18944. return 1 === e.length ? e[0] : gn.create(e, this._getOperator());
  18945. }
  18946. _apply(t) {
  18947. const e = this._parse(t);
  18948. return 0 === e.getFilters().length ? t : (function(t, e) {
  18949. let n = t;
  18950. const s = e.getFlattenedFilters();
  18951. for (const t of s) Ql(n, t), n = Yn(n, t);
  18952. }
  18953. // Checks if any of the provided filter operators are included in the given list of filters and
  18954. // returns the first one that is, or null if none are.
  18955. (t._query, e), new dh(t.firestore, t.converter, Yn(t._query, e)));
  18956. }
  18957. _getQueryConstraints() {
  18958. return this._queryConstraints;
  18959. }
  18960. _getOperator() {
  18961. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  18962. }
  18963. }
  18964. /**
  18965. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  18966. * the given filter constraints. A disjunction filter includes a document if it
  18967. * satisfies any of the given filters.
  18968. *
  18969. * @param queryConstraints - Optional. The list of
  18970. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  18971. * created with calls to {@link where}, {@link or}, or {@link and}.
  18972. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18973. */ function Sl(...t) {
  18974. // Only support QueryFilterConstraints
  18975. return t.forEach((t => zl("or", t))), Vl._create("or" /* CompositeOperator.OR */ , t);
  18976. }
  18977. /**
  18978. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  18979. * the given filter constraints. A conjunction filter includes a document if it
  18980. * satisfies all of the given filters.
  18981. *
  18982. * @param queryConstraints - Optional. The list of
  18983. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  18984. * created with calls to {@link where}, {@link or}, or {@link and}.
  18985. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18986. */ function Dl(...t) {
  18987. // Only support QueryFilterConstraints
  18988. return t.forEach((t => zl("and", t))), Vl._create("and" /* CompositeOperator.AND */ , t);
  18989. }
  18990. /**
  18991. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  18992. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  18993. * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query
  18994. * instance that also contains this `QueryOrderByConstraint`.
  18995. *
  18996. * Note: Documents that do not contain the orderBy field will not be present in
  18997. * the query result.
  18998. */ class Cl extends vl {
  18999. /**
  19000. * @internal
  19001. */
  19002. constructor(t, e) {
  19003. super(), this._field = t, this._direction = e,
  19004. /** The type of this query constraint */
  19005. this.type = "orderBy";
  19006. }
  19007. static _create(t, e) {
  19008. return new Cl(t, e);
  19009. }
  19010. _apply(t) {
  19011. const e = function(t, e, n) {
  19012. if (null !== t.startAt) throw new U(q.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  19013. if (null !== t.endAt) throw new U(q.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  19014. const s = new dn(e, n);
  19015. return function(t, e) {
  19016. if (null === jn(t)) {
  19017. // This is the first order by. It must match any inequality.
  19018. const n = zn(t);
  19019. null !== n && jl(t, n, e.field);
  19020. }
  19021. }(t, s), s;
  19022. }
  19023. /**
  19024. * Create a `Bound` from a query and a document.
  19025. *
  19026. * Note that the `Bound` will always include the key of the document
  19027. * and so only the provided document will compare equal to the returned
  19028. * position.
  19029. *
  19030. * Will throw if the document does not contain all fields of the order by
  19031. * of the query or if any of the fields in the order by are an uncommitted
  19032. * server timestamp.
  19033. */ (t._query, this._field, this._direction);
  19034. return new dh(t.firestore, t.converter, function(t, e) {
  19035. // TODO(dimond): validate that orderBy does not list the same key twice.
  19036. const n = t.explicitOrderBy.concat([ e ]);
  19037. return new Un(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  19038. }(t._query, e));
  19039. }
  19040. }
  19041. /**
  19042. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  19043. * specified field, optionally in descending order instead of ascending.
  19044. *
  19045. * Note: Documents that do not contain the specified field will not be present
  19046. * in the query result.
  19047. *
  19048. * @param fieldPath - The field to sort by.
  19049. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  19050. * not specified, order will be ascending.
  19051. * @returns The created {@link QueryOrderByConstraint}.
  19052. */ function xl(t, e = "asc") {
  19053. const n = e, s = Tl("orderBy", t);
  19054. return Cl._create(s, n);
  19055. }
  19056. /**
  19057. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  19058. * a Firestore query.
  19059. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  19060. * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new
  19061. * query instance that also contains this `QueryLimitConstraint`.
  19062. */ class Nl extends vl {
  19063. /**
  19064. * @internal
  19065. */
  19066. constructor(
  19067. /** The type of this query constraint */
  19068. t, e, n) {
  19069. super(), this.type = t, this._limit = e, this._limitType = n;
  19070. }
  19071. static _create(t, e, n) {
  19072. return new Nl(t, e, n);
  19073. }
  19074. _apply(t) {
  19075. return new dh(t.firestore, t.converter, Xn(t._query, this._limit, this._limitType));
  19076. }
  19077. }
  19078. /**
  19079. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  19080. * documents.
  19081. *
  19082. * @param limit - The maximum number of items to return.
  19083. * @returns The created {@link QueryLimitConstraint}.
  19084. */ function kl(t) {
  19085. return ch("limit", t), Nl._create("limit", t, "F" /* LimitType.First */);
  19086. }
  19087. /**
  19088. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  19089. * documents.
  19090. *
  19091. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  19092. * otherwise an exception will be thrown during execution.
  19093. *
  19094. * @param limit - The maximum number of items to return.
  19095. * @returns The created {@link QueryLimitConstraint}.
  19096. */ function Ml(t) {
  19097. return ch("limitToLast", t), Nl._create("limitToLast", t, "L" /* LimitType.Last */);
  19098. }
  19099. /**
  19100. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  19101. * result set returned by a Firestore query.
  19102. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  19103. * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a
  19104. * new query instance that also contains this `QueryStartAtConstraint`.
  19105. */ class $l extends vl {
  19106. /**
  19107. * @internal
  19108. */
  19109. constructor(
  19110. /** The type of this query constraint */
  19111. t, e, n) {
  19112. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  19113. }
  19114. static _create(t, e, n) {
  19115. return new $l(t, e, n);
  19116. }
  19117. _apply(t) {
  19118. const e = Ul(t, this.type, this._docOrFields, this._inclusive);
  19119. return new dh(t.firestore, t.converter, function(t, e) {
  19120. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  19121. }(t._query, e));
  19122. }
  19123. }
  19124. function Ol(...t) {
  19125. return $l._create("startAt", t,
  19126. /*inclusive=*/ !0);
  19127. }
  19128. function Fl(...t) {
  19129. return $l._create("startAfter", t,
  19130. /*inclusive=*/ !1);
  19131. }
  19132. /**
  19133. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  19134. * result set returned by a Firestore query.
  19135. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  19136. * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new
  19137. * query instance that also contains this `QueryEndAtConstraint`.
  19138. */ class Bl extends vl {
  19139. /**
  19140. * @internal
  19141. */
  19142. constructor(
  19143. /** The type of this query constraint */
  19144. t, e, n) {
  19145. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  19146. }
  19147. static _create(t, e, n) {
  19148. return new Bl(t, e, n);
  19149. }
  19150. _apply(t) {
  19151. const e = Ul(t, this.type, this._docOrFields, this._inclusive);
  19152. return new dh(t.firestore, t.converter, function(t, e) {
  19153. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  19154. }(t._query, e));
  19155. }
  19156. }
  19157. function Ll(...t) {
  19158. return Bl._create("endBefore", t,
  19159. /*inclusive=*/ !1);
  19160. }
  19161. function ql(...t) {
  19162. return Bl._create("endAt", t,
  19163. /*inclusive=*/ !0);
  19164. }
  19165. /** Helper function to create a bound from a document or fields */ function Ul(t, e, n, s) {
  19166. if (n[0] = getModularInstance(n[0]), n[0] instanceof pl) return function(t, e, n, s, i) {
  19167. if (!s) throw new U(q.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);
  19168. const r = [];
  19169. // Because people expect to continue/end a query at the exact document
  19170. // provided, we need to use the implicit sort order rather than the explicit
  19171. // sort order, because it's guaranteed to contain the document key. That way
  19172. // the position becomes unambiguous and the query continues/ends exactly at
  19173. // the provided document. Without the key (by using the explicit sort
  19174. // orders), multiple documents could match the position, yielding duplicate
  19175. // results.
  19176. for (const n of Hn(t)) if (n.field.isKeyField()) r.push(We(e, s.key)); else {
  19177. const t = s.data.field(n.field);
  19178. if (Ne(t)) throw new U(q.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
  19179. if (null === t) {
  19180. const t = n.field.canonicalString();
  19181. throw new U(q.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);
  19182. }
  19183. r.push(t);
  19184. }
  19185. return new hn(r, i);
  19186. }
  19187. /**
  19188. * Converts a list of field values to a `Bound` for the given query.
  19189. */ (t._query, t.firestore._databaseId, e, n[0]._document, s);
  19190. {
  19191. const i = Zh(t.firestore);
  19192. return function(t, e, n, s, i, r) {
  19193. // Use explicit order by's because it has to match the query the user made
  19194. const o = t.explicitOrderBy;
  19195. if (i.length > o.length) throw new U(q.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
  19196. const u = [];
  19197. for (let r = 0; r < i.length; r++) {
  19198. const c = i[r];
  19199. if (o[r].field.isKeyField()) {
  19200. if ("string" != typeof c) throw new U(q.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);
  19201. if (!Wn(t) && -1 !== c.indexOf("/")) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);
  19202. const n = t.path.child(ut.fromString(c));
  19203. if (!ht.isDocumentKey(n)) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
  19204. const i = new ht(n);
  19205. u.push(We(e, i));
  19206. } else {
  19207. const t = al(n, s, c);
  19208. u.push(t);
  19209. }
  19210. }
  19211. return new hn(u, r);
  19212. }
  19213. /**
  19214. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  19215. * appropriate errors if the value is anything other than a `DocumentReference`
  19216. * or `string`, or if the string is malformed.
  19217. */ (t._query, t.firestore._databaseId, i, e, n, s);
  19218. }
  19219. }
  19220. function Kl(t, e, n) {
  19221. if ("string" == typeof (n = getModularInstance(n))) {
  19222. if ("" === n) throw new U(q.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  19223. if (!Wn(e) && -1 !== n.indexOf("/")) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
  19224. const s = e.path.child(ut.fromString(n));
  19225. if (!ht.isDocumentKey(s)) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);
  19226. return We(t, new ht(s));
  19227. }
  19228. if (n instanceof fh) return We(t, n._key);
  19229. throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${oh(n)}.`);
  19230. }
  19231. /**
  19232. * Validates that the value passed into a disjunctive filter satisfies all
  19233. * array requirements.
  19234. */ function Gl(t, e) {
  19235. if (!Array.isArray(t) || 0 === t.length) throw new U(q.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
  19236. }
  19237. /**
  19238. * Given an operator, returns the set of operators that cannot be used with it.
  19239. *
  19240. * This is not a comprehensive check, and this function should be removed in the
  19241. * long term. Validations should occur in the Firestore backend.
  19242. *
  19243. * Operators in a query must adhere to the following set of rules:
  19244. * 1. Only one inequality per query.
  19245. * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  19246. */ function Ql(t, e) {
  19247. if (e.isInequality()) {
  19248. const n = zn(t), s = e.field;
  19249. if (null !== n && !n.isEqual(s)) throw new U(q.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${s.toString()}'`);
  19250. const i = jn(t);
  19251. null !== i && jl(t, s, i);
  19252. }
  19253. const n = function(t, e) {
  19254. for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;
  19255. return null;
  19256. }(t.filters, function(t) {
  19257. switch (t) {
  19258. case "!=" /* Operator.NOT_EQUAL */ :
  19259. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  19260. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  19261. case "in" /* Operator.IN */ :
  19262. return [ "not-in" /* Operator.NOT_IN */ ];
  19263. case "not-in" /* Operator.NOT_IN */ :
  19264. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  19265. default:
  19266. return [];
  19267. }
  19268. }(e.op));
  19269. if (null !== n)
  19270. // Special case when it's a duplicate op to give a slightly clearer error message.
  19271. throw n === e.op ? new U(q.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new U(q.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
  19272. }
  19273. function jl(t, e, n) {
  19274. if (!n.isEqual(e)) throw new U(q.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);
  19275. }
  19276. function zl(t, e) {
  19277. if (!(e instanceof Pl || e instanceof Vl)) throw new U(q.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  19278. }
  19279. class Wl {
  19280. convertValue(t, e = "none") {
  19281. switch (Le(t)) {
  19282. case 0 /* TypeOrder.NullValue */ :
  19283. return null;
  19284. case 1 /* TypeOrder.BooleanValue */ :
  19285. return t.booleanValue;
  19286. case 2 /* TypeOrder.NumberValue */ :
  19287. return Ce(t.integerValue || t.doubleValue);
  19288. case 3 /* TypeOrder.TimestampValue */ :
  19289. return this.convertTimestamp(t.timestampValue);
  19290. case 4 /* TypeOrder.ServerTimestampValue */ :
  19291. return this.convertServerTimestamp(t, e);
  19292. case 5 /* TypeOrder.StringValue */ :
  19293. return t.stringValue;
  19294. case 6 /* TypeOrder.BlobValue */ :
  19295. return this.convertBytes(xe(t.bytesValue));
  19296. case 7 /* TypeOrder.RefValue */ :
  19297. return this.convertReference(t.referenceValue);
  19298. case 8 /* TypeOrder.GeoPointValue */ :
  19299. return this.convertGeoPoint(t.geoPointValue);
  19300. case 9 /* TypeOrder.ArrayValue */ :
  19301. return this.convertArray(t.arrayValue, e);
  19302. case 10 /* TypeOrder.ObjectValue */ :
  19303. return this.convertObject(t.mapValue, e);
  19304. default:
  19305. throw O();
  19306. }
  19307. }
  19308. convertObject(t, e) {
  19309. return this.convertObjectMap(t.fields, e);
  19310. }
  19311. /**
  19312. * @internal
  19313. */ convertObjectMap(t, e = "none") {
  19314. const n = {};
  19315. return ge(t, ((t, s) => {
  19316. n[t] = this.convertValue(s, e);
  19317. })), n;
  19318. }
  19319. convertGeoPoint(t) {
  19320. return new jh(Ce(t.latitude), Ce(t.longitude));
  19321. }
  19322. convertArray(t, e) {
  19323. return (t.values || []).map((t => this.convertValue(t, e)));
  19324. }
  19325. convertServerTimestamp(t, e) {
  19326. switch (e) {
  19327. case "previous":
  19328. const n = ke(t);
  19329. return null == n ? null : this.convertValue(n, e);
  19330. case "estimate":
  19331. return this.convertTimestamp(Me(t));
  19332. default:
  19333. return null;
  19334. }
  19335. }
  19336. convertTimestamp(t) {
  19337. const e = De(t);
  19338. return new it(e.seconds, e.nanos);
  19339. }
  19340. convertDocumentKey(t, e) {
  19341. const n = ut.fromString(t);
  19342. F(ur(n));
  19343. const s = new Oe(n.get(1), n.get(3)), i = new ht(n.popFirst(5));
  19344. return s.isEqual(e) ||
  19345. // TODO(b/64130202): Somehow support foreign references.
  19346. k(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),
  19347. i;
  19348. }
  19349. }
  19350. /**
  19351. * @license
  19352. * Copyright 2020 Google LLC
  19353. *
  19354. * Licensed under the Apache License, Version 2.0 (the "License");
  19355. * you may not use this file except in compliance with the License.
  19356. * You may obtain a copy of the License at
  19357. *
  19358. * http://www.apache.org/licenses/LICENSE-2.0
  19359. *
  19360. * Unless required by applicable law or agreed to in writing, software
  19361. * distributed under the License is distributed on an "AS IS" BASIS,
  19362. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19363. * See the License for the specific language governing permissions and
  19364. * limitations under the License.
  19365. */
  19366. /**
  19367. * Converts custom model object of type T into `DocumentData` by applying the
  19368. * converter if it exists.
  19369. *
  19370. * This function is used when converting user objects to `DocumentData`
  19371. * because we want to provide the user with a more specific error message if
  19372. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  19373. * call.
  19374. */ function Hl(t, e, n) {
  19375. let s;
  19376. // Cast to `any` in order to satisfy the union type constraint on
  19377. // toFirestore().
  19378. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19379. return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e,
  19380. s;
  19381. }
  19382. class Jl extends Wl {
  19383. constructor(t) {
  19384. super(), this.firestore = t;
  19385. }
  19386. convertBytes(t) {
  19387. return new Uh(t);
  19388. }
  19389. convertReference(t) {
  19390. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19391. return new fh(this.firestore, /* converter= */ null, e);
  19392. }
  19393. }
  19394. /**
  19395. * @license
  19396. * Copyright 2022 Google LLC
  19397. *
  19398. * Licensed under the Apache License, Version 2.0 (the "License");
  19399. * you may not use this file except in compliance with the License.
  19400. * You may obtain a copy of the License at
  19401. *
  19402. * http://www.apache.org/licenses/LICENSE-2.0
  19403. *
  19404. * Unless required by applicable law or agreed to in writing, software
  19405. * distributed under the License is distributed on an "AS IS" BASIS,
  19406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19407. * See the License for the specific language governing permissions and
  19408. * limitations under the License.
  19409. */
  19410. /**
  19411. * Create an AggregateField object that can be used to compute the sum of
  19412. * a specified field over a range of documents in the result set of a query.
  19413. * @param field Specifies the field to sum across the result set.
  19414. * @internal TODO (sum/avg) remove when public
  19415. */ function Yl(t) {
  19416. return new Lh("sum", wl("sum", t));
  19417. }
  19418. /**
  19419. * Create an AggregateField object that can be used to compute the average of
  19420. * a specified field over a range of documents in the result set of a query.
  19421. * @param field Specifies the field to average across the result set.
  19422. * @internal TODO (sum/avg) remove when public
  19423. */ function Xl(t) {
  19424. return new Lh("avg", wl("average", t));
  19425. }
  19426. /**
  19427. * Create an AggregateField object that can be used to compute the count of
  19428. * documents in the result set of a query.
  19429. * @internal TODO (sum/avg) remove when public
  19430. */ function Zl() {
  19431. return new Lh("count");
  19432. }
  19433. /**
  19434. * Compares two 'AggregateField` instances for equality.
  19435. *
  19436. * @param left Compare this AggregateField to the `right`.
  19437. * @param right Compare this AggregateField to the `left`.
  19438. * @internal TODO (sum/avg) remove when public
  19439. */ function tf(t, e) {
  19440. var n, s;
  19441. return t instanceof Lh && e instanceof Lh && t._aggregateType === e._aggregateType && (null === (n = t._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (s = e._internalFieldPath) || void 0 === s ? void 0 : s.canonicalString());
  19442. }
  19443. /**
  19444. * Compares two `AggregateQuerySnapshot` instances for equality.
  19445. *
  19446. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  19447. * underlying queries that compare equal, and the same data.
  19448. *
  19449. * @param left - The first `AggregateQuerySnapshot` to compare.
  19450. * @param right - The second `AggregateQuerySnapshot` to compare.
  19451. *
  19452. * @returns `true` if the objects are "equal", as defined above, or `false`
  19453. * otherwise.
  19454. */ function ef(t, e) {
  19455. return ph(t.query, e.query) && deepEqual(t.data(), e.data());
  19456. }
  19457. /**
  19458. * @license
  19459. * Copyright 2020 Google LLC
  19460. *
  19461. * Licensed under the Apache License, Version 2.0 (the "License");
  19462. * you may not use this file except in compliance with the License.
  19463. * You may obtain a copy of the License at
  19464. *
  19465. * http://www.apache.org/licenses/LICENSE-2.0
  19466. *
  19467. * Unless required by applicable law or agreed to in writing, software
  19468. * distributed under the License is distributed on an "AS IS" BASIS,
  19469. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19470. * See the License for the specific language governing permissions and
  19471. * limitations under the License.
  19472. */
  19473. /**
  19474. * Metadata about a snapshot, describing the state of the snapshot.
  19475. */ class nf {
  19476. /** @hideconstructor */
  19477. constructor(t, e) {
  19478. this.hasPendingWrites = t, this.fromCache = e;
  19479. }
  19480. /**
  19481. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  19482. *
  19483. * @param other - The `SnapshotMetadata` to compare against.
  19484. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  19485. */ isEqual(t) {
  19486. return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
  19487. }
  19488. }
  19489. /**
  19490. * A `DocumentSnapshot` contains data read from a document in your Firestore
  19491. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  19492. * get a specific field.
  19493. *
  19494. * For a `DocumentSnapshot` that points to a non-existing document, any data
  19495. * access will return 'undefined'. You can use the `exists()` method to
  19496. * explicitly verify a document's existence.
  19497. */ class sf extends pl {
  19498. /** @hideconstructor protected */
  19499. constructor(t, e, n, s, i, r) {
  19500. super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;
  19501. }
  19502. /**
  19503. * Returns whether or not the data exists. True if the document exists.
  19504. */ exists() {
  19505. return super.exists();
  19506. }
  19507. /**
  19508. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  19509. * the document doesn't exist.
  19510. *
  19511. * By default, `serverTimestamp()` values that have not yet been
  19512. * set to their final value will be returned as `null`. You can override
  19513. * this by passing an options object.
  19514. *
  19515. * @param options - An options object to configure how data is retrieved from
  19516. * the snapshot (for example the desired behavior for server timestamps that
  19517. * have not yet been set to their final value).
  19518. * @returns An `Object` containing all fields in the document or `undefined` if
  19519. * the document doesn't exist.
  19520. */ data(t = {}) {
  19521. if (this._document) {
  19522. if (this._converter) {
  19523. // We only want to use the converter and create a new DocumentSnapshot
  19524. // if a converter has been provided.
  19525. const e = new rf(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
  19526. /* converter= */ null);
  19527. return this._converter.fromFirestore(e, t);
  19528. }
  19529. return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
  19530. }
  19531. }
  19532. /**
  19533. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  19534. * document or field doesn't exist.
  19535. *
  19536. * By default, a `serverTimestamp()` that has not yet been set to
  19537. * its final value will be returned as `null`. You can override this by
  19538. * passing an options object.
  19539. *
  19540. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  19541. * field.
  19542. * @param options - An options object to configure how the field is retrieved
  19543. * from the snapshot (for example the desired behavior for server timestamps
  19544. * that have not yet been set to their final value).
  19545. * @returns The data at the specified field location or undefined if no such
  19546. * field exists in the document.
  19547. */
  19548. // We are using `any` here to avoid an explicit cast by our users.
  19549. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19550. get(t, e = {}) {
  19551. if (this._document) {
  19552. const n = this._document.data.field(Tl("DocumentSnapshot.get", t));
  19553. if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
  19554. }
  19555. }
  19556. }
  19557. /**
  19558. * A `QueryDocumentSnapshot` contains data read from a document in your
  19559. * Firestore database as part of a query. The document is guaranteed to exist
  19560. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  19561. * specific field.
  19562. *
  19563. * A `QueryDocumentSnapshot` offers the same API surface as a
  19564. * `DocumentSnapshot`. Since query results contain only existing documents, the
  19565. * `exists` property will always be true and `data()` will never return
  19566. * 'undefined'.
  19567. */ class rf extends sf {
  19568. /**
  19569. * Retrieves all fields in the document as an `Object`.
  19570. *
  19571. * By default, `serverTimestamp()` values that have not yet been
  19572. * set to their final value will be returned as `null`. You can override
  19573. * this by passing an options object.
  19574. *
  19575. * @override
  19576. * @param options - An options object to configure how data is retrieved from
  19577. * the snapshot (for example the desired behavior for server timestamps that
  19578. * have not yet been set to their final value).
  19579. * @returns An `Object` containing all fields in the document.
  19580. */
  19581. data(t = {}) {
  19582. return super.data(t);
  19583. }
  19584. }
  19585. /**
  19586. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  19587. * representing the results of a query. The documents can be accessed as an
  19588. * array via the `docs` property or enumerated using the `forEach` method. The
  19589. * number of documents can be determined via the `empty` and `size`
  19590. * properties.
  19591. */ class of {
  19592. /** @hideconstructor */
  19593. constructor(t, e, n, s) {
  19594. this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new nf(s.hasPendingWrites, s.fromCache),
  19595. this.query = n;
  19596. }
  19597. /** An array of all the documents in the `QuerySnapshot`. */ get docs() {
  19598. const t = [];
  19599. return this.forEach((e => t.push(e))), t;
  19600. }
  19601. /** The number of documents in the `QuerySnapshot`. */ get size() {
  19602. return this._snapshot.docs.size;
  19603. }
  19604. /** True if there are no documents in the `QuerySnapshot`. */ get empty() {
  19605. return 0 === this.size;
  19606. }
  19607. /**
  19608. * Enumerates all of the documents in the `QuerySnapshot`.
  19609. *
  19610. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  19611. * each document in the snapshot.
  19612. * @param thisArg - The `this` binding for the callback.
  19613. */ forEach(t, e) {
  19614. this._snapshot.docs.forEach((n => {
  19615. t.call(e, new rf(this._firestore, this._userDataWriter, n.key, n, new nf(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));
  19616. }));
  19617. }
  19618. /**
  19619. * Returns an array of the documents changes since the last snapshot. If this
  19620. * is the first snapshot, all documents will be in the list as 'added'
  19621. * changes.
  19622. *
  19623. * @param options - `SnapshotListenOptions` that control whether metadata-only
  19624. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  19625. * snapshot events.
  19626. */ docChanges(t = {}) {
  19627. const e = !!t.includeMetadataChanges;
  19628. if (e && this._snapshot.excludesMetadataChanges) throw new U(q.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
  19629. return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges =
  19630. /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
  19631. function(t, e) {
  19632. if (t._snapshot.oldDocs.isEmpty()) {
  19633. let e = 0;
  19634. return t._snapshot.docChanges.map((n => {
  19635. const s = new rf(t._firestore, t._userDataWriter, n.doc.key, n.doc, new nf(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);
  19636. return n.doc, {
  19637. type: "added",
  19638. doc: s,
  19639. oldIndex: -1,
  19640. newIndex: e++
  19641. };
  19642. }));
  19643. }
  19644. {
  19645. // A `DocumentSet` that is updated incrementally as changes are applied to use
  19646. // to lookup the index of a document.
  19647. let n = t._snapshot.oldDocs;
  19648. return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {
  19649. const s = new rf(t._firestore, t._userDataWriter, e.doc.key, e.doc, new nf(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
  19650. let i = -1, r = -1;
  19651. return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)),
  19652. 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)),
  19653. {
  19654. type: uf(e.type),
  19655. doc: s,
  19656. oldIndex: i,
  19657. newIndex: r
  19658. };
  19659. }));
  19660. }
  19661. }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
  19662. }
  19663. }
  19664. function uf(t) {
  19665. switch (t) {
  19666. case 0 /* ChangeType.Added */ :
  19667. return "added";
  19668. case 2 /* ChangeType.Modified */ :
  19669. case 3 /* ChangeType.Metadata */ :
  19670. return "modified";
  19671. case 1 /* ChangeType.Removed */ :
  19672. return "removed";
  19673. default:
  19674. return O();
  19675. }
  19676. }
  19677. // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
  19678. // metadata
  19679. /**
  19680. * Returns true if the provided snapshots are equal.
  19681. *
  19682. * @param left - A snapshot to compare.
  19683. * @param right - A snapshot to compare.
  19684. * @returns true if the snapshots are equal.
  19685. */ function cf(t, e) {
  19686. return t instanceof sf && e instanceof sf ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof of && e instanceof of && (t._firestore === e._firestore && ph(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));
  19687. }
  19688. /**
  19689. * @license
  19690. * Copyright 2020 Google LLC
  19691. *
  19692. * Licensed under the Apache License, Version 2.0 (the "License");
  19693. * you may not use this file except in compliance with the License.
  19694. * You may obtain a copy of the License at
  19695. *
  19696. * http://www.apache.org/licenses/LICENSE-2.0
  19697. *
  19698. * Unless required by applicable law or agreed to in writing, software
  19699. * distributed under the License is distributed on an "AS IS" BASIS,
  19700. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19701. * See the License for the specific language governing permissions and
  19702. * limitations under the License.
  19703. */
  19704. /**
  19705. * Reads the document referred to by this `DocumentReference`.
  19706. *
  19707. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  19708. * for data from the server, but it may return cached data or fail if you are
  19709. * offline and the server cannot be reached. To specify this behavior, invoke
  19710. * {@link getDocFromCache} or {@link getDocFromServer}.
  19711. *
  19712. * @param reference - The reference of the document to fetch.
  19713. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  19714. * current document contents.
  19715. */ function af(t) {
  19716. t = uh(t, fh);
  19717. const e = uh(t.firestore, vh);
  19718. return za(bh(e), t._key).then((n => Af(e, t, n)));
  19719. }
  19720. class hf extends Wl {
  19721. constructor(t) {
  19722. super(), this.firestore = t;
  19723. }
  19724. convertBytes(t) {
  19725. return new Uh(t);
  19726. }
  19727. convertReference(t) {
  19728. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19729. return new fh(this.firestore, /* converter= */ null, e);
  19730. }
  19731. }
  19732. /**
  19733. * Reads the document referred to by this `DocumentReference` from cache.
  19734. * Returns an error if the document is not currently cached.
  19735. *
  19736. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19737. * current document contents.
  19738. */ function lf(t) {
  19739. t = uh(t, fh);
  19740. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19741. return ja(n, t._key).then((n => new sf(e, s, t._key, n, new nf(null !== n && n.hasLocalMutations,
  19742. /* fromCache= */ !0), t.converter)));
  19743. }
  19744. /**
  19745. * Reads the document referred to by this `DocumentReference` from the server.
  19746. * Returns an error if the network is not available.
  19747. *
  19748. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19749. * current document contents.
  19750. */ function ff(t) {
  19751. t = uh(t, fh);
  19752. const e = uh(t.firestore, vh);
  19753. return za(bh(e), t._key, {
  19754. source: "server"
  19755. }).then((n => Af(e, t, n)));
  19756. }
  19757. /**
  19758. * Executes the query and returns the results as a `QuerySnapshot`.
  19759. *
  19760. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  19761. * waiting for data from the server, but it may return cached data or fail if
  19762. * you are offline and the server cannot be reached. To specify this behavior,
  19763. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  19764. *
  19765. * @returns A `Promise` that will be resolved with the results of the query.
  19766. */ function df(t) {
  19767. t = uh(t, dh);
  19768. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19769. return El(t._query), Ha(n, t._query).then((n => new of(e, s, t, n)));
  19770. }
  19771. /**
  19772. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  19773. * Returns an empty result set if no documents matching the query are currently
  19774. * cached.
  19775. *
  19776. * @returns A `Promise` that will be resolved with the results of the query.
  19777. */ function wf(t) {
  19778. t = uh(t, dh);
  19779. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19780. return Wa(n, t._query).then((n => new of(e, s, t, n)));
  19781. }
  19782. /**
  19783. * Executes the query and returns the results as a `QuerySnapshot` from the
  19784. * server. Returns an error if the network is not available.
  19785. *
  19786. * @returns A `Promise` that will be resolved with the results of the query.
  19787. */ function _f(t) {
  19788. t = uh(t, dh);
  19789. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19790. return Ha(n, t._query, {
  19791. source: "server"
  19792. }).then((n => new of(e, s, t, n)));
  19793. }
  19794. function mf(t, e, n) {
  19795. t = uh(t, fh);
  19796. const s = uh(t.firestore, vh), i = Hl(t.converter, e, n);
  19797. return Ef(s, [ tl(Zh(s), "setDoc", t._key, i, null !== t.converter, n).toMutation(t._key, Fs.none()) ]);
  19798. }
  19799. function gf(t, e, n, ...s) {
  19800. t = uh(t, fh);
  19801. const i = uh(t.firestore, vh), r = Zh(i);
  19802. let o;
  19803. o = "string" == typeof (
  19804. // For Compat types, we have to "extract" the underlying types before
  19805. // performing validation.
  19806. e = getModularInstance(e)) || e instanceof Kh ? cl(r, "updateDoc", t._key, e, n, s) : ul(r, "updateDoc", t._key, e);
  19807. return Ef(i, [ o.toMutation(t._key, Fs.exists(!0)) ]);
  19808. }
  19809. /**
  19810. * Deletes the document referred to by the specified `DocumentReference`.
  19811. *
  19812. * @param reference - A reference to the document to delete.
  19813. * @returns A Promise resolved once the document has been successfully
  19814. * deleted from the backend (note that it won't resolve while you're offline).
  19815. */ function yf(t) {
  19816. return Ef(uh(t.firestore, vh), [ new Ys(t._key, Fs.none()) ]);
  19817. }
  19818. /**
  19819. * Add a new document to specified `CollectionReference` with the given data,
  19820. * assigning it a document ID automatically.
  19821. *
  19822. * @param reference - A reference to the collection to add this document to.
  19823. * @param data - An Object containing the data for the new document.
  19824. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  19825. * newly created document after it has been written to the backend (Note that it
  19826. * won't resolve while you're offline).
  19827. */ function pf(t, e) {
  19828. const n = uh(t.firestore, vh), s = gh(t), i = Hl(t.converter, e);
  19829. return Ef(n, [ tl(Zh(t.firestore), "addDoc", s._key, i, null !== t.converter, {}).toMutation(s._key, Fs.exists(!1)) ]).then((() => s));
  19830. }
  19831. function If(t, ...e) {
  19832. var n, s, i;
  19833. t = getModularInstance(t);
  19834. let r = {
  19835. includeMetadataChanges: !1
  19836. }, o = 0;
  19837. "object" != typeof e[o] || Th(e[o]) || (r = e[o], o++);
  19838. const u = {
  19839. includeMetadataChanges: r.includeMetadataChanges
  19840. };
  19841. if (Th(e[o])) {
  19842. const t = e[o];
  19843. e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t),
  19844. e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);
  19845. }
  19846. let c, a, h;
  19847. if (t instanceof fh) a = uh(t.firestore, vh), h = Gn(t._key.path), c = {
  19848. next: n => {
  19849. e[o] && e[o](Af(a, t, n));
  19850. },
  19851. error: e[o + 1],
  19852. complete: e[o + 2]
  19853. }; else {
  19854. const n = uh(t, dh);
  19855. a = uh(n.firestore, vh), h = n._query;
  19856. const s = new hf(a);
  19857. c = {
  19858. next: t => {
  19859. e[o] && e[o](new of(a, s, n, t));
  19860. },
  19861. error: e[o + 1],
  19862. complete: e[o + 2]
  19863. }, El(t._query);
  19864. }
  19865. return function(t, e, n, s) {
  19866. const i = new Va(s), r = new Nc(e, i, n);
  19867. return t.asyncQueue.enqueueAndForget((async () => Vc(await Ka(t), r))), () => {
  19868. i.Dc(), t.asyncQueue.enqueueAndForget((async () => Sc(await Ka(t), r)));
  19869. };
  19870. }(bh(a), h, u, c);
  19871. }
  19872. function Tf(t, e) {
  19873. return Ja(bh(t = uh(t, vh)), Th(e) ? e : {
  19874. next: e
  19875. });
  19876. }
  19877. /**
  19878. * Locally writes `mutations` on the async queue.
  19879. * @internal
  19880. */ function Ef(t, e) {
  19881. return function(t, e) {
  19882. const n = new K;
  19883. return t.asyncQueue.enqueueAndForget((async () => zc(await qa(t), e, n))), n.promise;
  19884. }(bh(t), e);
  19885. }
  19886. /**
  19887. * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`
  19888. * to a {@link DocumentSnapshot}.
  19889. */ function Af(t, e, n) {
  19890. const s = n.docs.get(e._key), i = new hf(t);
  19891. return new sf(t, i, e._key, s, new nf(n.hasPendingWrites, n.fromCache), e.converter);
  19892. }
  19893. /**
  19894. * @license
  19895. * Copyright 2022 Google LLC
  19896. *
  19897. * Licensed under the Apache License, Version 2.0 (the "License");
  19898. * you may not use this file except in compliance with the License.
  19899. * You may obtain a copy of the License at
  19900. *
  19901. * http://www.apache.org/licenses/LICENSE-2.0
  19902. *
  19903. * Unless required by applicable law or agreed to in writing, software
  19904. * distributed under the License is distributed on an "AS IS" BASIS,
  19905. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19906. * See the License for the specific language governing permissions and
  19907. * limitations under the License.
  19908. */
  19909. /**
  19910. * Calculates the number of documents in the result set of the given query,
  19911. * without actually downloading the documents.
  19912. *
  19913. * Using this function to count the documents is efficient because only the
  19914. * final count, not the documents' data, is downloaded. This function can even
  19915. * count the documents if the result set would be prohibitively large to
  19916. * download entirely (e.g. thousands of documents).
  19917. *
  19918. * The result received from the server is presented, unaltered, without
  19919. * considering any local state. That is, documents in the local cache are not
  19920. * taken into consideration, neither are local modifications not yet
  19921. * synchronized with the server. Previously-downloaded results, if any, are not
  19922. * used: every request using this source necessarily involves a round trip to
  19923. * the server.
  19924. *
  19925. * @param query - The query whose result set size to calculate.
  19926. * @returns A Promise that will be resolved with the count; the count can be
  19927. * retrieved from `snapshot.data().count`, where `snapshot` is the
  19928. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  19929. */ function vf(t) {
  19930. return Rf(t, {
  19931. count: Zl()
  19932. });
  19933. }
  19934. /**
  19935. * Calculates the specified aggregations over the documents in the result
  19936. * set of the given query, without actually downloading the documents.
  19937. *
  19938. * Using this function to perform aggregations is efficient because only the
  19939. * final aggregation values, not the documents' data, is downloaded. This
  19940. * function can even perform aggregations of the documents if the result set
  19941. * would be prohibitively large to download entirely (e.g. thousands of documents).
  19942. *
  19943. * The result received from the server is presented, unaltered, without
  19944. * considering any local state. That is, documents in the local cache are not
  19945. * taken into consideration, neither are local modifications not yet
  19946. * synchronized with the server. Previously-downloaded results, if any, are not
  19947. * used: every request using this source necessarily involves a round trip to
  19948. * the server.
  19949. *
  19950. * @param query The query whose result set to aggregate over.
  19951. * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates
  19952. * to perform over the result set. The AggregateSpec specifies aliases for each
  19953. * aggregate, which can be used to retrieve the aggregate result.
  19954. * @example
  19955. * ```typescript
  19956. * const aggregateSnapshot = await getAggregateFromServer(query, {
  19957. * countOfDocs: count(),
  19958. * totalHours: sum('hours'),
  19959. * averageScore: average('score')
  19960. * });
  19961. *
  19962. * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
  19963. * const totalHours: number = aggregateSnapshot.data().totalHours;
  19964. * const averageScore: number | null = aggregateSnapshot.data().averageScore;
  19965. * ```
  19966. * @internal TODO (sum/avg) remove when public
  19967. */ function Rf(t, e) {
  19968. const n = uh(t.firestore, vh), s = bh(n), i = function(t, e) {
  19969. const n = [];
  19970. for (const s in t) Object.prototype.hasOwnProperty.call(t, s) && n.push(e(t[s], s, t));
  19971. return n;
  19972. }(e, ((t, e) => new ni(e, t._aggregateType, t._internalFieldPath)));
  19973. // Run the aggregation and convert the results
  19974. return function(t, e, n) {
  19975. const s = new K;
  19976. return t.asyncQueue.enqueueAndForget((async () => {
  19977. // TODO (sum/avg) should we update this to use the event manager?
  19978. // Implement and call executeAggregateQueryViaSnapshotListener, similar
  19979. // to the implementation in firestoreClientGetDocumentsViaSnapshotListener
  19980. // above
  19981. try {
  19982. // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.
  19983. const i = await Ua(t);
  19984. s.resolve(Gu(i, e, n));
  19985. } catch (t) {
  19986. s.reject(t);
  19987. }
  19988. })), s.promise;
  19989. }(s, t._query, i).then((e =>
  19990. /**
  19991. * Converts the core aggregration result to an `AggregateQuerySnapshot`
  19992. * that can be returned to the consumer.
  19993. * @param query
  19994. * @param aggregateResult Core aggregation result
  19995. * @internal
  19996. */
  19997. function(t, e, n) {
  19998. const s = new hf(t);
  19999. return new qh(e, s, n);
  20000. }
  20001. /**
  20002. * @license
  20003. * Copyright 2023 Google LLC
  20004. *
  20005. * Licensed under the Apache License, Version 2.0 (the "License");
  20006. * you may not use this file except in compliance with the License.
  20007. * You may obtain a copy of the License at
  20008. *
  20009. * http://www.apache.org/licenses/LICENSE-2.0
  20010. *
  20011. * Unless required by applicable law or agreed to in writing, software
  20012. * distributed under the License is distributed on an "AS IS" BASIS,
  20013. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20014. * See the License for the specific language governing permissions and
  20015. * limitations under the License.
  20016. */ (n, t, e)));
  20017. }
  20018. class Pf {
  20019. constructor(t) {
  20020. this.kind = "memory", this._onlineComponentProvider = new Pa, (null == t ? void 0 : t.garbageCollector) ? this._offlineComponentProvider = t.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = new Ea;
  20021. }
  20022. toJSON() {
  20023. return {
  20024. kind: this.kind
  20025. };
  20026. }
  20027. }
  20028. class bf {
  20029. constructor(t) {
  20030. let e;
  20031. this.kind = "persistent", (null == t ? void 0 : t.tabManager) ? (t.tabManager._initialize(t),
  20032. e = t.tabManager) : (e = $f(void 0), e._initialize(t)), this._onlineComponentProvider = e._onlineComponentProvider,
  20033. this._offlineComponentProvider = e._offlineComponentProvider;
  20034. }
  20035. toJSON() {
  20036. return {
  20037. kind: this.kind
  20038. };
  20039. }
  20040. }
  20041. class Vf {
  20042. constructor() {
  20043. this.kind = "memoryEager", this._offlineComponentProvider = new Ea;
  20044. }
  20045. toJSON() {
  20046. return {
  20047. kind: this.kind
  20048. };
  20049. }
  20050. }
  20051. class Sf {
  20052. constructor(t) {
  20053. this.kind = "memoryLru", this._offlineComponentProvider = new Aa(t);
  20054. }
  20055. toJSON() {
  20056. return {
  20057. kind: this.kind
  20058. };
  20059. }
  20060. }
  20061. /**
  20062. * Creates an instance of `MemoryEagerGarbageCollector`. This is also the
  20063. * default garbage collector unless it is explicitly specified otherwise.
  20064. */ function Df() {
  20065. return new Vf;
  20066. }
  20067. /**
  20068. * Creates an instance of `MemoryLruGarbageCollector`.
  20069. *
  20070. * A target size can be specified as part of the setting parameter. The
  20071. * collector will start deleting documents once the cache size exceeds
  20072. * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).
  20073. */ function Cf(t) {
  20074. return new Sf(null == t ? void 0 : t.cacheSizeBytes);
  20075. }
  20076. /**
  20077. * Creates an instance of `MemoryLocalCache`. The instance can be set to
  20078. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20079. */ function xf(t) {
  20080. return new Pf(t);
  20081. }
  20082. /**
  20083. * Creates an instance of `PersistentLocalCache`. The instance can be set to
  20084. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20085. *
  20086. * Persistent cache cannot be used in a Node.js environment.
  20087. */ function Nf(t) {
  20088. return new bf(t);
  20089. }
  20090. class kf {
  20091. constructor(t) {
  20092. this.forceOwnership = t, this.kind = "persistentSingleTab";
  20093. }
  20094. toJSON() {
  20095. return {
  20096. kind: this.kind
  20097. };
  20098. }
  20099. /**
  20100. * @internal
  20101. */ _initialize(t) {
  20102. this._onlineComponentProvider = new Pa, this._offlineComponentProvider = new va(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes, this.forceOwnership);
  20103. }
  20104. }
  20105. class Mf {
  20106. constructor() {
  20107. this.kind = "PersistentMultipleTab";
  20108. }
  20109. toJSON() {
  20110. return {
  20111. kind: this.kind
  20112. };
  20113. }
  20114. /**
  20115. * @internal
  20116. */ _initialize(t) {
  20117. this._onlineComponentProvider = new Pa, this._offlineComponentProvider = new Ra(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes);
  20118. }
  20119. }
  20120. /**
  20121. * Creates an instance of `PersistentSingleTabManager`.
  20122. *
  20123. * @param settings Configures the created tab manager.
  20124. */ function $f(t) {
  20125. return new kf(null == t ? void 0 : t.forceOwnership);
  20126. }
  20127. /**
  20128. * Creates an instance of `PersistentMultipleTabManager`.
  20129. */ function Of() {
  20130. return new Mf;
  20131. }
  20132. /**
  20133. * @license
  20134. * Copyright 2022 Google LLC
  20135. *
  20136. * Licensed under the Apache License, Version 2.0 (the "License");
  20137. * you may not use this file except in compliance with the License.
  20138. * You may obtain a copy of the License at
  20139. *
  20140. * http://www.apache.org/licenses/LICENSE-2.0
  20141. *
  20142. * Unless required by applicable law or agreed to in writing, software
  20143. * distributed under the License is distributed on an "AS IS" BASIS,
  20144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20145. * See the License for the specific language governing permissions and
  20146. * limitations under the License.
  20147. */ const Ff = {
  20148. maxAttempts: 5
  20149. };
  20150. /**
  20151. * @license
  20152. * Copyright 2020 Google LLC
  20153. *
  20154. * Licensed under the Apache License, Version 2.0 (the "License");
  20155. * you may not use this file except in compliance with the License.
  20156. * You may obtain a copy of the License at
  20157. *
  20158. * http://www.apache.org/licenses/LICENSE-2.0
  20159. *
  20160. * Unless required by applicable law or agreed to in writing, software
  20161. * distributed under the License is distributed on an "AS IS" BASIS,
  20162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20163. * See the License for the specific language governing permissions and
  20164. * limitations under the License.
  20165. */
  20166. /**
  20167. * A write batch, used to perform multiple writes as a single atomic unit.
  20168. *
  20169. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  20170. * provides methods for adding writes to the write batch. None of the writes
  20171. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  20172. * called.
  20173. */
  20174. class Bf {
  20175. /** @hideconstructor */
  20176. constructor(t, e) {
  20177. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  20178. this._dataReader = Zh(t);
  20179. }
  20180. set(t, e, n) {
  20181. this._verifyNotCommitted();
  20182. const s = Lf(t, this._firestore), i = Hl(s.converter, e, n), r = tl(this._dataReader, "WriteBatch.set", s._key, i, null !== s.converter, n);
  20183. return this._mutations.push(r.toMutation(s._key, Fs.none())), this;
  20184. }
  20185. update(t, e, n, ...s) {
  20186. this._verifyNotCommitted();
  20187. const i = Lf(t, this._firestore);
  20188. // For Compat types, we have to "extract" the underlying types before
  20189. // performing validation.
  20190. let r;
  20191. return r = "string" == typeof (e = getModularInstance(e)) || e instanceof Kh ? cl(this._dataReader, "WriteBatch.update", i._key, e, n, s) : ul(this._dataReader, "WriteBatch.update", i._key, e),
  20192. this._mutations.push(r.toMutation(i._key, Fs.exists(!0))), this;
  20193. }
  20194. /**
  20195. * Deletes the document referred to by the provided {@link DocumentReference}.
  20196. *
  20197. * @param documentRef - A reference to the document to be deleted.
  20198. * @returns This `WriteBatch` instance. Used for chaining method calls.
  20199. */ delete(t) {
  20200. this._verifyNotCommitted();
  20201. const e = Lf(t, this._firestore);
  20202. return this._mutations = this._mutations.concat(new Ys(e._key, Fs.none())), this;
  20203. }
  20204. /**
  20205. * Commits all of the writes in this write batch as a single atomic unit.
  20206. *
  20207. * The result of these writes will only be reflected in document reads that
  20208. * occur after the returned promise resolves. If the client is offline, the
  20209. * write fails. If you would like to see local modifications or buffer writes
  20210. * until the client is online, use the full Firestore SDK.
  20211. *
  20212. * @returns A `Promise` resolved once all of the writes in the batch have been
  20213. * successfully written to the backend as an atomic unit (note that it won't
  20214. * resolve while you're offline).
  20215. */ commit() {
  20216. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  20217. }
  20218. _verifyNotCommitted() {
  20219. if (this._committed) throw new U(q.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  20220. }
  20221. }
  20222. function Lf(t, e) {
  20223. if ((t = getModularInstance(t)).firestore !== e) throw new U(q.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  20224. return t;
  20225. }
  20226. /**
  20227. * @license
  20228. * Copyright 2020 Google LLC
  20229. *
  20230. * Licensed under the Apache License, Version 2.0 (the "License");
  20231. * you may not use this file except in compliance with the License.
  20232. * You may obtain a copy of the License at
  20233. *
  20234. * http://www.apache.org/licenses/LICENSE-2.0
  20235. *
  20236. * Unless required by applicable law or agreed to in writing, software
  20237. * distributed under the License is distributed on an "AS IS" BASIS,
  20238. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20239. * See the License for the specific language governing permissions and
  20240. * limitations under the License.
  20241. */
  20242. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  20243. // legacy SDK.
  20244. /**
  20245. * A reference to a transaction.
  20246. *
  20247. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20248. * the methods to read and write data within the transaction context. See
  20249. * {@link runTransaction}.
  20250. */
  20251. /**
  20252. * @license
  20253. * Copyright 2020 Google LLC
  20254. *
  20255. * Licensed under the Apache License, Version 2.0 (the "License");
  20256. * you may not use this file except in compliance with the License.
  20257. * You may obtain a copy of the License at
  20258. *
  20259. * http://www.apache.org/licenses/LICENSE-2.0
  20260. *
  20261. * Unless required by applicable law or agreed to in writing, software
  20262. * distributed under the License is distributed on an "AS IS" BASIS,
  20263. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20264. * See the License for the specific language governing permissions and
  20265. * limitations under the License.
  20266. */
  20267. /**
  20268. * A reference to a transaction.
  20269. *
  20270. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20271. * the methods to read and write data within the transaction context. See
  20272. * {@link runTransaction}.
  20273. */
  20274. class qf extends class {
  20275. /** @hideconstructor */
  20276. constructor(t, e) {
  20277. this._firestore = t, this._transaction = e, this._dataReader = Zh(t);
  20278. }
  20279. /**
  20280. * Reads the document referenced by the provided {@link DocumentReference}.
  20281. *
  20282. * @param documentRef - A reference to the document to be read.
  20283. * @returns A `DocumentSnapshot` with the read data.
  20284. */ get(t) {
  20285. const e = Lf(t, this._firestore), n = new Jl(this._firestore);
  20286. return this._transaction.lookup([ e._key ]).then((t => {
  20287. if (!t || 1 !== t.length) return O();
  20288. const s = t[0];
  20289. if (s.isFoundDocument()) return new pl(this._firestore, n, s.key, s, e.converter);
  20290. if (s.isNoDocument()) return new pl(this._firestore, n, e._key, null, e.converter);
  20291. throw O();
  20292. }));
  20293. }
  20294. set(t, e, n) {
  20295. const s = Lf(t, this._firestore), i = Hl(s.converter, e, n), r = tl(this._dataReader, "Transaction.set", s._key, i, null !== s.converter, n);
  20296. return this._transaction.set(s._key, r), this;
  20297. }
  20298. update(t, e, n, ...s) {
  20299. const i = Lf(t, this._firestore);
  20300. // For Compat types, we have to "extract" the underlying types before
  20301. // performing validation.
  20302. let r;
  20303. return r = "string" == typeof (e = getModularInstance(e)) || e instanceof Kh ? cl(this._dataReader, "Transaction.update", i._key, e, n, s) : ul(this._dataReader, "Transaction.update", i._key, e),
  20304. this._transaction.update(i._key, r), this;
  20305. }
  20306. /**
  20307. * Deletes the document referred to by the provided {@link DocumentReference}.
  20308. *
  20309. * @param documentRef - A reference to the document to be deleted.
  20310. * @returns This `Transaction` instance. Used for chaining method calls.
  20311. */ delete(t) {
  20312. const e = Lf(t, this._firestore);
  20313. return this._transaction.delete(e._key), this;
  20314. }
  20315. } {
  20316. // This class implements the same logic as the Transaction API in the Lite SDK
  20317. // but is subclassed in order to return its own DocumentSnapshot types.
  20318. /** @hideconstructor */
  20319. constructor(t, e) {
  20320. super(t, e), this._firestore = t;
  20321. }
  20322. /**
  20323. * Reads the document referenced by the provided {@link DocumentReference}.
  20324. *
  20325. * @param documentRef - A reference to the document to be read.
  20326. * @returns A `DocumentSnapshot` with the read data.
  20327. */ get(t) {
  20328. const e = Lf(t, this._firestore), n = new hf(this._firestore);
  20329. return super.get(t).then((t => new sf(this._firestore, n, e._key, t._document, new nf(
  20330. /* hasPendingWrites= */ !1,
  20331. /* fromCache= */ !1), e.converter)));
  20332. }
  20333. }
  20334. /**
  20335. * Executes the given `updateFunction` and then attempts to commit the changes
  20336. * applied within the transaction. If any document read within the transaction
  20337. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  20338. * commit after 5 attempts, the transaction fails.
  20339. *
  20340. * The maximum number of writes allowed in a single transaction is 500.
  20341. *
  20342. * @param firestore - A reference to the Firestore database to run this
  20343. * transaction against.
  20344. * @param updateFunction - The function to execute within the transaction
  20345. * context.
  20346. * @param options - An options object to configure maximum number of attempts to
  20347. * commit.
  20348. * @returns If the transaction completed successfully or was explicitly aborted
  20349. * (the `updateFunction` returned a failed promise), the promise returned by the
  20350. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  20351. * rejected promise with the corresponding failure error is returned.
  20352. */ function Uf(t, e, n) {
  20353. t = uh(t, vh);
  20354. const s = Object.assign(Object.assign({}, Ff), n);
  20355. !function(t) {
  20356. if (t.maxAttempts < 1) throw new U(q.INVALID_ARGUMENT, "Max attempts must be at least 1");
  20357. }(s);
  20358. return function(t, e, n) {
  20359. const s = new K;
  20360. return t.asyncQueue.enqueueAndForget((async () => {
  20361. const i = await Ua(t);
  20362. new Ca(t.asyncQueue, i, n, e, s).run();
  20363. })), s.promise;
  20364. }(bh(t), (n => e(new qf(t, n))), s);
  20365. }
  20366. /**
  20367. * @license
  20368. * Copyright 2020 Google LLC
  20369. *
  20370. * Licensed under the Apache License, Version 2.0 (the "License");
  20371. * you may not use this file except in compliance with the License.
  20372. * You may obtain a copy of the License at
  20373. *
  20374. * http://www.apache.org/licenses/LICENSE-2.0
  20375. *
  20376. * Unless required by applicable law or agreed to in writing, software
  20377. * distributed under the License is distributed on an "AS IS" BASIS,
  20378. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20379. * See the License for the specific language governing permissions and
  20380. * limitations under the License.
  20381. */
  20382. /**
  20383. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  20384. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  20385. */ function Kf() {
  20386. return new el("deleteField");
  20387. }
  20388. /**
  20389. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  20390. * include a server-generated timestamp in the written data.
  20391. */ function Gf() {
  20392. return new sl("serverTimestamp");
  20393. }
  20394. /**
  20395. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20396. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  20397. * value that already exists on the server. Each specified element that doesn't
  20398. * already exist in the array will be added to the end. If the field being
  20399. * modified is not already an array it will be overwritten with an array
  20400. * containing exactly the specified elements.
  20401. *
  20402. * @param elements - The elements to union into the array.
  20403. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20404. * `updateDoc()`.
  20405. */ function Qf(...t) {
  20406. // NOTE: We don't actually parse the data until it's used in set() or
  20407. // update() since we'd need the Firestore instance to do this.
  20408. return new il("arrayUnion", t);
  20409. }
  20410. /**
  20411. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  20412. * updateDoc:1} that tells the server to remove the given elements from any
  20413. * array value that already exists on the server. All instances of each element
  20414. * specified will be removed from the array. If the field being modified is not
  20415. * already an array it will be overwritten with an empty array.
  20416. *
  20417. * @param elements - The elements to remove from the array.
  20418. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20419. * `updateDoc()`
  20420. */ function jf(...t) {
  20421. // NOTE: We don't actually parse the data until it's used in set() or
  20422. // update() since we'd need the Firestore instance to do this.
  20423. return new rl("arrayRemove", t);
  20424. }
  20425. /**
  20426. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20427. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  20428. * the given value.
  20429. *
  20430. * If either the operand or the current field value uses floating point
  20431. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  20432. * integers, values outside of JavaScript's safe number range
  20433. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  20434. * precision loss. Furthermore, once processed by the Firestore backend, all
  20435. * integer operations are capped between -2^63 and 2^63-1.
  20436. *
  20437. * If the current field value is not of type `number`, or if the field does not
  20438. * yet exist, the transformation sets the field to the given value.
  20439. *
  20440. * @param n - The value to increment by.
  20441. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20442. * `updateDoc()`
  20443. */ function zf(t) {
  20444. return new ol("increment", t);
  20445. }
  20446. /**
  20447. * @license
  20448. * Copyright 2020 Google LLC
  20449. *
  20450. * Licensed under the Apache License, Version 2.0 (the "License");
  20451. * you may not use this file except in compliance with the License.
  20452. * You may obtain a copy of the License at
  20453. *
  20454. * http://www.apache.org/licenses/LICENSE-2.0
  20455. *
  20456. * Unless required by applicable law or agreed to in writing, software
  20457. * distributed under the License is distributed on an "AS IS" BASIS,
  20458. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20459. * See the License for the specific language governing permissions and
  20460. * limitations under the License.
  20461. */
  20462. /**
  20463. * Creates a write batch, used for performing multiple writes as a single
  20464. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  20465. * is 500.
  20466. *
  20467. * Unlike transactions, write batches are persisted offline and therefore are
  20468. * preferable when you don't need to condition your writes on read data.
  20469. *
  20470. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  20471. * writes.
  20472. */ function Wf(t) {
  20473. return bh(t = uh(t, vh)), new Bf(t, (e => Ef(t, e)));
  20474. }
  20475. /**
  20476. * @license
  20477. * Copyright 2021 Google LLC
  20478. *
  20479. * Licensed under the Apache License, Version 2.0 (the "License");
  20480. * you may not use this file except in compliance with the License.
  20481. * You may obtain a copy of the License at
  20482. *
  20483. * http://www.apache.org/licenses/LICENSE-2.0
  20484. *
  20485. * Unless required by applicable law or agreed to in writing, software
  20486. * distributed under the License is distributed on an "AS IS" BASIS,
  20487. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20488. * See the License for the specific language governing permissions and
  20489. * limitations under the License.
  20490. */ function Hf(t, e) {
  20491. var n;
  20492. const s = bh(t = uh(t, vh));
  20493. if (!s._uninitializedComponentsProvider || "memory" === (null === (n = s._uninitializedComponentsProvider) || void 0 === n ? void 0 : n._offlineKind))
  20494. // PORTING NOTE: We don't return an error if the user has not enabled
  20495. // persistence since `enableIndexeddbPersistence()` can fail on the Web.
  20496. return M("Cannot enable indexes when persistence is disabled"), Promise.resolve();
  20497. const i = function(t) {
  20498. const e = "string" == typeof t ? function(t) {
  20499. try {
  20500. return JSON.parse(t);
  20501. } catch (t) {
  20502. throw new U(q.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == t ? void 0 : t.message));
  20503. }
  20504. }(t) : t, n = [];
  20505. if (Array.isArray(e.indexes)) for (const t of e.indexes) {
  20506. const e = Jf(t, "collectionGroup"), s = [];
  20507. if (Array.isArray(t.fields)) for (const e of t.fields) {
  20508. const t = ml("setIndexConfiguration", Jf(e, "fieldPath"));
  20509. "CONTAINS" === e.arrayConfig ? s.push(new _t(t, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === e.order ? s.push(new _t(t, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === e.order && s.push(new _t(t, 1 /* IndexKind.DESCENDING */));
  20510. }
  20511. n.push(new lt(lt.UNKNOWN_ID, e, s, gt.empty()));
  20512. }
  20513. return n;
  20514. }(e);
  20515. return Za(s, i);
  20516. }
  20517. function Jf(t, e) {
  20518. if ("string" != typeof t[e]) throw new U(q.INVALID_ARGUMENT, "Missing string value for: " + e);
  20519. return t[e];
  20520. }
  20521. /**
  20522. * Cloud Firestore
  20523. *
  20524. * @packageDocumentation
  20525. */ !function(t, e = !0) {
  20526. !function(t) {
  20527. S = t;
  20528. }(SDK_VERSION), _registerComponent(new Component("firestore", ((t, {instanceIdentifier: n, options: s}) => {
  20529. const i = t.getProvider("app").getImmediate(), r = new vh(new z(t.getProvider("auth-internal")), new Y(t.getProvider("app-check-internal")), function(t, e) {
  20530. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new U(q.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  20531. return new Oe(t.options.projectId, e);
  20532. }(i, n), i);
  20533. return s = Object.assign({
  20534. useFetchStreams: e
  20535. }, s), r._setSettings(s), r;
  20536. }), "PUBLIC").setMultipleInstances(!0)), registerVersion(b, "3.13.0", t),
  20537. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  20538. registerVersion(b, "3.13.0", "esm2017");
  20539. }();
  20540. export { Wl as AbstractUserDataWriter, Lh as AggregateField, qh as AggregateQuerySnapshot, Uh as Bytes, Ah as CACHE_SIZE_UNLIMITED, wh as CollectionReference, fh as DocumentReference, sf as DocumentSnapshot, Kh as FieldPath, Qh as FieldValue, vh as Firestore, U as FirestoreError, jh as GeoPoint, Eh as LoadBundleTask, dh as Query, Vl as QueryCompositeFilterConstraint, vl as QueryConstraint, rf as QueryDocumentSnapshot, Bl as QueryEndAtConstraint, Pl as QueryFieldFilterConstraint, Nl as QueryLimitConstraint, Cl as QueryOrderByConstraint, of as QuerySnapshot, $l as QueryStartAtConstraint, nf as SnapshotMetadata, it as Timestamp, qf as Transaction, Bf as WriteBatch, Oe as _DatabaseId, ht as _DocumentKey, X as _EmptyAppCheckTokenProvider, Q as _EmptyAuthCredentialsProvider, at as _FieldPath, ci as _TestingHooks, uh as _cast, B as _debugAssert, be as _isBase64Available, M as _logWarn, sh as _validateIsNotUsedTogether, pf as addDoc, tf as aggregateFieldEqual, ef as aggregateQuerySnapshotEqual, Dl as and, jf as arrayRemove, Qf as arrayUnion, Xl as average, xh as clearIndexedDbPersistence, _h as collection, mh as collectionGroup, lh as connectFirestoreEmulator, Zl as count, yf as deleteDoc, Kf as deleteField, Mh as disableNetwork, gh as doc, Gh as documentId, Sh as enableIndexedDbPersistence, Dh as enableMultiTabIndexedDbPersistence, kh as enableNetwork, ql as endAt, Ll as endBefore, bh as ensureFirestoreConfigured, Ef as executeWrite, Rf as getAggregateFromServer, vf as getCountFromServer, af as getDoc, lf as getDocFromCache, ff as getDocFromServer, df as getDocs, wf as getDocsFromCache, _f as getDocsFromServer, Ph as getFirestore, zf as increment, Rh as initializeFirestore, kl as limit, Ml as limitToLast, Oh as loadBundle, Df as memoryEagerGarbageCollector, xf as memoryLocalCache, Cf as memoryLruGarbageCollector, Fh as namedQuery, If as onSnapshot, Tf as onSnapshotsInSync, Sl as or, xl as orderBy, Nf as persistentLocalCache, Of as persistentMultipleTabManager, $f as persistentSingleTabManager, Rl as query, ph as queryEqual, yh as refEqual, Uf as runTransaction, Gf as serverTimestamp, mf as setDoc, Hf as setIndexConfiguration, x as setLogLevel, cf as snapshotEqual, Fl as startAfter, Ol as startAt, Yl as sum, $h as terminate, gf as updateDoc, Nh as waitForPendingWrites, bl as where, Wf as writeBatch };
  20541. //# sourceMappingURL=index.esm2017.js.map