No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.browser.esm2017.js 256KB

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