index.browser.esm2017.js 265 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179
  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, getDefaultEmulatorHostnameAndPort, createMockUserToken, getModularInstance, deepEqual } from '@firebase/util';
  5. /**
  6. * @license
  7. * Copyright 2017 Google LLC
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. /**
  22. * Simple wrapper around a nullable UID. Mostly exists to make code more
  23. * readable.
  24. */
  25. class d {
  26. constructor(t) {
  27. this.uid = t;
  28. }
  29. isAuthenticated() {
  30. return null != this.uid;
  31. }
  32. /**
  33. * Returns a key representing this user, suitable for inclusion in a
  34. * dictionary.
  35. */ toKey() {
  36. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  37. }
  38. isEqual(t) {
  39. return t.uid === this.uid;
  40. }
  41. }
  42. /** A user with a null UID. */ d.UNAUTHENTICATED = new d(null),
  43. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  44. // non-FirebaseAuth providers.
  45. d.GOOGLE_CREDENTIALS = new d("google-credentials-uid"), d.FIRST_PARTY = new d("first-party-uid"),
  46. d.MOCK_USER = new d("mock-user");
  47. /**
  48. * @license
  49. * Copyright 2017 Google LLC
  50. *
  51. * Licensed under the Apache License, Version 2.0 (the "License");
  52. * you may not use this file except in compliance with the License.
  53. * You may obtain a copy of the License at
  54. *
  55. * http://www.apache.org/licenses/LICENSE-2.0
  56. *
  57. * Unless required by applicable law or agreed to in writing, software
  58. * distributed under the License is distributed on an "AS IS" BASIS,
  59. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  60. * See the License for the specific language governing permissions and
  61. * limitations under the License.
  62. */
  63. let w = "9.23.0";
  64. /**
  65. * @license
  66. * Copyright 2017 Google LLC
  67. *
  68. * Licensed under the Apache License, Version 2.0 (the "License");
  69. * you may not use this file except in compliance with the License.
  70. * You may obtain a copy of the License at
  71. *
  72. * http://www.apache.org/licenses/LICENSE-2.0
  73. *
  74. * Unless required by applicable law or agreed to in writing, software
  75. * distributed under the License is distributed on an "AS IS" BASIS,
  76. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  77. * See the License for the specific language governing permissions and
  78. * limitations under the License.
  79. */
  80. const m = new Logger("@firebase/firestore");
  81. /**
  82. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  83. *
  84. * @param logLevel - The verbosity you set for activity and error logging. Can
  85. * be any of the following values:
  86. *
  87. * <ul>
  88. * <li>`debug` for the most verbose logging level, primarily for
  89. * debugging.</li>
  90. * <li>`error` to log errors only.</li>
  91. * <li><code>`silent` to turn off logging.</li>
  92. * </ul>
  93. */ function p(t) {
  94. m.setLogLevel(t);
  95. }
  96. function y(t, ...e) {
  97. if (m.logLevel <= LogLevel.DEBUG) {
  98. const n = e.map(v);
  99. m.debug(`Firestore (${w}): ${t}`, ...n);
  100. }
  101. }
  102. function g(t, ...e) {
  103. if (m.logLevel <= LogLevel.ERROR) {
  104. const n = e.map(v);
  105. m.error(`Firestore (${w}): ${t}`, ...n);
  106. }
  107. }
  108. /**
  109. * @internal
  110. */ function _(t, ...e) {
  111. if (m.logLevel <= LogLevel.WARN) {
  112. const n = e.map(v);
  113. m.warn(`Firestore (${w}): ${t}`, ...n);
  114. }
  115. }
  116. /**
  117. * Converts an additional log parameter to a string representation.
  118. */ function v(t) {
  119. if ("string" == typeof t) return t;
  120. try {
  121. return e = t, JSON.stringify(e);
  122. } catch (e) {
  123. // Converting to JSON failed, just log the object directly
  124. return t;
  125. }
  126. /**
  127. * @license
  128. * Copyright 2020 Google LLC
  129. *
  130. * Licensed under the Apache License, Version 2.0 (the "License");
  131. * you may not use this file except in compliance with the License.
  132. * You may obtain a copy of the License at
  133. *
  134. * http://www.apache.org/licenses/LICENSE-2.0
  135. *
  136. * Unless required by applicable law or agreed to in writing, software
  137. * distributed under the License is distributed on an "AS IS" BASIS,
  138. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  139. * See the License for the specific language governing permissions and
  140. * limitations under the License.
  141. */
  142. /** Formats an object as a JSON string, suitable for logging. */
  143. var e;
  144. }
  145. /**
  146. * @license
  147. * Copyright 2017 Google LLC
  148. *
  149. * Licensed under the Apache License, Version 2.0 (the "License");
  150. * you may not use this file except in compliance with the License.
  151. * You may obtain a copy of the License at
  152. *
  153. * http://www.apache.org/licenses/LICENSE-2.0
  154. *
  155. * Unless required by applicable law or agreed to in writing, software
  156. * distributed under the License is distributed on an "AS IS" BASIS,
  157. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  158. * See the License for the specific language governing permissions and
  159. * limitations under the License.
  160. */
  161. /**
  162. * Unconditionally fails, throwing an Error with the given message.
  163. * Messages are stripped in production builds.
  164. *
  165. * Returns `never` and can be used in expressions:
  166. * @example
  167. * let futureVar = fail('not implemented yet');
  168. */ function b(t = "Unexpected state") {
  169. // Log the failure in addition to throw an exception, just in case the
  170. // exception is swallowed.
  171. const e = `FIRESTORE (${w}) INTERNAL ASSERTION FAILED: ` + t;
  172. // NOTE: We don't use FirestoreError here because these are internal failures
  173. // that cannot be handled by the user. (Also it would create a circular
  174. // dependency between the error and assert modules which doesn't work.)
  175. throw g(e), new Error(e);
  176. }
  177. /**
  178. * Fails if the given assertion condition is false, throwing an Error with the
  179. * given message if it did.
  180. *
  181. * Messages are stripped in production builds.
  182. */ function E(t, e) {
  183. t || b();
  184. }
  185. /**
  186. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  187. * instance of `T` before casting.
  188. */ function I(t,
  189. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  190. e) {
  191. return t;
  192. }
  193. /**
  194. * @license
  195. * Copyright 2017 Google LLC
  196. *
  197. * Licensed under the Apache License, Version 2.0 (the "License");
  198. * you may not use this file except in compliance with the License.
  199. * You may obtain a copy of the License at
  200. *
  201. * http://www.apache.org/licenses/LICENSE-2.0
  202. *
  203. * Unless required by applicable law or agreed to in writing, software
  204. * distributed under the License is distributed on an "AS IS" BASIS,
  205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  206. * See the License for the specific language governing permissions and
  207. * limitations under the License.
  208. */ const T = "ok", A = "cancelled", R = "unknown", P = "invalid-argument", V = "deadline-exceeded", $ = "not-found", N = "already-exists", D = "permission-denied", F = "unauthenticated", x = "resource-exhausted", S = "failed-precondition", q = "aborted", O = "out-of-range", k = "unimplemented", C = "internal", M = "unavailable", L = "data-loss";
  209. /** An error returned by a Firestore operation. */ class U extends FirebaseError {
  210. /** @hideconstructor */
  211. constructor(
  212. /**
  213. * The backend error code associated with this error.
  214. */
  215. t,
  216. /**
  217. * A custom error description.
  218. */
  219. e) {
  220. super(t, e), this.code = t, this.message = e,
  221. // HACK: We write a toString property directly because Error is not a real
  222. // class and so inheritance does not work correctly. We could alternatively
  223. // do the same "back-door inheritance" trick that FirebaseError does.
  224. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  225. }
  226. }
  227. /**
  228. * @license
  229. * Copyright 2017 Google LLC
  230. *
  231. * Licensed under the Apache License, Version 2.0 (the "License");
  232. * you may not use this file except in compliance with the License.
  233. * You may obtain a copy of the License at
  234. *
  235. * http://www.apache.org/licenses/LICENSE-2.0
  236. *
  237. * Unless required by applicable law or agreed to in writing, software
  238. * distributed under the License is distributed on an "AS IS" BASIS,
  239. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  240. * See the License for the specific language governing permissions and
  241. * limitations under the License.
  242. */ class j {
  243. constructor() {
  244. this.promise = new Promise(((t, e) => {
  245. this.resolve = t, this.reject = e;
  246. }));
  247. }
  248. }
  249. /**
  250. * @license
  251. * Copyright 2017 Google LLC
  252. *
  253. * Licensed under the Apache License, Version 2.0 (the "License");
  254. * you may not use this file except in compliance with the License.
  255. * You may obtain a copy of the License at
  256. *
  257. * http://www.apache.org/licenses/LICENSE-2.0
  258. *
  259. * Unless required by applicable law or agreed to in writing, software
  260. * distributed under the License is distributed on an "AS IS" BASIS,
  261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  262. * See the License for the specific language governing permissions and
  263. * limitations under the License.
  264. */ class B {
  265. constructor(t, e) {
  266. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`);
  267. }
  268. }
  269. /**
  270. * A CredentialsProvider that always yields an empty token.
  271. * @internal
  272. */ class Q {
  273. getToken() {
  274. return Promise.resolve(null);
  275. }
  276. invalidateToken() {}
  277. start(t, e) {
  278. // Fire with initial user.
  279. t.enqueueRetryable((() => e(d.UNAUTHENTICATED)));
  280. }
  281. shutdown() {}
  282. }
  283. /**
  284. * A CredentialsProvider that always returns a constant token. Used for
  285. * emulator token mocking.
  286. */ class z {
  287. constructor(t) {
  288. this.token = t,
  289. /**
  290. * Stores the listener registered with setChangeListener()
  291. * This isn't actually necessary since the UID never changes, but we use this
  292. * to verify the listen contract is adhered to in tests.
  293. */
  294. this.changeListener = null;
  295. }
  296. getToken() {
  297. return Promise.resolve(this.token);
  298. }
  299. invalidateToken() {}
  300. start(t, e) {
  301. this.changeListener = e,
  302. // Fire with initial user.
  303. t.enqueueRetryable((() => e(this.token.user)));
  304. }
  305. shutdown() {
  306. this.changeListener = null;
  307. }
  308. }
  309. /** Credential provider for the Lite SDK. */ class W {
  310. constructor(t) {
  311. this.auth = null, t.onInit((t => {
  312. this.auth = t;
  313. }));
  314. }
  315. getToken() {
  316. return this.auth ? this.auth.getToken().then((t => t ? (E("string" == typeof t.accessToken),
  317. new B(t.accessToken, new d(this.auth.getUid()))) : null)) : Promise.resolve(null);
  318. }
  319. invalidateToken() {}
  320. start(t, e) {}
  321. shutdown() {}
  322. }
  323. /*
  324. * FirstPartyToken provides a fresh token each time its value
  325. * is requested, because if the token is too old, requests will be rejected.
  326. * Technically this may no longer be necessary since the SDK should gracefully
  327. * recover from unauthenticated errors (see b/33147818 for context), but it's
  328. * safer to keep the implementation as-is.
  329. */ class G {
  330. constructor(t, e, n) {
  331. this.t = t, this.i = e, this.o = n, this.type = "FirstParty", this.user = d.FIRST_PARTY,
  332. this.u = new Map;
  333. }
  334. /**
  335. * Gets an authorization token, using a provided factory function, or return
  336. * null.
  337. */ h() {
  338. return this.o ? this.o() : null;
  339. }
  340. get headers() {
  341. this.u.set("X-Goog-AuthUser", this.t);
  342. // Use array notation to prevent minification
  343. const t = this.h();
  344. return t && this.u.set("Authorization", t), this.i && this.u.set("X-Goog-Iam-Authorization-Token", this.i),
  345. this.u;
  346. }
  347. }
  348. /*
  349. * Provides user credentials required for the Firestore JavaScript SDK
  350. * to authenticate the user, using technique that is only available
  351. * to applications hosted by Google.
  352. */ class K {
  353. constructor(t, e, n) {
  354. this.t = t, this.i = e, this.o = n;
  355. }
  356. getToken() {
  357. return Promise.resolve(new G(this.t, this.i, this.o));
  358. }
  359. start(t, e) {
  360. // Fire with initial uid.
  361. t.enqueueRetryable((() => e(d.FIRST_PARTY)));
  362. }
  363. shutdown() {}
  364. invalidateToken() {}
  365. }
  366. class Y {
  367. constructor(t) {
  368. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  369. }
  370. }
  371. /** AppCheck token provider for the Lite SDK. */ class H {
  372. constructor(t) {
  373. this.l = t, this.appCheck = null, t.onInit((t => {
  374. this.appCheck = t;
  375. }));
  376. }
  377. getToken() {
  378. return this.appCheck ? this.appCheck.getToken().then((t => t ? (E("string" == typeof t.token),
  379. new Y(t.token)) : null)) : Promise.resolve(null);
  380. }
  381. invalidateToken() {}
  382. start(t, e) {}
  383. shutdown() {}
  384. }
  385. /**
  386. * Builds a CredentialsProvider depending on the type of
  387. * the credentials passed in.
  388. */
  389. /**
  390. * @license
  391. * Copyright 2017 Google LLC
  392. *
  393. * Licensed under the Apache License, Version 2.0 (the "License");
  394. * you may not use this file except in compliance with the License.
  395. * You may obtain a copy of the License at
  396. *
  397. * http://www.apache.org/licenses/LICENSE-2.0
  398. *
  399. * Unless required by applicable law or agreed to in writing, software
  400. * distributed under the License is distributed on an "AS IS" BASIS,
  401. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  402. * See the License for the specific language governing permissions and
  403. * limitations under the License.
  404. */
  405. class J {
  406. /**
  407. * Constructs a DatabaseInfo using the provided host, databaseId and
  408. * persistenceKey.
  409. *
  410. * @param databaseId - The database to use.
  411. * @param appId - The Firebase App Id.
  412. * @param persistenceKey - A unique identifier for this Firestore's local
  413. * storage (used in conjunction with the databaseId).
  414. * @param host - The Firestore backend host to connect to.
  415. * @param ssl - Whether to use SSL when connecting.
  416. * @param forceLongPolling - Whether to use the forceLongPolling option
  417. * when using WebChannel as the network transport.
  418. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  419. * option when using WebChannel as the network transport.
  420. * @param longPollingOptions Options that configure long-polling.
  421. * @param useFetchStreams Whether to use the Fetch API instead of
  422. * XMLHTTPRequest
  423. */
  424. constructor(t, e, n, r, s, i, o, u, c) {
  425. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = r, this.ssl = s,
  426. this.forceLongPolling = i, this.autoDetectLongPolling = o, this.longPollingOptions = u,
  427. this.useFetchStreams = c;
  428. }
  429. }
  430. /** The default database name for a project. */
  431. /**
  432. * Represents the database ID a Firestore client is associated with.
  433. * @internal
  434. */
  435. class X {
  436. constructor(t, e) {
  437. this.projectId = t, this.database = e || "(default)";
  438. }
  439. static empty() {
  440. return new X("", "");
  441. }
  442. get isDefaultDatabase() {
  443. return "(default)" === this.database;
  444. }
  445. isEqual(t) {
  446. return t instanceof X && t.projectId === this.projectId && t.database === this.database;
  447. }
  448. }
  449. /**
  450. * Path represents an ordered sequence of string segments.
  451. */
  452. class Z {
  453. constructor(t, e, n) {
  454. void 0 === e ? e = 0 : e > t.length && b(), void 0 === n ? n = t.length - e : n > t.length - e && b(),
  455. this.segments = t, this.offset = e, this.len = n;
  456. }
  457. get length() {
  458. return this.len;
  459. }
  460. isEqual(t) {
  461. return 0 === Z.comparator(this, t);
  462. }
  463. child(t) {
  464. const e = this.segments.slice(this.offset, this.limit());
  465. return t instanceof Z ? t.forEach((t => {
  466. e.push(t);
  467. })) : e.push(t), this.construct(e);
  468. }
  469. /** The index of one past the last segment of the path. */ limit() {
  470. return this.offset + this.length;
  471. }
  472. popFirst(t) {
  473. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  474. }
  475. popLast() {
  476. return this.construct(this.segments, this.offset, this.length - 1);
  477. }
  478. firstSegment() {
  479. return this.segments[this.offset];
  480. }
  481. lastSegment() {
  482. return this.get(this.length - 1);
  483. }
  484. get(t) {
  485. return this.segments[this.offset + t];
  486. }
  487. isEmpty() {
  488. return 0 === this.length;
  489. }
  490. isPrefixOf(t) {
  491. if (t.length < this.length) return !1;
  492. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  493. return !0;
  494. }
  495. isImmediateParentOf(t) {
  496. if (this.length + 1 !== t.length) return !1;
  497. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  498. return !0;
  499. }
  500. forEach(t) {
  501. for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  502. }
  503. toArray() {
  504. return this.segments.slice(this.offset, this.limit());
  505. }
  506. static comparator(t, e) {
  507. const n = Math.min(t.length, e.length);
  508. for (let r = 0; r < n; r++) {
  509. const n = t.get(r), s = e.get(r);
  510. if (n < s) return -1;
  511. if (n > s) return 1;
  512. }
  513. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  514. }
  515. }
  516. /**
  517. * A slash-separated path for navigating resources (documents and collections)
  518. * within Firestore.
  519. *
  520. * @internal
  521. */ class tt extends Z {
  522. construct(t, e, n) {
  523. return new tt(t, e, n);
  524. }
  525. canonicalString() {
  526. // NOTE: The client is ignorant of any path segments containing escape
  527. // sequences (e.g. __id123__) and just passes them through raw (they exist
  528. // for legacy reasons and should not be used frequently).
  529. return this.toArray().join("/");
  530. }
  531. toString() {
  532. return this.canonicalString();
  533. }
  534. /**
  535. * Creates a resource path from the given slash-delimited string. If multiple
  536. * arguments are provided, all components are combined. Leading and trailing
  537. * slashes from all components are ignored.
  538. */ static fromString(...t) {
  539. // NOTE: The client is ignorant of any path segments containing escape
  540. // sequences (e.g. __id123__) and just passes them through raw (they exist
  541. // for legacy reasons and should not be used frequently).
  542. const e = [];
  543. for (const n of t) {
  544. if (n.indexOf("//") >= 0) throw new U(P, `Invalid segment (${n}). Paths must not contain // in them.`);
  545. // Strip leading and traling slashed.
  546. e.push(...n.split("/").filter((t => t.length > 0)));
  547. }
  548. return new tt(e);
  549. }
  550. static emptyPath() {
  551. return new tt([]);
  552. }
  553. }
  554. const et = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  555. /**
  556. * A dot-separated path for navigating sub-objects within a document.
  557. * @internal
  558. */ class nt extends Z {
  559. construct(t, e, n) {
  560. return new nt(t, e, n);
  561. }
  562. /**
  563. * Returns true if the string could be used as a segment in a field path
  564. * without escaping.
  565. */ static isValidIdentifier(t) {
  566. return et.test(t);
  567. }
  568. canonicalString() {
  569. return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"),
  570. nt.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join(".");
  571. }
  572. toString() {
  573. return this.canonicalString();
  574. }
  575. /**
  576. * Returns true if this field references the key of a document.
  577. */ isKeyField() {
  578. return 1 === this.length && "__name__" === this.get(0);
  579. }
  580. /**
  581. * The field designating the key of a document.
  582. */ static keyField() {
  583. return new nt([ "__name__" ]);
  584. }
  585. /**
  586. * Parses a field string from the given server-formatted string.
  587. *
  588. * - Splitting the empty string is not allowed (for now at least).
  589. * - Empty segments within the string (e.g. if there are two consecutive
  590. * separators) are not allowed.
  591. *
  592. * TODO(b/37244157): we should make this more strict. Right now, it allows
  593. * non-identifier path components, even if they aren't escaped.
  594. */ static fromServerFormat(t) {
  595. const e = [];
  596. let n = "", r = 0;
  597. const s = () => {
  598. if (0 === n.length) throw new U(P, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
  599. e.push(n), n = "";
  600. };
  601. let i = !1;
  602. for (;r < t.length; ) {
  603. const e = t[r];
  604. if ("\\" === e) {
  605. if (r + 1 === t.length) throw new U(P, "Path has trailing escape character: " + t);
  606. const e = t[r + 1];
  607. if ("\\" !== e && "." !== e && "`" !== e) throw new U(P, "Path has invalid escape sequence: " + t);
  608. n += e, r += 2;
  609. } else "`" === e ? (i = !i, r++) : "." !== e || i ? (n += e, r++) : (s(), r++);
  610. }
  611. if (s(), i) throw new U(P, "Unterminated ` in path: " + t);
  612. return new nt(e);
  613. }
  614. static emptyPath() {
  615. return new nt([]);
  616. }
  617. }
  618. /**
  619. * @license
  620. * Copyright 2017 Google LLC
  621. *
  622. * Licensed under the Apache License, Version 2.0 (the "License");
  623. * you may not use this file except in compliance with the License.
  624. * You may obtain a copy of the License at
  625. *
  626. * http://www.apache.org/licenses/LICENSE-2.0
  627. *
  628. * Unless required by applicable law or agreed to in writing, software
  629. * distributed under the License is distributed on an "AS IS" BASIS,
  630. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  631. * See the License for the specific language governing permissions and
  632. * limitations under the License.
  633. */
  634. /**
  635. * @internal
  636. */ class rt {
  637. constructor(t) {
  638. this.path = t;
  639. }
  640. static fromPath(t) {
  641. return new rt(tt.fromString(t));
  642. }
  643. static fromName(t) {
  644. return new rt(tt.fromString(t).popFirst(5));
  645. }
  646. static empty() {
  647. return new rt(tt.emptyPath());
  648. }
  649. get collectionGroup() {
  650. return this.path.popLast().lastSegment();
  651. }
  652. /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
  653. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  654. }
  655. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {
  656. return this.path.get(this.path.length - 2);
  657. }
  658. /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {
  659. return this.path.popLast();
  660. }
  661. isEqual(t) {
  662. return null !== t && 0 === tt.comparator(this.path, t.path);
  663. }
  664. toString() {
  665. return this.path.toString();
  666. }
  667. static comparator(t, e) {
  668. return tt.comparator(t.path, e.path);
  669. }
  670. static isDocumentKey(t) {
  671. return t.length % 2 == 0;
  672. }
  673. /**
  674. * Creates and returns a new document key with the given segments.
  675. *
  676. * @param segments - The segments of the path to the document
  677. * @returns A new instance of DocumentKey
  678. */ static fromSegments(t) {
  679. return new rt(new tt(t.slice()));
  680. }
  681. }
  682. /**
  683. * @license
  684. * Copyright 2017 Google LLC
  685. *
  686. * Licensed under the Apache License, Version 2.0 (the "License");
  687. * you may not use this file except in compliance with the License.
  688. * You may obtain a copy of the License at
  689. *
  690. * http://www.apache.org/licenses/LICENSE-2.0
  691. *
  692. * Unless required by applicable law or agreed to in writing, software
  693. * distributed under the License is distributed on an "AS IS" BASIS,
  694. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  695. * See the License for the specific language governing permissions and
  696. * limitations under the License.
  697. */ function st(t, e, n) {
  698. if (!n) throw new U(P, `Function ${t}() cannot be called with an empty ${e}.`);
  699. }
  700. /**
  701. * Validates that two boolean options are not set at the same time.
  702. * @internal
  703. */
  704. /**
  705. * Validates that `path` refers to a document (indicated by the fact it contains
  706. * an even numbers of segments).
  707. */
  708. function it(t) {
  709. if (!rt.isDocumentKey(t)) throw new U(P, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
  710. }
  711. /**
  712. * Validates that `path` refers to a collection (indicated by the fact it
  713. * contains an odd numbers of segments).
  714. */ function ot(t) {
  715. if (rt.isDocumentKey(t)) throw new U(P, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
  716. }
  717. /**
  718. * Returns true if it's a non-null object without a custom prototype
  719. * (i.e. excludes Array, Date, etc.).
  720. */
  721. /** Returns a string describing the type / value of the provided input. */
  722. function ut(t) {
  723. if (void 0 === t) return "undefined";
  724. if (null === t) return "null";
  725. if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`),
  726. JSON.stringify(t);
  727. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  728. if ("object" == typeof t) {
  729. if (t instanceof Array) return "an array";
  730. {
  731. const e =
  732. /** try to get the constructor name for an object. */
  733. function(t) {
  734. if (t.constructor) return t.constructor.name;
  735. return null;
  736. }
  737. /**
  738. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  739. * underlying instance. Throws if `obj` is not an instance of `T`.
  740. *
  741. * This cast is used in the Lite and Full SDK to verify instance types for
  742. * arguments passed to the public API.
  743. * @internal
  744. */ (t);
  745. return e ? `a custom ${e} object` : "an object";
  746. }
  747. }
  748. return "function" == typeof t ? "a function" : b();
  749. }
  750. function ct(t,
  751. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  752. e) {
  753. if ("_delegate" in t && (
  754. // Unwrap Compat types
  755. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  756. t = t._delegate), !(t instanceof e)) {
  757. if (e.name === t.constructor.name) throw new U(P, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  758. {
  759. const n = ut(t);
  760. throw new U(P, `Expected type '${e.name}', but it was: ${n}`);
  761. }
  762. }
  763. return t;
  764. }
  765. function at(t, e) {
  766. if (e <= 0) throw new U(P, `Function ${t}() requires a positive number, but it was: ${e}.`);
  767. }
  768. /**
  769. * @license
  770. * Copyright 2023 Google LLC
  771. *
  772. * Licensed under the Apache License, Version 2.0 (the "License");
  773. * you may not use this file except in compliance with the License.
  774. * You may obtain a copy of the License at
  775. *
  776. * http://www.apache.org/licenses/LICENSE-2.0
  777. *
  778. * Unless required by applicable law or agreed to in writing, software
  779. * distributed under the License is distributed on an "AS IS" BASIS,
  780. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  781. * See the License for the specific language governing permissions and
  782. * limitations under the License.
  783. */
  784. /**
  785. * Compares two `ExperimentalLongPollingOptions` objects for equality.
  786. */
  787. /**
  788. * Creates and returns a new `ExperimentalLongPollingOptions` with the same
  789. * option values as the given instance.
  790. */
  791. function ht(t) {
  792. const e = {};
  793. return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e;
  794. }
  795. /**
  796. * @license
  797. * Copyright 2023 Google LLC
  798. *
  799. * Licensed under the Apache License, Version 2.0 (the "License");
  800. * you may not use this file except in compliance with the License.
  801. * You may obtain a copy of the License at
  802. *
  803. * http://www.apache.org/licenses/LICENSE-2.0
  804. *
  805. * Unless required by applicable law or agreed to in writing, software
  806. * distributed under the License is distributed on an "AS IS" BASIS,
  807. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  808. * See the License for the specific language governing permissions and
  809. * limitations under the License.
  810. */
  811. /**
  812. * The value returned from the most recent invocation of
  813. * `generateUniqueDebugId()`, or null if it has never been invoked.
  814. */ let lt = null;
  815. /**
  816. * Generates and returns an initial value for `lastUniqueDebugId`.
  817. *
  818. * The returned value is randomly selected from a range of integers that are
  819. * represented as 8 hexadecimal digits. This means that (within reason) any
  820. * numbers generated by incrementing the returned number by 1 will also be
  821. * represented by 8 hexadecimal digits. This leads to all "IDs" having the same
  822. * length when converted to a hexadecimal string, making reading logs containing
  823. * these IDs easier to follow. And since the return value is randomly selected
  824. * it will help to differentiate between logs from different executions.
  825. */
  826. /**
  827. * Generates and returns a unique ID as a hexadecimal string.
  828. *
  829. * The returned ID is intended to be used in debug logging messages to help
  830. * correlate log messages that may be spatially separated in the logs, but
  831. * logically related. For example, a network connection could include the same
  832. * "debug ID" string in all of its log messages to help trace a specific
  833. * connection over time.
  834. *
  835. * @return the 10-character generated ID (e.g. "0xa1b2c3d4").
  836. */
  837. function ft() {
  838. return null === lt ? lt = 268435456 + Math.round(2147483648 * Math.random()) : lt++,
  839. "0x" + lt.toString(16);
  840. }
  841. /**
  842. * @license
  843. * Copyright 2017 Google LLC
  844. *
  845. * Licensed under the Apache License, Version 2.0 (the "License");
  846. * you may not use this file except in compliance with the License.
  847. * You may obtain a copy of the License at
  848. *
  849. * http://www.apache.org/licenses/LICENSE-2.0
  850. *
  851. * Unless required by applicable law or agreed to in writing, software
  852. * distributed under the License is distributed on an "AS IS" BASIS,
  853. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  854. * See the License for the specific language governing permissions and
  855. * limitations under the License.
  856. */
  857. /**
  858. * Returns whether a variable is either undefined or null.
  859. */ function dt(t) {
  860. return null == t;
  861. }
  862. /** Returns whether the value represents -0. */ function wt(t) {
  863. // Detect if the value is -0.0. Based on polyfill from
  864. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  865. return 0 === t && 1 / t == -1 / 0;
  866. }
  867. /**
  868. * Returns whether a value is an integer and in the safe integer range
  869. * @param value - The value to test for being an integer and in the safe range
  870. */
  871. /**
  872. * @license
  873. * Copyright 2020 Google LLC
  874. *
  875. * Licensed under the Apache License, Version 2.0 (the "License");
  876. * you may not use this file except in compliance with the License.
  877. * You may obtain a copy of the License at
  878. *
  879. * http://www.apache.org/licenses/LICENSE-2.0
  880. *
  881. * Unless required by applicable law or agreed to in writing, software
  882. * distributed under the License is distributed on an "AS IS" BASIS,
  883. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  884. * See the License for the specific language governing permissions and
  885. * limitations under the License.
  886. */
  887. const mt = {
  888. BatchGetDocuments: "batchGet",
  889. Commit: "commit",
  890. RunQuery: "runQuery",
  891. RunAggregationQuery: "runAggregationQuery"
  892. };
  893. /**
  894. * Maps RPC names to the corresponding REST endpoint name.
  895. *
  896. * We use array notation to avoid mangling.
  897. */
  898. /**
  899. * @license
  900. * Copyright 2017 Google LLC
  901. *
  902. * Licensed under the Apache License, Version 2.0 (the "License");
  903. * you may not use this file except in compliance with the License.
  904. * You may obtain a copy of the License at
  905. *
  906. * http://www.apache.org/licenses/LICENSE-2.0
  907. *
  908. * Unless required by applicable law or agreed to in writing, software
  909. * distributed under the License is distributed on an "AS IS" BASIS,
  910. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  911. * See the License for the specific language governing permissions and
  912. * limitations under the License.
  913. */
  914. /**
  915. * Error Codes describing the different ways GRPC can fail. These are copied
  916. * directly from GRPC's sources here:
  917. *
  918. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  919. *
  920. * Important! The names of these identifiers matter because the string forms
  921. * are used for reverse lookups from the webchannel stream. Do NOT change the
  922. * names of these identifiers or change this into a const enum.
  923. */
  924. var pt, yt;
  925. /**
  926. * Converts an HTTP Status Code to the equivalent error code.
  927. *
  928. * @param status - An HTTP Status Code, like 200, 404, 503, etc.
  929. * @returns The equivalent Code. Unknown status codes are mapped to
  930. * Code.UNKNOWN.
  931. */
  932. function gt(t) {
  933. if (void 0 === t) return g("RPC_ERROR", "HTTP error has no status"), R;
  934. // The canonical error codes for Google APIs [1] specify mapping onto HTTP
  935. // status codes but the mapping is not bijective. In each case of ambiguity
  936. // this function chooses a primary error.
  937. // [1]
  938. // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  939. switch (t) {
  940. case 200:
  941. // OK
  942. return T;
  943. case 400:
  944. // Bad Request
  945. return S;
  946. // Other possibilities based on the forward mapping
  947. // return Code.INVALID_ARGUMENT;
  948. // return Code.OUT_OF_RANGE;
  949. case 401:
  950. // Unauthorized
  951. return F;
  952. case 403:
  953. // Forbidden
  954. return D;
  955. case 404:
  956. // Not Found
  957. return $;
  958. case 409:
  959. // Conflict
  960. return q;
  961. // Other possibilities:
  962. // return Code.ALREADY_EXISTS;
  963. case 416:
  964. // Range Not Satisfiable
  965. return O;
  966. case 429:
  967. // Too Many Requests
  968. return x;
  969. case 499:
  970. // Client Closed Request
  971. return A;
  972. case 500:
  973. // Internal Server Error
  974. return R;
  975. // Other possibilities:
  976. // return Code.INTERNAL;
  977. // return Code.DATA_LOSS;
  978. case 501:
  979. // Unimplemented
  980. return k;
  981. case 503:
  982. // Service Unavailable
  983. return M;
  984. case 504:
  985. // Gateway Timeout
  986. return V;
  987. default:
  988. return t >= 200 && t < 300 ? T : t >= 400 && t < 500 ? S : t >= 500 && t < 600 ? C : R;
  989. }
  990. }
  991. /**
  992. * @license
  993. * Copyright 2020 Google LLC
  994. *
  995. * Licensed under the Apache License, Version 2.0 (the "License");
  996. * you may not use this file except in compliance with the License.
  997. * You may obtain a copy of the License at
  998. *
  999. * http://www.apache.org/licenses/LICENSE-2.0
  1000. *
  1001. * Unless required by applicable law or agreed to in writing, software
  1002. * distributed under the License is distributed on an "AS IS" BASIS,
  1003. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1004. * See the License for the specific language governing permissions and
  1005. * limitations under the License.
  1006. */
  1007. /**
  1008. * A Rest-based connection that relies on the native HTTP stack
  1009. * (e.g. `fetch` or a polyfill).
  1010. */ (yt = pt || (pt = {}))[yt.OK = 0] = "OK", yt[yt.CANCELLED = 1] = "CANCELLED",
  1011. yt[yt.UNKNOWN = 2] = "UNKNOWN", yt[yt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  1012. yt[yt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", yt[yt.NOT_FOUND = 5] = "NOT_FOUND",
  1013. yt[yt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", yt[yt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  1014. yt[yt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", yt[yt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  1015. yt[yt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", yt[yt.ABORTED = 10] = "ABORTED",
  1016. yt[yt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", yt[yt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  1017. yt[yt.INTERNAL = 13] = "INTERNAL", yt[yt.UNAVAILABLE = 14] = "UNAVAILABLE", yt[yt.DATA_LOSS = 15] = "DATA_LOSS";
  1018. class _t extends
  1019. /**
  1020. * Base class for all Rest-based connections to the backend (WebChannel and
  1021. * HTTP).
  1022. */
  1023. class {
  1024. constructor(t) {
  1025. this.databaseInfo = t, this.databaseId = t.databaseId;
  1026. const e = t.ssl ? "https" : "http";
  1027. this.m = e + "://" + t.host, this.p = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  1028. }
  1029. get g() {
  1030. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  1031. // where to run the query, and expect the `request` to NOT specify the "path".
  1032. return !1;
  1033. }
  1034. v(t, e, n, r, s) {
  1035. const i = ft(), o = this.I(t, e);
  1036. y("RestConnection", `Sending RPC '${t}' ${i}:`, o, n);
  1037. const u = {};
  1038. return this.T(u, r, s), this.A(t, o, u, n).then((e => (y("RestConnection", `Received RPC '${t}' ${i}: `, e),
  1039. e)), (e => {
  1040. throw _("RestConnection", `RPC '${t}' ${i} failed with error: `, e, "url: ", o, "request:", n),
  1041. e;
  1042. }));
  1043. }
  1044. R(t, e, n, r, s, i) {
  1045. // The REST API automatically aggregates all of the streamed results, so we
  1046. // can just use the normal invoke() method.
  1047. return this.v(t, e, n, r, s);
  1048. }
  1049. /**
  1050. * Modifies the headers for a request, adding any authorization token if
  1051. * present and any additional headers for the request.
  1052. */ T(t, e, n) {
  1053. t["X-Goog-Api-Client"] = "gl-js/ fire/" + w,
  1054. // Content-Type: text/plain will avoid preflight requests which might
  1055. // mess with CORS and redirects by proxies. If we add custom headers
  1056. // we will need to change this code to potentially use the $httpOverwrite
  1057. // parameter supported by ESF to avoid triggering preflight requests.
  1058. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  1059. e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));
  1060. }
  1061. I(t, e) {
  1062. const n = mt[t];
  1063. return `${this.m}/v1/${e}:${n}`;
  1064. }
  1065. } {
  1066. /**
  1067. * @param databaseInfo - The connection info.
  1068. * @param fetchImpl - `fetch` or a Polyfill that implements the fetch API.
  1069. */
  1070. constructor(t, e) {
  1071. super(t), this.P = e;
  1072. }
  1073. V(t, e) {
  1074. throw new Error("Not supported by FetchConnection");
  1075. }
  1076. async A(t, e, n, r) {
  1077. var s;
  1078. const i = JSON.stringify(r);
  1079. let o;
  1080. try {
  1081. o = await this.P(e, {
  1082. method: "POST",
  1083. headers: n,
  1084. body: i
  1085. });
  1086. } catch (t) {
  1087. const e = t;
  1088. throw new U(gt(e.status), "Request failed with error: " + e.statusText);
  1089. }
  1090. if (!o.ok) {
  1091. let t = await o.json();
  1092. Array.isArray(t) && (t = t[0]);
  1093. const e = null === (s = null == t ? void 0 : t.error) || void 0 === s ? void 0 : s.message;
  1094. throw new U(gt(o.status), `Request failed with error: ${null != e ? e : o.statusText}`);
  1095. }
  1096. return o.json();
  1097. }
  1098. }
  1099. /**
  1100. * @license
  1101. * Copyright 2020 Google LLC
  1102. *
  1103. * Licensed under the Apache License, Version 2.0 (the "License");
  1104. * you may not use this file except in compliance with the License.
  1105. * You may obtain a copy of the License at
  1106. *
  1107. * http://www.apache.org/licenses/LICENSE-2.0
  1108. *
  1109. * Unless required by applicable law or agreed to in writing, software
  1110. * distributed under the License is distributed on an "AS IS" BASIS,
  1111. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1112. * See the License for the specific language governing permissions and
  1113. * limitations under the License.
  1114. */
  1115. /** Initializes the HTTP connection for the REST API. */
  1116. /**
  1117. * @license
  1118. * Copyright 2023 Google LLC
  1119. *
  1120. * Licensed under the Apache License, Version 2.0 (the "License");
  1121. * you may not use this file except in compliance with the License.
  1122. * You may obtain a copy of the License at
  1123. *
  1124. * http://www.apache.org/licenses/LICENSE-2.0
  1125. *
  1126. * Unless required by applicable law or agreed to in writing, software
  1127. * distributed under the License is distributed on an "AS IS" BASIS,
  1128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1129. * See the License for the specific language governing permissions and
  1130. * limitations under the License.
  1131. */
  1132. /**
  1133. * Concrete implementation of the Aggregate type.
  1134. */
  1135. class vt {
  1136. constructor(t, e, n) {
  1137. this.alias = t, this.$ = e, this.fieldPath = n;
  1138. }
  1139. }
  1140. /**
  1141. * @license
  1142. * Copyright 2020 Google LLC
  1143. *
  1144. * Licensed under the Apache License, Version 2.0 (the "License");
  1145. * you may not use this file except in compliance with the License.
  1146. * You may obtain a copy of the License at
  1147. *
  1148. * http://www.apache.org/licenses/LICENSE-2.0
  1149. *
  1150. * Unless required by applicable law or agreed to in writing, software
  1151. * distributed under the License is distributed on an "AS IS" BASIS,
  1152. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1153. * See the License for the specific language governing permissions and
  1154. * limitations under the License.
  1155. */
  1156. /**
  1157. * Generates `nBytes` of random bytes.
  1158. *
  1159. * If `nBytes < 0` , an error will be thrown.
  1160. */ function bt(t) {
  1161. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  1162. const e =
  1163. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1164. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  1165. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  1166. // Falls back to Math.random
  1167. for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
  1168. return n;
  1169. }
  1170. /**
  1171. * @license
  1172. * Copyright 2017 Google LLC
  1173. *
  1174. * Licensed under the Apache License, Version 2.0 (the "License");
  1175. * you may not use this file except in compliance with the License.
  1176. * You may obtain a copy of the License at
  1177. *
  1178. * http://www.apache.org/licenses/LICENSE-2.0
  1179. *
  1180. * Unless required by applicable law or agreed to in writing, software
  1181. * distributed under the License is distributed on an "AS IS" BASIS,
  1182. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1183. * See the License for the specific language governing permissions and
  1184. * limitations under the License.
  1185. */ class Et {
  1186. static N() {
  1187. // Alphanumeric characters
  1188. const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
  1189. // The largest byte value that is a multiple of `char.length`.
  1190. let n = "";
  1191. for (;n.length < 20; ) {
  1192. const r = bt(40);
  1193. for (let s = 0; s < r.length; ++s)
  1194. // Only accept values that are [0, maxMultiple), this ensures they can
  1195. // be evenly mapped to indices of `chars` via a modulo operation.
  1196. n.length < 20 && r[s] < e && (n += t.charAt(r[s] % t.length));
  1197. }
  1198. return n;
  1199. }
  1200. }
  1201. function It(t, e) {
  1202. return t < e ? -1 : t > e ? 1 : 0;
  1203. }
  1204. /** Helper to compare arrays using isEqual(). */ function Tt(t, e, n) {
  1205. return t.length === e.length && t.every(((t, r) => n(t, e[r])));
  1206. }
  1207. /**
  1208. * @license
  1209. * Copyright 2017 Google LLC
  1210. *
  1211. * Licensed under the Apache License, Version 2.0 (the "License");
  1212. * you may not use this file except in compliance with the License.
  1213. * You may obtain a copy of the License at
  1214. *
  1215. * http://www.apache.org/licenses/LICENSE-2.0
  1216. *
  1217. * Unless required by applicable law or agreed to in writing, software
  1218. * distributed under the License is distributed on an "AS IS" BASIS,
  1219. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1220. * See the License for the specific language governing permissions and
  1221. * limitations under the License.
  1222. */ function At(t) {
  1223. let e = 0;
  1224. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  1225. return e;
  1226. }
  1227. function Rt(t, e) {
  1228. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  1229. }
  1230. /**
  1231. * @license
  1232. * Copyright 2023 Google LLC
  1233. *
  1234. * Licensed under the Apache License, Version 2.0 (the "License");
  1235. * you may not use this file except in compliance with the License.
  1236. * You may obtain a copy of the License at
  1237. *
  1238. * http://www.apache.org/licenses/LICENSE-2.0
  1239. *
  1240. * Unless required by applicable law or agreed to in writing, software
  1241. * distributed under the License is distributed on an "AS IS" BASIS,
  1242. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1243. * See the License for the specific language governing permissions and
  1244. * limitations under the License.
  1245. */
  1246. /**
  1247. * An error encountered while decoding base64 string.
  1248. */
  1249. class Pt extends Error {
  1250. constructor() {
  1251. super(...arguments), this.name = "Base64DecodeError";
  1252. }
  1253. }
  1254. /**
  1255. * @license
  1256. * Copyright 2020 Google LLC
  1257. *
  1258. * Licensed under the Apache License, Version 2.0 (the "License");
  1259. * you may not use this file except in compliance with the License.
  1260. * You may obtain a copy of the License at
  1261. *
  1262. * http://www.apache.org/licenses/LICENSE-2.0
  1263. *
  1264. * Unless required by applicable law or agreed to in writing, software
  1265. * distributed under the License is distributed on an "AS IS" BASIS,
  1266. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1267. * See the License for the specific language governing permissions and
  1268. * limitations under the License.
  1269. */
  1270. /** Converts a Base64 encoded string to a binary string. */
  1271. /**
  1272. * @license
  1273. * Copyright 2020 Google LLC
  1274. *
  1275. * Licensed under the Apache License, Version 2.0 (the "License");
  1276. * you may not use this file except in compliance with the License.
  1277. * You may obtain a copy of the License at
  1278. *
  1279. * http://www.apache.org/licenses/LICENSE-2.0
  1280. *
  1281. * Unless required by applicable law or agreed to in writing, software
  1282. * distributed under the License is distributed on an "AS IS" BASIS,
  1283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1284. * See the License for the specific language governing permissions and
  1285. * limitations under the License.
  1286. */
  1287. /**
  1288. * Immutable class that represents a "proto" byte string.
  1289. *
  1290. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  1291. * sent on the wire. This class abstracts away this differentiation by holding
  1292. * the proto byte string in a common class that must be converted into a string
  1293. * before being sent as a proto.
  1294. * @internal
  1295. */
  1296. class Vt {
  1297. constructor(t) {
  1298. this.binaryString = t;
  1299. }
  1300. static fromBase64String(t) {
  1301. const e = function(t) {
  1302. try {
  1303. return atob(t);
  1304. } catch (t) {
  1305. // Check that `DOMException` is defined before using it to avoid
  1306. // "ReferenceError: Property 'DOMException' doesn't exist" in react-native.
  1307. // (https://github.com/firebase/firebase-js-sdk/issues/7115)
  1308. throw "undefined" != typeof DOMException && t instanceof DOMException ? new Pt("Invalid base64 string: " + t) : t;
  1309. }
  1310. }
  1311. /** Converts a binary string to a Base64 encoded string. */ (t);
  1312. return new Vt(e);
  1313. }
  1314. static fromUint8Array(t) {
  1315. // TODO(indexing); Remove the copy of the byte string here as this method
  1316. // is frequently called during indexing.
  1317. const e =
  1318. /**
  1319. * Helper function to convert an Uint8array to a binary string.
  1320. */
  1321. function(t) {
  1322. let e = "";
  1323. for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  1324. return e;
  1325. }
  1326. /**
  1327. * Helper function to convert a binary string to an Uint8Array.
  1328. */ (t);
  1329. return new Vt(e);
  1330. }
  1331. [Symbol.iterator]() {
  1332. let t = 0;
  1333. return {
  1334. next: () => t < this.binaryString.length ? {
  1335. value: this.binaryString.charCodeAt(t++),
  1336. done: !1
  1337. } : {
  1338. value: void 0,
  1339. done: !0
  1340. }
  1341. };
  1342. }
  1343. toBase64() {
  1344. return t = this.binaryString, btoa(t);
  1345. var t;
  1346. }
  1347. toUint8Array() {
  1348. return function(t) {
  1349. const e = new Uint8Array(t.length);
  1350. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  1351. return e;
  1352. }
  1353. /**
  1354. * @license
  1355. * Copyright 2020 Google LLC
  1356. *
  1357. * Licensed under the Apache License, Version 2.0 (the "License");
  1358. * you may not use this file except in compliance with the License.
  1359. * You may obtain a copy of the License at
  1360. *
  1361. * http://www.apache.org/licenses/LICENSE-2.0
  1362. *
  1363. * Unless required by applicable law or agreed to in writing, software
  1364. * distributed under the License is distributed on an "AS IS" BASIS,
  1365. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1366. * See the License for the specific language governing permissions and
  1367. * limitations under the License.
  1368. */
  1369. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  1370. (this.binaryString);
  1371. }
  1372. approximateByteSize() {
  1373. return 2 * this.binaryString.length;
  1374. }
  1375. compareTo(t) {
  1376. return It(this.binaryString, t.binaryString);
  1377. }
  1378. isEqual(t) {
  1379. return this.binaryString === t.binaryString;
  1380. }
  1381. }
  1382. Vt.EMPTY_BYTE_STRING = new Vt("");
  1383. const $t = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  1384. /**
  1385. * Converts the possible Proto values for a timestamp value into a "seconds and
  1386. * nanos" representation.
  1387. */ function Nt(t) {
  1388. // The json interface (for the browser) will return an iso timestamp string,
  1389. // while the proto js library (for node) will return a
  1390. // google.protobuf.Timestamp instance.
  1391. if (E(!!t), "string" == typeof t) {
  1392. // The date string can have higher precision (nanos) than the Date class
  1393. // (millis), so we do some custom parsing here.
  1394. // Parse the nanos right out of the string.
  1395. let e = 0;
  1396. const n = $t.exec(t);
  1397. if (E(!!n), n[1]) {
  1398. // Pad the fraction out to 9 digits (nanos).
  1399. let t = n[1];
  1400. t = (t + "000000000").substr(0, 9), e = Number(t);
  1401. }
  1402. // Parse the date to get the seconds.
  1403. const r = new Date(t);
  1404. return {
  1405. seconds: Math.floor(r.getTime() / 1e3),
  1406. nanos: e
  1407. };
  1408. }
  1409. return {
  1410. seconds: Dt(t.seconds),
  1411. nanos: Dt(t.nanos)
  1412. };
  1413. }
  1414. /**
  1415. * Converts the possible Proto types for numbers into a JavaScript number.
  1416. * Returns 0 if the value is not numeric.
  1417. */ function Dt(t) {
  1418. // TODO(bjornick): Handle int64 greater than 53 bits.
  1419. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  1420. }
  1421. /** Converts the possible Proto types for Blobs into a ByteString. */ function Ft(t) {
  1422. return "string" == typeof t ? Vt.fromBase64String(t) : Vt.fromUint8Array(t);
  1423. }
  1424. /**
  1425. * @license
  1426. * Copyright 2017 Google LLC
  1427. *
  1428. * Licensed under the Apache License, Version 2.0 (the "License");
  1429. * you may not use this file except in compliance with the License.
  1430. * You may obtain a copy of the License at
  1431. *
  1432. * http://www.apache.org/licenses/LICENSE-2.0
  1433. *
  1434. * Unless required by applicable law or agreed to in writing, software
  1435. * distributed under the License is distributed on an "AS IS" BASIS,
  1436. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1437. * See the License for the specific language governing permissions and
  1438. * limitations under the License.
  1439. */
  1440. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  1441. /**
  1442. * A `Timestamp` represents a point in time independent of any time zone or
  1443. * calendar, represented as seconds and fractions of seconds at nanosecond
  1444. * resolution in UTC Epoch time.
  1445. *
  1446. * It is encoded using the Proleptic Gregorian Calendar which extends the
  1447. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  1448. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  1449. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  1450. * 9999-12-31T23:59:59.999999999Z.
  1451. *
  1452. * For examples and further specifications, refer to the
  1453. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  1454. */
  1455. class xt {
  1456. /**
  1457. * Creates a new timestamp.
  1458. *
  1459. * @param seconds - The number of seconds of UTC time since Unix epoch
  1460. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  1461. * 9999-12-31T23:59:59Z inclusive.
  1462. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  1463. * resolution. Negative second values with fractions must still have
  1464. * non-negative nanoseconds values that count forward in time. Must be
  1465. * from 0 to 999,999,999 inclusive.
  1466. */
  1467. constructor(
  1468. /**
  1469. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  1470. */
  1471. t,
  1472. /**
  1473. * The fractions of a second at nanosecond resolution.*
  1474. */
  1475. e) {
  1476. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new U(P, "Timestamp nanoseconds out of range: " + e);
  1477. if (e >= 1e9) throw new U(P, "Timestamp nanoseconds out of range: " + e);
  1478. if (t < -62135596800) throw new U(P, "Timestamp seconds out of range: " + t);
  1479. // This will break in the year 10,000.
  1480. if (t >= 253402300800) throw new U(P, "Timestamp seconds out of range: " + t);
  1481. }
  1482. /**
  1483. * Creates a new timestamp with the current date, with millisecond precision.
  1484. *
  1485. * @returns a new timestamp representing the current date.
  1486. */ static now() {
  1487. return xt.fromMillis(Date.now());
  1488. }
  1489. /**
  1490. * Creates a new timestamp from the given date.
  1491. *
  1492. * @param date - The date to initialize the `Timestamp` from.
  1493. * @returns A new `Timestamp` representing the same point in time as the given
  1494. * date.
  1495. */ static fromDate(t) {
  1496. return xt.fromMillis(t.getTime());
  1497. }
  1498. /**
  1499. * Creates a new timestamp from the given number of milliseconds.
  1500. *
  1501. * @param milliseconds - Number of milliseconds since Unix epoch
  1502. * 1970-01-01T00:00:00Z.
  1503. * @returns A new `Timestamp` representing the same point in time as the given
  1504. * number of milliseconds.
  1505. */ static fromMillis(t) {
  1506. const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
  1507. return new xt(e, n);
  1508. }
  1509. /**
  1510. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  1511. * causes a loss of precision since `Date` objects only support millisecond
  1512. * precision.
  1513. *
  1514. * @returns JavaScript `Date` object representing the same point in time as
  1515. * this `Timestamp`, with millisecond precision.
  1516. */ toDate() {
  1517. return new Date(this.toMillis());
  1518. }
  1519. /**
  1520. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  1521. * epoch). This operation causes a loss of precision.
  1522. *
  1523. * @returns The point in time corresponding to this timestamp, represented as
  1524. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  1525. */ toMillis() {
  1526. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  1527. }
  1528. _compareTo(t) {
  1529. return this.seconds === t.seconds ? It(this.nanoseconds, t.nanoseconds) : It(this.seconds, t.seconds);
  1530. }
  1531. /**
  1532. * Returns true if this `Timestamp` is equal to the provided one.
  1533. *
  1534. * @param other - The `Timestamp` to compare against.
  1535. * @returns true if this `Timestamp` is equal to the provided one.
  1536. */ isEqual(t) {
  1537. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  1538. }
  1539. /** Returns a textual representation of this `Timestamp`. */ toString() {
  1540. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  1541. }
  1542. /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
  1543. return {
  1544. seconds: this.seconds,
  1545. nanoseconds: this.nanoseconds
  1546. };
  1547. }
  1548. /**
  1549. * Converts this object to a primitive string, which allows `Timestamp` objects
  1550. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  1551. */ valueOf() {
  1552. // This method returns a string of the form <seconds>.<nanoseconds> where
  1553. // <seconds> is translated to have a non-negative value and both <seconds>
  1554. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  1555. // Strings with this format then have a lexiographical ordering that matches
  1556. // the expected ordering. The <seconds> translation is done to avoid having
  1557. // a leading negative sign (i.e. a leading '-' character) in its string
  1558. // representation, which would affect its lexiographical ordering.
  1559. const t = this.seconds - -62135596800;
  1560. // Note: Up to 12 decimal digits are required to represent all valid
  1561. // 'seconds' values.
  1562. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  1563. }
  1564. }
  1565. /**
  1566. * @license
  1567. * Copyright 2020 Google LLC
  1568. *
  1569. * Licensed under the Apache License, Version 2.0 (the "License");
  1570. * you may not use this file except in compliance with the License.
  1571. * You may obtain a copy of the License at
  1572. *
  1573. * http://www.apache.org/licenses/LICENSE-2.0
  1574. *
  1575. * Unless required by applicable law or agreed to in writing, software
  1576. * distributed under the License is distributed on an "AS IS" BASIS,
  1577. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1578. * See the License for the specific language governing permissions and
  1579. * limitations under the License.
  1580. */
  1581. /**
  1582. * Represents a locally-applied ServerTimestamp.
  1583. *
  1584. * Server Timestamps are backed by MapValues that contain an internal field
  1585. * `__type__` with a value of `server_timestamp`. The previous value and local
  1586. * write time are stored in its `__previous_value__` and `__local_write_time__`
  1587. * fields respectively.
  1588. *
  1589. * Notes:
  1590. * - ServerTimestampValue instances are created as the result of applying a
  1591. * transform. They can only exist in the local view of a document. Therefore
  1592. * they do not need to be parsed or serialized.
  1593. * - When evaluated locally (e.g. for snapshot.data()), they by default
  1594. * evaluate to `null`. This behavior can be configured by passing custom
  1595. * FieldValueOptions to value().
  1596. * - With respect to other ServerTimestampValues, they sort by their
  1597. * localWriteTime.
  1598. */ function St(t) {
  1599. var e, n;
  1600. 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);
  1601. }
  1602. /**
  1603. * Returns the value of the field before this ServerTimestamp was set.
  1604. *
  1605. * Preserving the previous values allows the user to display the last resoled
  1606. * value until the backend responds with the timestamp.
  1607. */ function qt(t) {
  1608. const e = t.mapValue.fields.__previous_value__;
  1609. return St(e) ? qt(e) : e;
  1610. }
  1611. /**
  1612. * Returns the local time at which this timestamp was first set.
  1613. */ function Ot(t) {
  1614. const e = Nt(t.mapValue.fields.__local_write_time__.timestampValue);
  1615. return new xt(e.seconds, e.nanos);
  1616. }
  1617. /**
  1618. * @license
  1619. * Copyright 2020 Google LLC
  1620. *
  1621. * Licensed under the Apache License, Version 2.0 (the "License");
  1622. * you may not use this file except in compliance with the License.
  1623. * You may obtain a copy of the License at
  1624. *
  1625. * http://www.apache.org/licenses/LICENSE-2.0
  1626. *
  1627. * Unless required by applicable law or agreed to in writing, software
  1628. * distributed under the License is distributed on an "AS IS" BASIS,
  1629. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1630. * See the License for the specific language governing permissions and
  1631. * limitations under the License.
  1632. */ const kt = {
  1633. fields: {
  1634. __type__: {
  1635. stringValue: "__max__"
  1636. }
  1637. }
  1638. };
  1639. /** Extracts the backend's type order for the provided value. */
  1640. function Ct(t) {
  1641. 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 ? St(t) ? 4 /* TypeOrder.ServerTimestampValue */ :
  1642. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */
  1643. function(t) {
  1644. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  1645. }
  1646. /**
  1647. * @license
  1648. * Copyright 2022 Google LLC
  1649. *
  1650. * Licensed under the Apache License, Version 2.0 (the "License");
  1651. * you may not use this file except in compliance with the License.
  1652. * You may obtain a copy of the License at
  1653. *
  1654. * http://www.apache.org/licenses/LICENSE-2.0
  1655. *
  1656. * Unless required by applicable law or agreed to in writing, software
  1657. * distributed under the License is distributed on an "AS IS" BASIS,
  1658. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1659. * See the License for the specific language governing permissions and
  1660. * limitations under the License.
  1661. */
  1662. /**
  1663. * Represents a bound of a query.
  1664. *
  1665. * The bound is specified with the given components representing a position and
  1666. * whether it's just before or just after the position (relative to whatever the
  1667. * query order is).
  1668. *
  1669. * The position represents a logical index position for a query. It's a prefix
  1670. * of values for the (potentially implicit) order by clauses of a query.
  1671. *
  1672. * Bound provides a function to determine whether a document comes before or
  1673. * after a bound. This is influenced by whether the position is just before or
  1674. * just after the provided values.
  1675. */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : b();
  1676. }
  1677. /** Tests `left` and `right` for equality based on the backend semantics. */ function Mt(t, e) {
  1678. if (t === e) return !0;
  1679. const n = Ct(t);
  1680. if (n !== Ct(e)) return !1;
  1681. switch (n) {
  1682. case 0 /* TypeOrder.NullValue */ :
  1683. case 9007199254740991 /* TypeOrder.MaxValue */ :
  1684. return !0;
  1685. case 1 /* TypeOrder.BooleanValue */ :
  1686. return t.booleanValue === e.booleanValue;
  1687. case 4 /* TypeOrder.ServerTimestampValue */ :
  1688. return Ot(t).isEqual(Ot(e));
  1689. case 3 /* TypeOrder.TimestampValue */ :
  1690. return function(t, e) {
  1691. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  1692. // Use string equality for ISO 8601 timestamps
  1693. return t.timestampValue === e.timestampValue;
  1694. const n = Nt(t.timestampValue), r = Nt(e.timestampValue);
  1695. return n.seconds === r.seconds && n.nanos === r.nanos;
  1696. }(t, e);
  1697. case 5 /* TypeOrder.StringValue */ :
  1698. return t.stringValue === e.stringValue;
  1699. case 6 /* TypeOrder.BlobValue */ :
  1700. return function(t, e) {
  1701. return Ft(t.bytesValue).isEqual(Ft(e.bytesValue));
  1702. }(t, e);
  1703. case 7 /* TypeOrder.RefValue */ :
  1704. return t.referenceValue === e.referenceValue;
  1705. case 8 /* TypeOrder.GeoPointValue */ :
  1706. return function(t, e) {
  1707. return Dt(t.geoPointValue.latitude) === Dt(e.geoPointValue.latitude) && Dt(t.geoPointValue.longitude) === Dt(e.geoPointValue.longitude);
  1708. }(t, e);
  1709. case 2 /* TypeOrder.NumberValue */ :
  1710. return function(t, e) {
  1711. if ("integerValue" in t && "integerValue" in e) return Dt(t.integerValue) === Dt(e.integerValue);
  1712. if ("doubleValue" in t && "doubleValue" in e) {
  1713. const n = Dt(t.doubleValue), r = Dt(e.doubleValue);
  1714. return n === r ? wt(n) === wt(r) : isNaN(n) && isNaN(r);
  1715. }
  1716. return !1;
  1717. }(t, e);
  1718. case 9 /* TypeOrder.ArrayValue */ :
  1719. return Tt(t.arrayValue.values || [], e.arrayValue.values || [], Mt);
  1720. case 10 /* TypeOrder.ObjectValue */ :
  1721. return function(t, e) {
  1722. const n = t.mapValue.fields || {}, r = e.mapValue.fields || {};
  1723. if (At(n) !== At(r)) return !1;
  1724. for (const t in n) if (n.hasOwnProperty(t) && (void 0 === r[t] || !Mt(n[t], r[t]))) return !1;
  1725. return !0;
  1726. }
  1727. /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  1728. default:
  1729. return b();
  1730. }
  1731. }
  1732. function Lt(t, e) {
  1733. return void 0 !== (t.values || []).find((t => Mt(t, e)));
  1734. }
  1735. function Ut(t, e) {
  1736. if (t === e) return 0;
  1737. const n = Ct(t), r = Ct(e);
  1738. if (n !== r) return It(n, r);
  1739. switch (n) {
  1740. case 0 /* TypeOrder.NullValue */ :
  1741. case 9007199254740991 /* TypeOrder.MaxValue */ :
  1742. return 0;
  1743. case 1 /* TypeOrder.BooleanValue */ :
  1744. return It(t.booleanValue, e.booleanValue);
  1745. case 2 /* TypeOrder.NumberValue */ :
  1746. return function(t, e) {
  1747. const n = Dt(t.integerValue || t.doubleValue), r = Dt(e.integerValue || e.doubleValue);
  1748. return n < r ? -1 : n > r ? 1 : n === r ? 0 :
  1749. // one or both are NaN.
  1750. isNaN(n) ? isNaN(r) ? 0 : -1 : 1;
  1751. }(t, e);
  1752. case 3 /* TypeOrder.TimestampValue */ :
  1753. return jt(t.timestampValue, e.timestampValue);
  1754. case 4 /* TypeOrder.ServerTimestampValue */ :
  1755. return jt(Ot(t), Ot(e));
  1756. case 5 /* TypeOrder.StringValue */ :
  1757. return It(t.stringValue, e.stringValue);
  1758. case 6 /* TypeOrder.BlobValue */ :
  1759. return function(t, e) {
  1760. const n = Ft(t), r = Ft(e);
  1761. return n.compareTo(r);
  1762. }(t.bytesValue, e.bytesValue);
  1763. case 7 /* TypeOrder.RefValue */ :
  1764. return function(t, e) {
  1765. const n = t.split("/"), r = e.split("/");
  1766. for (let t = 0; t < n.length && t < r.length; t++) {
  1767. const e = It(n[t], r[t]);
  1768. if (0 !== e) return e;
  1769. }
  1770. return It(n.length, r.length);
  1771. }(t.referenceValue, e.referenceValue);
  1772. case 8 /* TypeOrder.GeoPointValue */ :
  1773. return function(t, e) {
  1774. const n = It(Dt(t.latitude), Dt(e.latitude));
  1775. if (0 !== n) return n;
  1776. return It(Dt(t.longitude), Dt(e.longitude));
  1777. }(t.geoPointValue, e.geoPointValue);
  1778. case 9 /* TypeOrder.ArrayValue */ :
  1779. return function(t, e) {
  1780. const n = t.values || [], r = e.values || [];
  1781. for (let t = 0; t < n.length && t < r.length; ++t) {
  1782. const e = Ut(n[t], r[t]);
  1783. if (e) return e;
  1784. }
  1785. return It(n.length, r.length);
  1786. }(t.arrayValue, e.arrayValue);
  1787. case 10 /* TypeOrder.ObjectValue */ :
  1788. return function(t, e) {
  1789. if (t === kt && e === kt) return 0;
  1790. if (t === kt) return 1;
  1791. if (e === kt) return -1;
  1792. const n = t.fields || {}, r = Object.keys(n), s = e.fields || {}, i = Object.keys(s);
  1793. // Even though MapValues are likely sorted correctly based on their insertion
  1794. // order (e.g. when received from the backend), local modifications can bring
  1795. // elements out of order. We need to re-sort the elements to ensure that
  1796. // canonical IDs are independent of insertion order.
  1797. r.sort(), i.sort();
  1798. for (let t = 0; t < r.length && t < i.length; ++t) {
  1799. const e = It(r[t], i[t]);
  1800. if (0 !== e) return e;
  1801. const o = Ut(n[r[t]], s[i[t]]);
  1802. if (0 !== o) return o;
  1803. }
  1804. return It(r.length, i.length);
  1805. }
  1806. /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue);
  1807. default:
  1808. throw b();
  1809. }
  1810. }
  1811. function jt(t, e) {
  1812. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return It(t, e);
  1813. const n = Nt(t), r = Nt(e), s = It(n.seconds, r.seconds);
  1814. return 0 !== s ? s : It(n.nanos, r.nanos);
  1815. }
  1816. function Bt(t, e) {
  1817. return {
  1818. referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`
  1819. };
  1820. }
  1821. /** Returns true if `value` is an ArrayValue. */ function Qt(t) {
  1822. return !!t && "arrayValue" in t;
  1823. }
  1824. /** Returns true if `value` is a NullValue. */ function zt(t) {
  1825. return !!t && "nullValue" in t;
  1826. }
  1827. /** Returns true if `value` is NaN. */ function Wt(t) {
  1828. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  1829. }
  1830. /** Returns true if `value` is a MapValue. */ function Gt(t) {
  1831. return !!t && "mapValue" in t;
  1832. }
  1833. /** Creates a deep copy of `source`. */ function Kt(t) {
  1834. if (t.geoPointValue) return {
  1835. geoPointValue: Object.assign({}, t.geoPointValue)
  1836. };
  1837. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  1838. timestampValue: Object.assign({}, t.timestampValue)
  1839. };
  1840. if (t.mapValue) {
  1841. const e = {
  1842. mapValue: {
  1843. fields: {}
  1844. }
  1845. };
  1846. return Rt(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = Kt(n))), e;
  1847. }
  1848. if (t.arrayValue) {
  1849. const e = {
  1850. arrayValue: {
  1851. values: []
  1852. }
  1853. };
  1854. for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = Kt(t.arrayValue.values[n]);
  1855. return e;
  1856. }
  1857. return Object.assign({}, t);
  1858. }
  1859. class Yt {
  1860. constructor(t, e) {
  1861. this.position = t, this.inclusive = e;
  1862. }
  1863. }
  1864. function Ht(t, e) {
  1865. if (null === t) return null === e;
  1866. if (null === e) return !1;
  1867. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  1868. for (let n = 0; n < t.position.length; n++) {
  1869. if (!Mt(t.position[n], e.position[n])) return !1;
  1870. }
  1871. return !0;
  1872. }
  1873. /**
  1874. * @license
  1875. * Copyright 2022 Google LLC
  1876. *
  1877. * Licensed under the Apache License, Version 2.0 (the "License");
  1878. * you may not use this file except in compliance with the License.
  1879. * You may obtain a copy of the License at
  1880. *
  1881. * http://www.apache.org/licenses/LICENSE-2.0
  1882. *
  1883. * Unless required by applicable law or agreed to in writing, software
  1884. * distributed under the License is distributed on an "AS IS" BASIS,
  1885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1886. * See the License for the specific language governing permissions and
  1887. * limitations under the License.
  1888. */ class Jt {}
  1889. class Xt extends Jt {
  1890. constructor(t, e, n) {
  1891. super(), this.field = t, this.op = e, this.value = n;
  1892. }
  1893. /**
  1894. * Creates a filter based on the provided arguments.
  1895. */ static create(t, e, n) {
  1896. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new ee(t, e, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new ie(t, n) : "in" /* Operator.IN */ === e ? new oe(t, n) : "not-in" /* Operator.NOT_IN */ === e ? new ue(t, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new ce(t, n) : new Xt(t, e, n);
  1897. }
  1898. static createKeyFieldInFilter(t, e, n) {
  1899. return "in" /* Operator.IN */ === e ? new ne(t, n) : new re(t, n);
  1900. }
  1901. matches(t) {
  1902. const e = t.data.field(this.field);
  1903. // Types do not have to match in NOT_EQUAL filters.
  1904. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(Ut(e, this.value)) : null !== e && Ct(this.value) === Ct(e) && this.matchesComparison(Ut(e, this.value));
  1905. // Only compare types with matching backend order (such as double and int).
  1906. }
  1907. matchesComparison(t) {
  1908. switch (this.op) {
  1909. case "<" /* Operator.LESS_THAN */ :
  1910. return t < 0;
  1911. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  1912. return t <= 0;
  1913. case "==" /* Operator.EQUAL */ :
  1914. return 0 === t;
  1915. case "!=" /* Operator.NOT_EQUAL */ :
  1916. return 0 !== t;
  1917. case ">" /* Operator.GREATER_THAN */ :
  1918. return t > 0;
  1919. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  1920. return t >= 0;
  1921. default:
  1922. return b();
  1923. }
  1924. }
  1925. isInequality() {
  1926. 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;
  1927. }
  1928. getFlattenedFilters() {
  1929. return [ this ];
  1930. }
  1931. getFilters() {
  1932. return [ this ];
  1933. }
  1934. getFirstInequalityField() {
  1935. return this.isInequality() ? this.field : null;
  1936. }
  1937. }
  1938. class Zt extends Jt {
  1939. constructor(t, e) {
  1940. super(), this.filters = t, this.op = e, this.D = null;
  1941. }
  1942. /**
  1943. * Creates a filter based on the provided arguments.
  1944. */ static create(t, e) {
  1945. return new Zt(t, e);
  1946. }
  1947. matches(t) {
  1948. return "and" /* CompositeOperator.AND */ === this.op ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));
  1949. }
  1950. getFlattenedFilters() {
  1951. return null !== this.D || (this.D = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])),
  1952. this.D;
  1953. }
  1954. // Returns a mutable copy of `this.filters`
  1955. getFilters() {
  1956. return Object.assign([], this.filters);
  1957. }
  1958. getFirstInequalityField() {
  1959. const t = this.F((t => t.isInequality()));
  1960. return null !== t ? t.field : null;
  1961. }
  1962. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  1963. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  1964. // predicate.
  1965. F(t) {
  1966. for (const e of this.getFlattenedFilters()) if (t(e)) return e;
  1967. return null;
  1968. }
  1969. }
  1970. function te(t, e) {
  1971. return t instanceof Xt ? function(t, e) {
  1972. return e instanceof Xt && t.op === e.op && t.field.isEqual(e.field) && Mt(t.value, e.value);
  1973. }(t, e) : t instanceof Zt ? function(t, e) {
  1974. if (e instanceof Zt && t.op === e.op && t.filters.length === e.filters.length) {
  1975. return t.filters.reduce(((t, n, r) => t && te(n, e.filters[r])), !0);
  1976. }
  1977. return !1;
  1978. }
  1979. /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void b();
  1980. }
  1981. class ee extends Xt {
  1982. constructor(t, e, n) {
  1983. super(t, e, n), this.key = rt.fromName(n.referenceValue);
  1984. }
  1985. matches(t) {
  1986. const e = rt.comparator(t.key, this.key);
  1987. return this.matchesComparison(e);
  1988. }
  1989. }
  1990. /** Filter that matches on key fields within an array. */ class ne extends Xt {
  1991. constructor(t, e) {
  1992. super(t, "in" /* Operator.IN */ , e), this.keys = se("in" /* Operator.IN */ , e);
  1993. }
  1994. matches(t) {
  1995. return this.keys.some((e => e.isEqual(t.key)));
  1996. }
  1997. }
  1998. /** Filter that matches on key fields not present within an array. */ class re extends Xt {
  1999. constructor(t, e) {
  2000. super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = se("not-in" /* Operator.NOT_IN */ , e);
  2001. }
  2002. matches(t) {
  2003. return !this.keys.some((e => e.isEqual(t.key)));
  2004. }
  2005. }
  2006. function se(t, e) {
  2007. var n;
  2008. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => rt.fromName(t.referenceValue)));
  2009. }
  2010. /** A Filter that implements the array-contains operator. */ class ie extends Xt {
  2011. constructor(t, e) {
  2012. super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e);
  2013. }
  2014. matches(t) {
  2015. const e = t.data.field(this.field);
  2016. return Qt(e) && Lt(e.arrayValue, this.value);
  2017. }
  2018. }
  2019. /** A Filter that implements the IN operator. */ class oe extends Xt {
  2020. constructor(t, e) {
  2021. super(t, "in" /* Operator.IN */ , e);
  2022. }
  2023. matches(t) {
  2024. const e = t.data.field(this.field);
  2025. return null !== e && Lt(this.value.arrayValue, e);
  2026. }
  2027. }
  2028. /** A Filter that implements the not-in operator. */ class ue extends Xt {
  2029. constructor(t, e) {
  2030. super(t, "not-in" /* Operator.NOT_IN */ , e);
  2031. }
  2032. matches(t) {
  2033. if (Lt(this.value.arrayValue, {
  2034. nullValue: "NULL_VALUE"
  2035. })) return !1;
  2036. const e = t.data.field(this.field);
  2037. return null !== e && !Lt(this.value.arrayValue, e);
  2038. }
  2039. }
  2040. /** A Filter that implements the array-contains-any operator. */ class ce extends Xt {
  2041. constructor(t, e) {
  2042. super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e);
  2043. }
  2044. matches(t) {
  2045. const e = t.data.field(this.field);
  2046. return !(!Qt(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => Lt(this.value.arrayValue, t)));
  2047. }
  2048. }
  2049. /**
  2050. * @license
  2051. * Copyright 2022 Google LLC
  2052. *
  2053. * Licensed under the Apache License, Version 2.0 (the "License");
  2054. * you may not use this file except in compliance with the License.
  2055. * You may obtain a copy of the License at
  2056. *
  2057. * http://www.apache.org/licenses/LICENSE-2.0
  2058. *
  2059. * Unless required by applicable law or agreed to in writing, software
  2060. * distributed under the License is distributed on an "AS IS" BASIS,
  2061. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2062. * See the License for the specific language governing permissions and
  2063. * limitations under the License.
  2064. */
  2065. /**
  2066. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  2067. */ class ae {
  2068. constructor(t, e = "asc" /* Direction.ASCENDING */) {
  2069. this.field = t, this.dir = e;
  2070. }
  2071. }
  2072. function he(t, e) {
  2073. return t.dir === e.dir && t.field.isEqual(e.field);
  2074. }
  2075. /**
  2076. * @license
  2077. * Copyright 2017 Google LLC
  2078. *
  2079. * Licensed under the Apache License, Version 2.0 (the "License");
  2080. * you may not use this file except in compliance with the License.
  2081. * You may obtain a copy of the License at
  2082. *
  2083. * http://www.apache.org/licenses/LICENSE-2.0
  2084. *
  2085. * Unless required by applicable law or agreed to in writing, software
  2086. * distributed under the License is distributed on an "AS IS" BASIS,
  2087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2088. * See the License for the specific language governing permissions and
  2089. * limitations under the License.
  2090. */
  2091. /**
  2092. * A version of a document in Firestore. This corresponds to the version
  2093. * timestamp, such as update_time or read_time.
  2094. */ class le {
  2095. constructor(t) {
  2096. this.timestamp = t;
  2097. }
  2098. static fromTimestamp(t) {
  2099. return new le(t);
  2100. }
  2101. static min() {
  2102. return new le(new xt(0, 0));
  2103. }
  2104. static max() {
  2105. return new le(new xt(253402300799, 999999999));
  2106. }
  2107. compareTo(t) {
  2108. return this.timestamp._compareTo(t.timestamp);
  2109. }
  2110. isEqual(t) {
  2111. return this.timestamp.isEqual(t.timestamp);
  2112. }
  2113. /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
  2114. // Convert to microseconds.
  2115. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  2116. }
  2117. toString() {
  2118. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  2119. }
  2120. toTimestamp() {
  2121. return this.timestamp;
  2122. }
  2123. }
  2124. /**
  2125. * @license
  2126. * Copyright 2017 Google LLC
  2127. *
  2128. * Licensed under the Apache License, Version 2.0 (the "License");
  2129. * you may not use this file except in compliance with the License.
  2130. * You may obtain a copy of the License at
  2131. *
  2132. * http://www.apache.org/licenses/LICENSE-2.0
  2133. *
  2134. * Unless required by applicable law or agreed to in writing, software
  2135. * distributed under the License is distributed on an "AS IS" BASIS,
  2136. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2137. * See the License for the specific language governing permissions and
  2138. * limitations under the License.
  2139. */
  2140. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2141. // tree.
  2142. class fe {
  2143. constructor(t, e) {
  2144. this.comparator = t, this.root = e || we.EMPTY;
  2145. }
  2146. // Returns a copy of the map, with the specified key/value added or replaced.
  2147. insert(t, e) {
  2148. return new fe(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, we.BLACK, null, null));
  2149. }
  2150. // Returns a copy of the map, with the specified key removed.
  2151. remove(t) {
  2152. return new fe(this.comparator, this.root.remove(t, this.comparator).copy(null, null, we.BLACK, null, null));
  2153. }
  2154. // Returns the value of the node with the given key, or null.
  2155. get(t) {
  2156. let e = this.root;
  2157. for (;!e.isEmpty(); ) {
  2158. const n = this.comparator(t, e.key);
  2159. if (0 === n) return e.value;
  2160. n < 0 ? e = e.left : n > 0 && (e = e.right);
  2161. }
  2162. return null;
  2163. }
  2164. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2165. // exist.
  2166. indexOf(t) {
  2167. // Number of nodes that were pruned when descending right
  2168. let e = 0, n = this.root;
  2169. for (;!n.isEmpty(); ) {
  2170. const r = this.comparator(t, n.key);
  2171. if (0 === r) return e + n.left.size;
  2172. r < 0 ? n = n.left : (
  2173. // Count all nodes left of the node plus the node itself
  2174. e += n.left.size + 1, n = n.right);
  2175. }
  2176. // Node not found
  2177. return -1;
  2178. }
  2179. isEmpty() {
  2180. return this.root.isEmpty();
  2181. }
  2182. // Returns the total number of nodes in the map.
  2183. get size() {
  2184. return this.root.size;
  2185. }
  2186. // Returns the minimum key in the map.
  2187. minKey() {
  2188. return this.root.minKey();
  2189. }
  2190. // Returns the maximum key in the map.
  2191. maxKey() {
  2192. return this.root.maxKey();
  2193. }
  2194. // Traverses the map in key order and calls the specified action function
  2195. // for each key/value pair. If action returns true, traversal is aborted.
  2196. // Returns the first truthy value returned by action, or the last falsey
  2197. // value returned by action.
  2198. inorderTraversal(t) {
  2199. return this.root.inorderTraversal(t);
  2200. }
  2201. forEach(t) {
  2202. this.inorderTraversal(((e, n) => (t(e, n), !1)));
  2203. }
  2204. toString() {
  2205. const t = [];
  2206. return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
  2207. }
  2208. // Traverses the map in reverse key order and calls the specified action
  2209. // function for each key/value pair. If action returns true, traversal is
  2210. // aborted.
  2211. // Returns the first truthy value returned by action, or the last falsey
  2212. // value returned by action.
  2213. reverseTraversal(t) {
  2214. return this.root.reverseTraversal(t);
  2215. }
  2216. // Returns an iterator over the SortedMap.
  2217. getIterator() {
  2218. return new de(this.root, null, this.comparator, !1);
  2219. }
  2220. getIteratorFrom(t) {
  2221. return new de(this.root, t, this.comparator, !1);
  2222. }
  2223. getReverseIterator() {
  2224. return new de(this.root, null, this.comparator, !0);
  2225. }
  2226. getReverseIteratorFrom(t) {
  2227. return new de(this.root, t, this.comparator, !0);
  2228. }
  2229. }
  2230. // end SortedMap
  2231. // An iterator over an LLRBNode.
  2232. class de {
  2233. constructor(t, e, n, r) {
  2234. this.isReverse = r, this.nodeStack = [];
  2235. let s = 1;
  2236. for (;!t.isEmpty(); ) if (s = e ? n(t.key, e) : 1,
  2237. // flip the comparison if we're going in reverse
  2238. e && r && (s *= -1), s < 0)
  2239. // This node is less than our start key. ignore it
  2240. t = this.isReverse ? t.left : t.right; else {
  2241. if (0 === s) {
  2242. // This node is exactly equal to our start key. Push it on the stack,
  2243. // but stop iterating;
  2244. this.nodeStack.push(t);
  2245. break;
  2246. }
  2247. // This node is greater than our start key, add it to the stack and move
  2248. // to the next one
  2249. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  2250. }
  2251. }
  2252. getNext() {
  2253. let t = this.nodeStack.pop();
  2254. const e = {
  2255. key: t.key,
  2256. value: t.value
  2257. };
  2258. 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),
  2259. t = t.left;
  2260. return e;
  2261. }
  2262. hasNext() {
  2263. return this.nodeStack.length > 0;
  2264. }
  2265. peek() {
  2266. if (0 === this.nodeStack.length) return null;
  2267. const t = this.nodeStack[this.nodeStack.length - 1];
  2268. return {
  2269. key: t.key,
  2270. value: t.value
  2271. };
  2272. }
  2273. }
  2274. // end SortedMapIterator
  2275. // Represents a node in a Left-leaning Red-Black tree.
  2276. class we {
  2277. constructor(t, e, n, r, s) {
  2278. this.key = t, this.value = e, this.color = null != n ? n : we.RED, this.left = null != r ? r : we.EMPTY,
  2279. this.right = null != s ? s : we.EMPTY, this.size = this.left.size + 1 + this.right.size;
  2280. }
  2281. // Returns a copy of the current node, optionally replacing pieces of it.
  2282. copy(t, e, n, r, s) {
  2283. return new we(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != r ? r : this.left, null != s ? s : this.right);
  2284. }
  2285. isEmpty() {
  2286. return !1;
  2287. }
  2288. // Traverses the tree in key order and calls the specified action function
  2289. // for each node. If action returns true, traversal is aborted.
  2290. // Returns the first truthy value returned by action, or the last falsey
  2291. // value returned by action.
  2292. inorderTraversal(t) {
  2293. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  2294. }
  2295. // Traverses the tree in reverse key order and calls the specified action
  2296. // function for each node. If action returns true, traversal is aborted.
  2297. // Returns the first truthy value returned by action, or the last falsey
  2298. // value returned by action.
  2299. reverseTraversal(t) {
  2300. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  2301. }
  2302. // Returns the minimum node in the tree.
  2303. min() {
  2304. return this.left.isEmpty() ? this : this.left.min();
  2305. }
  2306. // Returns the maximum key in the tree.
  2307. minKey() {
  2308. return this.min().key;
  2309. }
  2310. // Returns the maximum key in the tree.
  2311. maxKey() {
  2312. return this.right.isEmpty() ? this.key : this.right.maxKey();
  2313. }
  2314. // Returns new tree, with the key/value added.
  2315. insert(t, e, n) {
  2316. let r = this;
  2317. const s = n(t, r.key);
  2318. return r = s < 0 ? r.copy(null, null, null, r.left.insert(t, e, n), null) : 0 === s ? r.copy(null, e, null, null, null) : r.copy(null, null, null, null, r.right.insert(t, e, n)),
  2319. r.fixUp();
  2320. }
  2321. removeMin() {
  2322. if (this.left.isEmpty()) return we.EMPTY;
  2323. let t = this;
  2324. return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null),
  2325. t.fixUp();
  2326. }
  2327. // Returns new tree, with the specified item removed.
  2328. remove(t, e) {
  2329. let n, r = this;
  2330. if (e(t, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()),
  2331. r = r.copy(null, null, null, r.left.remove(t, e), null); else {
  2332. if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()),
  2333. 0 === e(t, r.key)) {
  2334. if (r.right.isEmpty()) return we.EMPTY;
  2335. n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin());
  2336. }
  2337. r = r.copy(null, null, null, null, r.right.remove(t, e));
  2338. }
  2339. return r.fixUp();
  2340. }
  2341. isRed() {
  2342. return this.color;
  2343. }
  2344. // Returns new tree after performing any needed rotations.
  2345. fixUp() {
  2346. let t = this;
  2347. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  2348. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  2349. }
  2350. moveRedLeft() {
  2351. let t = this.colorFlip();
  2352. return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()),
  2353. t = t.rotateLeft(), t = t.colorFlip()), t;
  2354. }
  2355. moveRedRight() {
  2356. let t = this.colorFlip();
  2357. return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;
  2358. }
  2359. rotateLeft() {
  2360. const t = this.copy(null, null, we.RED, null, this.right.left);
  2361. return this.right.copy(null, null, this.color, t, null);
  2362. }
  2363. rotateRight() {
  2364. const t = this.copy(null, null, we.RED, this.left.right, null);
  2365. return this.left.copy(null, null, this.color, null, t);
  2366. }
  2367. colorFlip() {
  2368. const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  2369. return this.copy(null, null, !this.color, t, e);
  2370. }
  2371. // For testing.
  2372. checkMaxDepth() {
  2373. const t = this.check();
  2374. return Math.pow(2, t) <= this.size + 1;
  2375. }
  2376. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  2377. // leaves is equal on both sides. This function verifies that or asserts.
  2378. check() {
  2379. if (this.isRed() && this.left.isRed()) throw b();
  2380. if (this.right.isRed()) throw b();
  2381. const t = this.left.check();
  2382. if (t !== this.right.check()) throw b();
  2383. return t + (this.isRed() ? 0 : 1);
  2384. }
  2385. }
  2386. // end LLRBNode
  2387. // Empty node is shared between all LLRB trees.
  2388. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2389. we.EMPTY = null, we.RED = !0, we.BLACK = !1;
  2390. // end LLRBEmptyNode
  2391. we.EMPTY = new
  2392. // Represents an empty node (a leaf node in the Red-Black Tree).
  2393. class {
  2394. constructor() {
  2395. this.size = 0;
  2396. }
  2397. get key() {
  2398. throw b();
  2399. }
  2400. get value() {
  2401. throw b();
  2402. }
  2403. get color() {
  2404. throw b();
  2405. }
  2406. get left() {
  2407. throw b();
  2408. }
  2409. get right() {
  2410. throw b();
  2411. }
  2412. // Returns a copy of the current node.
  2413. copy(t, e, n, r, s) {
  2414. return this;
  2415. }
  2416. // Returns a copy of the tree, with the specified key/value added.
  2417. insert(t, e, n) {
  2418. return new we(t, e);
  2419. }
  2420. // Returns a copy of the tree, with the specified key removed.
  2421. remove(t, e) {
  2422. return this;
  2423. }
  2424. isEmpty() {
  2425. return !0;
  2426. }
  2427. inorderTraversal(t) {
  2428. return !1;
  2429. }
  2430. reverseTraversal(t) {
  2431. return !1;
  2432. }
  2433. minKey() {
  2434. return null;
  2435. }
  2436. maxKey() {
  2437. return null;
  2438. }
  2439. isRed() {
  2440. return !1;
  2441. }
  2442. // For testing.
  2443. checkMaxDepth() {
  2444. return !0;
  2445. }
  2446. check() {
  2447. return 0;
  2448. }
  2449. };
  2450. /**
  2451. * @license
  2452. * Copyright 2017 Google LLC
  2453. *
  2454. * Licensed under the Apache License, Version 2.0 (the "License");
  2455. * you may not use this file except in compliance with the License.
  2456. * You may obtain a copy of the License at
  2457. *
  2458. * http://www.apache.org/licenses/LICENSE-2.0
  2459. *
  2460. * Unless required by applicable law or agreed to in writing, software
  2461. * distributed under the License is distributed on an "AS IS" BASIS,
  2462. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2463. * See the License for the specific language governing permissions and
  2464. * limitations under the License.
  2465. */
  2466. /**
  2467. * SortedSet is an immutable (copy-on-write) collection that holds elements
  2468. * in order specified by the provided comparator.
  2469. *
  2470. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  2471. * be equal!
  2472. */
  2473. class me {
  2474. constructor(t) {
  2475. this.comparator = t, this.data = new fe(this.comparator);
  2476. }
  2477. has(t) {
  2478. return null !== this.data.get(t);
  2479. }
  2480. first() {
  2481. return this.data.minKey();
  2482. }
  2483. last() {
  2484. return this.data.maxKey();
  2485. }
  2486. get size() {
  2487. return this.data.size;
  2488. }
  2489. indexOf(t) {
  2490. return this.data.indexOf(t);
  2491. }
  2492. /** Iterates elements in order defined by "comparator" */ forEach(t) {
  2493. this.data.inorderTraversal(((e, n) => (t(e), !1)));
  2494. }
  2495. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {
  2496. const n = this.data.getIteratorFrom(t[0]);
  2497. for (;n.hasNext(); ) {
  2498. const r = n.getNext();
  2499. if (this.comparator(r.key, t[1]) >= 0) return;
  2500. e(r.key);
  2501. }
  2502. }
  2503. /**
  2504. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  2505. */ forEachWhile(t, e) {
  2506. let n;
  2507. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {
  2508. if (!t(n.getNext().key)) return;
  2509. }
  2510. }
  2511. /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
  2512. const e = this.data.getIteratorFrom(t);
  2513. return e.hasNext() ? e.getNext().key : null;
  2514. }
  2515. getIterator() {
  2516. return new pe(this.data.getIterator());
  2517. }
  2518. getIteratorFrom(t) {
  2519. return new pe(this.data.getIteratorFrom(t));
  2520. }
  2521. /** Inserts or updates an element */ add(t) {
  2522. return this.copy(this.data.remove(t).insert(t, !0));
  2523. }
  2524. /** Deletes an element */ delete(t) {
  2525. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  2526. }
  2527. isEmpty() {
  2528. return this.data.isEmpty();
  2529. }
  2530. unionWith(t) {
  2531. let e = this;
  2532. // Make sure `result` always refers to the larger one of the two sets.
  2533. return e.size < t.size && (e = t, t = this), t.forEach((t => {
  2534. e = e.add(t);
  2535. })), e;
  2536. }
  2537. isEqual(t) {
  2538. if (!(t instanceof me)) return !1;
  2539. if (this.size !== t.size) return !1;
  2540. const e = this.data.getIterator(), n = t.data.getIterator();
  2541. for (;e.hasNext(); ) {
  2542. const t = e.getNext().key, r = n.getNext().key;
  2543. if (0 !== this.comparator(t, r)) return !1;
  2544. }
  2545. return !0;
  2546. }
  2547. toArray() {
  2548. const t = [];
  2549. return this.forEach((e => {
  2550. t.push(e);
  2551. })), t;
  2552. }
  2553. toString() {
  2554. const t = [];
  2555. return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
  2556. }
  2557. copy(t) {
  2558. const e = new me(this.comparator);
  2559. return e.data = t, e;
  2560. }
  2561. }
  2562. class pe {
  2563. constructor(t) {
  2564. this.iter = t;
  2565. }
  2566. getNext() {
  2567. return this.iter.getNext().key;
  2568. }
  2569. hasNext() {
  2570. return this.iter.hasNext();
  2571. }
  2572. }
  2573. /**
  2574. * @license
  2575. * Copyright 2020 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. * Provides a set of fields that can be used to partially patch a document.
  2591. * FieldMask is used in conjunction with ObjectValue.
  2592. * Examples:
  2593. * foo - Overwrites foo entirely with the provided value. If foo is not
  2594. * present in the companion ObjectValue, the field is deleted.
  2595. * foo.bar - Overwrites only the field bar of the object foo.
  2596. * If foo is not an object, foo is replaced with an object
  2597. * containing foo
  2598. */ class ye {
  2599. constructor(t) {
  2600. this.fields = t,
  2601. // TODO(dimond): validation of FieldMask
  2602. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  2603. t.sort(nt.comparator);
  2604. }
  2605. static empty() {
  2606. return new ye([]);
  2607. }
  2608. /**
  2609. * Returns a new FieldMask object that is the result of adding all the given
  2610. * fields paths to this field mask.
  2611. */ unionWith(t) {
  2612. let e = new me(nt.comparator);
  2613. for (const t of this.fields) e = e.add(t);
  2614. for (const n of t) e = e.add(n);
  2615. return new ye(e.toArray());
  2616. }
  2617. /**
  2618. * Verifies that `fieldPath` is included by at least one field in this field
  2619. * mask.
  2620. *
  2621. * This is an O(n) operation, where `n` is the size of the field mask.
  2622. */ covers(t) {
  2623. for (const e of this.fields) if (e.isPrefixOf(t)) return !0;
  2624. return !1;
  2625. }
  2626. isEqual(t) {
  2627. return Tt(this.fields, t.fields, ((t, e) => t.isEqual(e)));
  2628. }
  2629. }
  2630. /**
  2631. * @license
  2632. * Copyright 2017 Google LLC
  2633. *
  2634. * Licensed under the Apache License, Version 2.0 (the "License");
  2635. * you may not use this file except in compliance with the License.
  2636. * You may obtain a copy of the License at
  2637. *
  2638. * http://www.apache.org/licenses/LICENSE-2.0
  2639. *
  2640. * Unless required by applicable law or agreed to in writing, software
  2641. * distributed under the License is distributed on an "AS IS" BASIS,
  2642. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2643. * See the License for the specific language governing permissions and
  2644. * limitations under the License.
  2645. */
  2646. /**
  2647. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  2648. * ability to add and remove fields (via the ObjectValueBuilder).
  2649. */ class ge {
  2650. constructor(t) {
  2651. this.value = t;
  2652. }
  2653. static empty() {
  2654. return new ge({
  2655. mapValue: {}
  2656. });
  2657. }
  2658. /**
  2659. * Returns the value at the given path or null.
  2660. *
  2661. * @param path - the path to search
  2662. * @returns The value at the path or null if the path is not set.
  2663. */ field(t) {
  2664. if (t.isEmpty()) return this.value;
  2665. {
  2666. let e = this.value;
  2667. for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)],
  2668. !Gt(e)) return null;
  2669. return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;
  2670. }
  2671. }
  2672. /**
  2673. * Sets the field to the provided value.
  2674. *
  2675. * @param path - The field path to set.
  2676. * @param value - The value to set.
  2677. */ set(t, e) {
  2678. this.getFieldsMap(t.popLast())[t.lastSegment()] = Kt(e);
  2679. }
  2680. /**
  2681. * Sets the provided fields to the provided values.
  2682. *
  2683. * @param data - A map of fields to values (or null for deletes).
  2684. */ setAll(t) {
  2685. let e = nt.emptyPath(), n = {}, r = [];
  2686. t.forEach(((t, s) => {
  2687. if (!e.isImmediateParentOf(s)) {
  2688. // Insert the accumulated changes at this parent location
  2689. const t = this.getFieldsMap(e);
  2690. this.applyChanges(t, n, r), n = {}, r = [], e = s.popLast();
  2691. }
  2692. t ? n[s.lastSegment()] = Kt(t) : r.push(s.lastSegment());
  2693. }));
  2694. const s = this.getFieldsMap(e);
  2695. this.applyChanges(s, n, r);
  2696. }
  2697. /**
  2698. * Removes the field at the specified path. If there is no field at the
  2699. * specified path, nothing is changed.
  2700. *
  2701. * @param path - The field path to remove.
  2702. */ delete(t) {
  2703. const e = this.field(t.popLast());
  2704. Gt(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  2705. }
  2706. isEqual(t) {
  2707. return Mt(this.value, t.value);
  2708. }
  2709. /**
  2710. * Returns the map that contains the leaf element of `path`. If the parent
  2711. * entry does not yet exist, or if it is not a map, a new map will be created.
  2712. */ getFieldsMap(t) {
  2713. let e = this.value;
  2714. e.mapValue.fields || (e.mapValue = {
  2715. fields: {}
  2716. });
  2717. for (let n = 0; n < t.length; ++n) {
  2718. let r = e.mapValue.fields[t.get(n)];
  2719. Gt(r) && r.mapValue.fields || (r = {
  2720. mapValue: {
  2721. fields: {}
  2722. }
  2723. }, e.mapValue.fields[t.get(n)] = r), e = r;
  2724. }
  2725. return e.mapValue.fields;
  2726. }
  2727. /**
  2728. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  2729. * entries.
  2730. */ applyChanges(t, e, n) {
  2731. Rt(e, ((e, n) => t[e] = n));
  2732. for (const e of n) delete t[e];
  2733. }
  2734. clone() {
  2735. return new ge(Kt(this.value));
  2736. }
  2737. }
  2738. /**
  2739. * @license
  2740. * Copyright 2017 Google LLC
  2741. *
  2742. * Licensed under the Apache License, Version 2.0 (the "License");
  2743. * you may not use this file except in compliance with the License.
  2744. * You may obtain a copy of the License at
  2745. *
  2746. * http://www.apache.org/licenses/LICENSE-2.0
  2747. *
  2748. * Unless required by applicable law or agreed to in writing, software
  2749. * distributed under the License is distributed on an "AS IS" BASIS,
  2750. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2751. * See the License for the specific language governing permissions and
  2752. * limitations under the License.
  2753. */
  2754. /**
  2755. * Represents a document in Firestore with a key, version, data and whether it
  2756. * has local mutations applied to it.
  2757. *
  2758. * Documents can transition between states via `convertToFoundDocument()`,
  2759. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  2760. * not transition to one of these states even after all mutations have been
  2761. * applied, `isValidDocument()` returns false and the document should be removed
  2762. * from all views.
  2763. */ class _e {
  2764. constructor(t, e, n, r, s, i, o) {
  2765. this.key = t, this.documentType = e, this.version = n, this.readTime = r, this.createTime = s,
  2766. this.data = i, this.documentState = o;
  2767. }
  2768. /**
  2769. * Creates a document with no known version or data, but which can serve as
  2770. * base document for mutations.
  2771. */ static newInvalidDocument(t) {
  2772. return new _e(t, 0 /* DocumentType.INVALID */ ,
  2773. /* version */ le.min(),
  2774. /* readTime */ le.min(),
  2775. /* createTime */ le.min(), ge.empty(), 0 /* DocumentState.SYNCED */);
  2776. }
  2777. /**
  2778. * Creates a new document that is known to exist with the given data at the
  2779. * given version.
  2780. */ static newFoundDocument(t, e, n, r) {
  2781. return new _e(t, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  2782. /* version */ e,
  2783. /* readTime */ le.min(),
  2784. /* createTime */ n, r, 0 /* DocumentState.SYNCED */);
  2785. }
  2786. /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
  2787. return new _e(t, 2 /* DocumentType.NO_DOCUMENT */ ,
  2788. /* version */ e,
  2789. /* readTime */ le.min(),
  2790. /* createTime */ le.min(), ge.empty(), 0 /* DocumentState.SYNCED */);
  2791. }
  2792. /**
  2793. * Creates a new document that is known to exist at the given version but
  2794. * whose data is not known (e.g. a document that was updated without a known
  2795. * base document).
  2796. */ static newUnknownDocument(t, e) {
  2797. return new _e(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  2798. /* version */ e,
  2799. /* readTime */ le.min(),
  2800. /* createTime */ le.min(), ge.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  2801. }
  2802. /**
  2803. * Changes the document type to indicate that it exists and that its version
  2804. * and data are known.
  2805. */ convertToFoundDocument(t, e) {
  2806. // If a document is switching state from being an invalid or deleted
  2807. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  2808. // update from Watch or due to applying a local set mutation on top
  2809. // of a deleted document, our best guess about its createTime would be the
  2810. // version at which the document transitioned to a FOUND_DOCUMENT.
  2811. return !this.createTime.isEqual(le.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  2812. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  2813. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  2814. }
  2815. /**
  2816. * Changes the document type to indicate that it doesn't exist at the given
  2817. * version.
  2818. */ convertToNoDocument(t) {
  2819. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  2820. this.data = ge.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  2821. }
  2822. /**
  2823. * Changes the document type to indicate that it exists at a given version but
  2824. * that its data is not known (e.g. a document that was updated without a known
  2825. * base document).
  2826. */ convertToUnknownDocument(t) {
  2827. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  2828. this.data = ge.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  2829. this;
  2830. }
  2831. setHasCommittedMutations() {
  2832. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  2833. }
  2834. setHasLocalMutations() {
  2835. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = le.min(),
  2836. this;
  2837. }
  2838. setReadTime(t) {
  2839. return this.readTime = t, this;
  2840. }
  2841. get hasLocalMutations() {
  2842. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  2843. }
  2844. get hasCommittedMutations() {
  2845. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  2846. }
  2847. get hasPendingWrites() {
  2848. return this.hasLocalMutations || this.hasCommittedMutations;
  2849. }
  2850. isValidDocument() {
  2851. return 0 /* DocumentType.INVALID */ !== this.documentType;
  2852. }
  2853. isFoundDocument() {
  2854. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  2855. }
  2856. isNoDocument() {
  2857. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  2858. }
  2859. isUnknownDocument() {
  2860. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  2861. }
  2862. isEqual(t) {
  2863. return t instanceof _e && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
  2864. }
  2865. mutableCopy() {
  2866. return new _e(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  2867. }
  2868. toString() {
  2869. return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  2870. }
  2871. }
  2872. /**
  2873. * @license
  2874. * Copyright 2019 Google LLC
  2875. *
  2876. * Licensed under the Apache License, Version 2.0 (the "License");
  2877. * you may not use this file except in compliance with the License.
  2878. * You may obtain a copy of the License at
  2879. *
  2880. * http://www.apache.org/licenses/LICENSE-2.0
  2881. *
  2882. * Unless required by applicable law or agreed to in writing, software
  2883. * distributed under the License is distributed on an "AS IS" BASIS,
  2884. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2885. * See the License for the specific language governing permissions and
  2886. * limitations under the License.
  2887. */
  2888. // Visible for testing
  2889. class ve {
  2890. constructor(t, e = null, n = [], r = [], s = null, i = null, o = null) {
  2891. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = r, this.limit = s,
  2892. this.startAt = i, this.endAt = o, this.S = null;
  2893. }
  2894. }
  2895. /**
  2896. * Initializes a Target with a path and optional additional query constraints.
  2897. * Path must currently be empty if this is a collection group query.
  2898. *
  2899. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  2900. * using this factory method, because `Query` provides an implicit `orderBy`
  2901. * property.
  2902. */ function be(t, e = null, n = [], r = [], s = null, i = null, o = null) {
  2903. return new ve(t, e, n, r, s, i, o);
  2904. }
  2905. /**
  2906. * @license
  2907. * Copyright 2017 Google LLC
  2908. *
  2909. * Licensed under the Apache License, Version 2.0 (the "License");
  2910. * you may not use this file except in compliance with the License.
  2911. * You may obtain a copy of the License at
  2912. *
  2913. * http://www.apache.org/licenses/LICENSE-2.0
  2914. *
  2915. * Unless required by applicable law or agreed to in writing, software
  2916. * distributed under the License is distributed on an "AS IS" BASIS,
  2917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2918. * See the License for the specific language governing permissions and
  2919. * limitations under the License.
  2920. */
  2921. /**
  2922. * Query encapsulates all the query attributes we support in the SDK. It can
  2923. * be run against the LocalStore, as well as be converted to a `Target` to
  2924. * query the RemoteStore results.
  2925. *
  2926. * Visible for testing.
  2927. */
  2928. class Ee {
  2929. /**
  2930. * Initializes a Query with a path and optional additional query constraints.
  2931. * Path must currently be empty if this is a collection group query.
  2932. */
  2933. constructor(t, e = null, n = [], r = [], s = null, i = "F" /* LimitType.First */ , o = null, u = null) {
  2934. this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = r,
  2935. this.limit = s, this.limitType = i, this.startAt = o, this.endAt = u, this.q = null,
  2936. // The corresponding `Target` of this `Query` instance.
  2937. this.O = null, this.startAt, this.endAt;
  2938. }
  2939. }
  2940. /** Creates a new Query for a query that matches all documents at `path` */ function Ie(t) {
  2941. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  2942. }
  2943. function Te(t) {
  2944. for (const e of t.filters) {
  2945. const t = e.getFirstInequalityField();
  2946. if (null !== t) return t;
  2947. }
  2948. return null;
  2949. }
  2950. /**
  2951. * Creates a new Query for a collection group query that matches all documents
  2952. * within the provided collection group.
  2953. */
  2954. /**
  2955. * Returns whether the query matches a collection group rather than a specific
  2956. * collection.
  2957. */
  2958. function Ae(t) {
  2959. return null !== t.collectionGroup;
  2960. }
  2961. /**
  2962. * Returns the implicit order by constraint that is used to execute the Query,
  2963. * which can be different from the order by constraints the user provided (e.g.
  2964. * the SDK and backend always orders by `__name__`).
  2965. */ function Re(t) {
  2966. const e = I(t);
  2967. if (null === e.q) {
  2968. e.q = [];
  2969. const t = Te(e), n = Ie(e);
  2970. if (null !== t && null === n)
  2971. // In order to implicitly add key ordering, we must also add the
  2972. // inequality filter field for it to be a valid query.
  2973. // Note that the default inequality field and key ordering is ascending.
  2974. t.isKeyField() || e.q.push(new ae(t)), e.q.push(new ae(nt.keyField(), "asc" /* Direction.ASCENDING */)); else {
  2975. let t = !1;
  2976. for (const n of e.explicitOrderBy) e.q.push(n), n.field.isKeyField() && (t = !0);
  2977. if (!t) {
  2978. // The order of the implicit key ordering always matches the last
  2979. // explicit order by
  2980. const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  2981. e.q.push(new ae(nt.keyField(), t));
  2982. }
  2983. }
  2984. }
  2985. return e.q;
  2986. }
  2987. /**
  2988. * Converts this `Query` instance to it's corresponding `Target` representation.
  2989. */ function Pe(t) {
  2990. const e = I(t);
  2991. if (!e.O) if ("F" /* LimitType.First */ === e.limitType) e.O = be(e.path, e.collectionGroup, Re(e), e.filters, e.limit, e.startAt, e.endAt); else {
  2992. // Flip the orderBy directions since we want the last results
  2993. const t = [];
  2994. for (const n of Re(e)) {
  2995. const e = "desc" /* Direction.DESCENDING */ === n.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  2996. t.push(new ae(n.field, e));
  2997. }
  2998. // We need to swap the cursors to match the now-flipped query ordering.
  2999. const n = e.endAt ? new Yt(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Yt(e.startAt.position, e.startAt.inclusive) : null;
  3000. // Now return as a LimitType.First query.
  3001. e.O = be(e.path, e.collectionGroup, t, e.filters, e.limit, n, r);
  3002. }
  3003. return e.O;
  3004. }
  3005. function Ve(t, e) {
  3006. e.getFirstInequalityField(), Te(t);
  3007. const n = t.filters.concat([ e ]);
  3008. return new Ee(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  3009. }
  3010. function $e(t, e) {
  3011. return function(t, e) {
  3012. if (t.limit !== e.limit) return !1;
  3013. if (t.orderBy.length !== e.orderBy.length) return !1;
  3014. for (let n = 0; n < t.orderBy.length; n++) if (!he(t.orderBy[n], e.orderBy[n])) return !1;
  3015. if (t.filters.length !== e.filters.length) return !1;
  3016. for (let n = 0; n < t.filters.length; n++) if (!te(t.filters[n], e.filters[n])) return !1;
  3017. return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!Ht(t.startAt, e.startAt) && Ht(t.endAt, e.endAt);
  3018. }(Pe(t), Pe(e)) && t.limitType === e.limitType;
  3019. }
  3020. /**
  3021. * @license
  3022. * Copyright 2020 Google LLC
  3023. *
  3024. * Licensed under the Apache License, Version 2.0 (the "License");
  3025. * you may not use this file except in compliance with the License.
  3026. * You may obtain a copy of the License at
  3027. *
  3028. * http://www.apache.org/licenses/LICENSE-2.0
  3029. *
  3030. * Unless required by applicable law or agreed to in writing, software
  3031. * distributed under the License is distributed on an "AS IS" BASIS,
  3032. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3033. * See the License for the specific language governing permissions and
  3034. * limitations under the License.
  3035. */
  3036. /**
  3037. * Returns an DoubleValue for `value` that is encoded based the serializer's
  3038. * `useProto3Json` setting.
  3039. */
  3040. /**
  3041. * Returns a value for a number that's appropriate to put into a proto.
  3042. * The return value is an IntegerValue if it can safely represent the value,
  3043. * otherwise a DoubleValue is returned.
  3044. */
  3045. function Ne(t, e) {
  3046. return function(t) {
  3047. return "number" == typeof t && Number.isInteger(t) && !wt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  3048. }(e) ?
  3049. /**
  3050. * Returns an IntegerValue for `value`.
  3051. */
  3052. function(t) {
  3053. return {
  3054. integerValue: "" + t
  3055. };
  3056. }(e) : function(t, e) {
  3057. if (t.useProto3Json) {
  3058. if (isNaN(e)) return {
  3059. doubleValue: "NaN"
  3060. };
  3061. if (e === 1 / 0) return {
  3062. doubleValue: "Infinity"
  3063. };
  3064. if (e === -1 / 0) return {
  3065. doubleValue: "-Infinity"
  3066. };
  3067. }
  3068. return {
  3069. doubleValue: wt(e) ? "-0" : e
  3070. };
  3071. }(t, e);
  3072. }
  3073. /**
  3074. * @license
  3075. * Copyright 2018 Google LLC
  3076. *
  3077. * Licensed under the Apache License, Version 2.0 (the "License");
  3078. * you may not use this file except in compliance with the License.
  3079. * You may obtain a copy of the License at
  3080. *
  3081. * http://www.apache.org/licenses/LICENSE-2.0
  3082. *
  3083. * Unless required by applicable law or agreed to in writing, software
  3084. * distributed under the License is distributed on an "AS IS" BASIS,
  3085. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3086. * See the License for the specific language governing permissions and
  3087. * limitations under the License.
  3088. */
  3089. /** Used to represent a field transform on a mutation. */ class De {
  3090. constructor() {
  3091. // Make sure that the structural type of `TransformOperation` is unique.
  3092. // See https://github.com/microsoft/TypeScript/issues/5451
  3093. this._ = void 0;
  3094. }
  3095. }
  3096. /** Transforms a value into a server-generated timestamp. */ class Fe extends De {}
  3097. /** Transforms an array value via a union operation. */ class xe extends De {
  3098. constructor(t) {
  3099. super(), this.elements = t;
  3100. }
  3101. }
  3102. /** Transforms an array value via a remove operation. */ class Se extends De {
  3103. constructor(t) {
  3104. super(), this.elements = t;
  3105. }
  3106. }
  3107. /**
  3108. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  3109. * transforms. Converts all field values to integers or doubles, but unlike the
  3110. * backend does not cap integer values at 2^63. Instead, JavaScript number
  3111. * arithmetic is used and precision loss can occur for values greater than 2^53.
  3112. */ class qe extends De {
  3113. constructor(t, e) {
  3114. super(), this.serializer = t, this.k = e;
  3115. }
  3116. }
  3117. /**
  3118. * @license
  3119. * Copyright 2017 Google LLC
  3120. *
  3121. * Licensed under the Apache License, Version 2.0 (the "License");
  3122. * you may not use this file except in compliance with the License.
  3123. * You may obtain a copy of the License at
  3124. *
  3125. * http://www.apache.org/licenses/LICENSE-2.0
  3126. *
  3127. * Unless required by applicable law or agreed to in writing, software
  3128. * distributed under the License is distributed on an "AS IS" BASIS,
  3129. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3130. * See the License for the specific language governing permissions and
  3131. * limitations under the License.
  3132. */
  3133. /** A field path and the TransformOperation to perform upon it. */ class Oe {
  3134. constructor(t, e) {
  3135. this.field = t, this.transform = e;
  3136. }
  3137. }
  3138. /**
  3139. * Encodes a precondition for a mutation. This follows the model that the
  3140. * backend accepts with the special case of an explicit "empty" precondition
  3141. * (meaning no precondition).
  3142. */ class ke {
  3143. constructor(t, e) {
  3144. this.updateTime = t, this.exists = e;
  3145. }
  3146. /** Creates a new empty Precondition. */ static none() {
  3147. return new ke;
  3148. }
  3149. /** Creates a new Precondition with an exists flag. */ static exists(t) {
  3150. return new ke(void 0, t);
  3151. }
  3152. /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {
  3153. return new ke(t);
  3154. }
  3155. /** Returns whether this Precondition is empty. */ get isNone() {
  3156. return void 0 === this.updateTime && void 0 === this.exists;
  3157. }
  3158. isEqual(t) {
  3159. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  3160. }
  3161. }
  3162. /**
  3163. * A mutation describes a self-contained change to a document. Mutations can
  3164. * create, replace, delete, and update subsets of documents.
  3165. *
  3166. * Mutations not only act on the value of the document but also its version.
  3167. *
  3168. * For local mutations (mutations that haven't been committed yet), we preserve
  3169. * the existing version for Set and Patch mutations. For Delete mutations, we
  3170. * reset the version to 0.
  3171. *
  3172. * Here's the expected transition table.
  3173. *
  3174. * MUTATION APPLIED TO RESULTS IN
  3175. *
  3176. * SetMutation Document(v3) Document(v3)
  3177. * SetMutation NoDocument(v3) Document(v0)
  3178. * SetMutation InvalidDocument(v0) Document(v0)
  3179. * PatchMutation Document(v3) Document(v3)
  3180. * PatchMutation NoDocument(v3) NoDocument(v3)
  3181. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  3182. * DeleteMutation Document(v3) NoDocument(v0)
  3183. * DeleteMutation NoDocument(v3) NoDocument(v0)
  3184. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  3185. *
  3186. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  3187. * the resulting version for Set and Patch mutations. As deletes have no
  3188. * explicit update time, we use the commitTime of the WriteResponse for
  3189. * Delete mutations.
  3190. *
  3191. * If a mutation is acknowledged by the backend but fails the precondition check
  3192. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  3193. * the updated version.
  3194. *
  3195. * Field transforms are used only with Patch and Set Mutations. We use the
  3196. * `updateTransforms` message to store transforms, rather than the `transforms`s
  3197. * messages.
  3198. *
  3199. * ## Subclassing Notes
  3200. *
  3201. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  3202. * applyToLocalView() to implement the actual behavior of applying the mutation
  3203. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  3204. * example).
  3205. */ class Ce {}
  3206. /**
  3207. * A mutation that creates or replaces the document at the given key with the
  3208. * object value contents.
  3209. */ class Me extends Ce {
  3210. constructor(t, e, n, r = []) {
  3211. super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = r,
  3212. this.type = 0 /* MutationType.Set */;
  3213. }
  3214. getFieldMask() {
  3215. return null;
  3216. }
  3217. }
  3218. /**
  3219. * A mutation that modifies fields of the document at the given key with the
  3220. * given values. The values are applied through a field mask:
  3221. *
  3222. * * When a field is in both the mask and the values, the corresponding field
  3223. * is updated.
  3224. * * When a field is in neither the mask nor the values, the corresponding
  3225. * field is unmodified.
  3226. * * When a field is in the mask but not in the values, the corresponding field
  3227. * is deleted.
  3228. * * When a field is not in the mask but is in the values, the values map is
  3229. * ignored.
  3230. */ class Le extends Ce {
  3231. constructor(t, e, n, r, s = []) {
  3232. super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = r,
  3233. this.fieldTransforms = s, this.type = 1 /* MutationType.Patch */;
  3234. }
  3235. getFieldMask() {
  3236. return this.fieldMask;
  3237. }
  3238. }
  3239. /** A mutation that deletes the document at the given key. */ class Ue extends Ce {
  3240. constructor(t, e) {
  3241. super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ ,
  3242. this.fieldTransforms = [];
  3243. }
  3244. getFieldMask() {
  3245. return null;
  3246. }
  3247. }
  3248. /**
  3249. * A mutation that verifies the existence of the document at the given key with
  3250. * the provided precondition.
  3251. *
  3252. * The `verify` operation is only used in Transactions, and this class serves
  3253. * primarily to facilitate serialization into protos.
  3254. */ class je extends Ce {
  3255. constructor(t, e) {
  3256. super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ ,
  3257. this.fieldTransforms = [];
  3258. }
  3259. getFieldMask() {
  3260. return null;
  3261. }
  3262. }
  3263. /**
  3264. * @license
  3265. * Copyright 2017 Google LLC
  3266. *
  3267. * Licensed under the Apache License, Version 2.0 (the "License");
  3268. * you may not use this file except in compliance with the License.
  3269. * You may obtain a copy of the License at
  3270. *
  3271. * http://www.apache.org/licenses/LICENSE-2.0
  3272. *
  3273. * Unless required by applicable law or agreed to in writing, software
  3274. * distributed under the License is distributed on an "AS IS" BASIS,
  3275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3276. * See the License for the specific language governing permissions and
  3277. * limitations under the License.
  3278. */ const Be = (() => {
  3279. const t = {
  3280. asc: "ASCENDING",
  3281. desc: "DESCENDING"
  3282. };
  3283. return t;
  3284. })(), Qe = (() => {
  3285. const t = {
  3286. "<": "LESS_THAN",
  3287. "<=": "LESS_THAN_OR_EQUAL",
  3288. ">": "GREATER_THAN",
  3289. ">=": "GREATER_THAN_OR_EQUAL",
  3290. "==": "EQUAL",
  3291. "!=": "NOT_EQUAL",
  3292. "array-contains": "ARRAY_CONTAINS",
  3293. in: "IN",
  3294. "not-in": "NOT_IN",
  3295. "array-contains-any": "ARRAY_CONTAINS_ANY"
  3296. };
  3297. return t;
  3298. })(), ze = (() => {
  3299. const t = {
  3300. and: "AND",
  3301. or: "OR"
  3302. };
  3303. return t;
  3304. })();
  3305. /**
  3306. * This class generates JsonObject values for the Datastore API suitable for
  3307. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  3308. *
  3309. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  3310. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  3311. * format.
  3312. *
  3313. * For a description of the Proto3 JSON format check
  3314. * https://developers.google.com/protocol-buffers/docs/proto3#json
  3315. *
  3316. * TODO(klimt): We can remove the databaseId argument if we keep the full
  3317. * resource name in documents.
  3318. */
  3319. class We {
  3320. constructor(t, e) {
  3321. this.databaseId = t, this.useProto3Json = e;
  3322. }
  3323. }
  3324. /**
  3325. * Returns a value for a number (or null) that's appropriate to put into
  3326. * a google.protobuf.Int32Value proto.
  3327. * DO NOT USE THIS FOR ANYTHING ELSE.
  3328. * This method cheats. It's typed as returning "number" because that's what
  3329. * our generated proto interfaces say Int32Value must be. But GRPC actually
  3330. * expects a { value: <number> } struct.
  3331. */
  3332. /**
  3333. * Returns a value for a Date that's appropriate to put into a proto.
  3334. */
  3335. function Ge(t, e) {
  3336. if (t.useProto3Json) {
  3337. return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
  3338. }
  3339. return {
  3340. seconds: "" + e.seconds,
  3341. nanos: e.nanoseconds
  3342. };
  3343. }
  3344. /**
  3345. * Returns a value for bytes that's appropriate to put in a proto.
  3346. *
  3347. * Visible for testing.
  3348. */
  3349. function Ke(t, e) {
  3350. return t.useProto3Json ? e.toBase64() : e.toUint8Array();
  3351. }
  3352. function Ye(t, e) {
  3353. return Ge(t, e.toTimestamp());
  3354. }
  3355. function He(t) {
  3356. return E(!!t), le.fromTimestamp(function(t) {
  3357. const e = Nt(t);
  3358. return new xt(e.seconds, e.nanos);
  3359. }(t));
  3360. }
  3361. function Je(t, e) {
  3362. return function(t) {
  3363. return new tt([ "projects", t.projectId, "databases", t.database ]);
  3364. }(t).child("documents").child(e).canonicalString();
  3365. }
  3366. function Xe(t, e) {
  3367. return Je(t.databaseId, e.path);
  3368. }
  3369. function Ze(t, e) {
  3370. const n = function(t) {
  3371. const e = tt.fromString(t);
  3372. return E(dn(e)), e;
  3373. }(e);
  3374. if (n.get(1) !== t.databaseId.projectId) throw new U(P, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  3375. if (n.get(3) !== t.databaseId.database) throw new U(P, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  3376. return new rt((E((r = n).length > 4 && "documents" === r.get(4)), r.popFirst(5)));
  3377. var r;
  3378. /** Creates a Document proto from key and fields (but no create/update time) */}
  3379. function tn(t, e) {
  3380. return Je(t.databaseId, e);
  3381. }
  3382. function en(t) {
  3383. return new tt([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  3384. }
  3385. function nn(t, e, n) {
  3386. return {
  3387. name: Xe(t, e),
  3388. fields: n.value.mapValue.fields
  3389. };
  3390. }
  3391. function rn(t, e) {
  3392. return "found" in e ? function(t, e) {
  3393. E(!!e.found), e.found.name, e.found.updateTime;
  3394. const n = Ze(t, e.found.name), r = He(e.found.updateTime), s = e.found.createTime ? He(e.found.createTime) : le.min(), i = new ge({
  3395. mapValue: {
  3396. fields: e.found.fields
  3397. }
  3398. });
  3399. return _e.newFoundDocument(n, r, s, i);
  3400. }(t, e) : "missing" in e ? function(t, e) {
  3401. E(!!e.missing), E(!!e.readTime);
  3402. const n = Ze(t, e.missing), r = He(e.readTime);
  3403. return _e.newNoDocument(n, r);
  3404. }(t, e) : b();
  3405. }
  3406. function sn(t, e) {
  3407. let n;
  3408. if (e instanceof Me) n = {
  3409. update: nn(t, e.key, e.value)
  3410. }; else if (e instanceof Ue) n = {
  3411. delete: Xe(t, e.key)
  3412. }; else if (e instanceof Le) n = {
  3413. update: nn(t, e.key, e.data),
  3414. updateMask: fn(e.fieldMask)
  3415. }; else {
  3416. if (!(e instanceof je)) return b();
  3417. n = {
  3418. verify: Xe(t, e.key)
  3419. };
  3420. }
  3421. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
  3422. const n = e.transform;
  3423. if (n instanceof Fe) return {
  3424. fieldPath: e.field.canonicalString(),
  3425. setToServerValue: "REQUEST_TIME"
  3426. };
  3427. if (n instanceof xe) return {
  3428. fieldPath: e.field.canonicalString(),
  3429. appendMissingElements: {
  3430. values: n.elements
  3431. }
  3432. };
  3433. if (n instanceof Se) return {
  3434. fieldPath: e.field.canonicalString(),
  3435. removeAllFromArray: {
  3436. values: n.elements
  3437. }
  3438. };
  3439. if (n instanceof qe) return {
  3440. fieldPath: e.field.canonicalString(),
  3441. increment: n.k
  3442. };
  3443. throw b();
  3444. }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  3445. return void 0 !== e.updateTime ? {
  3446. updateTime: Ye(t, e.updateTime)
  3447. } : void 0 !== e.exists ? {
  3448. exists: e.exists
  3449. } : b();
  3450. }(t, e.precondition)), n;
  3451. }
  3452. function on(t, e) {
  3453. // Dissect the path into parent, collectionId, and optional key filter.
  3454. const n = {
  3455. structuredQuery: {}
  3456. }, r = e.path;
  3457. null !== e.collectionGroup ? (n.parent = tn(t, r), n.structuredQuery.from = [ {
  3458. collectionId: e.collectionGroup,
  3459. allDescendants: !0
  3460. } ]) : (n.parent = tn(t, r.popLast()), n.structuredQuery.from = [ {
  3461. collectionId: r.lastSegment()
  3462. } ]);
  3463. const s = function(t) {
  3464. if (0 === t.length) return;
  3465. return ln(Zt.create(t, "and" /* CompositeOperator.AND */));
  3466. }(e.filters);
  3467. s && (n.structuredQuery.where = s);
  3468. const i = function(t) {
  3469. if (0 === t.length) return;
  3470. return t.map((t =>
  3471. // visible for testing
  3472. function(t) {
  3473. return {
  3474. field: hn(t.field),
  3475. direction: un(t.dir)
  3476. };
  3477. }
  3478. // visible for testing
  3479. (t)));
  3480. }(e.orderBy);
  3481. i && (n.structuredQuery.orderBy = i);
  3482. const o = function(t, e) {
  3483. return t.useProto3Json || dt(e) ? e : {
  3484. value: e
  3485. };
  3486. }(t, e.limit);
  3487. var u;
  3488. return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {
  3489. before: (u = e.startAt).inclusive,
  3490. values: u.position
  3491. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  3492. return {
  3493. before: !t.inclusive,
  3494. values: t.position
  3495. };
  3496. }
  3497. // visible for testing
  3498. (e.endAt)), n;
  3499. }
  3500. function un(t) {
  3501. return Be[t];
  3502. }
  3503. // visible for testing
  3504. function cn(t) {
  3505. return Qe[t];
  3506. }
  3507. function an(t) {
  3508. return ze[t];
  3509. }
  3510. function hn(t) {
  3511. return {
  3512. fieldPath: t.canonicalString()
  3513. };
  3514. }
  3515. function ln(t) {
  3516. return t instanceof Xt ? function(t) {
  3517. if ("==" /* Operator.EQUAL */ === t.op) {
  3518. if (Wt(t.value)) return {
  3519. unaryFilter: {
  3520. field: hn(t.field),
  3521. op: "IS_NAN"
  3522. }
  3523. };
  3524. if (zt(t.value)) return {
  3525. unaryFilter: {
  3526. field: hn(t.field),
  3527. op: "IS_NULL"
  3528. }
  3529. };
  3530. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  3531. if (Wt(t.value)) return {
  3532. unaryFilter: {
  3533. field: hn(t.field),
  3534. op: "IS_NOT_NAN"
  3535. }
  3536. };
  3537. if (zt(t.value)) return {
  3538. unaryFilter: {
  3539. field: hn(t.field),
  3540. op: "IS_NOT_NULL"
  3541. }
  3542. };
  3543. }
  3544. return {
  3545. fieldFilter: {
  3546. field: hn(t.field),
  3547. op: cn(t.op),
  3548. value: t.value
  3549. }
  3550. };
  3551. }(t) : t instanceof Zt ? function(t) {
  3552. const e = t.getFilters().map((t => ln(t)));
  3553. if (1 === e.length) return e[0];
  3554. return {
  3555. compositeFilter: {
  3556. op: an(t.op),
  3557. filters: e
  3558. }
  3559. };
  3560. }(t) : b();
  3561. }
  3562. function fn(t) {
  3563. const e = [];
  3564. return t.fields.forEach((t => e.push(t.canonicalString()))), {
  3565. fieldPaths: e
  3566. };
  3567. }
  3568. function dn(t) {
  3569. // Resource names have at least 4 components (project ID, database ID)
  3570. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  3571. }
  3572. /**
  3573. * @license
  3574. * Copyright 2020 Google LLC
  3575. *
  3576. * Licensed under the Apache License, Version 2.0 (the "License");
  3577. * you may not use this file except in compliance with the License.
  3578. * You may obtain a copy of the License at
  3579. *
  3580. * http://www.apache.org/licenses/LICENSE-2.0
  3581. *
  3582. * Unless required by applicable law or agreed to in writing, software
  3583. * distributed under the License is distributed on an "AS IS" BASIS,
  3584. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3585. * See the License for the specific language governing permissions and
  3586. * limitations under the License.
  3587. */ function wn(t) {
  3588. return new We(t, /* useProto3Json= */ !0);
  3589. }
  3590. /**
  3591. * @license
  3592. * Copyright 2017 Google LLC
  3593. *
  3594. * Licensed under the Apache License, Version 2.0 (the "License");
  3595. * you may not use this file except in compliance with the License.
  3596. * You may obtain a copy of the License at
  3597. *
  3598. * http://www.apache.org/licenses/LICENSE-2.0
  3599. *
  3600. * Unless required by applicable law or agreed to in writing, software
  3601. * distributed under the License is distributed on an "AS IS" BASIS,
  3602. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3603. * See the License for the specific language governing permissions and
  3604. * limitations under the License.
  3605. */
  3606. /**
  3607. * A helper for running delayed tasks following an exponential backoff curve
  3608. * between attempts.
  3609. *
  3610. * Each delay is made up of a "base" delay which follows the exponential
  3611. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  3612. * base delay. This prevents clients from accidentally synchronizing their
  3613. * delays causing spikes of load to the backend.
  3614. */
  3615. class mn {
  3616. constructor(
  3617. /**
  3618. * The AsyncQueue to run backoff operations on.
  3619. */
  3620. t,
  3621. /**
  3622. * The ID to use when scheduling backoff operations on the AsyncQueue.
  3623. */
  3624. e,
  3625. /**
  3626. * The initial delay (used as the base delay on the first retry attempt).
  3627. * Note that jitter will still be applied, so the actual delay could be as
  3628. * little as 0.5*initialDelayMs.
  3629. */
  3630. n = 1e3
  3631. /**
  3632. * The multiplier to use to determine the extended base delay after each
  3633. * attempt.
  3634. */ , r = 1.5
  3635. /**
  3636. * The maximum base delay after which no further backoff is performed.
  3637. * Note that jitter will still be applied, so the actual delay could be as
  3638. * much as 1.5*maxDelayMs.
  3639. */ , s = 6e4) {
  3640. this.C = t, this.timerId = e, this.M = n, this.L = r, this.U = s, this.j = 0, this.B = null,
  3641. /** The last backoff attempt, as epoch milliseconds. */
  3642. this.W = Date.now(), this.reset();
  3643. }
  3644. /**
  3645. * Resets the backoff delay.
  3646. *
  3647. * The very next backoffAndWait() will have no delay. If it is called again
  3648. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  3649. * subsequent ones will increase according to the backoffFactor.
  3650. */ reset() {
  3651. this.j = 0;
  3652. }
  3653. /**
  3654. * Resets the backoff delay to the maximum delay (e.g. for use after a
  3655. * RESOURCE_EXHAUSTED error).
  3656. */ G() {
  3657. this.j = this.U;
  3658. }
  3659. /**
  3660. * Returns a promise that resolves after currentDelayMs, and increases the
  3661. * delay for any subsequent attempts. If there was a pending backoff operation
  3662. * already, it will be canceled.
  3663. */ K(t) {
  3664. // Cancel any pending backoff operation.
  3665. this.cancel();
  3666. // First schedule using the current base (which may be 0 and should be
  3667. // honored as such).
  3668. const e = Math.floor(this.j + this.Y()), n = Math.max(0, Date.now() - this.W), r = Math.max(0, e - n);
  3669. // Guard against lastAttemptTime being in the future due to a clock change.
  3670. r > 0 && y("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.j} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),
  3671. this.B = this.C.enqueueAfterDelay(this.timerId, r, (() => (this.W = Date.now(),
  3672. t()))),
  3673. // Apply backoff factor to determine next delay and ensure it is within
  3674. // bounds.
  3675. this.j *= this.L, this.j < this.M && (this.j = this.M), this.j > this.U && (this.j = this.U);
  3676. }
  3677. H() {
  3678. null !== this.B && (this.B.skipDelay(), this.B = null);
  3679. }
  3680. cancel() {
  3681. null !== this.B && (this.B.cancel(), this.B = null);
  3682. }
  3683. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ Y() {
  3684. return (Math.random() - .5) * this.j;
  3685. }
  3686. }
  3687. /**
  3688. * @license
  3689. * Copyright 2017 Google LLC
  3690. *
  3691. * Licensed under the Apache License, Version 2.0 (the "License");
  3692. * you may not use this file except in compliance with the License.
  3693. * You may obtain a copy of the License at
  3694. *
  3695. * http://www.apache.org/licenses/LICENSE-2.0
  3696. *
  3697. * Unless required by applicable law or agreed to in writing, software
  3698. * distributed under the License is distributed on an "AS IS" BASIS,
  3699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3700. * See the License for the specific language governing permissions and
  3701. * limitations under the License.
  3702. */
  3703. /**
  3704. * Datastore and its related methods are a wrapper around the external Google
  3705. * Cloud Datastore grpc API, which provides an interface that is more convenient
  3706. * for the rest of the client SDK architecture to consume.
  3707. */
  3708. /**
  3709. * An implementation of Datastore that exposes additional state for internal
  3710. * consumption.
  3711. */
  3712. class pn extends class {} {
  3713. constructor(t, e, n, r) {
  3714. super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n,
  3715. this.serializer = r, this.J = !1;
  3716. }
  3717. X() {
  3718. if (this.J) throw new U(S, "The client has already been terminated.");
  3719. }
  3720. /** Invokes the provided RPC with auth and AppCheck tokens. */ v(t, e, n) {
  3721. return this.X(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([r, s]) => this.connection.v(t, e, n, r, s))).catch((t => {
  3722. throw "FirebaseError" === t.name ? (t.code === F && (this.authCredentials.invalidateToken(),
  3723. this.appCheckCredentials.invalidateToken()), t) : new U(R, t.toString());
  3724. }));
  3725. }
  3726. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ R(t, e, n, r) {
  3727. return this.X(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.R(t, e, n, s, i, r))).catch((t => {
  3728. throw "FirebaseError" === t.name ? (t.code === F && (this.authCredentials.invalidateToken(),
  3729. this.appCheckCredentials.invalidateToken()), t) : new U(R, t.toString());
  3730. }));
  3731. }
  3732. terminate() {
  3733. this.J = !0;
  3734. }
  3735. }
  3736. // TODO(firestorexp): Make sure there is only one Datastore instance per
  3737. // firestore-exp client.
  3738. async function yn(t, e) {
  3739. const n = I(t), r = en(n.serializer) + "/documents", s = {
  3740. writes: e.map((t => sn(n.serializer, t)))
  3741. };
  3742. await n.v("Commit", r, s);
  3743. }
  3744. async function gn(t, e) {
  3745. const n = I(t), r = en(n.serializer) + "/documents", s = {
  3746. documents: e.map((t => Xe(n.serializer, t)))
  3747. }, i = await n.R("BatchGetDocuments", r, s, e.length), o = new Map;
  3748. i.forEach((t => {
  3749. const e = rn(n.serializer, t);
  3750. o.set(e.key.toString(), e);
  3751. }));
  3752. const u = [];
  3753. return e.forEach((t => {
  3754. const e = o.get(t.toString());
  3755. E(!!e), u.push(e);
  3756. })), u;
  3757. }
  3758. async function _n(t, e) {
  3759. const n = I(t), r = on(n.serializer, Pe(e));
  3760. return (await n.R("RunQuery", r.parent, {
  3761. structuredQuery: r.structuredQuery
  3762. })).filter((t => !!t.document)).map((t => function(t, e, n) {
  3763. const r = Ze(t, e.name), s = He(e.updateTime), i = e.createTime ? He(e.createTime) : le.min(), o = new ge({
  3764. mapValue: {
  3765. fields: e.fields
  3766. }
  3767. }), u = _e.newFoundDocument(r, s, i, o);
  3768. return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;
  3769. }(n.serializer, t.document, void 0)));
  3770. }
  3771. async function vn(t, e, n) {
  3772. var r;
  3773. const s = I(t), {request: i, Z: o} = function(t, e, n) {
  3774. const r = on(t, e), s = {}, i = [];
  3775. let o = 0;
  3776. return n.forEach((t => {
  3777. // Map all client-side aliases to a unique short-form
  3778. // alias. This avoids issues with client-side aliases that
  3779. // exceed the 1500-byte string size limit.
  3780. const e = "aggregate_" + o++;
  3781. s[e] = t.alias, "count" === t.$ ? i.push({
  3782. alias: e,
  3783. count: {}
  3784. }) : "avg" === t.$ ? i.push({
  3785. alias: e,
  3786. avg: {
  3787. field: hn(t.fieldPath)
  3788. }
  3789. }) : "sum" === t.$ && i.push({
  3790. alias: e,
  3791. sum: {
  3792. field: hn(t.fieldPath)
  3793. }
  3794. });
  3795. })), {
  3796. request: {
  3797. structuredAggregationQuery: {
  3798. aggregations: i,
  3799. structuredQuery: r.structuredQuery
  3800. },
  3801. parent: r.parent
  3802. },
  3803. Z: s
  3804. };
  3805. }(s.serializer, Pe(e), n), u = i.parent;
  3806. s.connection.g || delete i.parent;
  3807. const c = (await s.R("RunAggregationQuery", u, i, /*expectedResponseCount=*/ 1)).filter((t => !!t.result));
  3808. // Omit RunAggregationQueryResponse that only contain readTimes.
  3809. E(1 === c.length);
  3810. // Remap the short-form aliases that were sent to the server
  3811. // to the client-side aliases. Users will access the results
  3812. // using the client-side alias.
  3813. const a = null === (r = c[0].result) || void 0 === r ? void 0 : r.aggregateFields;
  3814. return Object.keys(a).reduce(((t, e) => (t[o[e]] = a[e], t)), {});
  3815. }
  3816. /**
  3817. * @license
  3818. * Copyright 2020 Google LLC
  3819. *
  3820. * Licensed under the Apache License, Version 2.0 (the "License");
  3821. * you may not use this file except in compliance with the License.
  3822. * You may obtain a copy of the License at
  3823. *
  3824. * http://www.apache.org/licenses/LICENSE-2.0
  3825. *
  3826. * Unless required by applicable law or agreed to in writing, software
  3827. * distributed under the License is distributed on an "AS IS" BASIS,
  3828. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3829. * See the License for the specific language governing permissions and
  3830. * limitations under the License.
  3831. */ const bn = new Map;
  3832. /**
  3833. * An instance map that ensures only one Datastore exists per Firestore
  3834. * instance.
  3835. */
  3836. /**
  3837. * Returns an initialized and started Datastore for the given Firestore
  3838. * instance. Callers must invoke removeComponents() when the Firestore
  3839. * instance is terminated.
  3840. */
  3841. function En(t) {
  3842. if (t._terminated) throw new U(S, "The client has already been terminated.");
  3843. if (!bn.has(t)) {
  3844. y("ComponentProvider", "Initializing Datastore");
  3845. const i = function(t) {
  3846. return new _t(t, fetch.bind(null));
  3847. }((e = t._databaseId, n = t.app.options.appId || "", r = t._persistenceKey, s = t._freezeSettings(),
  3848. new J(e, n, r, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, ht(s.experimentalLongPollingOptions), s.useFetchStreams))), o = wn(t._databaseId), u = function(t, e, n, r) {
  3849. return new pn(t, e, n, r);
  3850. }(t._authCredentials, t._appCheckCredentials, i, o);
  3851. bn.set(t, u);
  3852. }
  3853. var e, n, r, s;
  3854. /**
  3855. * @license
  3856. * Copyright 2018 Google LLC
  3857. *
  3858. * Licensed under the Apache License, Version 2.0 (the "License");
  3859. * you may not use this file except in compliance with the License.
  3860. * You may obtain a copy of the License at
  3861. *
  3862. * http://www.apache.org/licenses/LICENSE-2.0
  3863. *
  3864. * Unless required by applicable law or agreed to in writing, software
  3865. * distributed under the License is distributed on an "AS IS" BASIS,
  3866. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3867. * See the License for the specific language governing permissions and
  3868. * limitations under the License.
  3869. */ return bn.get(t);
  3870. }
  3871. /**
  3872. * Removes all components associated with the provided instance. Must be called
  3873. * when the `Firestore` instance is terminated.
  3874. */
  3875. /**
  3876. * A concrete type describing all the values that can be applied via a
  3877. * user-supplied `FirestoreSettings` object. This is a separate type so that
  3878. * defaults can be supplied and the value can be checked for equality.
  3879. */
  3880. class In {
  3881. constructor(t) {
  3882. var e, n;
  3883. if (void 0 === t.host) {
  3884. if (void 0 !== t.ssl) throw new U(P, "Can't provide ssl option if host option is not set");
  3885. this.host = "firestore.googleapis.com", this.ssl = true;
  3886. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  3887. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  3888. this.cache = t.localCache, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  3889. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new U(P, "cacheSizeBytes must be at least 1048576");
  3890. this.cacheSizeBytes = t.cacheSizeBytes;
  3891. }
  3892. !function(t, e, n, r) {
  3893. if (!0 === e && !0 === r) throw new U(P, `${t} and ${n} cannot be used together.`);
  3894. }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling),
  3895. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true :
  3896. // For backwards compatibility, coerce the value to boolean even though
  3897. // the TypeScript compiler has narrowed the type to boolean already.
  3898. // noinspection PointlessBooleanExpressionJS
  3899. this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  3900. this.experimentalLongPollingOptions = ht(null !== (n = t.experimentalLongPollingOptions) && void 0 !== n ? n : {}),
  3901. function(t) {
  3902. if (void 0 !== t.timeoutSeconds) {
  3903. if (isNaN(t.timeoutSeconds)) throw new U(P, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`);
  3904. if (t.timeoutSeconds < 5) throw new U(P, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`);
  3905. if (t.timeoutSeconds > 30) throw new U(P, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`);
  3906. }
  3907. }
  3908. /**
  3909. * @license
  3910. * Copyright 2020 Google LLC
  3911. *
  3912. * Licensed under the Apache License, Version 2.0 (the "License");
  3913. * you may not use this file except in compliance with the License.
  3914. * You may obtain a copy of the License at
  3915. *
  3916. * http://www.apache.org/licenses/LICENSE-2.0
  3917. *
  3918. * Unless required by applicable law or agreed to in writing, software
  3919. * distributed under the License is distributed on an "AS IS" BASIS,
  3920. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3921. * See the License for the specific language governing permissions and
  3922. * limitations under the License.
  3923. */
  3924. /**
  3925. * The Cloud Firestore service interface.
  3926. *
  3927. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  3928. */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams;
  3929. }
  3930. isEqual(t) {
  3931. 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,
  3932. n = t.experimentalLongPollingOptions, e.timeoutSeconds === n.timeoutSeconds) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  3933. var e, n;
  3934. }
  3935. }
  3936. class Tn {
  3937. /** @hideconstructor */
  3938. constructor(t, e, n, r) {
  3939. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  3940. this._app = r,
  3941. /**
  3942. * Whether it's a Firestore or Firestore Lite instance.
  3943. */
  3944. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new In({}),
  3945. this._settingsFrozen = !1;
  3946. }
  3947. /**
  3948. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  3949. * instance.
  3950. */ get app() {
  3951. if (!this._app) throw new U(S, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  3952. return this._app;
  3953. }
  3954. get _initialized() {
  3955. return this._settingsFrozen;
  3956. }
  3957. get _terminated() {
  3958. return void 0 !== this._terminateTask;
  3959. }
  3960. _setSettings(t) {
  3961. if (this._settingsFrozen) throw new U(S, "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.");
  3962. this._settings = new In(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  3963. if (!t) return new Q;
  3964. switch (t.type) {
  3965. case "firstParty":
  3966. return new K(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  3967. case "provider":
  3968. return t.client;
  3969. default:
  3970. throw new U(P, "makeAuthCredentialsProvider failed due to invalid credential type");
  3971. }
  3972. }(t.credentials));
  3973. }
  3974. _getSettings() {
  3975. return this._settings;
  3976. }
  3977. _freezeSettings() {
  3978. return this._settingsFrozen = !0, this._settings;
  3979. }
  3980. _delete() {
  3981. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  3982. }
  3983. /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
  3984. return {
  3985. app: this._app,
  3986. databaseId: this._databaseId,
  3987. settings: this._settings
  3988. };
  3989. }
  3990. /**
  3991. * Terminates all components used by this client. Subclasses can override
  3992. * this method to clean up their own dependencies, but must also call this
  3993. * method.
  3994. *
  3995. * Only ever called once.
  3996. */ _terminate() {
  3997. return function(t) {
  3998. const e = bn.get(t);
  3999. e && (y("ComponentProvider", "Removing Datastore"), bn.delete(t), e.terminate());
  4000. }(this), Promise.resolve();
  4001. }
  4002. }
  4003. function An(t, e, n) {
  4004. n || (n = "(default)");
  4005. const r = _getProvider(t, "firestore/lite");
  4006. if (r.isInitialized(n)) throw new U(S, "Firestore can only be initialized once per app.");
  4007. return r.initialize({
  4008. options: e,
  4009. instanceIdentifier: n
  4010. });
  4011. }
  4012. function Rn(e, n) {
  4013. const r = "object" == typeof e ? e : getApp(), s = "string" == typeof e ? e : n || "(default)", i = _getProvider(r, "firestore/lite").getImmediate({
  4014. identifier: s
  4015. });
  4016. if (!i._initialized) {
  4017. const t = getDefaultEmulatorHostnameAndPort("firestore");
  4018. t && Pn(i, ...t);
  4019. }
  4020. return i;
  4021. }
  4022. /**
  4023. * Modify this instance to communicate with the Cloud Firestore emulator.
  4024. *
  4025. * Note: This must be called before this instance has been used to do any
  4026. * operations.
  4027. *
  4028. * @param firestore - The `Firestore` instance to configure to connect to the
  4029. * emulator.
  4030. * @param host - the emulator host (ex: localhost).
  4031. * @param port - the emulator port (ex: 9000).
  4032. * @param options.mockUserToken - the mock auth token to use for unit testing
  4033. * Security Rules.
  4034. */ function Pn(t, e, n, r = {}) {
  4035. var s;
  4036. const i = (t = ct(t, Tn))._getSettings(), o = `${e}:${n}`;
  4037. if ("firestore.googleapis.com" !== i.host && i.host !== o && _("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),
  4038. t._setSettings(Object.assign(Object.assign({}, i), {
  4039. host: o,
  4040. ssl: !1
  4041. })), r.mockUserToken) {
  4042. let e, n;
  4043. if ("string" == typeof r.mockUserToken) e = r.mockUserToken, n = d.MOCK_USER; else {
  4044. // Let createMockUserToken validate first (catches common mistakes like
  4045. // invalid field "uid" and missing field "sub" / "user_id".)
  4046. e = createMockUserToken(r.mockUserToken, null === (s = t._app) || void 0 === s ? void 0 : s.options.projectId);
  4047. const i = r.mockUserToken.sub || r.mockUserToken.user_id;
  4048. if (!i) throw new U(P, "mockUserToken must contain 'sub' or 'user_id' field!");
  4049. n = new d(i);
  4050. }
  4051. t._authCredentials = new z(new B(e, n));
  4052. }
  4053. }
  4054. /**
  4055. * Terminates the provided `Firestore` instance.
  4056. *
  4057. * After calling `terminate()` only the `clearIndexedDbPersistence()` functions
  4058. * may be used. Any other function will throw a `FirestoreError`. Termination
  4059. * does not cancel any pending writes, and any promises that are awaiting a
  4060. * response from the server will not be resolved.
  4061. *
  4062. * To restart after termination, create a new instance of `Firestore` with
  4063. * {@link (getFirestore:1)}.
  4064. *
  4065. * Note: Under normal circumstances, calling `terminate()` is not required. This
  4066. * function is useful only when you want to force this instance to release all of
  4067. * its resources or in combination with {@link clearIndexedDbPersistence} to
  4068. * ensure that all local state is destroyed between test runs.
  4069. *
  4070. * @param firestore - The `Firestore` instance to terminate.
  4071. * @returns A `Promise` that is resolved when the instance has been successfully
  4072. * terminated.
  4073. */ function Vn(t) {
  4074. return t = ct(t, Tn), _removeServiceInstance(t.app, "firestore/lite"), t._delete();
  4075. }
  4076. /**
  4077. * @license
  4078. * Copyright 2020 Google LLC
  4079. *
  4080. * Licensed under the Apache License, Version 2.0 (the "License");
  4081. * you may not use this file except in compliance with the License.
  4082. * You may obtain a copy of the License at
  4083. *
  4084. * http://www.apache.org/licenses/LICENSE-2.0
  4085. *
  4086. * Unless required by applicable law or agreed to in writing, software
  4087. * distributed under the License is distributed on an "AS IS" BASIS,
  4088. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4089. * See the License for the specific language governing permissions and
  4090. * limitations under the License.
  4091. */
  4092. /**
  4093. * @license
  4094. * Copyright 2022 Google LLC
  4095. *
  4096. * Licensed under the Apache License, Version 2.0 (the "License");
  4097. * you may not use this file except in compliance with the License.
  4098. * You may obtain a copy of the License at
  4099. *
  4100. * http://www.apache.org/licenses/LICENSE-2.0
  4101. *
  4102. * Unless required by applicable law or agreed to in writing, software
  4103. * distributed under the License is distributed on an "AS IS" BASIS,
  4104. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4105. * See the License for the specific language governing permissions and
  4106. * limitations under the License.
  4107. */
  4108. /**
  4109. * Represents an aggregation that can be performed by Firestore.
  4110. */
  4111. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  4112. class $n {
  4113. /**
  4114. * Create a new AggregateField<T>
  4115. * @param _aggregateType Specifies the type of aggregation operation to perform.
  4116. * @param _internalFieldPath Optionally specifies the field that is aggregated.
  4117. * @internal
  4118. */
  4119. constructor(
  4120. // TODO (sum/avg) make aggregateType public when the feature is supported
  4121. t = "count", e) {
  4122. this._aggregateType = t, this._internalFieldPath = e,
  4123. /** A type string to uniquely identify instances of this class. */
  4124. this.type = "AggregateField";
  4125. }
  4126. }
  4127. /**
  4128. * The results of executing an aggregation query.
  4129. */ class Nn {
  4130. /** @hideconstructor */
  4131. constructor(t, e, n) {
  4132. this._userDataWriter = e, this._data = n,
  4133. /** A type string to uniquely identify instances of this class. */
  4134. this.type = "AggregateQuerySnapshot", this.query = t;
  4135. }
  4136. /**
  4137. * Returns the results of the aggregations performed over the underlying
  4138. * query.
  4139. *
  4140. * The keys of the returned object will be the same as those of the
  4141. * `AggregateSpec` object specified to the aggregation method, and the values
  4142. * will be the corresponding aggregation result.
  4143. *
  4144. * @returns The results of the aggregations performed over the underlying
  4145. * query.
  4146. */ data() {
  4147. return this._userDataWriter.convertObjectMap(this._data);
  4148. }
  4149. }
  4150. /**
  4151. * @license
  4152. * Copyright 2020 Google LLC
  4153. *
  4154. * Licensed under the Apache License, Version 2.0 (the "License");
  4155. * you may not use this file except in compliance with the License.
  4156. * You may obtain a copy of the License at
  4157. *
  4158. * http://www.apache.org/licenses/LICENSE-2.0
  4159. *
  4160. * Unless required by applicable law or agreed to in writing, software
  4161. * distributed under the License is distributed on an "AS IS" BASIS,
  4162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4163. * See the License for the specific language governing permissions and
  4164. * limitations under the License.
  4165. */
  4166. /**
  4167. * A `DocumentReference` refers to a document location in a Firestore database
  4168. * and can be used to write, read, or listen to the location. The document at
  4169. * the referenced location may or may not exist.
  4170. */ class Dn {
  4171. /** @hideconstructor */
  4172. constructor(t,
  4173. /**
  4174. * If provided, the `FirestoreDataConverter` associated with this instance.
  4175. */
  4176. e, n) {
  4177. this.converter = e, this._key = n,
  4178. /** The type of this Firestore reference. */
  4179. this.type = "document", this.firestore = t;
  4180. }
  4181. get _path() {
  4182. return this._key.path;
  4183. }
  4184. /**
  4185. * The document's identifier within its collection.
  4186. */ get id() {
  4187. return this._key.path.lastSegment();
  4188. }
  4189. /**
  4190. * A string representing the path of the referenced document (relative
  4191. * to the root of the database).
  4192. */ get path() {
  4193. return this._key.path.canonicalString();
  4194. }
  4195. /**
  4196. * The collection this `DocumentReference` belongs to.
  4197. */ get parent() {
  4198. return new xn(this.firestore, this.converter, this._key.path.popLast());
  4199. }
  4200. withConverter(t) {
  4201. return new Dn(this.firestore, t, this._key);
  4202. }
  4203. }
  4204. /**
  4205. * A `Query` refers to a query which you can read or listen to. You can also
  4206. * construct refined `Query` objects by adding filters and ordering.
  4207. */ class Fn {
  4208. // This is the lite version of the Query class in the main SDK.
  4209. /** @hideconstructor protected */
  4210. constructor(t,
  4211. /**
  4212. * If provided, the `FirestoreDataConverter` associated with this instance.
  4213. */
  4214. e, n) {
  4215. this.converter = e, this._query = n,
  4216. /** The type of this Firestore reference. */
  4217. this.type = "query", this.firestore = t;
  4218. }
  4219. withConverter(t) {
  4220. return new Fn(this.firestore, t, this._query);
  4221. }
  4222. }
  4223. /**
  4224. * A `CollectionReference` object can be used for adding documents, getting
  4225. * document references, and querying for documents (using {@link (query:1)}).
  4226. */ class xn extends Fn {
  4227. /** @hideconstructor */
  4228. constructor(t, e, n) {
  4229. super(t, e, new Ee(n)), this._path = n,
  4230. /** The type of this Firestore reference. */
  4231. this.type = "collection";
  4232. }
  4233. /** The collection's identifier. */ get id() {
  4234. return this._query.path.lastSegment();
  4235. }
  4236. /**
  4237. * A string representing the path of the referenced collection (relative
  4238. * to the root of the database).
  4239. */ get path() {
  4240. return this._query.path.canonicalString();
  4241. }
  4242. /**
  4243. * A reference to the containing `DocumentReference` if this is a
  4244. * subcollection. If this isn't a subcollection, the reference is null.
  4245. */ get parent() {
  4246. const t = this._path.popLast();
  4247. return t.isEmpty() ? null : new Dn(this.firestore,
  4248. /* converter= */ null, new rt(t));
  4249. }
  4250. withConverter(t) {
  4251. return new xn(this.firestore, t, this._path);
  4252. }
  4253. }
  4254. function Sn(t, e, ...n) {
  4255. if (t = getModularInstance(t), st("collection", "path", e), t instanceof Tn) {
  4256. const r = tt.fromString(e, ...n);
  4257. return ot(r), new xn(t, /* converter= */ null, r);
  4258. }
  4259. {
  4260. if (!(t instanceof Dn || t instanceof xn)) throw new U(P, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  4261. const r = t._path.child(tt.fromString(e, ...n));
  4262. return ot(r), new xn(t.firestore,
  4263. /* converter= */ null, r);
  4264. }
  4265. }
  4266. // TODO(firestorelite): Consider using ErrorFactory -
  4267. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  4268. /**
  4269. * Creates and returns a new `Query` instance that includes all documents in the
  4270. * database that are contained in a collection or subcollection with the
  4271. * given `collectionId`.
  4272. *
  4273. * @param firestore - A reference to the root `Firestore` instance.
  4274. * @param collectionId - Identifies the collections to query over. Every
  4275. * collection or subcollection with this ID as the last segment of its path
  4276. * will be included. Cannot contain a slash.
  4277. * @returns The created `Query`.
  4278. */ function qn(t, e) {
  4279. if (t = ct(t, Tn), st("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new U(P, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  4280. return new Fn(t,
  4281. /* converter= */ null, function(t) {
  4282. return new Ee(tt.emptyPath(), t);
  4283. }(e));
  4284. }
  4285. function On(t, e, ...n) {
  4286. if (t = getModularInstance(t),
  4287. // We allow omission of 'pathString' but explicitly prohibit passing in both
  4288. // 'undefined' and 'null'.
  4289. 1 === arguments.length && (e = Et.N()), st("doc", "path", e), t instanceof Tn) {
  4290. const r = tt.fromString(e, ...n);
  4291. return it(r), new Dn(t,
  4292. /* converter= */ null, new rt(r));
  4293. }
  4294. {
  4295. if (!(t instanceof Dn || t instanceof xn)) throw new U(P, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  4296. const r = t._path.child(tt.fromString(e, ...n));
  4297. return it(r), new Dn(t.firestore, t instanceof xn ? t.converter : null, new rt(r));
  4298. }
  4299. }
  4300. /**
  4301. * Returns true if the provided references are equal.
  4302. *
  4303. * @param left - A reference to compare.
  4304. * @param right - A reference to compare.
  4305. * @returns true if the references point to the same location in the same
  4306. * Firestore database.
  4307. */ function kn(t, e) {
  4308. return t = getModularInstance(t), e = getModularInstance(e), (t instanceof Dn || t instanceof xn) && (e instanceof Dn || e instanceof xn) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);
  4309. }
  4310. /**
  4311. * Returns true if the provided queries point to the same collection and apply
  4312. * the same constraints.
  4313. *
  4314. * @param left - A `Query` to compare.
  4315. * @param right - A `Query` to compare.
  4316. * @returns true if the references point to the same location in the same
  4317. * Firestore database.
  4318. */ function Cn(t, e) {
  4319. return t = getModularInstance(t), e = getModularInstance(e), t instanceof Fn && e instanceof Fn && (t.firestore === e.firestore && $e(t._query, e._query) && t.converter === e.converter);
  4320. }
  4321. /**
  4322. * @license
  4323. * Copyright 2020 Google LLC
  4324. *
  4325. * Licensed under the Apache License, Version 2.0 (the "License");
  4326. * you may not use this file except in compliance with the License.
  4327. * You may obtain a copy of the License at
  4328. *
  4329. * http://www.apache.org/licenses/LICENSE-2.0
  4330. *
  4331. * Unless required by applicable law or agreed to in writing, software
  4332. * distributed under the License is distributed on an "AS IS" BASIS,
  4333. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4334. * See the License for the specific language governing permissions and
  4335. * limitations under the License.
  4336. */
  4337. /**
  4338. * An immutable object representing an array of bytes.
  4339. */ class Mn {
  4340. /** @hideconstructor */
  4341. constructor(t) {
  4342. this._byteString = t;
  4343. }
  4344. /**
  4345. * Creates a new `Bytes` object from the given Base64 string, converting it to
  4346. * bytes.
  4347. *
  4348. * @param base64 - The Base64 string used to create the `Bytes` object.
  4349. */ static fromBase64String(t) {
  4350. try {
  4351. return new Mn(Vt.fromBase64String(t));
  4352. } catch (t) {
  4353. throw new U(P, "Failed to construct data from Base64 string: " + t);
  4354. }
  4355. }
  4356. /**
  4357. * Creates a new `Bytes` object from the given Uint8Array.
  4358. *
  4359. * @param array - The Uint8Array used to create the `Bytes` object.
  4360. */ static fromUint8Array(t) {
  4361. return new Mn(Vt.fromUint8Array(t));
  4362. }
  4363. /**
  4364. * Returns the underlying bytes as a Base64-encoded string.
  4365. *
  4366. * @returns The Base64-encoded string created from the `Bytes` object.
  4367. */ toBase64() {
  4368. return this._byteString.toBase64();
  4369. }
  4370. /**
  4371. * Returns the underlying bytes in a new `Uint8Array`.
  4372. *
  4373. * @returns The Uint8Array created from the `Bytes` object.
  4374. */ toUint8Array() {
  4375. return this._byteString.toUint8Array();
  4376. }
  4377. /**
  4378. * Returns a string representation of the `Bytes` object.
  4379. *
  4380. * @returns A string representation of the `Bytes` object.
  4381. */ toString() {
  4382. return "Bytes(base64: " + this.toBase64() + ")";
  4383. }
  4384. /**
  4385. * Returns true if this `Bytes` object is equal to the provided one.
  4386. *
  4387. * @param other - The `Bytes` object to compare against.
  4388. * @returns true if this `Bytes` object is equal to the provided one.
  4389. */ isEqual(t) {
  4390. return this._byteString.isEqual(t._byteString);
  4391. }
  4392. }
  4393. /**
  4394. * @license
  4395. * Copyright 2020 Google LLC
  4396. *
  4397. * Licensed under the Apache License, Version 2.0 (the "License");
  4398. * you may not use this file except in compliance with the License.
  4399. * You may obtain a copy of the License at
  4400. *
  4401. * http://www.apache.org/licenses/LICENSE-2.0
  4402. *
  4403. * Unless required by applicable law or agreed to in writing, software
  4404. * distributed under the License is distributed on an "AS IS" BASIS,
  4405. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4406. * See the License for the specific language governing permissions and
  4407. * limitations under the License.
  4408. */
  4409. /**
  4410. * A `FieldPath` refers to a field in a document. The path may consist of a
  4411. * single field name (referring to a top-level field in the document), or a
  4412. * list of field names (referring to a nested field in the document).
  4413. *
  4414. * Create a `FieldPath` by providing field names. If more than one field
  4415. * name is provided, the path will point to a nested field in a document.
  4416. */ class Ln {
  4417. /**
  4418. * Creates a `FieldPath` from the provided field names. If more than one field
  4419. * name is provided, the path will point to a nested field in a document.
  4420. *
  4421. * @param fieldNames - A list of field names.
  4422. */
  4423. constructor(...t) {
  4424. for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new U(P, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  4425. this._internalPath = new nt(t);
  4426. }
  4427. /**
  4428. * Returns true if this `FieldPath` is equal to the provided one.
  4429. *
  4430. * @param other - The `FieldPath` to compare against.
  4431. * @returns true if this `FieldPath` is equal to the provided one.
  4432. */ isEqual(t) {
  4433. return this._internalPath.isEqual(t._internalPath);
  4434. }
  4435. }
  4436. /**
  4437. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  4438. * It can be used in queries to sort or filter by the document ID.
  4439. */ function Un() {
  4440. return new Ln("__name__");
  4441. }
  4442. /**
  4443. * @license
  4444. * Copyright 2020 Google LLC
  4445. *
  4446. * Licensed under the Apache License, Version 2.0 (the "License");
  4447. * you may not use this file except in compliance with the License.
  4448. * You may obtain a copy of the License at
  4449. *
  4450. * http://www.apache.org/licenses/LICENSE-2.0
  4451. *
  4452. * Unless required by applicable law or agreed to in writing, software
  4453. * distributed under the License is distributed on an "AS IS" BASIS,
  4454. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4455. * See the License for the specific language governing permissions and
  4456. * limitations under the License.
  4457. */
  4458. /**
  4459. * Sentinel values that can be used when writing document fields with `set()`
  4460. * or `update()`.
  4461. */ class jn {
  4462. /**
  4463. * @param _methodName - The public API endpoint that returns this class.
  4464. * @hideconstructor
  4465. */
  4466. constructor(t) {
  4467. this._methodName = t;
  4468. }
  4469. }
  4470. /**
  4471. * @license
  4472. * Copyright 2017 Google LLC
  4473. *
  4474. * Licensed under the Apache License, Version 2.0 (the "License");
  4475. * you may not use this file except in compliance with the License.
  4476. * You may obtain a copy of the License at
  4477. *
  4478. * http://www.apache.org/licenses/LICENSE-2.0
  4479. *
  4480. * Unless required by applicable law or agreed to in writing, software
  4481. * distributed under the License is distributed on an "AS IS" BASIS,
  4482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4483. * See the License for the specific language governing permissions and
  4484. * limitations under the License.
  4485. */
  4486. /**
  4487. * An immutable object representing a geographic location in Firestore. The
  4488. * location is represented as latitude/longitude pair.
  4489. *
  4490. * Latitude values are in the range of [-90, 90].
  4491. * Longitude values are in the range of [-180, 180].
  4492. */ class Bn {
  4493. /**
  4494. * Creates a new immutable `GeoPoint` object with the provided latitude and
  4495. * longitude values.
  4496. * @param latitude - The latitude as number between -90 and 90.
  4497. * @param longitude - The longitude as number between -180 and 180.
  4498. */
  4499. constructor(t, e) {
  4500. if (!isFinite(t) || t < -90 || t > 90) throw new U(P, "Latitude must be a number between -90 and 90, but was: " + t);
  4501. if (!isFinite(e) || e < -180 || e > 180) throw new U(P, "Longitude must be a number between -180 and 180, but was: " + e);
  4502. this._lat = t, this._long = e;
  4503. }
  4504. /**
  4505. * The latitude of this `GeoPoint` instance.
  4506. */ get latitude() {
  4507. return this._lat;
  4508. }
  4509. /**
  4510. * The longitude of this `GeoPoint` instance.
  4511. */ get longitude() {
  4512. return this._long;
  4513. }
  4514. /**
  4515. * Returns true if this `GeoPoint` is equal to the provided one.
  4516. *
  4517. * @param other - The `GeoPoint` to compare against.
  4518. * @returns true if this `GeoPoint` is equal to the provided one.
  4519. */ isEqual(t) {
  4520. return this._lat === t._lat && this._long === t._long;
  4521. }
  4522. /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
  4523. return {
  4524. latitude: this._lat,
  4525. longitude: this._long
  4526. };
  4527. }
  4528. /**
  4529. * Actually private to JS consumers of our API, so this function is prefixed
  4530. * with an underscore.
  4531. */ _compareTo(t) {
  4532. return It(this._lat, t._lat) || It(this._long, t._long);
  4533. }
  4534. }
  4535. /**
  4536. * @license
  4537. * Copyright 2017 Google LLC
  4538. *
  4539. * Licensed under the Apache License, Version 2.0 (the "License");
  4540. * you may not use this file except in compliance with the License.
  4541. * You may obtain a copy of the License at
  4542. *
  4543. * http://www.apache.org/licenses/LICENSE-2.0
  4544. *
  4545. * Unless required by applicable law or agreed to in writing, software
  4546. * distributed under the License is distributed on an "AS IS" BASIS,
  4547. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4548. * See the License for the specific language governing permissions and
  4549. * limitations under the License.
  4550. */ const Qn = /^__.*__$/;
  4551. /** The result of parsing document data (e.g. for a setData call). */ class zn {
  4552. constructor(t, e, n) {
  4553. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  4554. }
  4555. toMutation(t, e) {
  4556. return null !== this.fieldMask ? new Le(t, this.data, this.fieldMask, e, this.fieldTransforms) : new Me(t, this.data, e, this.fieldTransforms);
  4557. }
  4558. }
  4559. /** The result of parsing "update" data (i.e. for an updateData call). */ class Wn {
  4560. constructor(t,
  4561. // The fieldMask does not include document transforms.
  4562. e, n) {
  4563. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  4564. }
  4565. toMutation(t, e) {
  4566. return new Le(t, this.data, this.fieldMask, e, this.fieldTransforms);
  4567. }
  4568. }
  4569. function Gn(t) {
  4570. switch (t) {
  4571. case 0 /* UserDataSource.Set */ :
  4572. // fall through
  4573. case 2 /* UserDataSource.MergeSet */ :
  4574. // fall through
  4575. case 1 /* UserDataSource.Update */ :
  4576. return !0;
  4577. case 3 /* UserDataSource.Argument */ :
  4578. case 4 /* UserDataSource.ArrayArgument */ :
  4579. return !1;
  4580. default:
  4581. throw b();
  4582. }
  4583. }
  4584. /** A "context" object passed around while parsing user data. */ class Kn {
  4585. /**
  4586. * Initializes a ParseContext with the given source and path.
  4587. *
  4588. * @param settings - The settings for the parser.
  4589. * @param databaseId - The database ID of the Firestore instance.
  4590. * @param serializer - The serializer to use to generate the Value proto.
  4591. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  4592. * rather than throw.
  4593. * @param fieldTransforms - A mutable list of field transforms encountered
  4594. * while parsing the data.
  4595. * @param fieldMask - A mutable list of field paths encountered while parsing
  4596. * the data.
  4597. *
  4598. * TODO(b/34871131): We don't support array paths right now, so path can be
  4599. * null to indicate the context represents any location within an array (in
  4600. * which case certain features will not work and errors will be somewhat
  4601. * compromised).
  4602. */
  4603. constructor(t, e, n, r, s, i) {
  4604. this.settings = t, this.databaseId = e, this.serializer = n, this.ignoreUndefinedProperties = r,
  4605. // Minor hack: If fieldTransforms is undefined, we assume this is an
  4606. // external call and we need to validate the entire path.
  4607. void 0 === s && this.tt(), this.fieldTransforms = s || [], this.fieldMask = i || [];
  4608. }
  4609. get path() {
  4610. return this.settings.path;
  4611. }
  4612. get et() {
  4613. return this.settings.et;
  4614. }
  4615. /** Returns a new context with the specified settings overwritten. */ nt(t) {
  4616. return new Kn(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  4617. }
  4618. rt(t) {
  4619. var e;
  4620. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.nt({
  4621. path: n,
  4622. st: !1
  4623. });
  4624. return r.it(t), r;
  4625. }
  4626. ot(t) {
  4627. var e;
  4628. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.nt({
  4629. path: n,
  4630. st: !1
  4631. });
  4632. return r.tt(), r;
  4633. }
  4634. ut(t) {
  4635. // TODO(b/34871131): We don't support array paths right now; so make path
  4636. // undefined.
  4637. return this.nt({
  4638. path: void 0,
  4639. st: !0
  4640. });
  4641. }
  4642. ct(t) {
  4643. return wr(t, this.settings.methodName, this.settings.ht || !1, this.path, this.settings.lt);
  4644. }
  4645. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {
  4646. return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));
  4647. }
  4648. tt() {
  4649. // TODO(b/34871131): Remove null check once we have proper paths for fields
  4650. // within arrays.
  4651. if (this.path) for (let t = 0; t < this.path.length; t++) this.it(this.path.get(t));
  4652. }
  4653. it(t) {
  4654. if (0 === t.length) throw this.ct("Document fields must not be empty");
  4655. if (Gn(this.et) && Qn.test(t)) throw this.ct('Document fields cannot begin and end with "__"');
  4656. }
  4657. }
  4658. /**
  4659. * Helper for parsing raw user input (provided via the API) into internal model
  4660. * classes.
  4661. */ class Yn {
  4662. constructor(t, e, n) {
  4663. this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = n || wn(t);
  4664. }
  4665. /** Creates a new top-level parse context. */ ft(t, e, n, r = !1) {
  4666. return new Kn({
  4667. et: t,
  4668. methodName: e,
  4669. lt: n,
  4670. path: nt.emptyPath(),
  4671. st: !1,
  4672. ht: r
  4673. }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  4674. }
  4675. }
  4676. function Hn(t) {
  4677. const e = t._freezeSettings(), n = wn(t._databaseId);
  4678. return new Yn(t._databaseId, !!e.ignoreUndefinedProperties, n);
  4679. }
  4680. /** Parse document data from a set() call. */ function Jn(t, e, n, r, s, i = {}) {
  4681. const o = t.ft(i.merge || i.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, s);
  4682. hr("Data must be an object, but it was:", o, r);
  4683. const u = cr(r, o);
  4684. let c, a;
  4685. if (i.merge) c = new ye(o.fieldMask), a = o.fieldTransforms; else if (i.mergeFields) {
  4686. const t = [];
  4687. for (const r of i.mergeFields) {
  4688. const s = lr(e, r, n);
  4689. if (!o.contains(s)) throw new U(P, `Field '${s}' is specified in your field mask but missing from your input data.`);
  4690. mr(t, s) || t.push(s);
  4691. }
  4692. c = new ye(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));
  4693. } else c = null, a = o.fieldTransforms;
  4694. return new zn(new ge(u), c, a);
  4695. }
  4696. class Xn extends jn {
  4697. _toFieldTransform(t) {
  4698. if (2 /* UserDataSource.MergeSet */ !== t.et) throw 1 /* UserDataSource.Update */ === t.et ? t.ct(`${this._methodName}() can only appear at the top level of your update data`) : t.ct(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
  4699. // No transform to add for a delete, but we need to add it to our
  4700. // fieldMask so it gets deleted.
  4701. return t.fieldMask.push(t.path), null;
  4702. }
  4703. isEqual(t) {
  4704. return t instanceof Xn;
  4705. }
  4706. }
  4707. /**
  4708. * Creates a child context for parsing SerializableFieldValues.
  4709. *
  4710. * This is different than calling `ParseContext.contextWith` because it keeps
  4711. * the fieldTransforms and fieldMask separate.
  4712. *
  4713. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  4714. * Although these values are used with writes, any elements in these FieldValues
  4715. * are not considered writes since they cannot contain any FieldValue sentinels,
  4716. * etc.
  4717. *
  4718. * @param fieldValue - The sentinel FieldValue for which to create a child
  4719. * context.
  4720. * @param context - The parent context.
  4721. * @param arrayElement - Whether or not the FieldValue has an array.
  4722. */ function Zn(t, e, n) {
  4723. return new Kn({
  4724. et: 3 /* UserDataSource.Argument */ ,
  4725. lt: e.settings.lt,
  4726. methodName: t._methodName,
  4727. st: n
  4728. }, e.databaseId, e.serializer, e.ignoreUndefinedProperties);
  4729. }
  4730. class tr extends jn {
  4731. _toFieldTransform(t) {
  4732. return new Oe(t.path, new Fe);
  4733. }
  4734. isEqual(t) {
  4735. return t instanceof tr;
  4736. }
  4737. }
  4738. class er extends jn {
  4739. constructor(t, e) {
  4740. super(t), this.dt = e;
  4741. }
  4742. _toFieldTransform(t) {
  4743. const e = Zn(this, t,
  4744. /*array=*/ !0), n = this.dt.map((t => ur(t, e))), r = new xe(n);
  4745. return new Oe(t.path, r);
  4746. }
  4747. isEqual(t) {
  4748. // TODO(mrschmidt): Implement isEquals
  4749. return this === t;
  4750. }
  4751. }
  4752. class nr extends jn {
  4753. constructor(t, e) {
  4754. super(t), this.dt = e;
  4755. }
  4756. _toFieldTransform(t) {
  4757. const e = Zn(this, t,
  4758. /*array=*/ !0), n = this.dt.map((t => ur(t, e))), r = new Se(n);
  4759. return new Oe(t.path, r);
  4760. }
  4761. isEqual(t) {
  4762. // TODO(mrschmidt): Implement isEquals
  4763. return this === t;
  4764. }
  4765. }
  4766. class rr extends jn {
  4767. constructor(t, e) {
  4768. super(t), this.wt = e;
  4769. }
  4770. _toFieldTransform(t) {
  4771. const e = new qe(t.serializer, Ne(t.serializer, this.wt));
  4772. return new Oe(t.path, e);
  4773. }
  4774. isEqual(t) {
  4775. // TODO(mrschmidt): Implement isEquals
  4776. return this === t;
  4777. }
  4778. }
  4779. /** Parse update data from an update() call. */ function sr(t, e, n, r) {
  4780. const s = t.ft(1 /* UserDataSource.Update */ , e, n);
  4781. hr("Data must be an object, but it was:", s, r);
  4782. const i = [], o = ge.empty();
  4783. Rt(r, ((t, r) => {
  4784. const u = dr(e, t, n);
  4785. // For Compat types, we have to "extract" the underlying types before
  4786. // performing validation.
  4787. r = getModularInstance(r);
  4788. const c = s.ot(u);
  4789. if (r instanceof Xn)
  4790. // Add it to the field mask, but don't add anything to updateData.
  4791. i.push(u); else {
  4792. const t = ur(r, c);
  4793. null != t && (i.push(u), o.set(u, t));
  4794. }
  4795. }));
  4796. const u = new ye(i);
  4797. return new Wn(o, u, s.fieldTransforms);
  4798. }
  4799. /** Parse update data from a list of field/value arguments. */ function ir(t, e, n, r, s, i) {
  4800. const o = t.ft(1 /* UserDataSource.Update */ , e, n), u = [ lr(e, r, n) ], c = [ s ];
  4801. if (i.length % 2 != 0) throw new U(P, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
  4802. for (let t = 0; t < i.length; t += 2) u.push(lr(e, i[t])), c.push(i[t + 1]);
  4803. const a = [], h = ge.empty();
  4804. // We iterate in reverse order to pick the last value for a field if the
  4805. // user specified the field multiple times.
  4806. for (let t = u.length - 1; t >= 0; --t) if (!mr(a, u[t])) {
  4807. const e = u[t];
  4808. let n = c[t];
  4809. // For Compat types, we have to "extract" the underlying types before
  4810. // performing validation.
  4811. n = getModularInstance(n);
  4812. const r = o.ot(e);
  4813. if (n instanceof Xn)
  4814. // Add it to the field mask, but don't add anything to updateData.
  4815. a.push(e); else {
  4816. const t = ur(n, r);
  4817. null != t && (a.push(e), h.set(e, t));
  4818. }
  4819. }
  4820. const f = new ye(a);
  4821. return new Wn(h, f, o.fieldTransforms);
  4822. }
  4823. /**
  4824. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  4825. * bound).
  4826. *
  4827. * @param allowArrays - Whether the query value is an array that may directly
  4828. * contain additional arrays (e.g. the operand of an `in` query).
  4829. */ function or(t, e, n, r = !1) {
  4830. return ur(n, t.ft(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  4831. }
  4832. /**
  4833. * Parses user data to Protobuf Values.
  4834. *
  4835. * @param input - Data to be parsed.
  4836. * @param context - A context object representing the current path being parsed,
  4837. * the source of the data being parsed, etc.
  4838. * @returns The parsed value, or null if the value was a FieldValue sentinel
  4839. * that should not be included in the resulting parsed data.
  4840. */ function ur(t, e) {
  4841. if (ar(
  4842. // Unwrap the API type from the Compat SDK. This will return the API type
  4843. // from firestore-exp.
  4844. t = getModularInstance(t))) return hr("Unsupported field value:", e, t), cr(t, e);
  4845. if (t instanceof jn)
  4846. // FieldValues usually parse into transforms (except deleteField())
  4847. // in which case we do not want to include this field in our parsed data
  4848. // (as doing so will overwrite the field directly prior to the transform
  4849. // trying to transform it). So we don't add this location to
  4850. // context.fieldMask and we return null as our parsing result.
  4851. /**
  4852. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  4853. * context.fieldTransforms.
  4854. */
  4855. return function(t, e) {
  4856. // Sentinels are only supported with writes, and not within arrays.
  4857. if (!Gn(e.et)) throw e.ct(`${t._methodName}() can only be used with update() and set()`);
  4858. if (!e.path) throw e.ct(`${t._methodName}() is not currently supported inside arrays`);
  4859. const n = t._toFieldTransform(e);
  4860. n && e.fieldTransforms.push(n);
  4861. }
  4862. /**
  4863. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  4864. *
  4865. * @returns The parsed value
  4866. */ (t, e), null;
  4867. if (void 0 === t && e.ignoreUndefinedProperties)
  4868. // If the input is undefined it can never participate in the fieldMask, so
  4869. // don't handle this below. If `ignoreUndefinedProperties` is false,
  4870. // `parseScalarValue` will reject an undefined value.
  4871. return null;
  4872. if (
  4873. // If context.path is null we are inside an array and we don't support
  4874. // field mask paths more granular than the top-level array.
  4875. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  4876. // TODO(b/34871131): Include the path containing the array in the error
  4877. // message.
  4878. // In the case of IN queries, the parsed data is an array (representing
  4879. // the set of values to be included for the IN query) that may directly
  4880. // contain additional arrays (each representing an individual field
  4881. // value), so we disable this validation.
  4882. if (e.settings.st && 4 /* UserDataSource.ArrayArgument */ !== e.et) throw e.ct("Nested arrays are not supported");
  4883. return function(t, e) {
  4884. const n = [];
  4885. let r = 0;
  4886. for (const s of t) {
  4887. let t = ur(s, e.ut(r));
  4888. null == t && (
  4889. // Just include nulls in the array for fields being replaced with a
  4890. // sentinel.
  4891. t = {
  4892. nullValue: "NULL_VALUE"
  4893. }), n.push(t), r++;
  4894. }
  4895. return {
  4896. arrayValue: {
  4897. values: n
  4898. }
  4899. };
  4900. }(t, e);
  4901. }
  4902. return function(t, e) {
  4903. if (null === (t = getModularInstance(t))) return {
  4904. nullValue: "NULL_VALUE"
  4905. };
  4906. if ("number" == typeof t) return Ne(e.serializer, t);
  4907. if ("boolean" == typeof t) return {
  4908. booleanValue: t
  4909. };
  4910. if ("string" == typeof t) return {
  4911. stringValue: t
  4912. };
  4913. if (t instanceof Date) {
  4914. const n = xt.fromDate(t);
  4915. return {
  4916. timestampValue: Ge(e.serializer, n)
  4917. };
  4918. }
  4919. if (t instanceof xt) {
  4920. // Firestore backend truncates precision down to microseconds. To ensure
  4921. // offline mode works the same with regards to truncation, perform the
  4922. // truncation immediately without waiting for the backend to do that.
  4923. const n = new xt(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  4924. return {
  4925. timestampValue: Ge(e.serializer, n)
  4926. };
  4927. }
  4928. if (t instanceof Bn) return {
  4929. geoPointValue: {
  4930. latitude: t.latitude,
  4931. longitude: t.longitude
  4932. }
  4933. };
  4934. if (t instanceof Mn) return {
  4935. bytesValue: Ke(e.serializer, t._byteString)
  4936. };
  4937. if (t instanceof Dn) {
  4938. const n = e.databaseId, r = t.firestore._databaseId;
  4939. if (!r.isEqual(n)) throw e.ct(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);
  4940. return {
  4941. referenceValue: Je(t.firestore._databaseId || e.databaseId, t._key.path)
  4942. };
  4943. }
  4944. throw e.ct(`Unsupported field value: ${ut(t)}`);
  4945. }
  4946. /**
  4947. * Checks whether an object looks like a JSON object that should be converted
  4948. * into a struct. Normal class/prototype instances are considered to look like
  4949. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  4950. * GeoPoints, etc. are not considered to look like JSON objects since they map
  4951. * to specific FieldValue types other than ObjectValue.
  4952. */ (t, e);
  4953. }
  4954. function cr(t, e) {
  4955. const n = {};
  4956. return !function(t) {
  4957. for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  4958. return !0;
  4959. }(t) ? Rt(t, ((t, r) => {
  4960. const s = ur(r, e.rt(t));
  4961. null != s && (n[t] = s);
  4962. })) :
  4963. // If we encounter an empty object, we explicitly add it to the update
  4964. // mask to ensure that the server creates a map entry.
  4965. e.path && e.path.length > 0 && e.fieldMask.push(e.path), {
  4966. mapValue: {
  4967. fields: n
  4968. }
  4969. };
  4970. }
  4971. function ar(t) {
  4972. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof xt || t instanceof Bn || t instanceof Mn || t instanceof Dn || t instanceof jn);
  4973. }
  4974. function hr(t, e, n) {
  4975. if (!ar(n) || !function(t) {
  4976. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  4977. }(n)) {
  4978. const r = ut(n);
  4979. throw "an object" === r ? e.ct(t + " a custom object") : e.ct(t + " " + r);
  4980. }
  4981. }
  4982. /**
  4983. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  4984. */ function lr(t, e, n) {
  4985. if ((
  4986. // If required, replace the FieldPath Compat class with with the firestore-exp
  4987. // FieldPath.
  4988. e = getModularInstance(e)) instanceof Ln) return e._internalPath;
  4989. if ("string" == typeof e) return dr(t, e);
  4990. throw wr("Field path arguments must be of type string or ", t,
  4991. /* hasConverter= */ !1,
  4992. /* path= */ void 0, n);
  4993. }
  4994. /**
  4995. * Matches any characters in a field path string that are reserved.
  4996. */ const fr = new RegExp("[~\\*/\\[\\]]");
  4997. /**
  4998. * Wraps fromDotSeparatedString with an error message about the method that
  4999. * was thrown.
  5000. * @param methodName - The publicly visible method name
  5001. * @param path - The dot-separated string form of a field path which will be
  5002. * split on dots.
  5003. * @param targetDoc - The document against which the field path will be
  5004. * evaluated.
  5005. */ function dr(t, e, n) {
  5006. if (e.search(fr) >= 0) throw wr(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t,
  5007. /* hasConverter= */ !1,
  5008. /* path= */ void 0, n);
  5009. try {
  5010. return new Ln(...e.split("."))._internalPath;
  5011. } catch (r) {
  5012. throw wr(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t,
  5013. /* hasConverter= */ !1,
  5014. /* path= */ void 0, n);
  5015. }
  5016. }
  5017. function wr(t, e, n, r, s) {
  5018. const i = r && !r.isEmpty(), o = void 0 !== s;
  5019. let u = `Function ${e}() called with invalid data`;
  5020. n && (u += " (via `toFirestore()`)"), u += ". ";
  5021. let c = "";
  5022. return (i || o) && (c += " (found", i && (c += ` in field ${r}`), o && (c += ` in document ${s}`),
  5023. c += ")"), new U(P, u + t + c);
  5024. }
  5025. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function mr(t, e) {
  5026. return t.some((t => t.isEqual(e)));
  5027. }
  5028. /**
  5029. * @license
  5030. * Copyright 2020 Google LLC
  5031. *
  5032. * Licensed under the Apache License, Version 2.0 (the "License");
  5033. * you may not use this file except in compliance with the License.
  5034. * You may obtain a copy of the License at
  5035. *
  5036. * http://www.apache.org/licenses/LICENSE-2.0
  5037. *
  5038. * Unless required by applicable law or agreed to in writing, software
  5039. * distributed under the License is distributed on an "AS IS" BASIS,
  5040. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5041. * See the License for the specific language governing permissions and
  5042. * limitations under the License.
  5043. */
  5044. /**
  5045. * A `DocumentSnapshot` contains data read from a document in your Firestore
  5046. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  5047. * get a specific field.
  5048. *
  5049. * For a `DocumentSnapshot` that points to a non-existing document, any data
  5050. * access will return 'undefined'. You can use the `exists()` method to
  5051. * explicitly verify a document's existence.
  5052. */ class pr {
  5053. // Note: This class is stripped down version of the DocumentSnapshot in
  5054. // the legacy SDK. The changes are:
  5055. // - No support for SnapshotMetadata.
  5056. // - No support for SnapshotOptions.
  5057. /** @hideconstructor protected */
  5058. constructor(t, e, n, r, s) {
  5059. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = r,
  5060. this._converter = s;
  5061. }
  5062. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
  5063. return this._key.path.lastSegment();
  5064. }
  5065. /**
  5066. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  5067. */ get ref() {
  5068. return new Dn(this._firestore, this._converter, this._key);
  5069. }
  5070. /**
  5071. * Signals whether or not the document at the snapshot's location exists.
  5072. *
  5073. * @returns true if the document exists.
  5074. */ exists() {
  5075. return null !== this._document;
  5076. }
  5077. /**
  5078. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  5079. * the document doesn't exist.
  5080. *
  5081. * @returns An `Object` containing all fields in the document or `undefined`
  5082. * if the document doesn't exist.
  5083. */ data() {
  5084. if (this._document) {
  5085. if (this._converter) {
  5086. // We only want to use the converter and create a new DocumentSnapshot
  5087. // if a converter has been provided.
  5088. const t = new yr(this._firestore, this._userDataWriter, this._key, this._document,
  5089. /* converter= */ null);
  5090. return this._converter.fromFirestore(t);
  5091. }
  5092. return this._userDataWriter.convertValue(this._document.data.value);
  5093. }
  5094. }
  5095. /**
  5096. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  5097. * document or field doesn't exist.
  5098. *
  5099. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  5100. * field.
  5101. * @returns The data at the specified field location or undefined if no such
  5102. * field exists in the document.
  5103. */
  5104. // We are using `any` here to avoid an explicit cast by our users.
  5105. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5106. get(t) {
  5107. if (this._document) {
  5108. const e = this._document.data.field(vr("DocumentSnapshot.get", t));
  5109. if (null !== e) return this._userDataWriter.convertValue(e);
  5110. }
  5111. }
  5112. }
  5113. /**
  5114. * A `QueryDocumentSnapshot` contains data read from a document in your
  5115. * Firestore database as part of a query. The document is guaranteed to exist
  5116. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  5117. * specific field.
  5118. *
  5119. * A `QueryDocumentSnapshot` offers the same API surface as a
  5120. * `DocumentSnapshot`. Since query results contain only existing documents, the
  5121. * `exists` property will always be true and `data()` will never return
  5122. * 'undefined'.
  5123. */ class yr extends pr {
  5124. /**
  5125. * Retrieves all fields in the document as an `Object`.
  5126. *
  5127. * @override
  5128. * @returns An `Object` containing all fields in the document.
  5129. */
  5130. data() {
  5131. return super.data();
  5132. }
  5133. }
  5134. /**
  5135. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  5136. * representing the results of a query. The documents can be accessed as an
  5137. * array via the `docs` property or enumerated using the `forEach` method. The
  5138. * number of documents can be determined via the `empty` and `size`
  5139. * properties.
  5140. */ class gr {
  5141. /** @hideconstructor */
  5142. constructor(t, e) {
  5143. this._docs = e, this.query = t;
  5144. }
  5145. /** An array of all the documents in the `QuerySnapshot`. */ get docs() {
  5146. return [ ...this._docs ];
  5147. }
  5148. /** The number of documents in the `QuerySnapshot`. */ get size() {
  5149. return this.docs.length;
  5150. }
  5151. /** True if there are no documents in the `QuerySnapshot`. */ get empty() {
  5152. return 0 === this.docs.length;
  5153. }
  5154. /**
  5155. * Enumerates all of the documents in the `QuerySnapshot`.
  5156. *
  5157. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  5158. * each document in the snapshot.
  5159. * @param thisArg - The `this` binding for the callback.
  5160. */ forEach(t, e) {
  5161. this._docs.forEach(t, e);
  5162. }
  5163. }
  5164. /**
  5165. * Returns true if the provided snapshots are equal.
  5166. *
  5167. * @param left - A snapshot to compare.
  5168. * @param right - A snapshot to compare.
  5169. * @returns true if the snapshots are equal.
  5170. */ function _r(t, e) {
  5171. return t = getModularInstance(t), e = getModularInstance(e), t instanceof pr && e instanceof pr ? 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 gr && e instanceof gr && (Cn(t.query, e.query) && Tt(t.docs, e.docs, _r));
  5172. }
  5173. /**
  5174. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  5175. */ function vr(t, e) {
  5176. return "string" == typeof e ? dr(t, e) : e instanceof Ln ? e._internalPath : e._delegate._internalPath;
  5177. }
  5178. /**
  5179. * @license
  5180. * Copyright 2020 Google LLC
  5181. *
  5182. * Licensed under the Apache License, Version 2.0 (the "License");
  5183. * you may not use this file except in compliance with the License.
  5184. * You may obtain a copy of the License at
  5185. *
  5186. * http://www.apache.org/licenses/LICENSE-2.0
  5187. *
  5188. * Unless required by applicable law or agreed to in writing, software
  5189. * distributed under the License is distributed on an "AS IS" BASIS,
  5190. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5191. * See the License for the specific language governing permissions and
  5192. * limitations under the License.
  5193. */
  5194. /**
  5195. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  5196. * to a Firestore query.
  5197. */
  5198. class br {}
  5199. /**
  5200. * A `QueryConstraint` is used to narrow the set of documents returned by a
  5201. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  5202. * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
  5203. * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and
  5204. * can then be passed to {@link (query:1)} to create a new query instance that
  5205. * also contains this `QueryConstraint`.
  5206. */ class Er extends br {}
  5207. function Ir(t, e, ...n) {
  5208. let r = [];
  5209. e instanceof br && r.push(e), r = r.concat(n), function(t) {
  5210. const e = t.filter((t => t instanceof Rr)).length, n = t.filter((t => t instanceof Tr)).length;
  5211. if (e > 1 || e > 0 && n > 0) throw new U(P, "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(...)))`.");
  5212. }
  5213. /**
  5214. * @license
  5215. * Copyright 2020 Google LLC
  5216. *
  5217. * Licensed under the Apache License, Version 2.0 (the "License");
  5218. * you may not use this file except in compliance with the License.
  5219. * You may obtain a copy of the License at
  5220. *
  5221. * http://www.apache.org/licenses/LICENSE-2.0
  5222. *
  5223. * Unless required by applicable law or agreed to in writing, software
  5224. * distributed under the License is distributed on an "AS IS" BASIS,
  5225. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5226. * See the License for the specific language governing permissions and
  5227. * limitations under the License.
  5228. */
  5229. /**
  5230. * Converts Firestore's internal types to the JavaScript types that we expose
  5231. * to the user.
  5232. *
  5233. * @internal
  5234. */ (r);
  5235. for (const e of r) t = e._apply(t);
  5236. return t;
  5237. }
  5238. /**
  5239. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  5240. * a Firestore query by filtering on one or more document fields.
  5241. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  5242. * be passed to {@link (query:1)} to create a new query instance that also contains
  5243. * this `QueryFieldFilterConstraint`.
  5244. */ class Tr extends Er {
  5245. /**
  5246. * @internal
  5247. */
  5248. constructor(t, e, n) {
  5249. super(), this._field = t, this._op = e, this._value = n,
  5250. /** The type of this query constraint */
  5251. this.type = "where";
  5252. }
  5253. static _create(t, e, n) {
  5254. return new Tr(t, e, n);
  5255. }
  5256. _apply(t) {
  5257. const e = this._parse(t);
  5258. return Br(t._query, e), new Fn(t.firestore, t.converter, Ve(t._query, e));
  5259. }
  5260. _parse(t) {
  5261. const e = Hn(t.firestore), n = function(t, e, n, r, s, i, o) {
  5262. let u;
  5263. if (s.isKeyField()) {
  5264. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === i || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === i) throw new U(P, `Invalid Query. You can't perform '${i}' queries on documentId().`);
  5265. if ("in" /* Operator.IN */ === i || "not-in" /* Operator.NOT_IN */ === i) {
  5266. jr(o, i);
  5267. const e = [];
  5268. for (const n of o) e.push(Ur(r, t, n));
  5269. u = {
  5270. arrayValue: {
  5271. values: e
  5272. }
  5273. };
  5274. } else u = Ur(r, t, o);
  5275. } else "in" /* Operator.IN */ !== i && "not-in" /* Operator.NOT_IN */ !== i && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== i || jr(o, i),
  5276. u = or(n, e, o,
  5277. /* allowArrays= */ "in" /* Operator.IN */ === i || "not-in" /* Operator.NOT_IN */ === i);
  5278. return Xt.create(s, i, u);
  5279. }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value);
  5280. return n;
  5281. }
  5282. }
  5283. /**
  5284. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  5285. * must contain the specified field and that the value should satisfy the
  5286. * relation constraint provided.
  5287. *
  5288. * @param fieldPath - The path to compare
  5289. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  5290. * "&lt;=", "!=").
  5291. * @param value - The value for comparison
  5292. * @returns The created {@link QueryFieldFilterConstraint}.
  5293. */ function Ar(t, e, n) {
  5294. const r = e, s = vr("where", t);
  5295. return Tr._create(s, r, n);
  5296. }
  5297. /**
  5298. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  5299. * returned by a Firestore query by performing the logical OR or AND of multiple
  5300. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  5301. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  5302. * {@link and} and can then be passed to {@link (query:1)} to create a new query
  5303. * instance that also contains the `QueryCompositeFilterConstraint`.
  5304. */ class Rr extends br {
  5305. /**
  5306. * @internal
  5307. */
  5308. constructor(
  5309. /** The type of this query constraint */
  5310. t, e) {
  5311. super(), this.type = t, this._queryConstraints = e;
  5312. }
  5313. static _create(t, e) {
  5314. return new Rr(t, e);
  5315. }
  5316. _parse(t) {
  5317. const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));
  5318. return 1 === e.length ? e[0] : Zt.create(e, this._getOperator());
  5319. }
  5320. _apply(t) {
  5321. const e = this._parse(t);
  5322. return 0 === e.getFilters().length ? t : (function(t, e) {
  5323. let n = t;
  5324. const r = e.getFlattenedFilters();
  5325. for (const t of r) Br(n, t), n = Ve(n, t);
  5326. }
  5327. // Checks if any of the provided filter operators are included in the given list of filters and
  5328. // returns the first one that is, or null if none are.
  5329. (t._query, e), new Fn(t.firestore, t.converter, Ve(t._query, e)));
  5330. }
  5331. _getQueryConstraints() {
  5332. return this._queryConstraints;
  5333. }
  5334. _getOperator() {
  5335. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  5336. }
  5337. }
  5338. /**
  5339. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  5340. * the given filter constraints. A disjunction filter includes a document if it
  5341. * satisfies any of the given filters.
  5342. *
  5343. * @param queryConstraints - Optional. The list of
  5344. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  5345. * created with calls to {@link where}, {@link or}, or {@link and}.
  5346. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  5347. */ function Pr(...t) {
  5348. // Only support QueryFilterConstraints
  5349. return t.forEach((t => zr("or", t))), Rr._create("or" /* CompositeOperator.OR */ , t);
  5350. }
  5351. /**
  5352. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  5353. * the given filter constraints. A conjunction filter includes a document if it
  5354. * satisfies all of the given filters.
  5355. *
  5356. * @param queryConstraints - Optional. The list of
  5357. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  5358. * created with calls to {@link where}, {@link or}, or {@link and}.
  5359. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  5360. */ function Vr(...t) {
  5361. // Only support QueryFilterConstraints
  5362. return t.forEach((t => zr("and", t))), Rr._create("and" /* CompositeOperator.AND */ , t);
  5363. }
  5364. /**
  5365. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  5366. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  5367. * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query
  5368. * instance that also contains this `QueryOrderByConstraint`.
  5369. *
  5370. * Note: Documents that do not contain the orderBy field will not be present in
  5371. * the query result.
  5372. */ class $r extends Er {
  5373. /**
  5374. * @internal
  5375. */
  5376. constructor(t, e) {
  5377. super(), this._field = t, this._direction = e,
  5378. /** The type of this query constraint */
  5379. this.type = "orderBy";
  5380. }
  5381. static _create(t, e) {
  5382. return new $r(t, e);
  5383. }
  5384. _apply(t) {
  5385. const e = function(t, e, n) {
  5386. if (null !== t.startAt) throw new U(P, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  5387. if (null !== t.endAt) throw new U(P, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  5388. const r = new ae(e, n);
  5389. return function(t, e) {
  5390. if (null === Ie(t)) {
  5391. // This is the first order by. It must match any inequality.
  5392. const n = Te(t);
  5393. null !== n && Qr(t, n, e.field);
  5394. }
  5395. }(t, r), r;
  5396. }
  5397. /**
  5398. * Create a `Bound` from a query and a document.
  5399. *
  5400. * Note that the `Bound` will always include the key of the document
  5401. * and so only the provided document will compare equal to the returned
  5402. * position.
  5403. *
  5404. * Will throw if the document does not contain all fields of the order by
  5405. * of the query or if any of the fields in the order by are an uncommitted
  5406. * server timestamp.
  5407. */ (t._query, this._field, this._direction);
  5408. return new Fn(t.firestore, t.converter, function(t, e) {
  5409. // TODO(dimond): validate that orderBy does not list the same key twice.
  5410. const n = t.explicitOrderBy.concat([ e ]);
  5411. return new Ee(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  5412. }(t._query, e));
  5413. }
  5414. }
  5415. /**
  5416. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  5417. * specified field, optionally in descending order instead of ascending.
  5418. *
  5419. * Note: Documents that do not contain the specified field will not be present
  5420. * in the query result.
  5421. *
  5422. * @param fieldPath - The field to sort by.
  5423. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  5424. * not specified, order will be ascending.
  5425. * @returns The created {@link QueryOrderByConstraint}.
  5426. */ function Nr(t, e = "asc") {
  5427. const n = e, r = vr("orderBy", t);
  5428. return $r._create(r, n);
  5429. }
  5430. /**
  5431. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  5432. * a Firestore query.
  5433. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  5434. * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new
  5435. * query instance that also contains this `QueryLimitConstraint`.
  5436. */ class Dr extends Er {
  5437. /**
  5438. * @internal
  5439. */
  5440. constructor(
  5441. /** The type of this query constraint */
  5442. t, e, n) {
  5443. super(), this.type = t, this._limit = e, this._limitType = n;
  5444. }
  5445. static _create(t, e, n) {
  5446. return new Dr(t, e, n);
  5447. }
  5448. _apply(t) {
  5449. return new Fn(t.firestore, t.converter, function(t, e, n) {
  5450. return new Ee(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  5451. }(t._query, this._limit, this._limitType));
  5452. }
  5453. }
  5454. /**
  5455. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  5456. * documents.
  5457. *
  5458. * @param limit - The maximum number of items to return.
  5459. * @returns The created {@link QueryLimitConstraint}.
  5460. */ function Fr(t) {
  5461. return at("limit", t), Dr._create("limit", t, "F" /* LimitType.First */);
  5462. }
  5463. /**
  5464. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  5465. * documents.
  5466. *
  5467. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  5468. * otherwise an exception will be thrown during execution.
  5469. *
  5470. * @param limit - The maximum number of items to return.
  5471. * @returns The created {@link QueryLimitConstraint}.
  5472. */ function xr(t) {
  5473. return at("limitToLast", t), Dr._create("limitToLast", t, "L" /* LimitType.Last */);
  5474. }
  5475. /**
  5476. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  5477. * result set returned by a Firestore query.
  5478. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  5479. * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a
  5480. * new query instance that also contains this `QueryStartAtConstraint`.
  5481. */ class Sr extends Er {
  5482. /**
  5483. * @internal
  5484. */
  5485. constructor(
  5486. /** The type of this query constraint */
  5487. t, e, n) {
  5488. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  5489. }
  5490. static _create(t, e, n) {
  5491. return new Sr(t, e, n);
  5492. }
  5493. _apply(t) {
  5494. const e = Lr(t, this.type, this._docOrFields, this._inclusive);
  5495. return new Fn(t.firestore, t.converter, function(t, e) {
  5496. return new Ee(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  5497. }(t._query, e));
  5498. }
  5499. }
  5500. function qr(...t) {
  5501. return Sr._create("startAt", t,
  5502. /*inclusive=*/ !0);
  5503. }
  5504. function Or(...t) {
  5505. return Sr._create("startAfter", t,
  5506. /*inclusive=*/ !1);
  5507. }
  5508. /**
  5509. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  5510. * result set returned by a Firestore query.
  5511. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  5512. * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new
  5513. * query instance that also contains this `QueryEndAtConstraint`.
  5514. */ class kr extends Er {
  5515. /**
  5516. * @internal
  5517. */
  5518. constructor(
  5519. /** The type of this query constraint */
  5520. t, e, n) {
  5521. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  5522. }
  5523. static _create(t, e, n) {
  5524. return new kr(t, e, n);
  5525. }
  5526. _apply(t) {
  5527. const e = Lr(t, this.type, this._docOrFields, this._inclusive);
  5528. return new Fn(t.firestore, t.converter, function(t, e) {
  5529. return new Ee(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  5530. }(t._query, e));
  5531. }
  5532. }
  5533. function Cr(...t) {
  5534. return kr._create("endBefore", t,
  5535. /*inclusive=*/ !1);
  5536. }
  5537. function Mr(...t) {
  5538. return kr._create("endAt", t,
  5539. /*inclusive=*/ !0);
  5540. }
  5541. /** Helper function to create a bound from a document or fields */ function Lr(t, e, n, r) {
  5542. if (n[0] = getModularInstance(n[0]), n[0] instanceof pr) return function(t, e, n, r, s) {
  5543. if (!r) throw new U($, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);
  5544. const i = [];
  5545. // Because people expect to continue/end a query at the exact document
  5546. // provided, we need to use the implicit sort order rather than the explicit
  5547. // sort order, because it's guaranteed to contain the document key. That way
  5548. // the position becomes unambiguous and the query continues/ends exactly at
  5549. // the provided document. Without the key (by using the explicit sort
  5550. // orders), multiple documents could match the position, yielding duplicate
  5551. // results.
  5552. for (const n of Re(t)) if (n.field.isKeyField()) i.push(Bt(e, r.key)); else {
  5553. const t = r.data.field(n.field);
  5554. if (St(t)) throw new U(P, '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.)');
  5555. if (null === t) {
  5556. const t = n.field.canonicalString();
  5557. throw new U(P, `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.`);
  5558. }
  5559. i.push(t);
  5560. }
  5561. return new Yt(i, s);
  5562. }
  5563. /**
  5564. * Converts a list of field values to a `Bound` for the given query.
  5565. */ (t._query, t.firestore._databaseId, e, n[0]._document, r);
  5566. {
  5567. const s = Hn(t.firestore);
  5568. return function(t, e, n, r, s, i) {
  5569. // Use explicit order by's because it has to match the query the user made
  5570. const o = t.explicitOrderBy;
  5571. if (s.length > o.length) throw new U(P, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
  5572. const u = [];
  5573. for (let i = 0; i < s.length; i++) {
  5574. const c = s[i];
  5575. if (o[i].field.isKeyField()) {
  5576. if ("string" != typeof c) throw new U(P, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);
  5577. if (!Ae(t) && -1 !== c.indexOf("/")) throw new U(P, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);
  5578. const n = t.path.child(tt.fromString(c));
  5579. if (!rt.isDocumentKey(n)) throw new U(P, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
  5580. const s = new rt(n);
  5581. u.push(Bt(e, s));
  5582. } else {
  5583. const t = or(n, r, c);
  5584. u.push(t);
  5585. }
  5586. }
  5587. return new Yt(u, i);
  5588. }
  5589. /**
  5590. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  5591. * appropriate errors if the value is anything other than a `DocumentReference`
  5592. * or `string`, or if the string is malformed.
  5593. */ (t._query, t.firestore._databaseId, s, e, n, r);
  5594. }
  5595. }
  5596. function Ur(t, e, n) {
  5597. if ("string" == typeof (n = getModularInstance(n))) {
  5598. if ("" === n) throw new U(P, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  5599. if (!Ae(e) && -1 !== n.indexOf("/")) throw new U(P, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
  5600. const r = e.path.child(tt.fromString(n));
  5601. if (!rt.isDocumentKey(r)) throw new U(P, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);
  5602. return Bt(t, new rt(r));
  5603. }
  5604. if (n instanceof Dn) return Bt(t, n._key);
  5605. throw new U(P, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${ut(n)}.`);
  5606. }
  5607. /**
  5608. * Validates that the value passed into a disjunctive filter satisfies all
  5609. * array requirements.
  5610. */ function jr(t, e) {
  5611. if (!Array.isArray(t) || 0 === t.length) throw new U(P, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
  5612. }
  5613. /**
  5614. * Given an operator, returns the set of operators that cannot be used with it.
  5615. *
  5616. * This is not a comprehensive check, and this function should be removed in the
  5617. * long term. Validations should occur in the Firestore backend.
  5618. *
  5619. * Operators in a query must adhere to the following set of rules:
  5620. * 1. Only one inequality per query.
  5621. * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  5622. */ function Br(t, e) {
  5623. if (e.isInequality()) {
  5624. const n = Te(t), r = e.field;
  5625. if (null !== n && !n.isEqual(r)) throw new U(P, `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 '${r.toString()}'`);
  5626. const s = Ie(t);
  5627. null !== s && Qr(t, r, s);
  5628. }
  5629. const n = function(t, e) {
  5630. for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;
  5631. return null;
  5632. }(t.filters, function(t) {
  5633. switch (t) {
  5634. case "!=" /* Operator.NOT_EQUAL */ :
  5635. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  5636. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  5637. case "in" /* Operator.IN */ :
  5638. return [ "not-in" /* Operator.NOT_IN */ ];
  5639. case "not-in" /* Operator.NOT_IN */ :
  5640. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  5641. default:
  5642. return [];
  5643. }
  5644. }(e.op));
  5645. if (null !== n)
  5646. // Special case when it's a duplicate op to give a slightly clearer error message.
  5647. throw n === e.op ? new U(P, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new U(P, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
  5648. }
  5649. function Qr(t, e, n) {
  5650. if (!n.isEqual(e)) throw new U(P, `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.`);
  5651. }
  5652. function zr(t, e) {
  5653. if (!(e instanceof Tr || e instanceof Rr)) throw new U(P, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  5654. }
  5655. /**
  5656. * @license
  5657. * Copyright 2020 Google LLC
  5658. *
  5659. * Licensed under the Apache License, Version 2.0 (the "License");
  5660. * you may not use this file except in compliance with the License.
  5661. * You may obtain a copy of the License at
  5662. *
  5663. * http://www.apache.org/licenses/LICENSE-2.0
  5664. *
  5665. * Unless required by applicable law or agreed to in writing, software
  5666. * distributed under the License is distributed on an "AS IS" BASIS,
  5667. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5668. * See the License for the specific language governing permissions and
  5669. * limitations under the License.
  5670. */
  5671. /**
  5672. * Converts custom model object of type T into `DocumentData` by applying the
  5673. * converter if it exists.
  5674. *
  5675. * This function is used when converting user objects to `DocumentData`
  5676. * because we want to provide the user with a more specific error message if
  5677. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  5678. * call.
  5679. */
  5680. function Wr(t, e, n) {
  5681. let r;
  5682. // Cast to `any` in order to satisfy the union type constraint on
  5683. // toFirestore().
  5684. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5685. return r = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e,
  5686. r;
  5687. }
  5688. class Gr extends class {
  5689. convertValue(t, e = "none") {
  5690. switch (Ct(t)) {
  5691. case 0 /* TypeOrder.NullValue */ :
  5692. return null;
  5693. case 1 /* TypeOrder.BooleanValue */ :
  5694. return t.booleanValue;
  5695. case 2 /* TypeOrder.NumberValue */ :
  5696. return Dt(t.integerValue || t.doubleValue);
  5697. case 3 /* TypeOrder.TimestampValue */ :
  5698. return this.convertTimestamp(t.timestampValue);
  5699. case 4 /* TypeOrder.ServerTimestampValue */ :
  5700. return this.convertServerTimestamp(t, e);
  5701. case 5 /* TypeOrder.StringValue */ :
  5702. return t.stringValue;
  5703. case 6 /* TypeOrder.BlobValue */ :
  5704. return this.convertBytes(Ft(t.bytesValue));
  5705. case 7 /* TypeOrder.RefValue */ :
  5706. return this.convertReference(t.referenceValue);
  5707. case 8 /* TypeOrder.GeoPointValue */ :
  5708. return this.convertGeoPoint(t.geoPointValue);
  5709. case 9 /* TypeOrder.ArrayValue */ :
  5710. return this.convertArray(t.arrayValue, e);
  5711. case 10 /* TypeOrder.ObjectValue */ :
  5712. return this.convertObject(t.mapValue, e);
  5713. default:
  5714. throw b();
  5715. }
  5716. }
  5717. convertObject(t, e) {
  5718. return this.convertObjectMap(t.fields, e);
  5719. }
  5720. /**
  5721. * @internal
  5722. */ convertObjectMap(t, e = "none") {
  5723. const n = {};
  5724. return Rt(t, ((t, r) => {
  5725. n[t] = this.convertValue(r, e);
  5726. })), n;
  5727. }
  5728. convertGeoPoint(t) {
  5729. return new Bn(Dt(t.latitude), Dt(t.longitude));
  5730. }
  5731. convertArray(t, e) {
  5732. return (t.values || []).map((t => this.convertValue(t, e)));
  5733. }
  5734. convertServerTimestamp(t, e) {
  5735. switch (e) {
  5736. case "previous":
  5737. const n = qt(t);
  5738. return null == n ? null : this.convertValue(n, e);
  5739. case "estimate":
  5740. return this.convertTimestamp(Ot(t));
  5741. default:
  5742. return null;
  5743. }
  5744. }
  5745. convertTimestamp(t) {
  5746. const e = Nt(t);
  5747. return new xt(e.seconds, e.nanos);
  5748. }
  5749. convertDocumentKey(t, e) {
  5750. const n = tt.fromString(t);
  5751. E(dn(n));
  5752. const r = new X(n.get(1), n.get(3)), s = new rt(n.popFirst(5));
  5753. return r.isEqual(e) ||
  5754. // TODO(b/64130202): Somehow support foreign references.
  5755. g(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),
  5756. s;
  5757. }
  5758. } {
  5759. constructor(t) {
  5760. super(), this.firestore = t;
  5761. }
  5762. convertBytes(t) {
  5763. return new Mn(t);
  5764. }
  5765. convertReference(t) {
  5766. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  5767. return new Dn(this.firestore, /* converter= */ null, e);
  5768. }
  5769. }
  5770. /**
  5771. * Reads the document referred to by the specified document reference.
  5772. *
  5773. * All documents are directly fetched from the server, even if the document was
  5774. * previously read or modified. Recent modifications are only reflected in the
  5775. * retrieved `DocumentSnapshot` if they have already been applied by the
  5776. * backend. If the client is offline, the read fails. If you like to use
  5777. * caching or see local modifications, please use the full Firestore SDK.
  5778. *
  5779. * @param reference - The reference of the document to fetch.
  5780. * @returns A Promise resolved with a `DocumentSnapshot` containing the current
  5781. * document contents.
  5782. */ function Kr(t) {
  5783. const e = En((t = ct(t, Dn)).firestore), n = new Gr(t.firestore);
  5784. return gn(e, [ t._key ]).then((e => {
  5785. E(1 === e.length);
  5786. const r = e[0];
  5787. return new pr(t.firestore, n, t._key, r.isFoundDocument() ? r : null, t.converter);
  5788. }));
  5789. }
  5790. /**
  5791. * Executes the query and returns the results as a {@link QuerySnapshot}.
  5792. *
  5793. * All queries are executed directly by the server, even if the the query was
  5794. * previously executed. Recent modifications are only reflected in the retrieved
  5795. * results if they have already been applied by the backend. If the client is
  5796. * offline, the operation fails. To see previously cached result and local
  5797. * modifications, use the full Firestore SDK.
  5798. *
  5799. * @param query - The `Query` to execute.
  5800. * @returns A Promise that will be resolved with the results of the query.
  5801. */ function Yr(t) {
  5802. !function(t) {
  5803. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new U(k, "limitToLast() queries require specifying at least one orderBy() clause");
  5804. }((t = ct(t, Fn))._query);
  5805. const e = En(t.firestore), n = new Gr(t.firestore);
  5806. return _n(e, t._query).then((e => {
  5807. const r = e.map((e => new yr(t.firestore, n, e.key, e, t.converter)));
  5808. return "L" /* LimitType.Last */ === t._query.limitType &&
  5809. // Limit to last queries reverse the orderBy constraint that was
  5810. // specified by the user. As such, we need to reverse the order of the
  5811. // results to return the documents in the expected order.
  5812. r.reverse(), new gr(t, r);
  5813. }));
  5814. }
  5815. function Hr(t, e, n) {
  5816. const r = Wr((t = ct(t, Dn)).converter, e, n), s = Jn(Hn(t.firestore), "setDoc", t._key, r, null !== t.converter, n);
  5817. return yn(En(t.firestore), [ s.toMutation(t._key, ke.none()) ]);
  5818. }
  5819. function Jr(t, e, n, ...r) {
  5820. const s = Hn((t = ct(t, Dn)).firestore);
  5821. // For Compat types, we have to "extract" the underlying types before
  5822. // performing validation.
  5823. let i;
  5824. i = "string" == typeof (e = getModularInstance(e)) || e instanceof Ln ? ir(s, "updateDoc", t._key, e, n, r) : sr(s, "updateDoc", t._key, e);
  5825. return yn(En(t.firestore), [ i.toMutation(t._key, ke.exists(!0)) ]);
  5826. }
  5827. /**
  5828. * Deletes the document referred to by the specified `DocumentReference`.
  5829. *
  5830. * The deletion will only be reflected in document reads that occur after the
  5831. * returned promise resolves. If the client is offline, the
  5832. * delete fails. If you would like to see local modifications or buffer writes
  5833. * until the client is online, use the full Firestore SDK.
  5834. *
  5835. * @param reference - A reference to the document to delete.
  5836. * @returns A `Promise` resolved once the document has been successfully
  5837. * deleted from the backend.
  5838. */ function Xr(t) {
  5839. return yn(En((t = ct(t, Dn)).firestore), [ new Ue(t._key, ke.none()) ]);
  5840. }
  5841. /**
  5842. * Add a new document to specified `CollectionReference` with the given data,
  5843. * assigning it a document ID automatically.
  5844. *
  5845. * The result of this write will only be reflected in document reads that occur
  5846. * after the returned promise resolves. If the client is offline, the
  5847. * write fails. If you would like to see local modifications or buffer writes
  5848. * until the client is online, use the full Firestore SDK.
  5849. *
  5850. * @param reference - A reference to the collection to add this document to.
  5851. * @param data - An Object containing the data for the new document.
  5852. * @throws Error - If the provided input is not a valid Firestore document.
  5853. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  5854. * newly created document after it has been written to the backend.
  5855. */ function Zr(t, e) {
  5856. const n = On(t = ct(t, xn)), r = Wr(t.converter, e), s = Jn(Hn(t.firestore), "addDoc", n._key, r, null !== n.converter, {});
  5857. return yn(En(t.firestore), [ s.toMutation(n._key, ke.exists(!1)) ]).then((() => n));
  5858. }
  5859. /**
  5860. * @license
  5861. * Copyright 2022 Google LLC
  5862. *
  5863. * Licensed under the Apache License, Version 2.0 (the "License");
  5864. * you may not use this file except in compliance with the License.
  5865. * You may obtain a copy of the License at
  5866. *
  5867. * http://www.apache.org/licenses/LICENSE-2.0
  5868. *
  5869. * Unless required by applicable law or agreed to in writing, software
  5870. * distributed under the License is distributed on an "AS IS" BASIS,
  5871. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5872. * See the License for the specific language governing permissions and
  5873. * limitations under the License.
  5874. */
  5875. /**
  5876. * Calculates the number of documents in the result set of the given query,
  5877. * without actually downloading the documents.
  5878. *
  5879. * Using this function to count the documents is efficient because only the
  5880. * final count, not the documents' data, is downloaded. This function can even
  5881. * count the documents if the result set would be prohibitively large to
  5882. * download entirely (e.g. thousands of documents).
  5883. *
  5884. * @param query - The query whose result set size to calculate.
  5885. * @returns A Promise that will be resolved with the count; the count can be
  5886. * retrieved from `snapshot.data().count`, where `snapshot` is the
  5887. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  5888. */ function ts(t) {
  5889. return es(t, {
  5890. count: ss()
  5891. });
  5892. }
  5893. /**
  5894. * Calculates the specified aggregations over the documents in the result
  5895. * set of the given query, without actually downloading the documents.
  5896. *
  5897. * Using this function to perform aggregations is efficient because only the
  5898. * final aggregation values, not the documents' data, is downloaded. This
  5899. * function can even perform aggregations of the documents if the result set
  5900. * would be prohibitively large to download entirely (e.g. thousands of documents).
  5901. *
  5902. * @param query The query whose result set to aggregate over.
  5903. * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates
  5904. * to perform over the result set. The AggregateSpec specifies aliases for each
  5905. * aggregate, which can be used to retrieve the aggregate result.
  5906. * @example
  5907. * ```typescript
  5908. * const aggregateSnapshot = await getAggregate(query, {
  5909. * countOfDocs: count(),
  5910. * totalHours: sum('hours'),
  5911. * averageScore: average('score')
  5912. * });
  5913. *
  5914. * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
  5915. * const totalHours: number = aggregateSnapshot.data().totalHours;
  5916. * const averageScore: number | null = aggregateSnapshot.data().averageScore;
  5917. * ```
  5918. * @internal TODO (sum/avg) remove when public
  5919. */ function es(t, e) {
  5920. const n = ct(t.firestore, Tn), r = En(n), s = function(t, e) {
  5921. const n = [];
  5922. for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && n.push(e(t[r], r, t));
  5923. return n;
  5924. }(e, ((t, e) => new vt(e, t._aggregateType, t._internalFieldPath)));
  5925. // Run the aggregation and convert the results
  5926. return vn(r, t._query, s).then((e => function(t, e, n) {
  5927. const r = new Gr(t);
  5928. return new Nn(e, r, n);
  5929. }
  5930. /**
  5931. * Create an AggregateField object that can be used to compute the sum of
  5932. * a specified field over a range of documents in the result set of a query.
  5933. * @param field Specifies the field to sum across the result set.
  5934. * @internal TODO (sum/avg) remove when public
  5935. */ (n, t, e)));
  5936. }
  5937. function ns(t) {
  5938. return new $n("sum", lr("sum", t));
  5939. }
  5940. /**
  5941. * Create an AggregateField object that can be used to compute the average of
  5942. * a specified field over a range of documents in the result set of a query.
  5943. * @param field Specifies the field to average across the result set.
  5944. * @internal TODO (sum/avg) remove when public
  5945. */ function rs(t) {
  5946. return new $n("avg", lr("average", t));
  5947. }
  5948. /**
  5949. * Create an AggregateField object that can be used to compute the count of
  5950. * documents in the result set of a query.
  5951. * @internal TODO (sum/avg) remove when public
  5952. */ function ss() {
  5953. return new $n("count");
  5954. }
  5955. /**
  5956. * Compares two 'AggregateField` instances for equality.
  5957. *
  5958. * @param left Compare this AggregateField to the `right`.
  5959. * @param right Compare this AggregateField to the `left`.
  5960. * @internal TODO (sum/avg) remove when public
  5961. */ function is(t, e) {
  5962. var n, r;
  5963. return t instanceof $n && e instanceof $n && t._aggregateType === e._aggregateType && (null === (n = t._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (r = e._internalFieldPath) || void 0 === r ? void 0 : r.canonicalString());
  5964. }
  5965. /**
  5966. * Compares two `AggregateQuerySnapshot` instances for equality.
  5967. *
  5968. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  5969. * underlying queries that compare equal, and the same data.
  5970. *
  5971. * @param left - The first `AggregateQuerySnapshot` to compare.
  5972. * @param right - The second `AggregateQuerySnapshot` to compare.
  5973. *
  5974. * @returns `true` if the objects are "equal", as defined above, or `false`
  5975. * otherwise.
  5976. */ function os(t, e) {
  5977. return Cn(t.query, e.query) && deepEqual(t.data(), e.data());
  5978. }
  5979. /**
  5980. * @license
  5981. * Copyright 2020 Google LLC
  5982. *
  5983. * Licensed under the Apache License, Version 2.0 (the "License");
  5984. * you may not use this file except in compliance with the License.
  5985. * You may obtain a copy of the License at
  5986. *
  5987. * http://www.apache.org/licenses/LICENSE-2.0
  5988. *
  5989. * Unless required by applicable law or agreed to in writing, software
  5990. * distributed under the License is distributed on an "AS IS" BASIS,
  5991. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5992. * See the License for the specific language governing permissions and
  5993. * limitations under the License.
  5994. */
  5995. /**
  5996. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  5997. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  5998. */ function us() {
  5999. return new Xn("deleteField");
  6000. }
  6001. /**
  6002. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  6003. * include a server-generated timestamp in the written data.
  6004. */ function cs() {
  6005. return new tr("serverTimestamp");
  6006. }
  6007. /**
  6008. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  6009. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  6010. * value that already exists on the server. Each specified element that doesn't
  6011. * already exist in the array will be added to the end. If the field being
  6012. * modified is not already an array it will be overwritten with an array
  6013. * containing exactly the specified elements.
  6014. *
  6015. * @param elements - The elements to union into the array.
  6016. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  6017. * `updateDoc()`.
  6018. */ function as(...t) {
  6019. // NOTE: We don't actually parse the data until it's used in set() or
  6020. // update() since we'd need the Firestore instance to do this.
  6021. return new er("arrayUnion", t);
  6022. }
  6023. /**
  6024. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  6025. * updateDoc:1} that tells the server to remove the given elements from any
  6026. * array value that already exists on the server. All instances of each element
  6027. * specified will be removed from the array. If the field being modified is not
  6028. * already an array it will be overwritten with an empty array.
  6029. *
  6030. * @param elements - The elements to remove from the array.
  6031. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  6032. * `updateDoc()`
  6033. */ function hs(...t) {
  6034. // NOTE: We don't actually parse the data until it's used in set() or
  6035. // update() since we'd need the Firestore instance to do this.
  6036. return new nr("arrayRemove", t);
  6037. }
  6038. /**
  6039. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  6040. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  6041. * the given value.
  6042. *
  6043. * If either the operand or the current field value uses floating point
  6044. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  6045. * integers, values outside of JavaScript's safe number range
  6046. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  6047. * precision loss. Furthermore, once processed by the Firestore backend, all
  6048. * integer operations are capped between -2^63 and 2^63-1.
  6049. *
  6050. * If the current field value is not of type `number`, or if the field does not
  6051. * yet exist, the transformation sets the field to the given value.
  6052. *
  6053. * @param n - The value to increment by.
  6054. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  6055. * `updateDoc()`
  6056. */ function ls(t) {
  6057. return new rr("increment", t);
  6058. }
  6059. /**
  6060. * @license
  6061. * Copyright 2020 Google LLC
  6062. *
  6063. * Licensed under the Apache License, Version 2.0 (the "License");
  6064. * you may not use this file except in compliance with the License.
  6065. * You may obtain a copy of the License at
  6066. *
  6067. * http://www.apache.org/licenses/LICENSE-2.0
  6068. *
  6069. * Unless required by applicable law or agreed to in writing, software
  6070. * distributed under the License is distributed on an "AS IS" BASIS,
  6071. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6072. * See the License for the specific language governing permissions and
  6073. * limitations under the License.
  6074. */
  6075. /**
  6076. * A write batch, used to perform multiple writes as a single atomic unit.
  6077. *
  6078. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  6079. * provides methods for adding writes to the write batch. None of the writes
  6080. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  6081. * called.
  6082. */ class fs {
  6083. /** @hideconstructor */
  6084. constructor(t, e) {
  6085. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  6086. this._dataReader = Hn(t);
  6087. }
  6088. set(t, e, n) {
  6089. this._verifyNotCommitted();
  6090. const r = ds(t, this._firestore), s = Wr(r.converter, e, n), i = Jn(this._dataReader, "WriteBatch.set", r._key, s, null !== r.converter, n);
  6091. return this._mutations.push(i.toMutation(r._key, ke.none())), this;
  6092. }
  6093. update(t, e, n, ...r) {
  6094. this._verifyNotCommitted();
  6095. const s = ds(t, this._firestore);
  6096. // For Compat types, we have to "extract" the underlying types before
  6097. // performing validation.
  6098. let i;
  6099. return i = "string" == typeof (e = getModularInstance(e)) || e instanceof Ln ? ir(this._dataReader, "WriteBatch.update", s._key, e, n, r) : sr(this._dataReader, "WriteBatch.update", s._key, e),
  6100. this._mutations.push(i.toMutation(s._key, ke.exists(!0))), this;
  6101. }
  6102. /**
  6103. * Deletes the document referred to by the provided {@link DocumentReference}.
  6104. *
  6105. * @param documentRef - A reference to the document to be deleted.
  6106. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6107. */ delete(t) {
  6108. this._verifyNotCommitted();
  6109. const e = ds(t, this._firestore);
  6110. return this._mutations = this._mutations.concat(new Ue(e._key, ke.none())), this;
  6111. }
  6112. /**
  6113. * Commits all of the writes in this write batch as a single atomic unit.
  6114. *
  6115. * The result of these writes will only be reflected in document reads that
  6116. * occur after the returned promise resolves. If the client is offline, the
  6117. * write fails. If you would like to see local modifications or buffer writes
  6118. * until the client is online, use the full Firestore SDK.
  6119. *
  6120. * @returns A `Promise` resolved once all of the writes in the batch have been
  6121. * successfully written to the backend as an atomic unit (note that it won't
  6122. * resolve while you're offline).
  6123. */ commit() {
  6124. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  6125. }
  6126. _verifyNotCommitted() {
  6127. if (this._committed) throw new U(S, "A write batch can no longer be used after commit() has been called.");
  6128. }
  6129. }
  6130. function ds(t, e) {
  6131. if ((t = getModularInstance(t)).firestore !== e) throw new U(P, "Provided document reference is from a different Firestore instance.");
  6132. return t;
  6133. }
  6134. /**
  6135. * Creates a write batch, used for performing multiple writes as a single
  6136. * atomic operation. The maximum number of writes allowed in a single WriteBatch
  6137. * is 500.
  6138. *
  6139. * The result of these writes will only be reflected in document reads that
  6140. * occur after the returned promise resolves. If the client is offline, the
  6141. * write fails. If you would like to see local modifications or buffer writes
  6142. * until the client is online, use the full Firestore SDK.
  6143. *
  6144. * @returns A `WriteBatch` that can be used to atomically execute multiple
  6145. * writes.
  6146. */ function ws(t) {
  6147. const e = En(t = ct(t, Tn));
  6148. return new fs(t, (t => yn(e, t)));
  6149. }
  6150. /**
  6151. * @license
  6152. * Copyright 2017 Google LLC
  6153. *
  6154. * Licensed under the Apache License, Version 2.0 (the "License");
  6155. * you may not use this file except in compliance with the License.
  6156. * You may obtain a copy of the License at
  6157. *
  6158. * http://www.apache.org/licenses/LICENSE-2.0
  6159. *
  6160. * Unless required by applicable law or agreed to in writing, software
  6161. * distributed under the License is distributed on an "AS IS" BASIS,
  6162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6163. * See the License for the specific language governing permissions and
  6164. * limitations under the License.
  6165. */
  6166. /**
  6167. * Internal transaction object responsible for accumulating the mutations to
  6168. * perform and the base versions for any documents read.
  6169. */ class ms {
  6170. constructor(t) {
  6171. this.datastore = t,
  6172. // The version of each document that was read during this transaction.
  6173. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  6174. /**
  6175. * A deferred usage error that occurred previously in this transaction that
  6176. * will cause the transaction to fail once it actually commits.
  6177. */
  6178. this.lastWriteError = null,
  6179. /**
  6180. * Set of documents that have been written in the transaction.
  6181. *
  6182. * When there's more than one write to the same key in a transaction, any
  6183. * writes after the first are handled differently.
  6184. */
  6185. this.writtenDocs = new Set;
  6186. }
  6187. async lookup(t) {
  6188. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new U(P, "Firestore transactions require all reads to be executed before all writes.");
  6189. const e = await gn(this.datastore, t);
  6190. return e.forEach((t => this.recordVersion(t))), e;
  6191. }
  6192. set(t, e) {
  6193. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  6194. }
  6195. update(t, e) {
  6196. try {
  6197. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  6198. } catch (t) {
  6199. this.lastWriteError = t;
  6200. }
  6201. this.writtenDocs.add(t.toString());
  6202. }
  6203. delete(t) {
  6204. this.write(new Ue(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  6205. }
  6206. async commit() {
  6207. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  6208. const t = this.readVersions;
  6209. // For each mutation, note that the doc was written.
  6210. this.mutations.forEach((e => {
  6211. t.delete(e.key.toString());
  6212. })),
  6213. // For each document that was read but not written to, we want to perform
  6214. // a `verify` operation.
  6215. t.forEach(((t, e) => {
  6216. const n = rt.fromPath(e);
  6217. this.mutations.push(new je(n, this.precondition(n)));
  6218. })), await yn(this.datastore, this.mutations), this.committed = !0;
  6219. }
  6220. recordVersion(t) {
  6221. let e;
  6222. if (t.isFoundDocument()) e = t.version; else {
  6223. if (!t.isNoDocument()) throw b();
  6224. // Represent a deleted doc using SnapshotVersion.min().
  6225. e = le.min();
  6226. }
  6227. const n = this.readVersions.get(t.key.toString());
  6228. if (n) {
  6229. if (!e.isEqual(n))
  6230. // This transaction will fail no matter what.
  6231. throw new U(q, "Document version changed between two reads.");
  6232. } else this.readVersions.set(t.key.toString(), e);
  6233. }
  6234. /**
  6235. * Returns the version of this document when it was read in this transaction,
  6236. * as a precondition, or no precondition if it was not read.
  6237. */ precondition(t) {
  6238. const e = this.readVersions.get(t.toString());
  6239. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(le.min()) ? ke.exists(!1) : ke.updateTime(e) : ke.none();
  6240. }
  6241. /**
  6242. * Returns the precondition for a document if the operation is an update.
  6243. */ preconditionForUpdate(t) {
  6244. const e = this.readVersions.get(t.toString());
  6245. // The first time a document is written, we want to take into account the
  6246. // read time and existence
  6247. if (!this.writtenDocs.has(t.toString()) && e) {
  6248. if (e.isEqual(le.min()))
  6249. // The document doesn't exist, so fail the transaction.
  6250. // This has to be validated locally because you can't send a
  6251. // precondition that a document does not exist without changing the
  6252. // semantics of the backend write to be an insert. This is the reverse
  6253. // of what we want, since we want to assert that the document doesn't
  6254. // exist but then send the update and have it fail. Since we can't
  6255. // express that to the backend, we have to validate locally.
  6256. // Note: this can change once we can send separate verify writes in the
  6257. // transaction.
  6258. throw new U(P, "Can't update a document that doesn't exist.");
  6259. // Document exists, base precondition on document update time.
  6260. return ke.updateTime(e);
  6261. }
  6262. // Document was not read, so we just use the preconditions for a blind
  6263. // update.
  6264. return ke.exists(!0);
  6265. }
  6266. write(t) {
  6267. this.ensureCommitNotCalled(), this.mutations.push(t);
  6268. }
  6269. ensureCommitNotCalled() {}
  6270. }
  6271. /**
  6272. * @license
  6273. * Copyright 2022 Google LLC
  6274. *
  6275. * Licensed under the Apache License, Version 2.0 (the "License");
  6276. * you may not use this file except in compliance with the License.
  6277. * You may obtain a copy of the License at
  6278. *
  6279. * http://www.apache.org/licenses/LICENSE-2.0
  6280. *
  6281. * Unless required by applicable law or agreed to in writing, software
  6282. * distributed under the License is distributed on an "AS IS" BASIS,
  6283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6284. * See the License for the specific language governing permissions and
  6285. * limitations under the License.
  6286. */ const ps = {
  6287. maxAttempts: 5
  6288. };
  6289. /**
  6290. * @license
  6291. * Copyright 2019 Google LLC
  6292. *
  6293. * Licensed under the Apache License, Version 2.0 (the "License");
  6294. * you may not use this file except in compliance with the License.
  6295. * You may obtain a copy of the License at
  6296. *
  6297. * http://www.apache.org/licenses/LICENSE-2.0
  6298. *
  6299. * Unless required by applicable law or agreed to in writing, software
  6300. * distributed under the License is distributed on an "AS IS" BASIS,
  6301. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6302. * See the License for the specific language governing permissions and
  6303. * limitations under the License.
  6304. */
  6305. /**
  6306. * TransactionRunner encapsulates the logic needed to run and retry transactions
  6307. * with backoff.
  6308. */
  6309. class ys {
  6310. constructor(t, e, n, r, s) {
  6311. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = r,
  6312. this.deferred = s, this.yt = n.maxAttempts, this.gt = new mn(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  6313. }
  6314. /** Runs the transaction and sets the result on deferred. */ run() {
  6315. this.yt -= 1, this._t();
  6316. }
  6317. _t() {
  6318. this.gt.K((async () => {
  6319. const t = new ms(this.datastore), e = this.vt(t);
  6320. e && e.then((e => {
  6321. this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {
  6322. this.deferred.resolve(e);
  6323. })).catch((t => {
  6324. this.bt(t);
  6325. }))));
  6326. })).catch((t => {
  6327. this.bt(t);
  6328. }));
  6329. }));
  6330. }
  6331. vt(t) {
  6332. try {
  6333. const e = this.updateFunction(t);
  6334. return !dt(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  6335. null);
  6336. } catch (t) {
  6337. // Do not retry errors thrown by user provided updateFunction.
  6338. return this.deferred.reject(t), null;
  6339. }
  6340. }
  6341. bt(t) {
  6342. this.yt > 0 && this.Et(t) ? (this.yt -= 1, this.asyncQueue.enqueueAndForget((() => (this._t(),
  6343. Promise.resolve())))) : this.deferred.reject(t);
  6344. }
  6345. Et(t) {
  6346. if ("FirebaseError" === t.name) {
  6347. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  6348. // non-matching document versions with ABORTED. These errors should be retried.
  6349. const e = t.code;
  6350. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !
  6351. /**
  6352. * Determines whether an error code represents a permanent error when received
  6353. * in response to a non-write operation.
  6354. *
  6355. * See isPermanentWriteError for classifying write errors.
  6356. */
  6357. function(t) {
  6358. switch (t) {
  6359. default:
  6360. return b();
  6361. case A:
  6362. case R:
  6363. case V:
  6364. case x:
  6365. case C:
  6366. case M:
  6367. // Unauthenticated means something went wrong with our token and we need
  6368. // to retry with new credentials which will happen automatically.
  6369. case F:
  6370. return !1;
  6371. case P:
  6372. case $:
  6373. case N:
  6374. case D:
  6375. case S:
  6376. // Aborted might be retried in some scenarios, but that is dependant on
  6377. // the context and should handled individually by the calling code.
  6378. // See https://cloud.google.com/apis/design/errors.
  6379. case q:
  6380. case O:
  6381. case k:
  6382. case L:
  6383. return !0;
  6384. }
  6385. }(e);
  6386. }
  6387. return !1;
  6388. }
  6389. }
  6390. /**
  6391. * @license
  6392. * Copyright 2020 Google LLC
  6393. *
  6394. * Licensed under the Apache License, Version 2.0 (the "License");
  6395. * you may not use this file except in compliance with the License.
  6396. * You may obtain a copy of the License at
  6397. *
  6398. * http://www.apache.org/licenses/LICENSE-2.0
  6399. *
  6400. * Unless required by applicable law or agreed to in writing, software
  6401. * distributed under the License is distributed on an "AS IS" BASIS,
  6402. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6403. * See the License for the specific language governing permissions and
  6404. * limitations under the License.
  6405. */
  6406. /** The Platform's 'document' implementation or null if not available. */ function gs() {
  6407. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  6408. // eslint-disable-next-line no-restricted-globals
  6409. return "undefined" != typeof document ? document : null;
  6410. }
  6411. /**
  6412. * @license
  6413. * Copyright 2017 Google LLC
  6414. *
  6415. * Licensed under the Apache License, Version 2.0 (the "License");
  6416. * you may not use this file except in compliance with the License.
  6417. * You may obtain a copy of the License at
  6418. *
  6419. * http://www.apache.org/licenses/LICENSE-2.0
  6420. *
  6421. * Unless required by applicable law or agreed to in writing, software
  6422. * distributed under the License is distributed on an "AS IS" BASIS,
  6423. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6424. * See the License for the specific language governing permissions and
  6425. * limitations under the License.
  6426. */
  6427. /**
  6428. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  6429. *
  6430. * It is created via DelayedOperation.createAndSchedule().
  6431. *
  6432. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  6433. *
  6434. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  6435. * in newer versions of TypeScript defines `finally`, which is not available in
  6436. * IE.
  6437. */ class _s {
  6438. constructor(t, e, n, r, s) {
  6439. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = r, this.removalCallback = s,
  6440. this.deferred = new j, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  6441. // It's normal for the deferred promise to be canceled (due to cancellation)
  6442. // and so we attach a dummy catch callback to avoid
  6443. // 'UnhandledPromiseRejectionWarning' log spam.
  6444. this.deferred.promise.catch((t => {}));
  6445. }
  6446. /**
  6447. * Creates and returns a DelayedOperation that has been scheduled to be
  6448. * executed on the provided asyncQueue after the provided delayMs.
  6449. *
  6450. * @param asyncQueue - The queue to schedule the operation on.
  6451. * @param id - A Timer ID identifying the type of operation this is.
  6452. * @param delayMs - The delay (ms) before the operation should be scheduled.
  6453. * @param op - The operation to run.
  6454. * @param removalCallback - A callback to be called synchronously once the
  6455. * operation is executed or canceled, notifying the AsyncQueue to remove it
  6456. * from its delayedOperations list.
  6457. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  6458. * the DelayedOperation class public.
  6459. */ static createAndSchedule(t, e, n, r, s) {
  6460. const i = Date.now() + n, o = new _s(t, e, i, r, s);
  6461. return o.start(n), o;
  6462. }
  6463. /**
  6464. * Starts the timer. This is called immediately after construction by
  6465. * createAndSchedule().
  6466. */ start(t) {
  6467. this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);
  6468. }
  6469. /**
  6470. * Queues the operation to run immediately (if it hasn't already been run or
  6471. * canceled).
  6472. */ skipDelay() {
  6473. return this.handleDelayElapsed();
  6474. }
  6475. /**
  6476. * Cancels the operation if it hasn't already been executed or canceled. The
  6477. * promise will be rejected.
  6478. *
  6479. * As long as the operation has not yet been run, calling cancel() provides a
  6480. * guarantee that the operation will not be run.
  6481. */ cancel(t) {
  6482. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new U(A, "Operation cancelled" + (t ? ": " + t : ""))));
  6483. }
  6484. handleDelayElapsed() {
  6485. this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(),
  6486. this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));
  6487. }
  6488. clearTimeout() {
  6489. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  6490. this.timerHandle = null);
  6491. }
  6492. }
  6493. /**
  6494. * @license
  6495. * Copyright 2020 Google LLC
  6496. *
  6497. * Licensed under the Apache License, Version 2.0 (the "License");
  6498. * you may not use this file except in compliance with the License.
  6499. * You may obtain a copy of the License at
  6500. *
  6501. * http://www.apache.org/licenses/LICENSE-2.0
  6502. *
  6503. * Unless required by applicable law or agreed to in writing, software
  6504. * distributed under the License is distributed on an "AS IS" BASIS,
  6505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6506. * See the License for the specific language governing permissions and
  6507. * limitations under the License.
  6508. */ class vs {
  6509. constructor() {
  6510. // The last promise in the queue.
  6511. this.It = Promise.resolve(),
  6512. // A list of retryable operations. Retryable operations are run in order and
  6513. // retried with backoff.
  6514. this.Tt = [],
  6515. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  6516. // be changed again.
  6517. this.At = !1,
  6518. // Operations scheduled to be queued in the future. Operations are
  6519. // automatically removed after they are run or canceled.
  6520. this.Rt = [],
  6521. // visible for testing
  6522. this.Pt = null,
  6523. // Flag set while there's an outstanding AsyncQueue operation, used for
  6524. // assertion sanity-checks.
  6525. this.Vt = !1,
  6526. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  6527. this.$t = !1,
  6528. // List of TimerIds to fast-forward delays for.
  6529. this.Nt = [],
  6530. // Backoff timer used to schedule retries for retryable operations
  6531. this.gt = new mn(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  6532. // Visibility handler that triggers an immediate retry of all retryable
  6533. // operations. Meant to speed up recovery when we regain file system access
  6534. // after page comes into foreground.
  6535. this.Dt = () => {
  6536. const t = gs();
  6537. t && y("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.gt.H();
  6538. };
  6539. const t = gs();
  6540. t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Dt);
  6541. }
  6542. get isShuttingDown() {
  6543. return this.At;
  6544. }
  6545. /**
  6546. * Adds a new operation to the queue without waiting for it to complete (i.e.
  6547. * we ignore the Promise result).
  6548. */ enqueueAndForget(t) {
  6549. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  6550. this.enqueue(t);
  6551. }
  6552. enqueueAndForgetEvenWhileRestricted(t) {
  6553. this.Ft(),
  6554. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  6555. this.xt(t);
  6556. }
  6557. enterRestrictedMode(t) {
  6558. if (!this.At) {
  6559. this.At = !0, this.$t = t || !1;
  6560. const e = gs();
  6561. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Dt);
  6562. }
  6563. }
  6564. enqueue(t) {
  6565. if (this.Ft(), this.At)
  6566. // Return a Promise which never resolves.
  6567. return new Promise((() => {}));
  6568. // Create a deferred Promise that we can return to the callee. This
  6569. // allows us to return a "hanging Promise" only to the callee and still
  6570. // advance the queue even when the operation is not run.
  6571. const e = new j;
  6572. return this.xt((() => this.At && this.$t ? Promise.resolve() : (t().then(e.resolve, e.reject),
  6573. e.promise))).then((() => e.promise));
  6574. }
  6575. enqueueRetryable(t) {
  6576. this.enqueueAndForget((() => (this.Tt.push(t), this.St())));
  6577. }
  6578. /**
  6579. * Runs the next operation from the retryable queue. If the operation fails,
  6580. * reschedules with backoff.
  6581. */ async St() {
  6582. if (0 !== this.Tt.length) {
  6583. try {
  6584. await this.Tt[0](), this.Tt.shift(), this.gt.reset();
  6585. } catch (t) {
  6586. if (!
  6587. /**
  6588. * @license
  6589. * Copyright 2017 Google LLC
  6590. *
  6591. * Licensed under the Apache License, Version 2.0 (the "License");
  6592. * you may not use this file except in compliance with the License.
  6593. * You may obtain a copy of the License at
  6594. *
  6595. * http://www.apache.org/licenses/LICENSE-2.0
  6596. *
  6597. * Unless required by applicable law or agreed to in writing, software
  6598. * distributed under the License is distributed on an "AS IS" BASIS,
  6599. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6600. * See the License for the specific language governing permissions and
  6601. * limitations under the License.
  6602. */
  6603. /** Verifies whether `e` is an IndexedDbTransactionError. */
  6604. function(t) {
  6605. // Use name equality, as instanceof checks on errors don't work with errors
  6606. // that wrap other errors.
  6607. return "IndexedDbTransactionError" === t.name;
  6608. }
  6609. /**
  6610. * @license
  6611. * Copyright 2020 Google LLC
  6612. *
  6613. * Licensed under the Apache License, Version 2.0 (the "License");
  6614. * you may not use this file except in compliance with the License.
  6615. * You may obtain a copy of the License at
  6616. *
  6617. * http://www.apache.org/licenses/LICENSE-2.0
  6618. *
  6619. * Unless required by applicable law or agreed to in writing, software
  6620. * distributed under the License is distributed on an "AS IS" BASIS,
  6621. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6622. * See the License for the specific language governing permissions and
  6623. * limitations under the License.
  6624. */ (t)) throw t;
  6625. // Failure will be handled by AsyncQueue
  6626. y("AsyncQueue", "Operation failed with retryable error: " + t);
  6627. }
  6628. this.Tt.length > 0 &&
  6629. // If there are additional operations, we re-schedule `retryNextOp()`.
  6630. // This is necessary to run retryable operations that failed during
  6631. // their initial attempt since we don't know whether they are already
  6632. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  6633. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  6634. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  6635. // call scheduled here.
  6636. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  6637. // new backoff on every call, there is only ever a single additional
  6638. // operation in the queue.
  6639. this.gt.K((() => this.St()));
  6640. }
  6641. }
  6642. xt(t) {
  6643. const e = this.It.then((() => (this.Vt = !0, t().catch((t => {
  6644. this.Pt = t, this.Vt = !1;
  6645. const e =
  6646. /**
  6647. * Chrome includes Error.message in Error.stack. Other browsers do not.
  6648. * This returns expected output of message + stack when available.
  6649. * @param error - Error or FirestoreError
  6650. */
  6651. function(t) {
  6652. let e = t.message || "";
  6653. t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
  6654. return e;
  6655. }
  6656. /**
  6657. * @license
  6658. * Copyright 2020 Google LLC
  6659. *
  6660. * Licensed under the Apache License, Version 2.0 (the "License");
  6661. * you may not use this file except in compliance with the License.
  6662. * You may obtain a copy of the License at
  6663. *
  6664. * http://www.apache.org/licenses/LICENSE-2.0
  6665. *
  6666. * Unless required by applicable law or agreed to in writing, software
  6667. * distributed under the License is distributed on an "AS IS" BASIS,
  6668. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6669. * See the License for the specific language governing permissions and
  6670. * limitations under the License.
  6671. */
  6672. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  6673. // legacy SDK.
  6674. /**
  6675. * A reference to a transaction.
  6676. *
  6677. * The `Transaction` object passed to a transaction's `updateFunction` provides
  6678. * the methods to read and write data within the transaction context. See
  6679. * {@link runTransaction}.
  6680. */ (t);
  6681. // Re-throw the error so that this.tail becomes a rejected Promise and
  6682. // all further attempts to chain (via .then) will just short-circuit
  6683. // and return the rejected Promise.
  6684. throw g("INTERNAL UNHANDLED ERROR: ", e), t;
  6685. })).then((t => (this.Vt = !1, t))))));
  6686. return this.It = e, e;
  6687. }
  6688. enqueueAfterDelay(t, e, n) {
  6689. this.Ft(),
  6690. // Fast-forward delays for timerIds that have been overriden.
  6691. this.Nt.indexOf(t) > -1 && (e = 0);
  6692. const r = _s.createAndSchedule(this, t, e, n, (t => this.qt(t)));
  6693. return this.Rt.push(r), r;
  6694. }
  6695. Ft() {
  6696. this.Pt && b();
  6697. }
  6698. verifyOperationInProgress() {}
  6699. /**
  6700. * Waits until all currently queued tasks are finished executing. Delayed
  6701. * operations are not run.
  6702. */ async Ot() {
  6703. // Operations in the queue prior to draining may have enqueued additional
  6704. // operations. Keep draining the queue until the tail is no longer advanced,
  6705. // which indicates that no more new operations were enqueued and that all
  6706. // operations were executed.
  6707. let t;
  6708. do {
  6709. t = this.It, await t;
  6710. } while (t !== this.It);
  6711. }
  6712. /**
  6713. * For Tests: Determine if a delayed operation with a particular TimerId
  6714. * exists.
  6715. */ kt(t) {
  6716. for (const e of this.Rt) if (e.timerId === t) return !0;
  6717. return !1;
  6718. }
  6719. /**
  6720. * For Tests: Runs some or all delayed operations early.
  6721. *
  6722. * @param lastTimerId - Delayed operations up to and including this TimerId
  6723. * will be drained. Pass TimerId.All to run all delayed operations.
  6724. * @returns a Promise that resolves once all operations have been run.
  6725. */ Ct(t) {
  6726. // Note that draining may generate more delayed ops, so we do that first.
  6727. return this.Ot().then((() => {
  6728. // Run ops in the same order they'd run if they ran naturally.
  6729. this.Rt.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));
  6730. for (const e of this.Rt) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break;
  6731. return this.Ot();
  6732. }));
  6733. }
  6734. /**
  6735. * For Tests: Skip all subsequent delays for a timer id.
  6736. */ Mt(t) {
  6737. this.Nt.push(t);
  6738. }
  6739. /** Called once a DelayedOperation is run or canceled. */ qt(t) {
  6740. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  6741. const e = this.Rt.indexOf(t);
  6742. this.Rt.splice(e, 1);
  6743. }
  6744. }
  6745. class bs {
  6746. /** @hideconstructor */
  6747. constructor(t, e) {
  6748. this._firestore = t, this._transaction = e, this._dataReader = Hn(t);
  6749. }
  6750. /**
  6751. * Reads the document referenced by the provided {@link DocumentReference}.
  6752. *
  6753. * @param documentRef - A reference to the document to be read.
  6754. * @returns A `DocumentSnapshot` with the read data.
  6755. */ get(t) {
  6756. const e = ds(t, this._firestore), n = new Gr(this._firestore);
  6757. return this._transaction.lookup([ e._key ]).then((t => {
  6758. if (!t || 1 !== t.length) return b();
  6759. const r = t[0];
  6760. if (r.isFoundDocument()) return new pr(this._firestore, n, r.key, r, e.converter);
  6761. if (r.isNoDocument()) return new pr(this._firestore, n, e._key, null, e.converter);
  6762. throw b();
  6763. }));
  6764. }
  6765. set(t, e, n) {
  6766. const r = ds(t, this._firestore), s = Wr(r.converter, e, n), i = Jn(this._dataReader, "Transaction.set", r._key, s, null !== r.converter, n);
  6767. return this._transaction.set(r._key, i), this;
  6768. }
  6769. update(t, e, n, ...r) {
  6770. const s = ds(t, this._firestore);
  6771. // For Compat types, we have to "extract" the underlying types before
  6772. // performing validation.
  6773. let i;
  6774. return i = "string" == typeof (e = getModularInstance(e)) || e instanceof Ln ? ir(this._dataReader, "Transaction.update", s._key, e, n, r) : sr(this._dataReader, "Transaction.update", s._key, e),
  6775. this._transaction.update(s._key, i), this;
  6776. }
  6777. /**
  6778. * Deletes the document referred to by the provided {@link DocumentReference}.
  6779. *
  6780. * @param documentRef - A reference to the document to be deleted.
  6781. * @returns This `Transaction` instance. Used for chaining method calls.
  6782. */ delete(t) {
  6783. const e = ds(t, this._firestore);
  6784. return this._transaction.delete(e._key), this;
  6785. }
  6786. }
  6787. /**
  6788. * Executes the given `updateFunction` and then attempts to commit the changes
  6789. * applied within the transaction. If any document read within the transaction
  6790. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  6791. * commit after 5 attempts, the transaction fails.
  6792. *
  6793. * The maximum number of writes allowed in a single transaction is 500.
  6794. *
  6795. * @param firestore - A reference to the Firestore database to run this
  6796. * transaction against.
  6797. * @param updateFunction - The function to execute within the transaction
  6798. * context.
  6799. * @param options - An options object to configure maximum number of attempts to
  6800. * commit.
  6801. * @returns If the transaction completed successfully or was explicitly aborted
  6802. * (the `updateFunction` returned a failed promise), the promise returned by the
  6803. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  6804. * rejected promise with the corresponding failure error is returned.
  6805. */ function Es(t, e, n) {
  6806. const r = En(t = ct(t, Tn)), s = Object.assign(Object.assign({}, ps), n);
  6807. !function(t) {
  6808. if (t.maxAttempts < 1) throw new U(P, "Max attempts must be at least 1");
  6809. }(s);
  6810. const i = new j;
  6811. return new ys(new vs, r, s, (n => e(new bs(t, n))), i).run(), i.promise;
  6812. }
  6813. /**
  6814. * Firestore Lite
  6815. *
  6816. * @remarks Firestore Lite is a small online-only SDK that allows read
  6817. * and write access to your Firestore database. All operations connect
  6818. * directly to the backend, and `onSnapshot()` APIs are not supported.
  6819. * @packageDocumentation
  6820. */ !function(t) {
  6821. w = t;
  6822. }(`${SDK_VERSION}_lite`), _registerComponent(new Component("firestore/lite", ((t, {instanceIdentifier: e, options: n}) => {
  6823. const r = t.getProvider("app").getImmediate(), s = new Tn(new W(t.getProvider("auth-internal")), new H(t.getProvider("app-check-internal")), function(t, e) {
  6824. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new U(P, '"projectId" not provided in firebase.initializeApp.');
  6825. return new X(t.options.projectId, e);
  6826. }
  6827. /**
  6828. * @license
  6829. * Copyright 2017 Google LLC
  6830. *
  6831. * Licensed under the Apache License, Version 2.0 (the "License");
  6832. * you may not use this file except in compliance with the License.
  6833. * You may obtain a copy of the License at
  6834. *
  6835. * http://www.apache.org/licenses/LICENSE-2.0
  6836. *
  6837. * Unless required by applicable law or agreed to in writing, software
  6838. * distributed under the License is distributed on an "AS IS" BASIS,
  6839. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6840. * See the License for the specific language governing permissions and
  6841. * limitations under the License.
  6842. */ (r, e), r);
  6843. return n && s._setSettings(n), s;
  6844. }), "PUBLIC").setMultipleInstances(!0)),
  6845. // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation
  6846. registerVersion("firestore-lite", "3.13.0", ""), registerVersion("firestore-lite", "3.13.0", "esm2017");
  6847. export { $n as AggregateField, Nn as AggregateQuerySnapshot, Mn as Bytes, xn as CollectionReference, Dn as DocumentReference, pr as DocumentSnapshot, Ln as FieldPath, jn as FieldValue, Tn as Firestore, U as FirestoreError, Bn as GeoPoint, Fn as Query, Rr as QueryCompositeFilterConstraint, Er as QueryConstraint, yr as QueryDocumentSnapshot, kr as QueryEndAtConstraint, Tr as QueryFieldFilterConstraint, Dr as QueryLimitConstraint, $r as QueryOrderByConstraint, gr as QuerySnapshot, Sr as QueryStartAtConstraint, xt as Timestamp, bs as Transaction, fs as WriteBatch, Zr as addDoc, is as aggregateFieldEqual, os as aggregateQuerySnapshotEqual, Vr as and, hs as arrayRemove, as as arrayUnion, rs as average, Sn as collection, qn as collectionGroup, Pn as connectFirestoreEmulator, ss as count, Xr as deleteDoc, us as deleteField, On as doc, Un as documentId, Mr as endAt, Cr as endBefore, es as getAggregate, ts as getCount, Kr as getDoc, Yr as getDocs, Rn as getFirestore, ls as increment, An as initializeFirestore, Fr as limit, xr as limitToLast, Pr as or, Nr as orderBy, Ir as query, Cn as queryEqual, kn as refEqual, Es as runTransaction, cs as serverTimestamp, Hr as setDoc, p as setLogLevel, _r as snapshotEqual, Or as startAfter, qr as startAt, ns as sum, Vn as terminate, Jr as updateDoc, Ar as where, ws as writeBatch };
  6848. //# sourceMappingURL=index.browser.esm2017.js.map