Sin descripción
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.

internal.d.ts 261KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561
  1. /**
  2. * Cloud Firestore
  3. *
  4. * @packageDocumentation
  5. */
  6. import { DocumentData as DocumentData_2 } from '@firebase/firestore-types';
  7. import { EmulatorMockTokenOptions } from '@firebase/util';
  8. import { FirebaseApp } from '@firebase/app';
  9. import { FirebaseError } from '@firebase/util';
  10. import { _FirebaseService } from '@firebase/app';
  11. import { LogLevelString as LogLevel } from '@firebase/logger';
  12. import { SetOptions as SetOptions_2 } from '@firebase/firestore-types';
  13. /**
  14. * Converts Firestore's internal types to the JavaScript types that we expose
  15. * to the user.
  16. *
  17. * @internal
  18. */
  19. export declare abstract class AbstractUserDataWriter {
  20. convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown;
  21. private convertObject;
  22. private convertGeoPoint;
  23. private convertArray;
  24. private convertServerTimestamp;
  25. private convertTimestamp;
  26. protected convertDocumentKey(name: string, expectedDatabaseId: _DatabaseId): _DocumentKey;
  27. protected abstract convertReference(name: string): unknown;
  28. protected abstract convertBytes(bytes: _ByteString): unknown;
  29. }
  30. /**
  31. * Describes a map whose keys are active target ids. We do not care about the type of the
  32. * values.
  33. */
  34. declare type ActiveTargets = SortedMap<TargetId, unknown>;
  35. /**
  36. * Add a new document to specified `CollectionReference` with the given data,
  37. * assigning it a document ID automatically.
  38. *
  39. * @param reference - A reference to the collection to add this document to.
  40. * @param data - An Object containing the data for the new document.
  41. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  42. * newly created document after it has been written to the backend (Note that it
  43. * won't resolve while you're offline).
  44. */
  45. export declare function addDoc<T>(reference: CollectionReference<T>, data: WithFieldValue<T>): Promise<DocumentReference<T>>;
  46. /**
  47. * Returns a new map where every key is prefixed with the outer key appended
  48. * to a dot.
  49. */
  50. export declare type AddPrefixToKeys<Prefix extends string, T extends Record<string, unknown>> = {
  51. [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
  52. };
  53. /**
  54. * Represents an aggregation that can be performed by Firestore.
  55. */
  56. export declare class AggregateField<T> {
  57. /** A type string to uniquely identify instances of this class. */
  58. type: string;
  59. }
  60. /**
  61. * The union of all `AggregateField` types that are supported by Firestore.
  62. */
  63. export declare type AggregateFieldType = AggregateField<number>;
  64. /**
  65. * The results of executing an aggregation query.
  66. */
  67. export declare class AggregateQuerySnapshot<T extends AggregateSpec> {
  68. private readonly _data;
  69. /** A type string to uniquely identify instances of this class. */
  70. readonly type = "AggregateQuerySnapshot";
  71. /**
  72. * The underlying query over which the aggregations recorded in this
  73. * `AggregateQuerySnapshot` were performed.
  74. */
  75. readonly query: Query<unknown>;
  76. /** @hideconstructor */
  77. constructor(query: Query<unknown>, _data: AggregateSpecData<T>);
  78. /**
  79. * Returns the results of the aggregations performed over the underlying
  80. * query.
  81. *
  82. * The keys of the returned object will be the same as those of the
  83. * `AggregateSpec` object specified to the aggregation method, and the values
  84. * will be the corresponding aggregation result.
  85. *
  86. * @returns The results of the aggregations performed over the underlying
  87. * query.
  88. */
  89. data(): AggregateSpecData<T>;
  90. }
  91. /**
  92. * Compares two `AggregateQuerySnapshot` instances for equality.
  93. *
  94. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  95. * underlying queries that compare equal, and the same data.
  96. *
  97. * @param left - The first `AggregateQuerySnapshot` to compare.
  98. * @param right - The second `AggregateQuerySnapshot` to compare.
  99. *
  100. * @returns `true` if the objects are "equal", as defined above, or `false`
  101. * otherwise.
  102. */
  103. export declare function aggregateQuerySnapshotEqual<T extends AggregateSpec>(left: AggregateQuerySnapshot<T>, right: AggregateQuerySnapshot<T>): boolean;
  104. /**
  105. * A type whose property values are all `AggregateField` objects.
  106. */
  107. export declare interface AggregateSpec {
  108. [field: string]: AggregateFieldType;
  109. }
  110. /**
  111. * A type whose keys are taken from an `AggregateSpec`, and whose values are the
  112. * result of the aggregation performed by the corresponding `AggregateField`
  113. * from the input `AggregateSpec`.
  114. */
  115. export declare type AggregateSpecData<T extends AggregateSpec> = {
  116. [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never;
  117. };
  118. /**
  119. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  120. * the given filter constraints. A conjunction filter includes a document if it
  121. * satisfies all of the given filters.
  122. *
  123. * @param queryConstraints - Optional. The list of
  124. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  125. * created with calls to {@link where}, {@link or}, or {@link and}.
  126. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  127. * @internal TODO remove this internal tag with OR Query support in the server
  128. */
  129. export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;
  130. declare interface ApiClientObjectMap<T> {
  131. [k: string]: T;
  132. }
  133. /**
  134. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  135. * to a Firestore query.
  136. */
  137. declare abstract class AppliableConstraint {
  138. /**
  139. * Takes the provided {@link Query} and returns a copy of the {@link Query} with this
  140. * {@link AppliableConstraint} applied.
  141. */
  142. abstract _apply<T>(query: Query<T>): Query<T>;
  143. }
  144. /**
  145. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  146. * updateDoc:1} that tells the server to remove the given elements from any
  147. * array value that already exists on the server. All instances of each element
  148. * specified will be removed from the array. If the field being modified is not
  149. * already an array it will be overwritten with an empty array.
  150. *
  151. * @param elements - The elements to remove from the array.
  152. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  153. * `updateDoc()`
  154. */
  155. export declare function arrayRemove(...elements: unknown[]): FieldValue;
  156. /**
  157. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  158. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  159. * value that already exists on the server. Each specified element that doesn't
  160. * already exist in the array will be added to the end. If the field being
  161. * modified is not already an array it will be overwritten with an array
  162. * containing exactly the specified elements.
  163. *
  164. * @param elements - The elements to union into the array.
  165. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  166. * `updateDoc()`.
  167. */
  168. export declare function arrayUnion(...elements: unknown[]): FieldValue;
  169. declare interface AsyncQueue {
  170. readonly isShuttingDown: boolean;
  171. /**
  172. * Adds a new operation to the queue without waiting for it to complete (i.e.
  173. * we ignore the Promise result).
  174. */
  175. enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;
  176. /**
  177. * Regardless if the queue has initialized shutdown, adds a new operation to the
  178. * queue without waiting for it to complete (i.e. we ignore the Promise result).
  179. */
  180. enqueueAndForgetEvenWhileRestricted<T extends unknown>(op: () => Promise<T>): void;
  181. /**
  182. * Initialize the shutdown of this queue. Once this method is called, the
  183. * only possible way to request running an operation is through
  184. * `enqueueEvenWhileRestricted()`.
  185. *
  186. * @param purgeExistingTasks Whether already enqueued tasked should be
  187. * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults
  188. * to false.
  189. */
  190. enterRestrictedMode(purgeExistingTasks?: boolean): void;
  191. /**
  192. * Adds a new operation to the queue. Returns a promise that will be resolved
  193. * when the promise returned by the new operation is (with its value).
  194. */
  195. enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>;
  196. /**
  197. * Enqueue a retryable operation.
  198. *
  199. * A retryable operation is rescheduled with backoff if it fails with a
  200. * IndexedDbTransactionError (the error type used by SimpleDb). All
  201. * retryable operations are executed in order and only run if all prior
  202. * operations were retried successfully.
  203. */
  204. enqueueRetryable(op: () => Promise<void>): void;
  205. /**
  206. * Schedules an operation to be queued on the AsyncQueue once the specified
  207. * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel
  208. * or fast-forward the operation prior to its running.
  209. */
  210. enqueueAfterDelay<T extends unknown>(timerId: TimerId, delayMs: number, op: () => Promise<T>): DelayedOperation<T>;
  211. /**
  212. * Verifies there's an operation currently in-progress on the AsyncQueue.
  213. * Unfortunately we can't verify that the running code is in the promise chain
  214. * of that operation, so this isn't a foolproof check, but it should be enough
  215. * to catch some bugs.
  216. */
  217. verifyOperationInProgress(): void;
  218. }
  219. declare type AuthTokenFactory = () => string;
  220. /**
  221. * Path represents an ordered sequence of string segments.
  222. */
  223. declare abstract class BasePath<B extends BasePath<B>> {
  224. private segments;
  225. private offset;
  226. private len;
  227. constructor(segments: string[], offset?: number, length?: number);
  228. /**
  229. * Abstract constructor method to construct an instance of B with the given
  230. * parameters.
  231. */
  232. protected abstract construct(segments: string[], offset?: number, length?: number): B;
  233. /**
  234. * Returns a String representation.
  235. *
  236. * Implementing classes are required to provide deterministic implementations as
  237. * the String representation is used to obtain canonical Query IDs.
  238. */
  239. abstract toString(): string;
  240. get length(): number;
  241. isEqual(other: B): boolean;
  242. child(nameOrPath: string | B): B;
  243. /** The index of one past the last segment of the path. */
  244. private limit;
  245. popFirst(size?: number): B;
  246. popLast(): B;
  247. firstSegment(): string;
  248. lastSegment(): string;
  249. get(index: number): string;
  250. isEmpty(): boolean;
  251. isPrefixOf(other: this): boolean;
  252. isImmediateParentOf(potentialChild: this): boolean;
  253. forEach(fn: (segment: string) => void): void;
  254. toArray(): string[];
  255. static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): number;
  256. }
  257. /**
  258. * @license
  259. * Copyright 2017 Google LLC
  260. *
  261. * Licensed under the Apache License, Version 2.0 (the "License");
  262. * you may not use this file except in compliance with the License.
  263. * You may obtain a copy of the License at
  264. *
  265. * http://www.apache.org/licenses/LICENSE-2.0
  266. *
  267. * Unless required by applicable law or agreed to in writing, software
  268. * distributed under the License is distributed on an "AS IS" BASIS,
  269. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  270. * See the License for the specific language governing permissions and
  271. * limitations under the License.
  272. */
  273. /**
  274. * BatchID is a locally assigned ID for a batch of mutations that have been
  275. * applied.
  276. */
  277. declare type BatchId = number;
  278. /**
  279. * Represents a bound of a query.
  280. *
  281. * The bound is specified with the given components representing a position and
  282. * whether it's just before or just after the position (relative to whatever the
  283. * query order is).
  284. *
  285. * The position represents a logical index position for a query. It's a prefix
  286. * of values for the (potentially implicit) order by clauses of a query.
  287. *
  288. * Bound provides a function to determine whether a document comes before or
  289. * after a bound. This is influenced by whether the position is just before or
  290. * just after the provided values.
  291. */
  292. declare class Bound {
  293. readonly position: Value[];
  294. readonly inclusive: boolean;
  295. constructor(position: Value[], inclusive: boolean);
  296. }
  297. /**
  298. * Provides interfaces to save and read Firestore bundles.
  299. */
  300. declare interface BundleCache {
  301. /**
  302. * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined
  303. * if no bundle metadata is found under the given id.
  304. */
  305. getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise<BundleMetadata | undefined>;
  306. /**
  307. * Saves a `BundleMetadata` from a bundle into local storage, using its id as
  308. * the persistent key.
  309. */
  310. saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise<void>;
  311. /**
  312. * Gets a saved `NamedQuery` for the given query name. Returns undefined if
  313. * no queries are found under the given name.
  314. */
  315. getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise<NamedQuery | undefined>;
  316. /**
  317. * Saves a `NamedQuery` from a bundle, using its name as the persistent key.
  318. */
  319. saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise<void>;
  320. }
  321. /** Properties of a BundledQuery. */
  322. declare interface BundledQuery {
  323. /** BundledQuery parent */
  324. parent?: string | null;
  325. /** BundledQuery structuredQuery */
  326. structuredQuery?: StructuredQuery | null;
  327. /** BundledQuery limitType */
  328. limitType?: LimitType_2 | null;
  329. }
  330. /**
  331. * Represents a Firestore bundle saved by the SDK in its local storage.
  332. */
  333. declare interface BundleMetadata {
  334. /**
  335. * Id of the bundle. It is used together with `createTime` to determine if a
  336. * bundle has been loaded by the SDK.
  337. */
  338. readonly id: string;
  339. /** Schema version of the bundle. */
  340. readonly version: number;
  341. /**
  342. * Set to the snapshot version of the bundle if created by the Server SDKs.
  343. * Otherwise set to SnapshotVersion.MIN.
  344. */
  345. readonly createTime: SnapshotVersion;
  346. }
  347. /** Properties of a BundleMetadata. */
  348. declare interface BundleMetadata_2 {
  349. /** BundleMetadata id */
  350. id?: string | null;
  351. /** BundleMetadata createTime */
  352. createTime?: Timestamp_2 | null;
  353. /** BundleMetadata version */
  354. version?: number | null;
  355. /** BundleMetadata totalDocuments */
  356. totalDocuments?: number | null;
  357. /** BundleMetadata totalBytes */
  358. totalBytes?: number | null;
  359. }
  360. /**
  361. * An immutable object representing an array of bytes.
  362. */
  363. export declare class Bytes {
  364. _byteString: _ByteString;
  365. /** @hideconstructor */
  366. constructor(byteString: _ByteString);
  367. /**
  368. * Creates a new `Bytes` object from the given Base64 string, converting it to
  369. * bytes.
  370. *
  371. * @param base64 - The Base64 string used to create the `Bytes` object.
  372. */
  373. static fromBase64String(base64: string): Bytes;
  374. /**
  375. * Creates a new `Bytes` object from the given Uint8Array.
  376. *
  377. * @param array - The Uint8Array used to create the `Bytes` object.
  378. */
  379. static fromUint8Array(array: Uint8Array): Bytes;
  380. /**
  381. * Returns the underlying bytes as a Base64-encoded string.
  382. *
  383. * @returns The Base64-encoded string created from the `Bytes` object.
  384. */
  385. toBase64(): string;
  386. /**
  387. * Returns the underlying bytes in a new `Uint8Array`.
  388. *
  389. * @returns The Uint8Array created from the `Bytes` object.
  390. */
  391. toUint8Array(): Uint8Array;
  392. /**
  393. * Returns a string representation of the `Bytes` object.
  394. *
  395. * @returns A string representation of the `Bytes` object.
  396. */
  397. toString(): string;
  398. /**
  399. * Returns true if this `Bytes` object is equal to the provided one.
  400. *
  401. * @param other - The `Bytes` object to compare against.
  402. * @returns true if this `Bytes` object is equal to the provided one.
  403. */
  404. isEqual(other: Bytes): boolean;
  405. }
  406. /**
  407. * @license
  408. * Copyright 2020 Google LLC
  409. *
  410. * Licensed under the Apache License, Version 2.0 (the "License");
  411. * you may not use this file except in compliance with the License.
  412. * You may obtain a copy of the License at
  413. *
  414. * http://www.apache.org/licenses/LICENSE-2.0
  415. *
  416. * Unless required by applicable law or agreed to in writing, software
  417. * distributed under the License is distributed on an "AS IS" BASIS,
  418. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  419. * See the License for the specific language governing permissions and
  420. * limitations under the License.
  421. */
  422. /**
  423. * Immutable class that represents a "proto" byte string.
  424. *
  425. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  426. * sent on the wire. This class abstracts away this differentiation by holding
  427. * the proto byte string in a common class that must be converted into a string
  428. * before being sent as a proto.
  429. * @internal
  430. */
  431. export declare class _ByteString {
  432. private readonly binaryString;
  433. static readonly EMPTY_BYTE_STRING: _ByteString;
  434. private constructor();
  435. static fromBase64String(base64: string): _ByteString;
  436. static fromUint8Array(array: Uint8Array): _ByteString;
  437. [Symbol.iterator](): Iterator<number>;
  438. toBase64(): string;
  439. toUint8Array(): Uint8Array;
  440. approximateByteSize(): number;
  441. compareTo(other: _ByteString): number;
  442. isEqual(other: _ByteString): boolean;
  443. }
  444. /**
  445. * Constant used to indicate the LRU garbage collection should be disabled.
  446. * Set this value as the `cacheSizeBytes` on the settings passed to the
  447. * {@link Firestore} instance.
  448. */
  449. export declare const CACHE_SIZE_UNLIMITED = -1;
  450. /**
  451. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  452. * underlying instance. Throws if `obj` is not an instance of `T`.
  453. *
  454. * This cast is used in the Lite and Full SDK to verify instance types for
  455. * arguments passed to the public API.
  456. * @internal
  457. */
  458. export declare function _cast<T>(obj: object, constructor: {
  459. new (...args: any[]): T;
  460. }): T | never;
  461. declare const enum ChangeType {
  462. Added = 0,
  463. Removed = 1,
  464. Modified = 2,
  465. Metadata = 3
  466. }
  467. /**
  468. * Helper for calculating the nested fields for a given type T1. This is needed
  469. * to distribute union types such as `undefined | {...}` (happens for optional
  470. * props) or `{a: A} | {b: B}`.
  471. *
  472. * In this use case, `V` is used to distribute the union types of `T[K]` on
  473. * `Record`, since `T[K]` is evaluated as an expression and not distributed.
  474. *
  475. * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
  476. */
  477. export declare type ChildUpdateFields<K extends string, V> = V extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<V>> : never;
  478. /**
  479. * Clears the persistent storage. This includes pending writes and cached
  480. * documents.
  481. *
  482. * Must be called while the {@link Firestore} instance is not started (after the app is
  483. * terminated or when the app is first initialized). On startup, this function
  484. * must be called before other functions (other than {@link
  485. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  486. * instance is still running, the promise will be rejected with the error code
  487. * of `failed-precondition`.
  488. *
  489. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  490. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  491. * dropping existing data but does not attempt to securely overwrite or
  492. * otherwise make cached data unrecoverable. For applications that are sensitive
  493. * to the disclosure of cached data in between user sessions, we strongly
  494. * recommend not enabling persistence at all.
  495. *
  496. * @param firestore - The {@link Firestore} instance to clear persistence for.
  497. * @returns A `Promise` that is resolved when the persistent storage is
  498. * cleared. Otherwise, the promise is rejected with an error.
  499. */
  500. export declare function clearIndexedDbPersistence(firestore: Firestore): Promise<void>;
  501. /**
  502. * A randomly-generated key assigned to each Firestore instance at startup.
  503. */
  504. declare type ClientId = string;
  505. /**
  506. * Gets a `CollectionReference` instance that refers to the collection at
  507. * the specified absolute path.
  508. *
  509. * @param firestore - A reference to the root `Firestore` instance.
  510. * @param path - A slash-separated path to a collection.
  511. * @param pathSegments - Additional path segments to apply relative to the first
  512. * argument.
  513. * @throws If the final path has an even number of segments and does not point
  514. * to a collection.
  515. * @returns The `CollectionReference` instance.
  516. */
  517. export declare function collection(firestore: Firestore_2, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
  518. /**
  519. * Gets a `CollectionReference` instance that refers to a subcollection of
  520. * `reference` at the the specified relative path.
  521. *
  522. * @param reference - A reference to a collection.
  523. * @param path - A slash-separated path to a collection.
  524. * @param pathSegments - Additional path segments to apply relative to the first
  525. * argument.
  526. * @throws If the final path has an even number of segments and does not point
  527. * to a collection.
  528. * @returns The `CollectionReference` instance.
  529. */
  530. export declare function collection(reference: CollectionReference<unknown>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
  531. /**
  532. * Gets a `CollectionReference` instance that refers to a subcollection of
  533. * `reference` at the the specified relative path.
  534. *
  535. * @param reference - A reference to a Firestore document.
  536. * @param path - A slash-separated path to a collection.
  537. * @param pathSegments - Additional path segments that will be applied relative
  538. * to the first argument.
  539. * @throws If the final path has an even number of segments and does not point
  540. * to a collection.
  541. * @returns The `CollectionReference` instance.
  542. */
  543. export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
  544. /**
  545. * Creates and returns a new `Query` instance that includes all documents in the
  546. * database that are contained in a collection or subcollection with the
  547. * given `collectionId`.
  548. *
  549. * @param firestore - A reference to the root `Firestore` instance.
  550. * @param collectionId - Identifies the collections to query over. Every
  551. * collection or subcollection with this ID as the last segment of its path
  552. * will be included. Cannot contain a slash.
  553. * @returns The created `Query`.
  554. */
  555. export declare function collectionGroup(firestore: Firestore_2, collectionId: string): Query<DocumentData>;
  556. /**
  557. * A `CollectionReference` object can be used for adding documents, getting
  558. * document references, and querying for documents (using {@link query}).
  559. */
  560. export declare class CollectionReference<T = DocumentData> extends Query<T> {
  561. readonly _path: _ResourcePath;
  562. /** The type of this Firestore reference. */
  563. readonly type = "collection";
  564. /** @hideconstructor */
  565. constructor(firestore: Firestore_2, converter: FirestoreDataConverter_2<T> | null, _path: _ResourcePath);
  566. /** The collection's identifier. */
  567. get id(): string;
  568. /**
  569. * A string representing the path of the referenced collection (relative
  570. * to the root of the database).
  571. */
  572. get path(): string;
  573. /**
  574. * A reference to the containing `DocumentReference` if this is a
  575. * subcollection. If this isn't a subcollection, the reference is null.
  576. */
  577. get parent(): DocumentReference<DocumentData> | null;
  578. /**
  579. * Applies a custom data converter to this `CollectionReference`, allowing you
  580. * to use your own custom model objects with Firestore. When you call {@link
  581. * addDoc} with the returned `CollectionReference` instance, the provided
  582. * converter will convert between Firestore data and your custom type `U`.
  583. *
  584. * @param converter - Converts objects to and from Firestore.
  585. * @returns A `CollectionReference<U>` that uses the provided converter.
  586. */
  587. withConverter<U>(converter: FirestoreDataConverter_2<U>): CollectionReference<U>;
  588. /**
  589. * Removes the current converter.
  590. *
  591. * @param converter - `null` removes the current converter.
  592. * @returns A `CollectionReference<DocumentData>` that does not use a
  593. * converter.
  594. */
  595. withConverter(converter: null): CollectionReference<DocumentData>;
  596. }
  597. /**
  598. * @license
  599. * Copyright 2017 Google LLC
  600. *
  601. * Licensed under the Apache License, Version 2.0 (the "License");
  602. * you may not use this file except in compliance with the License.
  603. * You may obtain a copy of the License at
  604. *
  605. * http://www.apache.org/licenses/LICENSE-2.0
  606. *
  607. * Unless required by applicable law or agreed to in writing, software
  608. * distributed under the License is distributed on an "AS IS" BASIS,
  609. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  610. * See the License for the specific language governing permissions and
  611. * limitations under the License.
  612. */
  613. declare type Comparator<K> = (key1: K, key2: K) => number;
  614. declare interface ComponentConfiguration {
  615. asyncQueue: AsyncQueue;
  616. databaseInfo: DatabaseInfo;
  617. authCredentials: CredentialsProvider<User>;
  618. appCheckCredentials: CredentialsProvider<string>;
  619. clientId: ClientId;
  620. initialUser: User;
  621. maxConcurrentLimboResolutions: number;
  622. }
  623. declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR';
  624. declare const enum CompositeOperator {
  625. OR = "or",
  626. AND = "and"
  627. }
  628. /**
  629. * Modify this instance to communicate with the Cloud Firestore emulator.
  630. *
  631. * Note: This must be called before this instance has been used to do any
  632. * operations.
  633. *
  634. * @param firestore - The `Firestore` instance to configure to connect to the
  635. * emulator.
  636. * @param host - the emulator host (ex: localhost).
  637. * @param port - the emulator port (ex: 9000).
  638. * @param options.mockUserToken - the mock auth token to use for unit testing
  639. * Security Rules.
  640. */
  641. export declare function connectFirestoreEmulator(firestore: Firestore_2, host: string, port: number, options?: {
  642. mockUserToken?: EmulatorMockTokenOptions | string;
  643. }): void;
  644. /**
  645. * A Listener for credential change events. The listener should fetch a new
  646. * token and may need to invalidate other state if the current user has also
  647. * changed.
  648. */
  649. declare type CredentialChangeListener<T> = (credential: T) => Promise<void>;
  650. /**
  651. * Provides methods for getting the uid and token for the current user and
  652. * listening for changes.
  653. */
  654. declare interface CredentialsProvider<T> {
  655. /**
  656. * Starts the credentials provider and specifies a listener to be notified of
  657. * credential changes (sign-in / sign-out, token changes). It is immediately
  658. * called once with the initial user.
  659. *
  660. * The change listener is invoked on the provided AsyncQueue.
  661. */
  662. start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<T>): void;
  663. /** Requests a token for the current user. */
  664. getToken(): Promise<Token | null>;
  665. /**
  666. * Marks the last retrieved token as invalid, making the next GetToken request
  667. * force-refresh the token.
  668. */
  669. invalidateToken(): void;
  670. shutdown(): void;
  671. }
  672. /** Settings for private credentials */
  673. declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings;
  674. /**
  675. * Represents the database ID a Firestore client is associated with.
  676. * @internal
  677. */
  678. export declare class _DatabaseId {
  679. readonly projectId: string;
  680. readonly database: string;
  681. constructor(projectId: string, database?: string);
  682. static empty(): _DatabaseId;
  683. get isDefaultDatabase(): boolean;
  684. isEqual(other: {}): boolean;
  685. }
  686. /**
  687. * @license
  688. * Copyright 2017 Google LLC
  689. *
  690. * Licensed under the Apache License, Version 2.0 (the "License");
  691. * you may not use this file except in compliance with the License.
  692. * You may obtain a copy of the License at
  693. *
  694. * http://www.apache.org/licenses/LICENSE-2.0
  695. *
  696. * Unless required by applicable law or agreed to in writing, software
  697. * distributed under the License is distributed on an "AS IS" BASIS,
  698. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  699. * See the License for the specific language governing permissions and
  700. * limitations under the License.
  701. */
  702. declare class DatabaseInfo {
  703. readonly databaseId: _DatabaseId;
  704. readonly appId: string;
  705. readonly persistenceKey: string;
  706. readonly host: string;
  707. readonly ssl: boolean;
  708. readonly forceLongPolling: boolean;
  709. readonly autoDetectLongPolling: boolean;
  710. readonly useFetchStreams: boolean;
  711. /**
  712. * Constructs a DatabaseInfo using the provided host, databaseId and
  713. * persistenceKey.
  714. *
  715. * @param databaseId - The database to use.
  716. * @param appId - The Firebase App Id.
  717. * @param persistenceKey - A unique identifier for this Firestore's local
  718. * storage (used in conjunction with the databaseId).
  719. * @param host - The Firestore backend host to connect to.
  720. * @param ssl - Whether to use SSL when connecting.
  721. * @param forceLongPolling - Whether to use the forceLongPolling option
  722. * when using WebChannel as the network transport.
  723. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  724. * option when using WebChannel as the network transport.
  725. * @param useFetchStreams Whether to use the Fetch API instead of
  726. * XMLHTTPRequest
  727. */
  728. constructor(databaseId: _DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, useFetchStreams: boolean);
  729. }
  730. /**
  731. * Datastore and its related methods are a wrapper around the external Google
  732. * Cloud Datastore grpc API, which provides an interface that is more convenient
  733. * for the rest of the client SDK architecture to consume.
  734. */
  735. declare abstract class Datastore {
  736. abstract terminate(): void;
  737. }
  738. /**
  739. * Fails if the given assertion condition is false, throwing an Error with the
  740. * given message if it did.
  741. *
  742. * The code of callsites invoking this function are stripped out in production
  743. * builds. Any side-effects of code within the debugAssert() invocation will not
  744. * happen in this case.
  745. *
  746. * @internal
  747. */
  748. export declare function _debugAssert(assertion: boolean, message: string): asserts assertion;
  749. /**
  750. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  751. *
  752. * It is created via DelayedOperation.createAndSchedule().
  753. *
  754. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  755. *
  756. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  757. * in newer versions of TypeScript defines `finally`, which is not available in
  758. * IE.
  759. */
  760. declare class DelayedOperation<T extends unknown> implements PromiseLike<T> {
  761. private readonly asyncQueue;
  762. readonly timerId: TimerId;
  763. readonly targetTimeMs: number;
  764. private readonly op;
  765. private readonly removalCallback;
  766. private timerHandle;
  767. private readonly deferred;
  768. private constructor();
  769. /**
  770. * Creates and returns a DelayedOperation that has been scheduled to be
  771. * executed on the provided asyncQueue after the provided delayMs.
  772. *
  773. * @param asyncQueue - The queue to schedule the operation on.
  774. * @param id - A Timer ID identifying the type of operation this is.
  775. * @param delayMs - The delay (ms) before the operation should be scheduled.
  776. * @param op - The operation to run.
  777. * @param removalCallback - A callback to be called synchronously once the
  778. * operation is executed or canceled, notifying the AsyncQueue to remove it
  779. * from its delayedOperations list.
  780. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  781. * the DelayedOperation class public.
  782. */
  783. static createAndSchedule<R extends unknown>(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise<R>, removalCallback: (op: DelayedOperation<R>) => void): DelayedOperation<R>;
  784. /**
  785. * Starts the timer. This is called immediately after construction by
  786. * createAndSchedule().
  787. */
  788. private start;
  789. /**
  790. * Queues the operation to run immediately (if it hasn't already been run or
  791. * canceled).
  792. */
  793. skipDelay(): void;
  794. /**
  795. * Cancels the operation if it hasn't already been executed or canceled. The
  796. * promise will be rejected.
  797. *
  798. * As long as the operation has not yet been run, calling cancel() provides a
  799. * guarantee that the operation will not be run.
  800. */
  801. cancel(reason?: string): void;
  802. then: <TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined) => Promise<TResult1 | TResult2>;
  803. private handleDelayElapsed;
  804. private clearTimeout;
  805. }
  806. /**
  807. * Deletes the document referred to by the specified `DocumentReference`.
  808. *
  809. * @param reference - A reference to the document to delete.
  810. * @returns A Promise resolved once the document has been successfully
  811. * deleted from the backend (note that it won't resolve while you're offline).
  812. */
  813. export declare function deleteDoc(reference: DocumentReference<unknown>): Promise<void>;
  814. /**
  815. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  816. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  817. */
  818. export declare function deleteField(): FieldValue;
  819. /**
  820. * The direction of sorting in an order by.
  821. */
  822. declare const enum Direction {
  823. ASCENDING = "asc",
  824. DESCENDING = "desc"
  825. }
  826. /**
  827. * Disables network usage for this instance. It can be re-enabled via {@link
  828. * enableNetwork}. While the network is disabled, any snapshot listeners,
  829. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  830. * operations will be queued until the network is restored.
  831. *
  832. * @returns A `Promise` that is resolved once the network has been disabled.
  833. */
  834. export declare function disableNetwork(firestore: Firestore): Promise<void>;
  835. /**
  836. * Gets a `DocumentReference` instance that refers to the document at the
  837. * specified absolute path.
  838. *
  839. * @param firestore - A reference to the root `Firestore` instance.
  840. * @param path - A slash-separated path to a document.
  841. * @param pathSegments - Additional path segments that will be applied relative
  842. * to the first argument.
  843. * @throws If the final path has an odd number of segments and does not point to
  844. * a document.
  845. * @returns The `DocumentReference` instance.
  846. */
  847. export declare function doc(firestore: Firestore_2, path: string, ...pathSegments: string[]): DocumentReference<DocumentData>;
  848. /**
  849. * Gets a `DocumentReference` instance that refers to a document within
  850. * `reference` at the specified relative path. If no path is specified, an
  851. * automatically-generated unique ID will be used for the returned
  852. * `DocumentReference`.
  853. *
  854. * @param reference - A reference to a collection.
  855. * @param path - A slash-separated path to a document. Has to be omitted to use
  856. * auto-genrated IDs.
  857. * @param pathSegments - Additional path segments that will be applied relative
  858. * to the first argument.
  859. * @throws If the final path has an odd number of segments and does not point to
  860. * a document.
  861. * @returns The `DocumentReference` instance.
  862. */
  863. export declare function doc<T>(reference: CollectionReference<T>, path?: string, ...pathSegments: string[]): DocumentReference<T>;
  864. /**
  865. * Gets a `DocumentReference` instance that refers to a document within
  866. * `reference` at the specified relative path.
  867. *
  868. * @param reference - A reference to a Firestore document.
  869. * @param path - A slash-separated path to a document.
  870. * @param pathSegments - Additional path segments that will be applied relative
  871. * to the first argument.
  872. * @throws If the final path has an odd number of segments and does not point to
  873. * a document.
  874. * @returns The `DocumentReference` instance.
  875. */
  876. export declare function doc(reference: DocumentReference<unknown>, path: string, ...pathSegments: string[]): DocumentReference<DocumentData>;
  877. /**
  878. * Represents a document in Firestore with a key, version, data and whether the
  879. * data has local mutations applied to it.
  880. */
  881. declare interface Document_2 {
  882. /** The key for this document */
  883. readonly key: _DocumentKey;
  884. /**
  885. * The version of this document if it exists or a version at which this
  886. * document was guaranteed to not exist.
  887. */
  888. readonly version: SnapshotVersion;
  889. /**
  890. * The timestamp at which this document was read from the remote server. Uses
  891. * `SnapshotVersion.min()` for documents created by the user.
  892. */
  893. readonly readTime: SnapshotVersion;
  894. /**
  895. * The timestamp at which the document was created. This value increases
  896. * monotonically when a document is deleted then recreated. It can also be
  897. * compared to `createTime` of other documents and the `readTime` of a query.
  898. */
  899. readonly createTime: SnapshotVersion;
  900. /** The underlying data of this document or an empty value if no data exists. */
  901. readonly data: ObjectValue;
  902. /** Returns whether local mutations were applied via the mutation queue. */
  903. readonly hasLocalMutations: boolean;
  904. /** Returns whether mutations were applied based on a write acknowledgment. */
  905. readonly hasCommittedMutations: boolean;
  906. /**
  907. * Whether this document had a local mutation applied that has not yet been
  908. * acknowledged by Watch.
  909. */
  910. readonly hasPendingWrites: boolean;
  911. /**
  912. * Returns whether this document is valid (i.e. it is an entry in the
  913. * RemoteDocumentCache, was created by a mutation or read from the backend).
  914. */
  915. isValidDocument(): boolean;
  916. /**
  917. * Returns whether the document exists and its data is known at the current
  918. * version.
  919. */
  920. isFoundDocument(): boolean;
  921. /**
  922. * Returns whether the document is known to not exist at the current version.
  923. */
  924. isNoDocument(): boolean;
  925. /**
  926. * Returns whether the document exists and its data is unknown at the current
  927. * version.
  928. */
  929. isUnknownDocument(): boolean;
  930. isEqual(other: Document_2 | null | undefined): boolean;
  931. /** Creates a mutable copy of this document. */
  932. mutableCopy(): MutableDocument;
  933. toString(): string;
  934. }
  935. /**
  936. * A `DocumentChange` represents a change to the documents matching a query.
  937. * It contains the document affected and the type of change that occurred.
  938. */
  939. export declare interface DocumentChange<T = DocumentData> {
  940. /** The type of change ('added', 'modified', or 'removed'). */
  941. readonly type: DocumentChangeType;
  942. /** The document affected by this change. */
  943. readonly doc: QueryDocumentSnapshot<T>;
  944. /**
  945. * The index of the changed document in the result set immediately prior to
  946. * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects
  947. * have been applied). Is `-1` for 'added' events.
  948. */
  949. readonly oldIndex: number;
  950. /**
  951. * The index of the changed document in the result set immediately after
  952. * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`
  953. * objects and the current `DocumentChange` object have been applied).
  954. * Is -1 for 'removed' events.
  955. */
  956. readonly newIndex: number;
  957. }
  958. /**
  959. * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.
  960. */
  961. export declare type DocumentChangeType = 'added' | 'removed' | 'modified';
  962. declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number;
  963. /**
  964. * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to
  965. * values.
  966. */
  967. export declare interface DocumentData {
  968. /** A mapping between a field and its value. */
  969. [field: string]: any;
  970. }
  971. /**
  972. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  973. * It can be used in queries to sort or filter by the document ID.
  974. */
  975. export declare function documentId(): FieldPath;
  976. /**
  977. * @internal
  978. */
  979. export declare class _DocumentKey {
  980. readonly path: _ResourcePath;
  981. constructor(path: _ResourcePath);
  982. static fromPath(path: string): _DocumentKey;
  983. static fromName(name: string): _DocumentKey;
  984. static empty(): _DocumentKey;
  985. get collectionGroup(): string;
  986. /** Returns true if the document is in the specified collectionId. */
  987. hasCollectionId(collectionId: string): boolean;
  988. /** Returns the collection group (i.e. the name of the parent collection) for this key. */
  989. getCollectionGroup(): string;
  990. /** Returns the fully qualified path to the parent collection. */
  991. getCollectionPath(): _ResourcePath;
  992. isEqual(other: _DocumentKey | null): boolean;
  993. toString(): string;
  994. static comparator(k1: _DocumentKey, k2: _DocumentKey): number;
  995. static isDocumentKey(path: _ResourcePath): boolean;
  996. /**
  997. * Creates and returns a new document key with the given segments.
  998. *
  999. * @param segments - The segments of the path to the document
  1000. * @returns A new instance of DocumentKey
  1001. */
  1002. static fromSegments(segments: string[]): _DocumentKey;
  1003. }
  1004. declare type DocumentKeyMap<T> = ObjectMap<_DocumentKey, T>;
  1005. declare type DocumentKeySet = SortedSet<_DocumentKey>;
  1006. declare type DocumentMap = SortedMap<_DocumentKey, Document_2>;
  1007. /**
  1008. * Provides methods to read and write document overlays.
  1009. *
  1010. * An overlay is a saved mutation, that gives a local view of a document when
  1011. * applied to the remote version of the document.
  1012. *
  1013. * Each overlay stores the largest batch ID that is included in the overlay,
  1014. * which allows us to remove the overlay once all batches leading up to it have
  1015. * been acknowledged.
  1016. */
  1017. declare interface DocumentOverlayCache {
  1018. /**
  1019. * Gets the saved overlay mutation for the given document key.
  1020. * Returns null if there is no overlay for that key.
  1021. */
  1022. getOverlay(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<Overlay | null>;
  1023. /**
  1024. * Gets the saved overlay mutation for the given document keys. Skips keys for
  1025. * which there are no overlays.
  1026. */
  1027. getOverlays(transaction: PersistenceTransaction, keys: _DocumentKey[]): PersistencePromise<OverlayMap>;
  1028. /**
  1029. * Saves the given document mutation map to persistence as overlays.
  1030. * All overlays will have their largest batch id set to `largestBatchId`.
  1031. */
  1032. saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise<void>;
  1033. /** Removes overlays for the given document keys and batch ID. */
  1034. removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise<void>;
  1035. /**
  1036. * Returns all saved overlays for the given collection.
  1037. *
  1038. * @param transaction - The persistence transaction to use for this operation.
  1039. * @param collection - The collection path to get the overlays for.
  1040. * @param sinceBatchId - The minimum batch ID to filter by (exclusive).
  1041. * Only overlays that contain a change past `sinceBatchId` are returned.
  1042. * @returns Mapping of each document key in the collection to its overlay.
  1043. */
  1044. getOverlaysForCollection(transaction: PersistenceTransaction, collection: _ResourcePath, sinceBatchId: number): PersistencePromise<OverlayMap>;
  1045. /**
  1046. * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the
  1047. * provided collection group, processed by ascending batch ID. The method
  1048. * always returns all overlays for a batch even if the last batch contains
  1049. * more documents than the remaining limit.
  1050. *
  1051. * @param transaction - The persistence transaction used for this operation.
  1052. * @param collectionGroup - The collection group to get the overlays for.
  1053. * @param sinceBatchId - The minimum batch ID to filter by (exclusive).
  1054. * Only overlays that contain a change past `sinceBatchId` are returned.
  1055. * @param count - The number of overlays to return. Can be exceeded if the last
  1056. * batch contains more entries.
  1057. * @return Mapping of each document key in the collection group to its overlay.
  1058. */
  1059. getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise<OverlayMap>;
  1060. }
  1061. /**
  1062. * A `DocumentReference` refers to a document location in a Firestore database
  1063. * and can be used to write, read, or listen to the location. The document at
  1064. * the referenced location may or may not exist.
  1065. */
  1066. export declare class DocumentReference<T = DocumentData> {
  1067. /**
  1068. * If provided, the `FirestoreDataConverter` associated with this instance.
  1069. */
  1070. readonly converter: FirestoreDataConverter_2<T> | null;
  1071. readonly _key: _DocumentKey;
  1072. /** The type of this Firestore reference. */
  1073. readonly type = "document";
  1074. /**
  1075. * The {@link Firestore} instance the document is in.
  1076. * This is useful for performing transactions, for example.
  1077. */
  1078. readonly firestore: Firestore_2;
  1079. /** @hideconstructor */
  1080. constructor(firestore: Firestore_2,
  1081. /**
  1082. * If provided, the `FirestoreDataConverter` associated with this instance.
  1083. */
  1084. converter: FirestoreDataConverter_2<T> | null, _key: _DocumentKey);
  1085. get _path(): _ResourcePath;
  1086. /**
  1087. * The document's identifier within its collection.
  1088. */
  1089. get id(): string;
  1090. /**
  1091. * A string representing the path of the referenced document (relative
  1092. * to the root of the database).
  1093. */
  1094. get path(): string;
  1095. /**
  1096. * The collection this `DocumentReference` belongs to.
  1097. */
  1098. get parent(): CollectionReference<T>;
  1099. /**
  1100. * Applies a custom data converter to this `DocumentReference`, allowing you
  1101. * to use your own custom model objects with Firestore. When you call {@link
  1102. * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`
  1103. * instance, the provided converter will convert between Firestore data and
  1104. * your custom type `U`.
  1105. *
  1106. * @param converter - Converts objects to and from Firestore.
  1107. * @returns A `DocumentReference<U>` that uses the provided converter.
  1108. */
  1109. withConverter<U>(converter: FirestoreDataConverter_2<U>): DocumentReference<U>;
  1110. /**
  1111. * Removes the current converter.
  1112. *
  1113. * @param converter - `null` removes the current converter.
  1114. * @returns A `DocumentReference<DocumentData>` that does not use a converter.
  1115. */
  1116. withConverter(converter: null): DocumentReference<DocumentData>;
  1117. }
  1118. /**
  1119. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  1120. * in order specified by the provided comparator. We always add a document key
  1121. * comparator on top of what is provided to guarantee document equality based on
  1122. * the key.
  1123. */
  1124. declare class DocumentSet {
  1125. /**
  1126. * Returns an empty copy of the existing DocumentSet, using the same
  1127. * comparator.
  1128. */
  1129. static emptySet(oldSet: DocumentSet): DocumentSet;
  1130. private comparator;
  1131. private keyedMap;
  1132. private sortedSet;
  1133. /** The default ordering is by key if the comparator is omitted */
  1134. constructor(comp?: DocumentComparator);
  1135. has(key: _DocumentKey): boolean;
  1136. get(key: _DocumentKey): Document_2 | null;
  1137. first(): Document_2 | null;
  1138. last(): Document_2 | null;
  1139. isEmpty(): boolean;
  1140. /**
  1141. * Returns the index of the provided key in the document set, or -1 if the
  1142. * document key is not present in the set;
  1143. */
  1144. indexOf(key: _DocumentKey): number;
  1145. get size(): number;
  1146. /** Iterates documents in order defined by "comparator" */
  1147. forEach(cb: (doc: Document_2) => void): void;
  1148. /** Inserts or updates a document with the same key */
  1149. add(doc: Document_2): DocumentSet;
  1150. /** Deletes a document with a given key */
  1151. delete(key: _DocumentKey): DocumentSet;
  1152. isEqual(other: DocumentSet | null | undefined): boolean;
  1153. toString(): string;
  1154. private copy;
  1155. }
  1156. /**
  1157. * A `DocumentSnapshot` contains data read from a document in your Firestore
  1158. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  1159. * get a specific field.
  1160. *
  1161. * For a `DocumentSnapshot` that points to a non-existing document, any data
  1162. * access will return 'undefined'. You can use the `exists()` method to
  1163. * explicitly verify a document's existence.
  1164. */
  1165. export declare class DocumentSnapshot<T = DocumentData> extends DocumentSnapshot_2<T> {
  1166. readonly _firestore: Firestore;
  1167. private readonly _firestoreImpl;
  1168. /**
  1169. * Metadata about the `DocumentSnapshot`, including information about its
  1170. * source and local modifications.
  1171. */
  1172. readonly metadata: SnapshotMetadata;
  1173. /** @hideconstructor protected */
  1174. constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: _DocumentKey, document: Document_2 | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter<T> | null);
  1175. /**
  1176. * Returns whether or not the data exists. True if the document exists.
  1177. */
  1178. exists(): this is QueryDocumentSnapshot<T>;
  1179. /**
  1180. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  1181. * the document doesn't exist.
  1182. *
  1183. * By default, `serverTimestamp()` values that have not yet been
  1184. * set to their final value will be returned as `null`. You can override
  1185. * this by passing an options object.
  1186. *
  1187. * @param options - An options object to configure how data is retrieved from
  1188. * the snapshot (for example the desired behavior for server timestamps that
  1189. * have not yet been set to their final value).
  1190. * @returns An `Object` containing all fields in the document or `undefined` if
  1191. * the document doesn't exist.
  1192. */
  1193. data(options?: SnapshotOptions): T | undefined;
  1194. /**
  1195. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  1196. * document or field doesn't exist.
  1197. *
  1198. * By default, a `serverTimestamp()` that has not yet been set to
  1199. * its final value will be returned as `null`. You can override this by
  1200. * passing an options object.
  1201. *
  1202. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  1203. * field.
  1204. * @param options - An options object to configure how the field is retrieved
  1205. * from the snapshot (for example the desired behavior for server timestamps
  1206. * that have not yet been set to their final value).
  1207. * @returns The data at the specified field location or undefined if no such
  1208. * field exists in the document.
  1209. */
  1210. get(fieldPath: string | FieldPath, options?: SnapshotOptions): any;
  1211. }
  1212. /**
  1213. * A `DocumentSnapshot` contains data read from a document in your Firestore
  1214. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  1215. * get a specific field.
  1216. *
  1217. * For a `DocumentSnapshot` that points to a non-existing document, any data
  1218. * access will return 'undefined'. You can use the `exists()` method to
  1219. * explicitly verify a document's existence.
  1220. */
  1221. declare class DocumentSnapshot_2<T = DocumentData> {
  1222. _firestore: Firestore_2;
  1223. _userDataWriter: AbstractUserDataWriter;
  1224. _key: _DocumentKey;
  1225. _document: Document_2 | null;
  1226. _converter: UntypedFirestoreDataConverter<T> | null;
  1227. /** @hideconstructor protected */
  1228. constructor(_firestore: Firestore_2, _userDataWriter: AbstractUserDataWriter, _key: _DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter<T> | null);
  1229. /** Property of the `DocumentSnapshot` that provides the document's ID. */
  1230. get id(): string;
  1231. /**
  1232. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  1233. */
  1234. get ref(): DocumentReference<T>;
  1235. /**
  1236. * Signals whether or not the document at the snapshot's location exists.
  1237. *
  1238. * @returns true if the document exists.
  1239. */
  1240. exists(): this is QueryDocumentSnapshot_2<T>;
  1241. /**
  1242. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  1243. * the document doesn't exist.
  1244. *
  1245. * @returns An `Object` containing all fields in the document or `undefined`
  1246. * if the document doesn't exist.
  1247. */
  1248. data(): T | undefined;
  1249. /**
  1250. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  1251. * document or field doesn't exist.
  1252. *
  1253. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  1254. * field.
  1255. * @returns The data at the specified field location or undefined if no such
  1256. * field exists in the document.
  1257. */
  1258. get(fieldPath: string | FieldPath): any;
  1259. }
  1260. declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>;
  1261. declare interface DocumentViewChange {
  1262. type: ChangeType;
  1263. doc: Document_2;
  1264. }
  1265. /**
  1266. * An AppCheck token provider that always yields an empty token.
  1267. * @internal
  1268. */
  1269. export declare class _EmptyAppCheckTokenProvider implements CredentialsProvider<string> {
  1270. getToken(): Promise<Token | null>;
  1271. invalidateToken(): void;
  1272. start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<string>): void;
  1273. shutdown(): void;
  1274. }
  1275. /**
  1276. * A CredentialsProvider that always yields an empty token.
  1277. * @internal
  1278. */
  1279. export declare class _EmptyAuthCredentialsProvider implements CredentialsProvider<User> {
  1280. getToken(): Promise<Token | null>;
  1281. invalidateToken(): void;
  1282. start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<User>): void;
  1283. shutdown(): void;
  1284. }
  1285. export { EmulatorMockTokenOptions }
  1286. /**
  1287. * Attempts to enable persistent storage, if possible.
  1288. *
  1289. * Must be called before any other functions (other than
  1290. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  1291. * {@link clearIndexedDbPersistence}.
  1292. *
  1293. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  1294. * returns. Note that even after this failure, the {@link Firestore} instance will
  1295. * remain usable, however offline persistence will be disabled.
  1296. *
  1297. * There are several reasons why this can fail, which can be identified by
  1298. * the `code` on the error.
  1299. *
  1300. * * failed-precondition: The app is already open in another browser tab.
  1301. * * unimplemented: The browser is incompatible with the offline
  1302. * persistence implementation.
  1303. *
  1304. * @param firestore - The {@link Firestore} instance to enable persistence for.
  1305. * @param persistenceSettings - Optional settings object to configure
  1306. * persistence.
  1307. * @returns A `Promise` that represents successfully enabling persistent storage.
  1308. */
  1309. export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise<void>;
  1310. /**
  1311. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  1312. * across all tabs, all operations share access to local persistence, including
  1313. * shared execution of queries and latency-compensated local document updates
  1314. * across all connected instances.
  1315. *
  1316. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  1317. * it returns. Note that even after this failure, the {@link Firestore} instance will
  1318. * remain usable, however offline persistence will be disabled.
  1319. *
  1320. * There are several reasons why this can fail, which can be identified by
  1321. * the `code` on the error.
  1322. *
  1323. * * failed-precondition: The app is already open in another browser tab and
  1324. * multi-tab is not enabled.
  1325. * * unimplemented: The browser is incompatible with the offline
  1326. * persistence implementation.
  1327. *
  1328. * @param firestore - The {@link Firestore} instance to enable persistence for.
  1329. * @returns A `Promise` that represents successfully enabling persistent
  1330. * storage.
  1331. */
  1332. export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;
  1333. /**
  1334. * Re-enables use of the network for this {@link Firestore} instance after a prior
  1335. * call to {@link disableNetwork}.
  1336. *
  1337. * @returns A `Promise` that is resolved once the network has been enabled.
  1338. */
  1339. export declare function enableNetwork(firestore: Firestore): Promise<void>;
  1340. /**
  1341. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at
  1342. * the provided document (inclusive). The end position is relative to the order
  1343. * of the query. The document must contain all of the fields provided in the
  1344. * orderBy of the query.
  1345. *
  1346. * @param snapshot - The snapshot of the document to end at.
  1347. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1348. */
  1349. export declare function endAt(snapshot: DocumentSnapshot_2<unknown>): QueryEndAtConstraint;
  1350. /**
  1351. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at
  1352. * the provided fields relative to the order of the query. The order of the field
  1353. * values must match the order of the order by clauses of the query.
  1354. *
  1355. * @param fieldValues - The field values to end this query at, in order
  1356. * of the query's order by.
  1357. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1358. */
  1359. export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;
  1360. /**
  1361. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end
  1362. * before the provided document (exclusive). The end position is relative to the
  1363. * order of the query. The document must contain all of the fields provided in
  1364. * the orderBy of the query.
  1365. *
  1366. * @param snapshot - The snapshot of the document to end before.
  1367. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1368. */
  1369. export declare function endBefore(snapshot: DocumentSnapshot_2<unknown>): QueryEndAtConstraint;
  1370. /**
  1371. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end
  1372. * before the provided fields relative to the order of the query. The order of
  1373. * the field values must match the order of the order by clauses of the query.
  1374. *
  1375. * @param fieldValues - The field values to end this query before, in order
  1376. * of the query's order by.
  1377. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1378. */
  1379. export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;
  1380. /**
  1381. * @internal
  1382. */
  1383. export declare function ensureFirestoreConfigured(firestore: Firestore): FirestoreClient;
  1384. declare interface Entry<K, V> {
  1385. key: K;
  1386. value: V;
  1387. }
  1388. /**
  1389. * EventManager is responsible for mapping queries to query event emitters.
  1390. * It handles "fan-out". -- Identical queries will re-use the same watch on the
  1391. * backend.
  1392. *
  1393. * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be
  1394. * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This
  1395. * allows users to tree-shake the Watch logic.
  1396. */
  1397. declare interface EventManager {
  1398. onListen?: (query: Query_2) => Promise<ViewSnapshot>;
  1399. onUnlisten?: (query: Query_2) => Promise<void>;
  1400. }
  1401. /**
  1402. * Locally writes `mutations` on the async queue.
  1403. * @internal
  1404. */
  1405. export declare function executeWrite(firestore: Firestore, mutations: Mutation[]): Promise<void>;
  1406. declare class FieldFilter extends Filter {
  1407. readonly field: _FieldPath;
  1408. readonly op: Operator;
  1409. readonly value: Value;
  1410. protected constructor(field: _FieldPath, op: Operator, value: Value);
  1411. /**
  1412. * Creates a filter based on the provided arguments.
  1413. */
  1414. static create(field: _FieldPath, op: Operator, value: Value): FieldFilter;
  1415. private static createKeyFieldInFilter;
  1416. matches(doc: Document_2): boolean;
  1417. protected matchesComparison(comparison: number): boolean;
  1418. isInequality(): boolean;
  1419. getFlattenedFilters(): readonly FieldFilter[];
  1420. getFilters(): Filter[];
  1421. getFirstInequalityField(): _FieldPath | null;
  1422. }
  1423. declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN';
  1424. /**
  1425. * An index definition for field indexes in Firestore.
  1426. *
  1427. * Every index is associated with a collection. The definition contains a list
  1428. * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
  1429. * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
  1430. *
  1431. * Unlike the backend, the SDK does not differentiate between collection or
  1432. * collection group-scoped indices. Every index can be used for both single
  1433. * collection and collection group queries.
  1434. */
  1435. declare class FieldIndex {
  1436. /**
  1437. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1438. * has not yet been persisted).
  1439. */
  1440. readonly indexId: number;
  1441. /** The collection ID this index applies to. */
  1442. readonly collectionGroup: string;
  1443. /** The field segments for this index. */
  1444. readonly fields: IndexSegment[];
  1445. /** Shows how up-to-date the index is for the current user. */
  1446. readonly indexState: IndexState_2;
  1447. /** An ID for an index that has not yet been added to persistence. */
  1448. static UNKNOWN_ID: number;
  1449. constructor(
  1450. /**
  1451. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1452. * has not yet been persisted).
  1453. */
  1454. indexId: number,
  1455. /** The collection ID this index applies to. */
  1456. collectionGroup: string,
  1457. /** The field segments for this index. */
  1458. fields: IndexSegment[],
  1459. /** Shows how up-to-date the index is for the current user. */
  1460. indexState: IndexState_2);
  1461. }
  1462. /**
  1463. * Provides a set of fields that can be used to partially patch a document.
  1464. * FieldMask is used in conjunction with ObjectValue.
  1465. * Examples:
  1466. * foo - Overwrites foo entirely with the provided value. If foo is not
  1467. * present in the companion ObjectValue, the field is deleted.
  1468. * foo.bar - Overwrites only the field bar of the object foo.
  1469. * If foo is not an object, foo is replaced with an object
  1470. * containing foo
  1471. */
  1472. declare class FieldMask {
  1473. readonly fields: _FieldPath[];
  1474. constructor(fields: _FieldPath[]);
  1475. static empty(): FieldMask;
  1476. /**
  1477. * Returns a new FieldMask object that is the result of adding all the given
  1478. * fields paths to this field mask.
  1479. */
  1480. unionWith(extraFields: _FieldPath[]): FieldMask;
  1481. /**
  1482. * Verifies that `fieldPath` is included by at least one field in this field
  1483. * mask.
  1484. *
  1485. * This is an O(n) operation, where `n` is the size of the field mask.
  1486. */
  1487. covers(fieldPath: _FieldPath): boolean;
  1488. isEqual(other: FieldMask): boolean;
  1489. }
  1490. /**
  1491. * A `FieldPath` refers to a field in a document. The path may consist of a
  1492. * single field name (referring to a top-level field in the document), or a
  1493. * list of field names (referring to a nested field in the document).
  1494. *
  1495. * Create a `FieldPath` by providing field names. If more than one field
  1496. * name is provided, the path will point to a nested field in a document.
  1497. */
  1498. export declare class FieldPath {
  1499. /** Internal representation of a Firestore field path. */
  1500. readonly _internalPath: _FieldPath;
  1501. /**
  1502. * Creates a `FieldPath` from the provided field names. If more than one field
  1503. * name is provided, the path will point to a nested field in a document.
  1504. *
  1505. * @param fieldNames - A list of field names.
  1506. */
  1507. constructor(...fieldNames: string[]);
  1508. /**
  1509. * Returns true if this `FieldPath` is equal to the provided one.
  1510. *
  1511. * @param other - The `FieldPath` to compare against.
  1512. * @returns true if this `FieldPath` is equal to the provided one.
  1513. */
  1514. isEqual(other: FieldPath): boolean;
  1515. }
  1516. /**
  1517. * A dot-separated path for navigating sub-objects within a document.
  1518. * @internal
  1519. */
  1520. export declare class _FieldPath extends BasePath<_FieldPath> {
  1521. protected construct(segments: string[], offset?: number, length?: number): _FieldPath;
  1522. /**
  1523. * Returns true if the string could be used as a segment in a field path
  1524. * without escaping.
  1525. */
  1526. private static isValidIdentifier;
  1527. canonicalString(): string;
  1528. toString(): string;
  1529. /**
  1530. * Returns true if this field references the key of a document.
  1531. */
  1532. isKeyField(): boolean;
  1533. /**
  1534. * The field designating the key of a document.
  1535. */
  1536. static keyField(): _FieldPath;
  1537. /**
  1538. * Parses a field string from the given server-formatted string.
  1539. *
  1540. * - Splitting the empty string is not allowed (for now at least).
  1541. * - Empty segments within the string (e.g. if there are two consecutive
  1542. * separators) are not allowed.
  1543. *
  1544. * TODO(b/37244157): we should make this more strict. Right now, it allows
  1545. * non-identifier path components, even if they aren't escaped.
  1546. */
  1547. static fromServerFormat(path: string): _FieldPath;
  1548. static emptyPath(): _FieldPath;
  1549. }
  1550. /** A field path and the TransformOperation to perform upon it. */
  1551. declare class FieldTransform {
  1552. readonly field: _FieldPath;
  1553. readonly transform: TransformOperation;
  1554. constructor(field: _FieldPath, transform: TransformOperation);
  1555. }
  1556. declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME';
  1557. /**
  1558. * Sentinel values that can be used when writing document fields with `set()`
  1559. * or `update()`.
  1560. */
  1561. export declare abstract class FieldValue {
  1562. _methodName: string;
  1563. /**
  1564. * @param _methodName - The public API endpoint that returns this class.
  1565. * @hideconstructor
  1566. */
  1567. constructor(_methodName: string);
  1568. /** Compares `FieldValue`s for equality. */
  1569. abstract isEqual(other: FieldValue): boolean;
  1570. abstract _toFieldTransform(context: ParseContext): FieldTransform | null;
  1571. }
  1572. declare abstract class Filter {
  1573. abstract matches(doc: Document_2): boolean;
  1574. abstract getFlattenedFilters(): readonly FieldFilter[];
  1575. abstract getFilters(): Filter[];
  1576. abstract getFirstInequalityField(): _FieldPath | null;
  1577. }
  1578. /**
  1579. * The Cloud Firestore service interface.
  1580. *
  1581. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  1582. */
  1583. export declare class Firestore extends Firestore_2 {
  1584. /**
  1585. * Whether it's a {@link Firestore} or Firestore Lite instance.
  1586. */
  1587. type: 'firestore-lite' | 'firestore';
  1588. readonly _queue: AsyncQueue;
  1589. readonly _persistenceKey: string;
  1590. _firestoreClient: FirestoreClient | undefined;
  1591. /** @hideconstructor */
  1592. constructor(authCredentialsProvider: CredentialsProvider<User>, appCheckCredentialsProvider: CredentialsProvider<string>, databaseId: _DatabaseId, app?: FirebaseApp);
  1593. _terminate(): Promise<void>;
  1594. }
  1595. /**
  1596. * The Cloud Firestore service interface.
  1597. *
  1598. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  1599. */
  1600. declare class Firestore_2 implements FirestoreService {
  1601. _authCredentials: CredentialsProvider<User>;
  1602. _appCheckCredentials: CredentialsProvider<string>;
  1603. readonly _databaseId: _DatabaseId;
  1604. readonly _app?: FirebaseApp | undefined;
  1605. /**
  1606. * Whether it's a Firestore or Firestore Lite instance.
  1607. */
  1608. type: 'firestore-lite' | 'firestore';
  1609. readonly _persistenceKey: string;
  1610. private _settings;
  1611. private _settingsFrozen;
  1612. private _terminateTask?;
  1613. /** @hideconstructor */
  1614. constructor(_authCredentials: CredentialsProvider<User>, _appCheckCredentials: CredentialsProvider<string>, _databaseId: _DatabaseId, _app?: FirebaseApp | undefined);
  1615. /**
  1616. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  1617. * instance.
  1618. */
  1619. get app(): FirebaseApp;
  1620. get _initialized(): boolean;
  1621. get _terminated(): boolean;
  1622. _setSettings(settings: PrivateSettings): void;
  1623. _getSettings(): FirestoreSettingsImpl;
  1624. _freezeSettings(): FirestoreSettingsImpl;
  1625. _delete(): Promise<void>;
  1626. /** Returns a JSON-serializable representation of this `Firestore` instance. */
  1627. toJSON(): object;
  1628. /**
  1629. * Terminates all components used by this client. Subclasses can override
  1630. * this method to clean up their own dependencies, but must also call this
  1631. * method.
  1632. *
  1633. * Only ever called once.
  1634. */
  1635. protected _terminate(): Promise<void>;
  1636. }
  1637. /**
  1638. * FirestoreClient is a top-level class that constructs and owns all of the
  1639. * pieces of the client SDK architecture. It is responsible for creating the
  1640. * async queue that is shared by all of the other components in the system.
  1641. */
  1642. declare class FirestoreClient {
  1643. private authCredentials;
  1644. private appCheckCredentials;
  1645. /**
  1646. * Asynchronous queue responsible for all of our internal processing. When
  1647. * we get incoming work from the user (via public API) or the network
  1648. * (incoming GRPC messages), we should always schedule onto this queue.
  1649. * This ensures all of our work is properly serialized (e.g. we don't
  1650. * start processing a new operation while the previous one is waiting for
  1651. * an async I/O to complete).
  1652. */
  1653. asyncQueue: AsyncQueue;
  1654. private databaseInfo;
  1655. private user;
  1656. private readonly clientId;
  1657. private authCredentialListener;
  1658. private appCheckCredentialListener;
  1659. offlineComponents?: OfflineComponentProvider;
  1660. onlineComponents?: OnlineComponentProvider;
  1661. constructor(authCredentials: CredentialsProvider<User>, appCheckCredentials: CredentialsProvider<string>,
  1662. /**
  1663. * Asynchronous queue responsible for all of our internal processing. When
  1664. * we get incoming work from the user (via public API) or the network
  1665. * (incoming GRPC messages), we should always schedule onto this queue.
  1666. * This ensures all of our work is properly serialized (e.g. we don't
  1667. * start processing a new operation while the previous one is waiting for
  1668. * an async I/O to complete).
  1669. */
  1670. asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo);
  1671. getConfiguration(): Promise<ComponentConfiguration>;
  1672. setCredentialChangeListener(listener: (user: User) => Promise<void>): void;
  1673. setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise<void>): void;
  1674. /**
  1675. * Checks that the client has not been terminated. Ensures that other methods on
  1676. * this class cannot be called after the client is terminated.
  1677. */
  1678. verifyNotTerminated(): void;
  1679. terminate(): Promise<void>;
  1680. }
  1681. /**
  1682. * Converter used by `withConverter()` to transform user objects of type `T`
  1683. * into Firestore data.
  1684. *
  1685. * Using the converter allows you to specify generic type arguments when
  1686. * storing and retrieving objects from Firestore.
  1687. *
  1688. * @example
  1689. * ```typescript
  1690. * class Post {
  1691. * constructor(readonly title: string, readonly author: string) {}
  1692. *
  1693. * toString(): string {
  1694. * return this.title + ', by ' + this.author;
  1695. * }
  1696. * }
  1697. *
  1698. * const postConverter = {
  1699. * toFirestore(post: WithFieldValue<Post>): DocumentData {
  1700. * return {title: post.title, author: post.author};
  1701. * },
  1702. * fromFirestore(
  1703. * snapshot: QueryDocumentSnapshot,
  1704. * options: SnapshotOptions
  1705. * ): Post {
  1706. * const data = snapshot.data(options)!;
  1707. * return new Post(data.title, data.author);
  1708. * }
  1709. * };
  1710. *
  1711. * const postSnap = await firebase.firestore()
  1712. * .collection('posts')
  1713. * .withConverter(postConverter)
  1714. * .doc().get();
  1715. * const post = postSnap.data();
  1716. * if (post !== undefined) {
  1717. * post.title; // string
  1718. * post.toString(); // Should be defined
  1719. * post.someNonExistentProperty; // TS error
  1720. * }
  1721. * ```
  1722. */
  1723. export declare interface FirestoreDataConverter<T> extends FirestoreDataConverter_2<T> {
  1724. /**
  1725. * Called by the Firestore SDK to convert a custom model object of type `T`
  1726. * into a plain JavaScript object (suitable for writing directly to the
  1727. * Firestore database). To use `set()` with `merge` and `mergeFields`,
  1728. * `toFirestore()` must be defined with `PartialWithFieldValue<T>`.
  1729. *
  1730. * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as
  1731. * {@link (deleteField:1)} to be used as property values.
  1732. */
  1733. toFirestore(modelObject: WithFieldValue<T>): DocumentData;
  1734. /**
  1735. * Called by the Firestore SDK to convert a custom model object of type `T`
  1736. * into a plain JavaScript object (suitable for writing directly to the
  1737. * Firestore database). Used with {@link (setDoc:1)}, {@link (WriteBatch.set:1)}
  1738. * and {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.
  1739. *
  1740. * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow
  1741. * FieldValues such as {@link (arrayUnion:1)} to be used as property values.
  1742. * It also supports nested `Partial` by allowing nested fields to be
  1743. * omitted.
  1744. */
  1745. toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions): DocumentData;
  1746. /**
  1747. * Called by the Firestore SDK to convert Firestore data into an object of
  1748. * type T. You can access your data by calling: `snapshot.data(options)`.
  1749. *
  1750. * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.
  1751. * @param options - The `SnapshotOptions` from the initial call to `data()`.
  1752. */
  1753. fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>, options?: SnapshotOptions): T;
  1754. }
  1755. /**
  1756. * Converter used by `withConverter()` to transform user objects of type `T`
  1757. * into Firestore data.
  1758. *
  1759. * Using the converter allows you to specify generic type arguments when
  1760. * storing and retrieving objects from Firestore.
  1761. *
  1762. * @example
  1763. * ```typescript
  1764. * class Post {
  1765. * constructor(readonly title: string, readonly author: string) {}
  1766. *
  1767. * toString(): string {
  1768. * return this.title + ', by ' + this.author;
  1769. * }
  1770. * }
  1771. *
  1772. * const postConverter = {
  1773. * toFirestore(post: WithFieldValue<Post>): DocumentData {
  1774. * return {title: post.title, author: post.author};
  1775. * },
  1776. * fromFirestore(snapshot: QueryDocumentSnapshot): Post {
  1777. * const data = snapshot.data(options)!;
  1778. * return new Post(data.title, data.author);
  1779. * }
  1780. * };
  1781. *
  1782. * const postSnap = await firebase.firestore()
  1783. * .collection('posts')
  1784. * .withConverter(postConverter)
  1785. * .doc().get();
  1786. * const post = postSnap.data();
  1787. * if (post !== undefined) {
  1788. * post.title; // string
  1789. * post.toString(); // Should be defined
  1790. * post.someNonExistentProperty; // TS error
  1791. * }
  1792. * ```
  1793. */
  1794. declare interface FirestoreDataConverter_2<T> {
  1795. /**
  1796. * Called by the Firestore SDK to convert a custom model object of type `T`
  1797. * into a plain Javascript object (suitable for writing directly to the
  1798. * Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
  1799. * and {@link @firebase/firestore/lite#(Transaction.set:1)}.
  1800. *
  1801. * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as
  1802. * {@link (deleteField:1)} to be used as property values.
  1803. */
  1804. toFirestore(modelObject: WithFieldValue<T>): DocumentData;
  1805. /**
  1806. * Called by the Firestore SDK to convert a custom model object of type `T`
  1807. * into a plain Javascript object (suitable for writing directly to the
  1808. * Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
  1809. * and {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` or `mergeFields`.
  1810. *
  1811. * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow
  1812. * FieldValues such as {@link (arrayUnion:1)} to be used as property values.
  1813. * It also supports nested `Partial` by allowing nested fields to be
  1814. * omitted.
  1815. */
  1816. toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions): DocumentData;
  1817. /**
  1818. * Called by the Firestore SDK to convert Firestore data into an object of
  1819. * type T. You can access your data by calling: `snapshot.data()`.
  1820. *
  1821. * @param snapshot - A `QueryDocumentSnapshot` containing your data and
  1822. * metadata.
  1823. */
  1824. fromFirestore(snapshot: QueryDocumentSnapshot_2<DocumentData>): T;
  1825. }
  1826. /** An error returned by a Firestore operation. */
  1827. export declare class FirestoreError extends FirebaseError {
  1828. /**
  1829. * The backend error code associated with this error.
  1830. */
  1831. readonly code: FirestoreErrorCode;
  1832. /**
  1833. * A custom error description.
  1834. */
  1835. readonly message: string;
  1836. /** The stack of the error. */
  1837. readonly stack?: string;
  1838. /** @hideconstructor */
  1839. constructor(
  1840. /**
  1841. * The backend error code associated with this error.
  1842. */
  1843. code: FirestoreErrorCode,
  1844. /**
  1845. * A custom error description.
  1846. */
  1847. message: string);
  1848. }
  1849. /**
  1850. * The set of Firestore status codes. The codes are the same at the ones
  1851. * exposed by gRPC here:
  1852. * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
  1853. *
  1854. * Possible values:
  1855. * - 'cancelled': The operation was cancelled (typically by the caller).
  1856. * - 'unknown': Unknown error or an error from a different error domain.
  1857. * - 'invalid-argument': Client specified an invalid argument. Note that this
  1858. * differs from 'failed-precondition'. 'invalid-argument' indicates
  1859. * arguments that are problematic regardless of the state of the system
  1860. * (e.g. an invalid field name).
  1861. * - 'deadline-exceeded': Deadline expired before operation could complete.
  1862. * For operations that change the state of the system, this error may be
  1863. * returned even if the operation has completed successfully. For example,
  1864. * a successful response from a server could have been delayed long enough
  1865. * for the deadline to expire.
  1866. * - 'not-found': Some requested document was not found.
  1867. * - 'already-exists': Some document that we attempted to create already
  1868. * exists.
  1869. * - 'permission-denied': The caller does not have permission to execute the
  1870. * specified operation.
  1871. * - 'resource-exhausted': Some resource has been exhausted, perhaps a
  1872. * per-user quota, or perhaps the entire file system is out of space.
  1873. * - 'failed-precondition': Operation was rejected because the system is not
  1874. * in a state required for the operation's execution.
  1875. * - 'aborted': The operation was aborted, typically due to a concurrency
  1876. * issue like transaction aborts, etc.
  1877. * - 'out-of-range': Operation was attempted past the valid range.
  1878. * - 'unimplemented': Operation is not implemented or not supported/enabled.
  1879. * - 'internal': Internal errors. Means some invariants expected by
  1880. * underlying system has been broken. If you see one of these errors,
  1881. * something is very broken.
  1882. * - 'unavailable': The service is currently unavailable. This is most likely
  1883. * a transient condition and may be corrected by retrying with a backoff.
  1884. * - 'data-loss': Unrecoverable data loss or corruption.
  1885. * - 'unauthenticated': The request does not have valid authentication
  1886. * credentials for the operation.
  1887. */
  1888. export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated';
  1889. /**
  1890. * An interface implemented by FirebaseFirestore that provides compatibility
  1891. * with the usage in this file.
  1892. *
  1893. * This interface mainly exists to remove a cyclic dependency.
  1894. */
  1895. declare interface FirestoreService extends _FirebaseService {
  1896. _authCredentials: CredentialsProvider<User>;
  1897. _appCheckCredentials: CredentialsProvider<string>;
  1898. _persistenceKey: string;
  1899. _databaseId: _DatabaseId;
  1900. _terminated: boolean;
  1901. _freezeSettings(): FirestoreSettingsImpl;
  1902. }
  1903. /**
  1904. * Specifies custom configurations for your Cloud Firestore instance.
  1905. * You must set these before invoking any other methods.
  1906. */
  1907. export declare interface FirestoreSettings extends FirestoreSettings_2 {
  1908. /**
  1909. * An approximate cache size threshold for the on-disk data. If the cache
  1910. * grows beyond this size, Firestore will start removing data that hasn't been
  1911. * recently used. The size is not a guarantee that the cache will stay below
  1912. * that size, only that if the cache exceeds the given size, cleanup will be
  1913. * attempted.
  1914. *
  1915. * The default value is 40 MB. The threshold must be set to at least 1 MB, and
  1916. * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.
  1917. */
  1918. cacheSizeBytes?: number;
  1919. /**
  1920. * Forces the SDK’s underlying network transport (WebChannel) to use
  1921. * long-polling. Each response from the backend will be closed immediately
  1922. * after the backend sends data (by default responses are kept open in
  1923. * case the backend has more data to send). This avoids incompatibility
  1924. * issues with certain proxies, antivirus software, etc. that incorrectly
  1925. * buffer traffic indefinitely. Use of this option will cause some
  1926. * performance degradation though.
  1927. *
  1928. * This setting cannot be used with `experimentalAutoDetectLongPolling` and
  1929. * may be removed in a future release. If you find yourself using it to
  1930. * work around a specific network reliability issue, please tell us about
  1931. * it in https://github.com/firebase/firebase-js-sdk/issues/1674.
  1932. */
  1933. experimentalForceLongPolling?: boolean;
  1934. /**
  1935. * Configures the SDK's underlying transport (WebChannel) to automatically
  1936. * detect if long-polling should be used. This is very similar to
  1937. * `experimentalForceLongPolling`, but only uses long-polling if required.
  1938. *
  1939. * This setting will likely be enabled by default in future releases and
  1940. * cannot be combined with `experimentalForceLongPolling`.
  1941. */
  1942. experimentalAutoDetectLongPolling?: boolean;
  1943. }
  1944. /**
  1945. * Specifies custom configurations for your Cloud Firestore instance.
  1946. * You must set these before invoking any other methods.
  1947. */
  1948. declare interface FirestoreSettings_2 {
  1949. /** The hostname to connect to. */
  1950. host?: string;
  1951. /** Whether to use SSL when connecting. */
  1952. ssl?: boolean;
  1953. /**
  1954. * Whether to skip nested properties that are set to `undefined` during
  1955. * object serialization. If set to `true`, these properties are skipped
  1956. * and not written to Firestore. If set to `false` or omitted, the SDK
  1957. * throws an exception when it encounters properties of type `undefined`.
  1958. */
  1959. ignoreUndefinedProperties?: boolean;
  1960. }
  1961. /**
  1962. * A concrete type describing all the values that can be applied via a
  1963. * user-supplied `FirestoreSettings` object. This is a separate type so that
  1964. * defaults can be supplied and the value can be checked for equality.
  1965. */
  1966. declare class FirestoreSettingsImpl {
  1967. /** The hostname to connect to. */
  1968. readonly host: string;
  1969. /** Whether to use SSL when connecting. */
  1970. readonly ssl: boolean;
  1971. readonly cacheSizeBytes: number;
  1972. readonly experimentalForceLongPolling: boolean;
  1973. readonly experimentalAutoDetectLongPolling: boolean;
  1974. readonly ignoreUndefinedProperties: boolean;
  1975. readonly useFetchStreams: boolean;
  1976. credentials?: any;
  1977. constructor(settings: PrivateSettings);
  1978. isEqual(other: FirestoreSettingsImpl): boolean;
  1979. }
  1980. declare namespace firestoreV1ApiClientInterfaces {
  1981. interface ArrayValue {
  1982. values?: Value[];
  1983. }
  1984. interface BatchGetDocumentsRequest {
  1985. database?: string;
  1986. documents?: string[];
  1987. mask?: DocumentMask;
  1988. transaction?: string;
  1989. newTransaction?: TransactionOptions;
  1990. readTime?: string;
  1991. }
  1992. interface BatchGetDocumentsResponse {
  1993. found?: Document;
  1994. missing?: string;
  1995. transaction?: string;
  1996. readTime?: string;
  1997. }
  1998. interface BeginTransactionRequest {
  1999. options?: TransactionOptions;
  2000. }
  2001. interface BeginTransactionResponse {
  2002. transaction?: string;
  2003. }
  2004. interface CollectionSelector {
  2005. collectionId?: string;
  2006. allDescendants?: boolean;
  2007. }
  2008. interface CommitRequest {
  2009. database?: string;
  2010. writes?: Write[];
  2011. transaction?: string;
  2012. }
  2013. interface CommitResponse {
  2014. writeResults?: WriteResult[];
  2015. commitTime?: string;
  2016. }
  2017. interface CompositeFilter {
  2018. op?: CompositeFilterOp;
  2019. filters?: Filter[];
  2020. }
  2021. interface Cursor {
  2022. values?: Value[];
  2023. before?: boolean;
  2024. }
  2025. interface Document {
  2026. name?: string;
  2027. fields?: ApiClientObjectMap<Value>;
  2028. createTime?: Timestamp_2;
  2029. updateTime?: Timestamp_2;
  2030. }
  2031. interface DocumentChange {
  2032. document?: Document;
  2033. targetIds?: number[];
  2034. removedTargetIds?: number[];
  2035. }
  2036. interface DocumentDelete {
  2037. document?: string;
  2038. removedTargetIds?: number[];
  2039. readTime?: Timestamp_2;
  2040. }
  2041. interface DocumentMask {
  2042. fieldPaths?: string[];
  2043. }
  2044. interface DocumentRemove {
  2045. document?: string;
  2046. removedTargetIds?: number[];
  2047. readTime?: string;
  2048. }
  2049. interface DocumentTransform {
  2050. document?: string;
  2051. fieldTransforms?: FieldTransform[];
  2052. }
  2053. interface DocumentsTarget {
  2054. documents?: string[];
  2055. }
  2056. interface Empty {
  2057. }
  2058. interface ExistenceFilter {
  2059. targetId?: number;
  2060. count?: number;
  2061. }
  2062. interface FieldFilter {
  2063. field?: FieldReference;
  2064. op?: FieldFilterOp;
  2065. value?: Value;
  2066. }
  2067. interface FieldReference {
  2068. fieldPath?: string;
  2069. }
  2070. interface FieldTransform {
  2071. fieldPath?: string;
  2072. setToServerValue?: FieldTransformSetToServerValue;
  2073. appendMissingElements?: ArrayValue;
  2074. removeAllFromArray?: ArrayValue;
  2075. increment?: Value;
  2076. }
  2077. interface Filter {
  2078. compositeFilter?: CompositeFilter;
  2079. fieldFilter?: FieldFilter;
  2080. unaryFilter?: UnaryFilter;
  2081. }
  2082. interface Index {
  2083. name?: string;
  2084. collectionId?: string;
  2085. fields?: IndexField[];
  2086. state?: IndexState;
  2087. }
  2088. interface IndexField {
  2089. fieldPath?: string;
  2090. mode?: IndexFieldMode;
  2091. }
  2092. interface LatLng {
  2093. latitude?: number;
  2094. longitude?: number;
  2095. }
  2096. interface ListCollectionIdsRequest {
  2097. pageSize?: number;
  2098. pageToken?: string;
  2099. }
  2100. interface ListCollectionIdsResponse {
  2101. collectionIds?: string[];
  2102. nextPageToken?: string;
  2103. }
  2104. interface ListDocumentsResponse {
  2105. documents?: Document[];
  2106. nextPageToken?: string;
  2107. }
  2108. interface ListIndexesResponse {
  2109. indexes?: Index[];
  2110. nextPageToken?: string;
  2111. }
  2112. interface ListenRequest {
  2113. addTarget?: Target;
  2114. removeTarget?: number;
  2115. labels?: ApiClientObjectMap<string>;
  2116. }
  2117. interface ListenResponse {
  2118. targetChange?: TargetChange;
  2119. documentChange?: DocumentChange;
  2120. documentDelete?: DocumentDelete;
  2121. documentRemove?: DocumentRemove;
  2122. filter?: ExistenceFilter;
  2123. }
  2124. interface MapValue {
  2125. fields?: ApiClientObjectMap<Value>;
  2126. }
  2127. interface Operation {
  2128. name?: string;
  2129. metadata?: ApiClientObjectMap<any>;
  2130. done?: boolean;
  2131. error?: Status;
  2132. response?: ApiClientObjectMap<any>;
  2133. }
  2134. interface Order {
  2135. field?: FieldReference;
  2136. direction?: OrderDirection;
  2137. }
  2138. interface Precondition {
  2139. exists?: boolean;
  2140. updateTime?: Timestamp_2;
  2141. }
  2142. interface Projection {
  2143. fields?: FieldReference[];
  2144. }
  2145. interface QueryTarget {
  2146. parent?: string;
  2147. structuredQuery?: StructuredQuery;
  2148. }
  2149. interface ReadOnly {
  2150. readTime?: string;
  2151. }
  2152. interface ReadWrite {
  2153. retryTransaction?: string;
  2154. }
  2155. interface RollbackRequest {
  2156. transaction?: string;
  2157. }
  2158. interface RunQueryRequest {
  2159. parent?: string;
  2160. structuredQuery?: StructuredQuery;
  2161. transaction?: string;
  2162. newTransaction?: TransactionOptions;
  2163. readTime?: string;
  2164. }
  2165. interface RunQueryResponse {
  2166. transaction?: string;
  2167. document?: Document;
  2168. readTime?: string;
  2169. skippedResults?: number;
  2170. }
  2171. interface RunAggregationQueryRequest {
  2172. parent?: string;
  2173. structuredAggregationQuery?: StructuredAggregationQuery;
  2174. transaction?: string;
  2175. newTransaction?: TransactionOptions;
  2176. readTime?: string;
  2177. }
  2178. interface RunAggregationQueryResponse {
  2179. result?: AggregationResult;
  2180. transaction?: string;
  2181. readTime?: string;
  2182. }
  2183. interface AggregationResult {
  2184. aggregateFields?: ApiClientObjectMap<Value>;
  2185. }
  2186. interface StructuredAggregationQuery {
  2187. structuredQuery?: StructuredQuery;
  2188. aggregations?: Aggregation[];
  2189. }
  2190. interface Aggregation {
  2191. count?: Count;
  2192. alias?: string;
  2193. }
  2194. interface Count {
  2195. upTo?: number;
  2196. }
  2197. interface Status {
  2198. code?: number;
  2199. message?: string;
  2200. details?: Array<ApiClientObjectMap<any>>;
  2201. }
  2202. interface StructuredQuery {
  2203. select?: Projection;
  2204. from?: CollectionSelector[];
  2205. where?: Filter;
  2206. orderBy?: Order[];
  2207. startAt?: Cursor;
  2208. endAt?: Cursor;
  2209. offset?: number;
  2210. limit?: number | {
  2211. value: number;
  2212. };
  2213. }
  2214. interface Target {
  2215. query?: QueryTarget;
  2216. documents?: DocumentsTarget;
  2217. resumeToken?: string | Uint8Array;
  2218. readTime?: Timestamp_2;
  2219. targetId?: number;
  2220. once?: boolean;
  2221. }
  2222. interface TargetChange {
  2223. targetChangeType?: TargetChangeTargetChangeType;
  2224. targetIds?: number[];
  2225. cause?: Status;
  2226. resumeToken?: string | Uint8Array;
  2227. readTime?: Timestamp_2;
  2228. }
  2229. interface TransactionOptions {
  2230. readOnly?: ReadOnly;
  2231. readWrite?: ReadWrite;
  2232. }
  2233. interface UnaryFilter {
  2234. op?: UnaryFilterOp;
  2235. field?: FieldReference;
  2236. }
  2237. interface Value {
  2238. nullValue?: ValueNullValue;
  2239. booleanValue?: boolean;
  2240. integerValue?: string | number;
  2241. doubleValue?: string | number;
  2242. timestampValue?: Timestamp_2;
  2243. stringValue?: string;
  2244. bytesValue?: string | Uint8Array;
  2245. referenceValue?: string;
  2246. geoPointValue?: LatLng;
  2247. arrayValue?: ArrayValue;
  2248. mapValue?: MapValue;
  2249. }
  2250. interface Write {
  2251. update?: Document;
  2252. delete?: string;
  2253. verify?: string;
  2254. transform?: DocumentTransform;
  2255. updateMask?: DocumentMask;
  2256. updateTransforms?: FieldTransform[];
  2257. currentDocument?: Precondition;
  2258. }
  2259. interface WriteRequest {
  2260. streamId?: string;
  2261. writes?: Write[];
  2262. streamToken?: string | Uint8Array;
  2263. labels?: ApiClientObjectMap<string>;
  2264. }
  2265. interface WriteResponse {
  2266. streamId?: string;
  2267. streamToken?: string | Uint8Array;
  2268. writeResults?: WriteResult[];
  2269. commitTime?: Timestamp_2;
  2270. }
  2271. interface WriteResult {
  2272. updateTime?: Timestamp_2;
  2273. transformResults?: Value[];
  2274. }
  2275. }
  2276. declare interface FirstPartyCredentialsSettings {
  2277. ['type']: 'gapi';
  2278. ['client']: unknown;
  2279. ['sessionIndex']: string;
  2280. ['iamToken']: string | null;
  2281. ['authTokenFactory']: AuthTokenFactory | null;
  2282. }
  2283. /**
  2284. * @license
  2285. * Copyright 2017 Google LLC
  2286. *
  2287. * Licensed under the Apache License, Version 2.0 (the "License");
  2288. * you may not use this file except in compliance with the License.
  2289. * You may obtain a copy of the License at
  2290. *
  2291. * http://www.apache.org/licenses/LICENSE-2.0
  2292. *
  2293. * Unless required by applicable law or agreed to in writing, software
  2294. * distributed under the License is distributed on an "AS IS" BASIS,
  2295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2296. * See the License for the specific language governing permissions and
  2297. * limitations under the License.
  2298. */
  2299. declare type FulfilledHandler<T, R> = ((result: T) => R | PersistencePromise<R>) | null;
  2300. /**
  2301. * @license
  2302. * Copyright 2017 Google LLC
  2303. *
  2304. * Licensed under the Apache License, Version 2.0 (the "License");
  2305. * you may not use this file except in compliance with the License.
  2306. * You may obtain a copy of the License at
  2307. *
  2308. * http://www.apache.org/licenses/LICENSE-2.0
  2309. *
  2310. * Unless required by applicable law or agreed to in writing, software
  2311. * distributed under the License is distributed on an "AS IS" BASIS,
  2312. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2313. * See the License for the specific language governing permissions and
  2314. * limitations under the License.
  2315. */
  2316. /**
  2317. * An immutable object representing a geographic location in Firestore. The
  2318. * location is represented as latitude/longitude pair.
  2319. *
  2320. * Latitude values are in the range of [-90, 90].
  2321. * Longitude values are in the range of [-180, 180].
  2322. */
  2323. export declare class GeoPoint {
  2324. private _lat;
  2325. private _long;
  2326. /**
  2327. * Creates a new immutable `GeoPoint` object with the provided latitude and
  2328. * longitude values.
  2329. * @param latitude - The latitude as number between -90 and 90.
  2330. * @param longitude - The longitude as number between -180 and 180.
  2331. */
  2332. constructor(latitude: number, longitude: number);
  2333. /**
  2334. * The latitude of this `GeoPoint` instance.
  2335. */
  2336. get latitude(): number;
  2337. /**
  2338. * The longitude of this `GeoPoint` instance.
  2339. */
  2340. get longitude(): number;
  2341. /**
  2342. * Returns true if this `GeoPoint` is equal to the provided one.
  2343. *
  2344. * @param other - The `GeoPoint` to compare against.
  2345. * @returns true if this `GeoPoint` is equal to the provided one.
  2346. */
  2347. isEqual(other: GeoPoint): boolean;
  2348. /** Returns a JSON-serializable representation of this GeoPoint. */
  2349. toJSON(): {
  2350. latitude: number;
  2351. longitude: number;
  2352. };
  2353. /**
  2354. * Actually private to JS consumers of our API, so this function is prefixed
  2355. * with an underscore.
  2356. */
  2357. _compareTo(other: GeoPoint): number;
  2358. }
  2359. /**
  2360. * Calculates the number of documents in the result set of the given query,
  2361. * without actually downloading the documents.
  2362. *
  2363. * Using this function to count the documents is efficient because only the
  2364. * final count, not the documents' data, is downloaded. This function can even
  2365. * count the documents if the result set would be prohibitively large to
  2366. * download entirely (e.g. thousands of documents).
  2367. *
  2368. * The result received from the server is presented, unaltered, without
  2369. * considering any local state. That is, documents in the local cache are not
  2370. * taken into consideration, neither are local modifications not yet
  2371. * synchronized with the server. Previously-downloaded results, if any, are not
  2372. * used: every request using this source necessarily involves a round trip to
  2373. * the server.
  2374. *
  2375. * @param query - The query whose result set size to calculate.
  2376. * @returns A Promise that will be resolved with the count; the count can be
  2377. * retrieved from `snapshot.data().count`, where `snapshot` is the
  2378. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  2379. */
  2380. export declare function getCountFromServer(query: Query<unknown>): Promise<AggregateQuerySnapshot<{
  2381. count: AggregateField<number>;
  2382. }>>;
  2383. /**
  2384. * Reads the document referred to by this `DocumentReference`.
  2385. *
  2386. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  2387. * for data from the server, but it may return cached data or fail if you are
  2388. * offline and the server cannot be reached. To specify this behavior, invoke
  2389. * {@link getDocFromCache} or {@link getDocFromServer}.
  2390. *
  2391. * @param reference - The reference of the document to fetch.
  2392. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  2393. * current document contents.
  2394. */
  2395. export declare function getDoc<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  2396. /**
  2397. * Reads the document referred to by this `DocumentReference` from cache.
  2398. * Returns an error if the document is not currently cached.
  2399. *
  2400. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  2401. * current document contents.
  2402. */
  2403. export declare function getDocFromCache<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  2404. /**
  2405. * Reads the document referred to by this `DocumentReference` from the server.
  2406. * Returns an error if the network is not available.
  2407. *
  2408. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  2409. * current document contents.
  2410. */
  2411. export declare function getDocFromServer<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  2412. /**
  2413. * Executes the query and returns the results as a `QuerySnapshot`.
  2414. *
  2415. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  2416. * waiting for data from the server, but it may return cached data or fail if
  2417. * you are offline and the server cannot be reached. To specify this behavior,
  2418. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  2419. *
  2420. * @returns A `Promise` that will be resolved with the results of the query.
  2421. */
  2422. export declare function getDocs<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
  2423. /**
  2424. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  2425. * Returns an empty result set if no documents matching the query are currently
  2426. * cached.
  2427. *
  2428. * @returns A `Promise` that will be resolved with the results of the query.
  2429. */
  2430. export declare function getDocsFromCache<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
  2431. /**
  2432. * Executes the query and returns the results as a `QuerySnapshot` from the
  2433. * server. Returns an error if the network is not available.
  2434. *
  2435. * @returns A `Promise` that will be resolved with the results of the query.
  2436. */
  2437. export declare function getDocsFromServer<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
  2438. /**
  2439. * Returns the existing default {@link Firestore} instance that is associated with the
  2440. * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2441. * instance with default settings.
  2442. *
  2443. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}
  2444. * instance is associated with.
  2445. * @returns The {@link Firestore} instance of the provided app.
  2446. */
  2447. export declare function getFirestore(app: FirebaseApp): Firestore;
  2448. /**
  2449. * Returns the existing {@link Firestore} instance that is associated with the
  2450. * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2451. * instance with default settings.
  2452. *
  2453. * @param databaseId - The name of database.
  2454. * @returns The {@link Firestore} instance of the provided app.
  2455. * @internal
  2456. */
  2457. export declare function getFirestore(databaseId: string): Firestore;
  2458. /**
  2459. * Returns the existing default {@link Firestore} instance that is associated with the
  2460. * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2461. * instance with default settings.
  2462. *
  2463. * @returns The {@link Firestore} instance of the provided app.
  2464. */
  2465. export declare function getFirestore(): Firestore;
  2466. /**
  2467. * Returns the existing default {@link Firestore} instance that is associated with the
  2468. * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2469. * instance with default settings.
  2470. *
  2471. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}
  2472. * instance is associated with.
  2473. * @param databaseId - The name of database.
  2474. * @returns The {@link Firestore} instance of the provided app.
  2475. * @internal
  2476. */
  2477. export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore;
  2478. /**
  2479. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  2480. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  2481. * the given value.
  2482. *
  2483. * If either the operand or the current field value uses floating point
  2484. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  2485. * integers, values outside of JavaScript's safe number range
  2486. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  2487. * precision loss. Furthermore, once processed by the Firestore backend, all
  2488. * integer operations are capped between -2^63 and 2^63-1.
  2489. *
  2490. * If the current field value is not of type `number`, or if the field does not
  2491. * yet exist, the transformation sets the field to the given value.
  2492. *
  2493. * @param n - The value to increment by.
  2494. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  2495. * `updateDoc()`
  2496. */
  2497. export declare function increment(n: number): FieldValue;
  2498. /**
  2499. * The SDK definition of a Firestore index.
  2500. * @beta
  2501. */
  2502. export declare interface Index {
  2503. /** The ID of the collection to index. */
  2504. readonly collectionGroup: string;
  2505. /** A list of fields to index. */
  2506. readonly fields?: IndexField[];
  2507. [key: string]: unknown;
  2508. }
  2509. /**
  2510. * A list of Firestore indexes to speed up local query execution.
  2511. *
  2512. * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}
  2513. * for a description of the format of the index definition.
  2514. * @beta
  2515. */
  2516. export declare interface IndexConfiguration {
  2517. /** A list of all Firestore indexes. */
  2518. readonly indexes?: Index[];
  2519. [key: string]: unknown;
  2520. }
  2521. /**
  2522. * A single field element in an index configuration.
  2523. * @beta
  2524. */
  2525. export declare interface IndexField {
  2526. /** The field path to index. */
  2527. readonly fieldPath: string;
  2528. /**
  2529. * What type of array index to create. Set to `CONTAINS` for `array-contains`
  2530. * and `array-contains-any` indexes.
  2531. *
  2532. * Only one of `arrayConfig` or `order` should be set;
  2533. */
  2534. readonly arrayConfig?: 'CONTAINS';
  2535. /**
  2536. * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for
  2537. * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.
  2538. *
  2539. * Only one of `arrayConfig` or `order` should be set.
  2540. */
  2541. readonly order?: 'ASCENDING' | 'DESCENDING';
  2542. [key: string]: unknown;
  2543. }
  2544. declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
  2545. /** The type of the index, e.g. for which type of query it can be used. */
  2546. declare const enum IndexKind {
  2547. /**
  2548. * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.
  2549. */
  2550. ASCENDING = 0,
  2551. /**
  2552. * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.
  2553. */
  2554. DESCENDING = 1,
  2555. /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */
  2556. CONTAINS = 2
  2557. }
  2558. /**
  2559. * Represents a set of indexes that are used to execute queries efficiently.
  2560. *
  2561. * Currently the only index is a [collection id] =&gt; [parent path] index, used
  2562. * to execute Collection Group queries.
  2563. */
  2564. declare interface IndexManager {
  2565. /**
  2566. * Creates an index entry mapping the collectionId (last segment of the path)
  2567. * to the parent path (either the containing document location or the empty
  2568. * path for root-level collections). Index entries can be retrieved via
  2569. * getCollectionParents().
  2570. *
  2571. * NOTE: Currently we don't remove index entries. If this ends up being an
  2572. * issue we can devise some sort of GC strategy.
  2573. */
  2574. addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: _ResourcePath): PersistencePromise<void>;
  2575. /**
  2576. * Retrieves all parent locations containing the given collectionId, as a
  2577. * list of paths (each path being either a document location or the empty
  2578. * path for a root-level collection).
  2579. */
  2580. getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise<_ResourcePath[]>;
  2581. /**
  2582. * Adds a field path index.
  2583. *
  2584. * Values for this index are persisted via the index backfill, which runs
  2585. * asynchronously in the background. Once the first values are written,
  2586. * an index can be used to serve partial results for any matching queries.
  2587. * Any unindexed portion of the database will continue to be served via
  2588. * collection scons.
  2589. */
  2590. addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise<void>;
  2591. /** Removes the given field index and deletes all index values. */
  2592. deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise<void>;
  2593. /**
  2594. * Returns a list of field indexes that correspond to the specified collection
  2595. * group.
  2596. *
  2597. * @param collectionGroup The collection group to get matching field indexes
  2598. * for.
  2599. * @return A collection of field indexes for the specified collection group.
  2600. */
  2601. getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise<FieldIndex[]>;
  2602. /** Returns all configured field indexes. */
  2603. getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise<FieldIndex[]>;
  2604. /**
  2605. * Returns the type of index (if any) that can be used to serve the given
  2606. * target.
  2607. */
  2608. getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise<IndexType>;
  2609. /**
  2610. * Returns the documents that match the given target based on the provided
  2611. * index or `null` if the target does not have a matching index.
  2612. */
  2613. getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise<_DocumentKey[] | null>;
  2614. /**
  2615. * Returns the next collection group to update. Returns `null` if no group
  2616. * exists.
  2617. */
  2618. getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise<string | null>;
  2619. /**
  2620. * Sets the collection group's latest read time.
  2621. *
  2622. * This method updates the index offset for all field indices for the
  2623. * collection group and increments their sequence number. Subsequent calls to
  2624. * `getNextCollectionGroupToUpdate()` will return a different collection group
  2625. * (unless only one collection group is configured).
  2626. */
  2627. updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise<void>;
  2628. /** Updates the index entries for the provided documents. */
  2629. updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise<void>;
  2630. /**
  2631. * Iterates over all field indexes that are used to serve the given target,
  2632. * and returns the minimum offset of them all.
  2633. */
  2634. getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise<IndexOffset>;
  2635. /** Returns the minimum offset for the given collection group. */
  2636. getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise<IndexOffset>;
  2637. }
  2638. /**
  2639. * Stores the latest read time, document and batch ID that were processed for an
  2640. * index.
  2641. */
  2642. declare class IndexOffset {
  2643. /**
  2644. * The latest read time version that has been indexed by Firestore for this
  2645. * field index.
  2646. */
  2647. readonly readTime: SnapshotVersion;
  2648. /**
  2649. * The key of the last document that was indexed for this query. Use
  2650. * `DocumentKey.empty()` if no document has been indexed.
  2651. */
  2652. readonly documentKey: _DocumentKey;
  2653. readonly largestBatchId: number;
  2654. constructor(
  2655. /**
  2656. * The latest read time version that has been indexed by Firestore for this
  2657. * field index.
  2658. */
  2659. readTime: SnapshotVersion,
  2660. /**
  2661. * The key of the last document that was indexed for this query. Use
  2662. * `DocumentKey.empty()` if no document has been indexed.
  2663. */
  2664. documentKey: _DocumentKey, largestBatchId: number);
  2665. /** Returns an offset that sorts before all regular offsets. */
  2666. static min(): IndexOffset;
  2667. /** Returns an offset that sorts after all regular offsets. */
  2668. static max(): IndexOffset;
  2669. }
  2670. /** An index component consisting of field path and index type. */
  2671. declare class IndexSegment {
  2672. /** The field path of the component. */
  2673. readonly fieldPath: _FieldPath;
  2674. /** The fields sorting order. */
  2675. readonly kind: IndexKind;
  2676. constructor(
  2677. /** The field path of the component. */
  2678. fieldPath: _FieldPath,
  2679. /** The fields sorting order. */
  2680. kind: IndexKind);
  2681. }
  2682. declare type IndexState = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR';
  2683. /**
  2684. * Stores the "high water mark" that indicates how updated the Index is for the
  2685. * current user.
  2686. */
  2687. declare class IndexState_2 {
  2688. /**
  2689. * Indicates when the index was last updated (relative to other indexes).
  2690. */
  2691. readonly sequenceNumber: number;
  2692. /** The the latest indexed read time, document and batch id. */
  2693. readonly offset: IndexOffset;
  2694. constructor(
  2695. /**
  2696. * Indicates when the index was last updated (relative to other indexes).
  2697. */
  2698. sequenceNumber: number,
  2699. /** The the latest indexed read time, document and batch id. */
  2700. offset: IndexOffset);
  2701. /** The state of an index that has not yet been backfilled. */
  2702. static empty(): IndexState_2;
  2703. }
  2704. /** Represents the index state as it relates to a particular target. */
  2705. declare const enum IndexType {
  2706. /** Indicates that no index could be found for serving the target. */
  2707. NONE = 0,
  2708. /**
  2709. * Indicates that only a "partial index" could be found for serving the
  2710. * target. A partial index is one which does not have a segment for every
  2711. * filter/orderBy in the target.
  2712. */
  2713. PARTIAL = 1,
  2714. /**
  2715. * Indicates that a "full index" could be found for serving the target. A full
  2716. * index is one which has a segment for every filter/orderBy in the target.
  2717. */
  2718. FULL = 2
  2719. }
  2720. /**
  2721. * Initializes a new instance of {@link Firestore} with the provided settings.
  2722. * Can only be called before any other function, including
  2723. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  2724. * equivalent to calling {@link (getFirestore:1)}.
  2725. *
  2726. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  2727. * be associated.
  2728. * @param settings - A settings object to configure the {@link Firestore} instance.
  2729. * @param databaseId - The name of database.
  2730. * @returns A newly initialized {@link Firestore} instance.
  2731. */
  2732. export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore;
  2733. /**
  2734. * True if and only if the Base64 conversion functions are available.
  2735. * @internal
  2736. */
  2737. export declare function _isBase64Available(): boolean;
  2738. /**
  2739. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  2740. * documents.
  2741. *
  2742. * @param limit - The maximum number of items to return.
  2743. * @returns The created {@link QueryLimitConstraint}.
  2744. */
  2745. export declare function limit(limit: number): QueryLimitConstraint;
  2746. /**
  2747. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  2748. * documents.
  2749. *
  2750. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  2751. * otherwise an exception will be thrown during execution.
  2752. *
  2753. * @param limit - The maximum number of items to return.
  2754. * @returns The created {@link QueryLimitConstraint}.
  2755. */
  2756. export declare function limitToLast(limit: number): QueryLimitConstraint;
  2757. declare const enum LimitType {
  2758. First = "F",
  2759. Last = "L"
  2760. }
  2761. /** LimitType enum. */
  2762. declare type LimitType_2 = 'FIRST' | 'LAST';
  2763. declare type ListenSequenceNumber = number;
  2764. declare class LLRBEmptyNode<K, V> {
  2765. get key(): never;
  2766. get value(): never;
  2767. get color(): never;
  2768. get left(): never;
  2769. get right(): never;
  2770. size: number;
  2771. copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBEmptyNode<K, V>;
  2772. insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
  2773. remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V>;
  2774. isEmpty(): boolean;
  2775. inorderTraversal(action: (k: K, v: V) => boolean): boolean;
  2776. reverseTraversal(action: (k: K, v: V) => boolean): boolean;
  2777. minKey(): K | null;
  2778. maxKey(): K | null;
  2779. isRed(): boolean;
  2780. checkMaxDepth(): boolean;
  2781. protected check(): 0;
  2782. }
  2783. declare class LLRBNode<K, V> {
  2784. key: K;
  2785. value: V;
  2786. readonly color: boolean;
  2787. readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  2788. readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  2789. readonly size: number;
  2790. static EMPTY: LLRBEmptyNode<any, any>;
  2791. static RED: boolean;
  2792. static BLACK: boolean;
  2793. constructor(key: K, value: V, color?: boolean, left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>, right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>);
  2794. copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBNode<K, V>;
  2795. isEmpty(): boolean;
  2796. inorderTraversal<T>(action: (k: K, v: V) => T): T;
  2797. reverseTraversal<T>(action: (k: K, v: V) => T): T;
  2798. private min;
  2799. minKey(): K | null;
  2800. maxKey(): K | null;
  2801. insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
  2802. private removeMin;
  2803. remove(key: K, comparator: Comparator<K>): LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  2804. isRed(): boolean;
  2805. private fixUp;
  2806. private moveRedLeft;
  2807. private moveRedRight;
  2808. private rotateLeft;
  2809. private rotateRight;
  2810. private colorFlip;
  2811. checkMaxDepth(): boolean;
  2812. protected check(): number;
  2813. }
  2814. /**
  2815. * Loads a Firestore bundle into the local cache.
  2816. *
  2817. * @param firestore - The {@link Firestore} instance to load bundles for.
  2818. * @param bundleData - An object representing the bundle to be loaded. Valid
  2819. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  2820. *
  2821. * @returns A `LoadBundleTask` object, which notifies callers with progress
  2822. * updates, and completion or error events. It can be used as a
  2823. * `Promise<LoadBundleTaskProgress>`.
  2824. */
  2825. export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string): LoadBundleTask;
  2826. /**
  2827. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  2828. * loading, as well as task completion and error events.
  2829. *
  2830. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  2831. */
  2832. export declare class LoadBundleTask implements PromiseLike<LoadBundleTaskProgress> {
  2833. private _progressObserver;
  2834. private _taskCompletionResolver;
  2835. private _lastProgress;
  2836. /**
  2837. * Registers functions to listen to bundle loading progress events.
  2838. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  2839. * each time a Firestore document is loaded from the bundle.
  2840. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  2841. * error, and there should be no more updates after this.
  2842. * @param complete - Called when the loading task is complete.
  2843. */
  2844. onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void;
  2845. /**
  2846. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  2847. *
  2848. * @param onRejected - Called when an error occurs during bundle loading.
  2849. */
  2850. catch<R>(onRejected: (a: Error) => R | PromiseLike<R>): Promise<R | LoadBundleTaskProgress>;
  2851. /**
  2852. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  2853. *
  2854. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  2855. * The update will always have its `taskState` set to `"Success"`.
  2856. * @param onRejected - Called when an error occurs during bundle loading.
  2857. */
  2858. then<T, R>(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike<T>, onRejected?: (a: Error) => R | PromiseLike<R>): Promise<T | R>;
  2859. /**
  2860. * Notifies all observers that bundle loading has completed, with a provided
  2861. * `LoadBundleTaskProgress` object.
  2862. *
  2863. * @private
  2864. */
  2865. _completeWith(progress: LoadBundleTaskProgress): void;
  2866. /**
  2867. * Notifies all observers that bundle loading has failed, with a provided
  2868. * `Error` as the reason.
  2869. *
  2870. * @private
  2871. */
  2872. _failWith(error: FirestoreError): void;
  2873. /**
  2874. * Notifies a progress update of loading a bundle.
  2875. * @param progress - The new progress.
  2876. *
  2877. * @private
  2878. */
  2879. _updateProgress(progress: LoadBundleTaskProgress): void;
  2880. }
  2881. /**
  2882. * Represents a progress update or a final state from loading bundles.
  2883. */
  2884. export declare interface LoadBundleTaskProgress {
  2885. /** How many documents have been loaded. */
  2886. documentsLoaded: number;
  2887. /** How many documents are in the bundle being loaded. */
  2888. totalDocuments: number;
  2889. /** How many bytes have been loaded. */
  2890. bytesLoaded: number;
  2891. /** How many bytes are in the bundle being loaded. */
  2892. totalBytes: number;
  2893. /** Current task state. */
  2894. taskState: TaskState;
  2895. }
  2896. /**
  2897. * A readonly view of the local state of all documents we're tracking (i.e. we
  2898. * have a cached version in remoteDocumentCache or local mutations for the
  2899. * document). The view is computed by applying the mutations in the
  2900. * MutationQueue to the RemoteDocumentCache.
  2901. */
  2902. declare class LocalDocumentsView {
  2903. readonly remoteDocumentCache: RemoteDocumentCache;
  2904. readonly mutationQueue: MutationQueue;
  2905. readonly documentOverlayCache: DocumentOverlayCache;
  2906. readonly indexManager: IndexManager;
  2907. constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager);
  2908. /**
  2909. * Get the local view of the document identified by `key`.
  2910. *
  2911. * @returns Local view of the document or null if we don't have any cached
  2912. * state for it.
  2913. */
  2914. getDocument(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<Document_2>;
  2915. /**
  2916. * Gets the local view of the documents identified by `keys`.
  2917. *
  2918. * If we don't have cached state for a document in `keys`, a NoDocument will
  2919. * be stored for that key in the resulting set.
  2920. */
  2921. getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise<DocumentMap>;
  2922. /**
  2923. * Similar to `getDocuments`, but creates the local view from the given
  2924. * `baseDocs` without retrieving documents from the local store.
  2925. *
  2926. * @param transaction - The transaction this operation is scoped to.
  2927. * @param docs - The documents to apply local mutations to get the local views.
  2928. * @param existenceStateChanged - The set of document keys whose existence state
  2929. * is changed. This is useful to determine if some documents overlay needs
  2930. * to be recalculated.
  2931. */
  2932. getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise<DocumentMap>;
  2933. /**
  2934. * Gets the overlayed documents for the given document map, which will include
  2935. * the local view of those documents and a `FieldMask` indicating which fields
  2936. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  2937. */
  2938. getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise<OverlayedDocumentMap>;
  2939. /**
  2940. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  2941. * if the map does not already contain an entry for the given document key.
  2942. */
  2943. private populateOverlays;
  2944. /**
  2945. * Computes the local view for the given documents.
  2946. *
  2947. * @param docs - The documents to compute views for. It also has the base
  2948. * version of the documents.
  2949. * @param overlays - The overlays that need to be applied to the given base
  2950. * version of the documents.
  2951. * @param existenceStateChanged - A set of documents whose existence states
  2952. * might have changed. This is used to determine if we need to re-calculate
  2953. * overlays from mutation queues.
  2954. * @return A map represents the local documents view.
  2955. */
  2956. computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise<OverlayedDocumentMap>;
  2957. private recalculateAndSaveOverlays;
  2958. /**
  2959. * Recalculates overlays by reading the documents from remote document cache
  2960. * first, and saves them after they are calculated.
  2961. */
  2962. recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<DocumentKeyMap<FieldMask | null>>;
  2963. /**
  2964. * Performs a query against the local view of all documents.
  2965. *
  2966. * @param transaction - The persistence transaction.
  2967. * @param query - The query to match documents against.
  2968. * @param offset - Read time and key to start scanning by (exclusive).
  2969. */
  2970. getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset): PersistencePromise<DocumentMap>;
  2971. /**
  2972. * Given a collection group, returns the next documents that follow the provided offset, along
  2973. * with an updated batch ID.
  2974. *
  2975. * <p>The documents returned by this method are ordered by remote version from the provided
  2976. * offset. If there are no more remote documents after the provided offset, documents with
  2977. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  2978. * returned together, the total number of documents returned can exceed {@code count}.
  2979. *
  2980. * @param transaction
  2981. * @param collectionGroup The collection group for the documents.
  2982. * @param offset The offset to index into.
  2983. * @param count The number of documents to return
  2984. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  2985. */
  2986. getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise<LocalWriteResult>;
  2987. private getDocumentsMatchingDocumentQuery;
  2988. private getDocumentsMatchingCollectionGroupQuery;
  2989. private getDocumentsMatchingCollectionQuery;
  2990. }
  2991. declare interface LocalStore {
  2992. collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults>;
  2993. /** Manages the list of active field and collection indices. */
  2994. indexManager: IndexManager;
  2995. /**
  2996. * The "local" view of all documents (layering mutationQueue on top of
  2997. * remoteDocumentCache).
  2998. */
  2999. localDocuments: LocalDocumentsView;
  3000. }
  3001. /** The result of a write to the local store. */
  3002. declare interface LocalWriteResult {
  3003. batchId: BatchId;
  3004. changes: DocumentMap;
  3005. }
  3006. export { LogLevel }
  3007. /**
  3008. * @internal
  3009. */
  3010. export declare function _logWarn(msg: string, ...obj: unknown[]): void;
  3011. declare interface LruGarbageCollector {
  3012. readonly params: LruParams;
  3013. collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise<LruResults>;
  3014. /** Given a percentile of target to collect, returns the number of targets to collect. */
  3015. calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise<number>;
  3016. /** Returns the nth sequence number, counting in order from the smallest. */
  3017. nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise<number>;
  3018. /**
  3019. * Removes documents that have a sequence number equal to or less than the
  3020. * upper bound and are not otherwise pinned.
  3021. */
  3022. removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise<number>;
  3023. getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;
  3024. /**
  3025. * Removes targets with a sequence number equal to or less than the given
  3026. * upper bound, and removes document associations with those targets.
  3027. */
  3028. removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise<number>;
  3029. }
  3030. declare class LruParams {
  3031. readonly cacheSizeCollectionThreshold: number;
  3032. readonly percentileToCollect: number;
  3033. readonly maximumSequenceNumbersToCollect: number;
  3034. private static readonly DEFAULT_COLLECTION_PERCENTILE;
  3035. private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT;
  3036. static withCacheSize(cacheSize: number): LruParams;
  3037. static readonly DEFAULT: LruParams;
  3038. static readonly DISABLED: LruParams;
  3039. constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number);
  3040. }
  3041. /**
  3042. * Describes the results of a garbage collection run. `didRun` will be set to
  3043. * `false` if collection was skipped (either it is disabled or the cache size
  3044. * has not hit the threshold). If collection ran, the other fields will be
  3045. * filled in with the details of the results.
  3046. */
  3047. declare interface LruResults {
  3048. readonly didRun: boolean;
  3049. readonly sequenceNumbersCollected: number;
  3050. readonly targetsRemoved: number;
  3051. readonly documentsRemoved: number;
  3052. }
  3053. declare type MapValue = firestoreV1ApiClientInterfaces.MapValue;
  3054. /**
  3055. * Represents a document in Firestore with a key, version, data and whether it
  3056. * has local mutations applied to it.
  3057. *
  3058. * Documents can transition between states via `convertToFoundDocument()`,
  3059. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3060. * not transition to one of these states even after all mutations have been
  3061. * applied, `isValidDocument()` returns false and the document should be removed
  3062. * from all views.
  3063. */
  3064. declare class MutableDocument implements Document_2 {
  3065. readonly key: _DocumentKey;
  3066. private documentType;
  3067. version: SnapshotVersion;
  3068. readTime: SnapshotVersion;
  3069. createTime: SnapshotVersion;
  3070. data: ObjectValue;
  3071. private documentState;
  3072. private constructor();
  3073. /**
  3074. * Creates a document with no known version or data, but which can serve as
  3075. * base document for mutations.
  3076. */
  3077. static newInvalidDocument(documentKey: _DocumentKey): MutableDocument;
  3078. /**
  3079. * Creates a new document that is known to exist with the given data at the
  3080. * given version.
  3081. */
  3082. static newFoundDocument(documentKey: _DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument;
  3083. /** Creates a new document that is known to not exist at the given version. */
  3084. static newNoDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument;
  3085. /**
  3086. * Creates a new document that is known to exist at the given version but
  3087. * whose data is not known (e.g. a document that was updated without a known
  3088. * base document).
  3089. */
  3090. static newUnknownDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument;
  3091. /**
  3092. * Changes the document type to indicate that it exists and that its version
  3093. * and data are known.
  3094. */
  3095. convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument;
  3096. /**
  3097. * Changes the document type to indicate that it doesn't exist at the given
  3098. * version.
  3099. */
  3100. convertToNoDocument(version: SnapshotVersion): MutableDocument;
  3101. /**
  3102. * Changes the document type to indicate that it exists at a given version but
  3103. * that its data is not known (e.g. a document that was updated without a known
  3104. * base document).
  3105. */
  3106. convertToUnknownDocument(version: SnapshotVersion): MutableDocument;
  3107. setHasCommittedMutations(): MutableDocument;
  3108. setHasLocalMutations(): MutableDocument;
  3109. setReadTime(readTime: SnapshotVersion): MutableDocument;
  3110. get hasLocalMutations(): boolean;
  3111. get hasCommittedMutations(): boolean;
  3112. get hasPendingWrites(): boolean;
  3113. isValidDocument(): boolean;
  3114. isFoundDocument(): boolean;
  3115. isNoDocument(): boolean;
  3116. isUnknownDocument(): boolean;
  3117. isEqual(other: Document_2 | null | undefined): boolean;
  3118. mutableCopy(): MutableDocument;
  3119. toString(): string;
  3120. }
  3121. /** Miscellaneous collection types / constants. */
  3122. declare type MutableDocumentMap = SortedMap<_DocumentKey, MutableDocument>;
  3123. /**
  3124. * A mutation describes a self-contained change to a document. Mutations can
  3125. * create, replace, delete, and update subsets of documents.
  3126. *
  3127. * Mutations not only act on the value of the document but also its version.
  3128. *
  3129. * For local mutations (mutations that haven't been committed yet), we preserve
  3130. * the existing version for Set and Patch mutations. For Delete mutations, we
  3131. * reset the version to 0.
  3132. *
  3133. * Here's the expected transition table.
  3134. *
  3135. * MUTATION APPLIED TO RESULTS IN
  3136. *
  3137. * SetMutation Document(v3) Document(v3)
  3138. * SetMutation NoDocument(v3) Document(v0)
  3139. * SetMutation InvalidDocument(v0) Document(v0)
  3140. * PatchMutation Document(v3) Document(v3)
  3141. * PatchMutation NoDocument(v3) NoDocument(v3)
  3142. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  3143. * DeleteMutation Document(v3) NoDocument(v0)
  3144. * DeleteMutation NoDocument(v3) NoDocument(v0)
  3145. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  3146. *
  3147. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  3148. * the resulting version for Set and Patch mutations. As deletes have no
  3149. * explicit update time, we use the commitTime of the WriteResponse for
  3150. * Delete mutations.
  3151. *
  3152. * If a mutation is acknowledged by the backend but fails the precondition check
  3153. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  3154. * the updated version.
  3155. *
  3156. * Field transforms are used only with Patch and Set Mutations. We use the
  3157. * `updateTransforms` message to store transforms, rather than the `transforms`s
  3158. * messages.
  3159. *
  3160. * ## Subclassing Notes
  3161. *
  3162. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  3163. * applyToLocalView() to implement the actual behavior of applying the mutation
  3164. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  3165. * example).
  3166. */
  3167. declare abstract class Mutation {
  3168. abstract readonly type: MutationType;
  3169. abstract readonly key: _DocumentKey;
  3170. abstract readonly precondition: Precondition;
  3171. abstract readonly fieldTransforms: FieldTransform[];
  3172. /**
  3173. * Returns a `FieldMask` representing the fields that will be changed by
  3174. * applying this mutation. Returns `null` if the mutation will overwrite the
  3175. * entire document.
  3176. */
  3177. abstract getFieldMask(): FieldMask | null;
  3178. }
  3179. /**
  3180. * A batch of mutations that will be sent as one unit to the backend.
  3181. */
  3182. declare class MutationBatch {
  3183. batchId: BatchId;
  3184. localWriteTime: Timestamp;
  3185. baseMutations: Mutation[];
  3186. mutations: Mutation[];
  3187. /**
  3188. * @param batchId - The unique ID of this mutation batch.
  3189. * @param localWriteTime - The original write time of this mutation.
  3190. * @param baseMutations - Mutations that are used to populate the base
  3191. * values when this mutation is applied locally. This can be used to locally
  3192. * overwrite values that are persisted in the remote document cache. Base
  3193. * mutations are never sent to the backend.
  3194. * @param mutations - The user-provided mutations in this mutation batch.
  3195. * User-provided mutations are applied both locally and remotely on the
  3196. * backend.
  3197. */
  3198. constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]);
  3199. /**
  3200. * Applies all the mutations in this MutationBatch to the specified document
  3201. * to compute the state of the remote document
  3202. *
  3203. * @param document - The document to apply mutations to.
  3204. * @param batchResult - The result of applying the MutationBatch to the
  3205. * backend.
  3206. */
  3207. applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void;
  3208. /**
  3209. * Computes the local view of a document given all the mutations in this
  3210. * batch.
  3211. *
  3212. * @param document - The document to apply mutations to.
  3213. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  3214. * @returns A `FieldMask` representing all the fields that are mutated.
  3215. */
  3216. applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null;
  3217. /**
  3218. * Computes the local view for all provided documents given the mutations in
  3219. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  3220. * replace all the mutation applications.
  3221. */
  3222. applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap;
  3223. keys(): DocumentKeySet;
  3224. isEqual(other: MutationBatch): boolean;
  3225. }
  3226. /** The result of applying a mutation batch to the backend. */
  3227. declare class MutationBatchResult {
  3228. readonly batch: MutationBatch;
  3229. readonly commitVersion: SnapshotVersion;
  3230. readonly mutationResults: MutationResult[];
  3231. /**
  3232. * A pre-computed mapping from each mutated document to the resulting
  3233. * version.
  3234. */
  3235. readonly docVersions: DocumentVersionMap;
  3236. private constructor();
  3237. /**
  3238. * Creates a new MutationBatchResult for the given batch and results. There
  3239. * must be one result for each mutation in the batch. This static factory
  3240. * caches a document=&gt;version mapping (docVersions).
  3241. */
  3242. static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult;
  3243. }
  3244. declare type MutationMap = DocumentKeyMap<Mutation>;
  3245. /** A queue of mutations to apply to the remote store. */
  3246. declare interface MutationQueue {
  3247. /** Returns true if this queue contains no mutation batches. */
  3248. checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean>;
  3249. /**
  3250. * Creates a new mutation batch and adds it to this mutation queue.
  3251. *
  3252. * @param transaction - The transaction this operation is scoped to.
  3253. * @param localWriteTime - The original write time of this mutation.
  3254. * @param baseMutations - Mutations that are used to populate the base values
  3255. * when this mutation is applied locally. These mutations are used to locally
  3256. * overwrite values that are persisted in the remote document cache.
  3257. * @param mutations - The user-provided mutations in this mutation batch.
  3258. */
  3259. addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise<MutationBatch>;
  3260. /**
  3261. * Loads the mutation batch with the given batchId.
  3262. */
  3263. lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise<MutationBatch | null>;
  3264. /**
  3265. * Gets the first unacknowledged mutation batch after the passed in batchId
  3266. * in the mutation queue or null if empty.
  3267. *
  3268. * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the
  3269. * first mutation in the queue.
  3270. *
  3271. * @returns the next mutation or null if there wasn't one.
  3272. */
  3273. getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise<MutationBatch | null>;
  3274. /**
  3275. * Gets the largest (latest) batch id in mutation queue for the current user
  3276. * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is
  3277. * empty.
  3278. *
  3279. * @returns the largest batch id in the mutation queue that is not
  3280. * acknowledged.
  3281. */
  3282. getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise<BatchId>;
  3283. /** Gets all mutation batches in the mutation queue. */
  3284. getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise<MutationBatch[]>;
  3285. /**
  3286. * Finds all mutation batches that could possibly affect the given
  3287. * document key. Not all mutations in a batch will necessarily affect the
  3288. * document key, so when looping through the batch you'll need to check that
  3289. * the mutation itself matches the key.
  3290. *
  3291. * Batches are guaranteed to be in sorted order.
  3292. *
  3293. * Note that because of this requirement implementations are free to return
  3294. * mutation batches that don't contain the document key at all if it's
  3295. * convenient.
  3296. */
  3297. getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutationBatch[]>;
  3298. /**
  3299. * Finds all mutation batches that could possibly affect the given set of
  3300. * document keys. Not all mutations in a batch will necessarily affect each
  3301. * key, so when looping through the batch you'll need to check that the
  3302. * mutation itself matches the key.
  3303. *
  3304. * Batches are guaranteed to be in sorted order.
  3305. *
  3306. * Note that because of this requirement implementations are free to return
  3307. * mutation batches that don't contain any of the document keys at all if it's
  3308. * convenient.
  3309. */
  3310. getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap<_DocumentKey, unknown>): PersistencePromise<MutationBatch[]>;
  3311. /**
  3312. * Finds all mutation batches that could affect the results for the given
  3313. * query. Not all mutations in a batch will necessarily affect the query, so
  3314. * when looping through the batch you'll need to check that the mutation
  3315. * itself matches the query.
  3316. *
  3317. * Batches are guaranteed to be in sorted order.
  3318. *
  3319. * Note that because of this requirement implementations are free to return
  3320. * mutation batches that don't match the query at all if it's convenient.
  3321. *
  3322. * NOTE: A PatchMutation does not need to include all fields in the query
  3323. * filter criteria in order to be a match (but any fields it does contain do
  3324. * need to match).
  3325. */
  3326. getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise<MutationBatch[]>;
  3327. /**
  3328. * Removes the given mutation batch from the queue. This is useful in two
  3329. * circumstances:
  3330. *
  3331. * + Removing an applied mutation from the head of the queue
  3332. * + Removing a rejected mutation from anywhere in the queue
  3333. *
  3334. * Multi-Tab Note: This operation should only be called by the primary client.
  3335. */
  3336. removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise<void>;
  3337. /**
  3338. * Performs a consistency check, examining the mutation queue for any
  3339. * leaks, if possible.
  3340. */
  3341. performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise<void>;
  3342. }
  3343. /** The result of successfully applying a mutation to the backend. */
  3344. declare class MutationResult {
  3345. /**
  3346. * The version at which the mutation was committed:
  3347. *
  3348. * - For most operations, this is the updateTime in the WriteResult.
  3349. * - For deletes, the commitTime of the WriteResponse (because deletes are
  3350. * not stored and have no updateTime).
  3351. *
  3352. * Note that these versions can be different: No-op writes will not change
  3353. * the updateTime even though the commitTime advances.
  3354. */
  3355. readonly version: SnapshotVersion;
  3356. /**
  3357. * The resulting fields returned from the backend after a mutation
  3358. * containing field transforms has been committed. Contains one FieldValue
  3359. * for each FieldTransform that was in the mutation.
  3360. *
  3361. * Will be empty if the mutation did not contain any field transforms.
  3362. */
  3363. readonly transformResults: Array<Value | null>;
  3364. constructor(
  3365. /**
  3366. * The version at which the mutation was committed:
  3367. *
  3368. * - For most operations, this is the updateTime in the WriteResult.
  3369. * - For deletes, the commitTime of the WriteResponse (because deletes are
  3370. * not stored and have no updateTime).
  3371. *
  3372. * Note that these versions can be different: No-op writes will not change
  3373. * the updateTime even though the commitTime advances.
  3374. */
  3375. version: SnapshotVersion,
  3376. /**
  3377. * The resulting fields returned from the backend after a mutation
  3378. * containing field transforms has been committed. Contains one FieldValue
  3379. * for each FieldTransform that was in the mutation.
  3380. *
  3381. * Will be empty if the mutation did not contain any field transforms.
  3382. */
  3383. transformResults: Array<Value | null>);
  3384. }
  3385. declare const enum MutationType {
  3386. Set = 0,
  3387. Patch = 1,
  3388. Delete = 2,
  3389. Verify = 3
  3390. }
  3391. /**
  3392. * Represents a Query saved by the SDK in its local storage.
  3393. */
  3394. declare interface NamedQuery {
  3395. /** The name of the query. */
  3396. readonly name: string;
  3397. /** The underlying query associated with `name`. */
  3398. readonly query: Query_2;
  3399. /** The time at which the results for this query were read. */
  3400. readonly readTime: SnapshotVersion;
  3401. }
  3402. /**
  3403. * Reads a Firestore {@link Query} from local cache, identified by the given
  3404. * name.
  3405. *
  3406. * The named queries are packaged into bundles on the server side (along
  3407. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  3408. * in local cache, use this method to extract a {@link Query} by name.
  3409. *
  3410. * @param firestore - The {@link Firestore} instance to read the query from.
  3411. * @param name - The name of the query.
  3412. * @returns A `Promise` that is resolved with the Query or `null`.
  3413. */
  3414. export declare function namedQuery(firestore: Firestore, name: string): Promise<Query | null>;
  3415. /** Properties of a NamedQuery. */
  3416. declare interface NamedQuery_2 {
  3417. /** NamedQuery name */
  3418. name?: string | null;
  3419. /** NamedQuery bundledQuery */
  3420. bundledQuery?: BundledQuery | null;
  3421. /** NamedQuery readTime */
  3422. readTime?: Timestamp_2 | null;
  3423. }
  3424. /**
  3425. * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1,
  3426. * 'bar.qux': T2}). Intersect them together to make a single map containing
  3427. * all possible keys that are all marked as optional
  3428. */
  3429. export declare type NestedUpdateFields<T extends Record<string, unknown>> = UnionToIntersection<{
  3430. [K in keyof T & string]: ChildUpdateFields<K, T[K]>;
  3431. }[keyof T & string]>;
  3432. /**
  3433. * @license
  3434. * Copyright 2017 Google LLC
  3435. *
  3436. * Licensed under the Apache License, Version 2.0 (the "License");
  3437. * you may not use this file except in compliance with the License.
  3438. * You may obtain a copy of the License at
  3439. *
  3440. * http://www.apache.org/licenses/LICENSE-2.0
  3441. *
  3442. * Unless required by applicable law or agreed to in writing, software
  3443. * distributed under the License is distributed on an "AS IS" BASIS,
  3444. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3445. * See the License for the specific language governing permissions and
  3446. * limitations under the License.
  3447. */
  3448. /**
  3449. * A map implementation that uses objects as keys. Objects must have an
  3450. * associated equals function and must be immutable. Entries in the map are
  3451. * stored together with the key being produced from the mapKeyFn. This map
  3452. * automatically handles collisions of keys.
  3453. */
  3454. declare class ObjectMap<KeyType, ValueType> {
  3455. private mapKeyFn;
  3456. private equalsFn;
  3457. /**
  3458. * The inner map for a key/value pair. Due to the possibility of collisions we
  3459. * keep a list of entries that we do a linear search through to find an actual
  3460. * match. Note that collisions should be rare, so we still expect near
  3461. * constant time lookups in practice.
  3462. */
  3463. private inner;
  3464. /** The number of entries stored in the map */
  3465. private innerSize;
  3466. constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean);
  3467. /** Get a value for this key, or undefined if it does not exist. */
  3468. get(key: KeyType): ValueType | undefined;
  3469. has(key: KeyType): boolean;
  3470. /** Put this key and value in the map. */
  3471. set(key: KeyType, value: ValueType): void;
  3472. /**
  3473. * Remove this key from the map. Returns a boolean if anything was deleted.
  3474. */
  3475. delete(key: KeyType): boolean;
  3476. forEach(fn: (key: KeyType, val: ValueType) => void): void;
  3477. isEmpty(): boolean;
  3478. size(): number;
  3479. }
  3480. /**
  3481. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3482. * ability to add and remove fields (via the ObjectValueBuilder).
  3483. */
  3484. declare class ObjectValue {
  3485. readonly value: {
  3486. mapValue: MapValue;
  3487. };
  3488. constructor(value: {
  3489. mapValue: MapValue;
  3490. });
  3491. static empty(): ObjectValue;
  3492. /**
  3493. * Returns the value at the given path or null.
  3494. *
  3495. * @param path - the path to search
  3496. * @returns The value at the path or null if the path is not set.
  3497. */
  3498. field(path: _FieldPath): Value | null;
  3499. /**
  3500. * Sets the field to the provided value.
  3501. *
  3502. * @param path - The field path to set.
  3503. * @param value - The value to set.
  3504. */
  3505. set(path: _FieldPath, value: Value): void;
  3506. /**
  3507. * Sets the provided fields to the provided values.
  3508. *
  3509. * @param data - A map of fields to values (or null for deletes).
  3510. */
  3511. setAll(data: Map<_FieldPath, Value | null>): void;
  3512. /**
  3513. * Removes the field at the specified path. If there is no field at the
  3514. * specified path, nothing is changed.
  3515. *
  3516. * @param path - The field path to remove.
  3517. */
  3518. delete(path: _FieldPath): void;
  3519. isEqual(other: ObjectValue): boolean;
  3520. /**
  3521. * Returns the map that contains the leaf element of `path`. If the parent
  3522. * entry does not yet exist, or if it is not a map, a new map will be created.
  3523. */
  3524. private getFieldsMap;
  3525. /**
  3526. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3527. * entries.
  3528. */
  3529. private applyChanges;
  3530. clone(): ObjectValue;
  3531. }
  3532. /**
  3533. * Initializes and wires components that are needed to interface with the local
  3534. * cache. Implementations override `initialize()` to provide all components.
  3535. */
  3536. declare interface OfflineComponentProvider {
  3537. persistence: Persistence;
  3538. sharedClientState: SharedClientState;
  3539. localStore: LocalStore;
  3540. gcScheduler: Scheduler | null;
  3541. indexBackfillerScheduler: Scheduler | null;
  3542. synchronizeTabs: boolean;
  3543. initialize(cfg: ComponentConfiguration): Promise<void>;
  3544. terminate(): Promise<void>;
  3545. }
  3546. /**
  3547. * Initializes and wires the components that are needed to interface with the
  3548. * network.
  3549. */
  3550. declare class OnlineComponentProvider {
  3551. protected localStore: LocalStore;
  3552. protected sharedClientState: SharedClientState;
  3553. datastore: Datastore;
  3554. eventManager: EventManager;
  3555. remoteStore: RemoteStore;
  3556. syncEngine: SyncEngine;
  3557. initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise<void>;
  3558. createEventManager(cfg: ComponentConfiguration): EventManager;
  3559. createDatastore(cfg: ComponentConfiguration): Datastore;
  3560. createRemoteStore(cfg: ComponentConfiguration): RemoteStore;
  3561. createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine;
  3562. terminate(): Promise<void>;
  3563. }
  3564. /**
  3565. * Describes the online state of the Firestore client. Note that this does not
  3566. * indicate whether or not the remote store is trying to connect or not. This is
  3567. * primarily used by the View / EventManager code to change their behavior while
  3568. * offline (e.g. get() calls shouldn't wait for data from the server and
  3569. * snapshot events should set metadata.isFromCache=true).
  3570. *
  3571. * The string values should not be changed since they are persisted in
  3572. * WebStorage.
  3573. */
  3574. declare const enum OnlineState {
  3575. /**
  3576. * The Firestore client is in an unknown online state. This means the client
  3577. * is either not actively trying to establish a connection or it is currently
  3578. * trying to establish a connection, but it has not succeeded or failed yet.
  3579. * Higher-level components should not operate in offline mode.
  3580. */
  3581. Unknown = "Unknown",
  3582. /**
  3583. * The client is connected and the connections are healthy. This state is
  3584. * reached after a successful connection and there has been at least one
  3585. * successful message received from the backends.
  3586. */
  3587. Online = "Online",
  3588. /**
  3589. * The client is either trying to establish a connection but failing, or it
  3590. * has been explicitly marked offline via a call to disableNetwork().
  3591. * Higher-level components should operate in offline mode.
  3592. */
  3593. Offline = "Offline"
  3594. }
  3595. /**
  3596. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3597. * individual `onNext` and `onError` callbacks or pass a single observer
  3598. * object with `next` and `error` callbacks.
  3599. *
  3600. * NOTE: Although an `onCompletion` callback can be provided, it will
  3601. * never be called because the snapshot stream is never-ending.
  3602. *
  3603. * @param reference - A reference to the document to listen to.
  3604. * @param observer - A single object containing `next` and `error` callbacks.
  3605. * @returns An unsubscribe function that can be called to cancel
  3606. * the snapshot listener.
  3607. */
  3608. export declare function onSnapshot<T>(reference: DocumentReference<T>, observer: {
  3609. next?: (snapshot: DocumentSnapshot<T>) => void;
  3610. error?: (error: FirestoreError) => void;
  3611. complete?: () => void;
  3612. }): Unsubscribe;
  3613. /**
  3614. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3615. * individual `onNext` and `onError` callbacks or pass a single observer
  3616. * object with `next` and `error` callbacks.
  3617. *
  3618. * NOTE: Although an `onCompletion` callback can be provided, it will
  3619. * never be called because the snapshot stream is never-ending.
  3620. *
  3621. * @param reference - A reference to the document to listen to.
  3622. * @param options - Options controlling the listen behavior.
  3623. * @param observer - A single object containing `next` and `error` callbacks.
  3624. * @returns An unsubscribe function that can be called to cancel
  3625. * the snapshot listener.
  3626. */
  3627. export declare function onSnapshot<T>(reference: DocumentReference<T>, options: SnapshotListenOptions, observer: {
  3628. next?: (snapshot: DocumentSnapshot<T>) => void;
  3629. error?: (error: FirestoreError) => void;
  3630. complete?: () => void;
  3631. }): Unsubscribe;
  3632. /**
  3633. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3634. * individual `onNext` and `onError` callbacks or pass a single observer
  3635. * object with `next` and `error` callbacks.
  3636. *
  3637. * NOTE: Although an `onCompletion` callback can be provided, it will
  3638. * never be called because the snapshot stream is never-ending.
  3639. *
  3640. * @param reference - A reference to the document to listen to.
  3641. * @param onNext - A callback to be called every time a new `DocumentSnapshot`
  3642. * is available.
  3643. * @param onError - A callback to be called if the listen fails or is
  3644. * cancelled. No further callbacks will occur.
  3645. * @param onCompletion - Can be provided, but will not be called since streams are
  3646. * never ending.
  3647. * @returns An unsubscribe function that can be called to cancel
  3648. * the snapshot listener.
  3649. */
  3650. export declare function onSnapshot<T>(reference: DocumentReference<T>, onNext: (snapshot: DocumentSnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3651. /**
  3652. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3653. * individual `onNext` and `onError` callbacks or pass a single observer
  3654. * object with `next` and `error` callbacks.
  3655. *
  3656. * NOTE: Although an `onCompletion` callback can be provided, it will
  3657. * never be called because the snapshot stream is never-ending.
  3658. *
  3659. * @param reference - A reference to the document to listen to.
  3660. * @param options - Options controlling the listen behavior.
  3661. * @param onNext - A callback to be called every time a new `DocumentSnapshot`
  3662. * is available.
  3663. * @param onError - A callback to be called if the listen fails or is
  3664. * cancelled. No further callbacks will occur.
  3665. * @param onCompletion - Can be provided, but will not be called since streams are
  3666. * never ending.
  3667. * @returns An unsubscribe function that can be called to cancel
  3668. * the snapshot listener.
  3669. */
  3670. export declare function onSnapshot<T>(reference: DocumentReference<T>, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3671. /**
  3672. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3673. * individual `onNext` and `onError` callbacks or pass a single observer
  3674. * object with `next` and `error` callbacks. The listener can be cancelled by
  3675. * calling the function that is returned when `onSnapshot` is called.
  3676. *
  3677. * NOTE: Although an `onCompletion` callback can be provided, it will
  3678. * never be called because the snapshot stream is never-ending.
  3679. *
  3680. * @param query - The query to listen to.
  3681. * @param observer - A single object containing `next` and `error` callbacks.
  3682. * @returns An unsubscribe function that can be called to cancel
  3683. * the snapshot listener.
  3684. */
  3685. export declare function onSnapshot<T>(query: Query<T>, observer: {
  3686. next?: (snapshot: QuerySnapshot<T>) => void;
  3687. error?: (error: FirestoreError) => void;
  3688. complete?: () => void;
  3689. }): Unsubscribe;
  3690. /**
  3691. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3692. * individual `onNext` and `onError` callbacks or pass a single observer
  3693. * object with `next` and `error` callbacks. The listener can be cancelled by
  3694. * calling the function that is returned when `onSnapshot` is called.
  3695. *
  3696. * NOTE: Although an `onCompletion` callback can be provided, it will
  3697. * never be called because the snapshot stream is never-ending.
  3698. *
  3699. * @param query - The query to listen to.
  3700. * @param options - Options controlling the listen behavior.
  3701. * @param observer - A single object containing `next` and `error` callbacks.
  3702. * @returns An unsubscribe function that can be called to cancel
  3703. * the snapshot listener.
  3704. */
  3705. export declare function onSnapshot<T>(query: Query<T>, options: SnapshotListenOptions, observer: {
  3706. next?: (snapshot: QuerySnapshot<T>) => void;
  3707. error?: (error: FirestoreError) => void;
  3708. complete?: () => void;
  3709. }): Unsubscribe;
  3710. /**
  3711. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3712. * individual `onNext` and `onError` callbacks or pass a single observer
  3713. * object with `next` and `error` callbacks. The listener can be cancelled by
  3714. * calling the function that is returned when `onSnapshot` is called.
  3715. *
  3716. * NOTE: Although an `onCompletion` callback can be provided, it will
  3717. * never be called because the snapshot stream is never-ending.
  3718. *
  3719. * @param query - The query to listen to.
  3720. * @param onNext - A callback to be called every time a new `QuerySnapshot`
  3721. * is available.
  3722. * @param onCompletion - Can be provided, but will not be called since streams are
  3723. * never ending.
  3724. * @param onError - A callback to be called if the listen fails or is
  3725. * cancelled. No further callbacks will occur.
  3726. * @returns An unsubscribe function that can be called to cancel
  3727. * the snapshot listener.
  3728. */
  3729. export declare function onSnapshot<T>(query: Query<T>, onNext: (snapshot: QuerySnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3730. /**
  3731. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3732. * individual `onNext` and `onError` callbacks or pass a single observer
  3733. * object with `next` and `error` callbacks. The listener can be cancelled by
  3734. * calling the function that is returned when `onSnapshot` is called.
  3735. *
  3736. * NOTE: Although an `onCompletion` callback can be provided, it will
  3737. * never be called because the snapshot stream is never-ending.
  3738. *
  3739. * @param query - The query to listen to.
  3740. * @param options - Options controlling the listen behavior.
  3741. * @param onNext - A callback to be called every time a new `QuerySnapshot`
  3742. * is available.
  3743. * @param onCompletion - Can be provided, but will not be called since streams are
  3744. * never ending.
  3745. * @param onError - A callback to be called if the listen fails or is
  3746. * cancelled. No further callbacks will occur.
  3747. * @returns An unsubscribe function that can be called to cancel
  3748. * the snapshot listener.
  3749. */
  3750. export declare function onSnapshot<T>(query: Query<T>, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3751. /**
  3752. * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
  3753. * event indicates that all listeners affected by a given change have fired,
  3754. * even if a single server-generated change affects multiple listeners.
  3755. *
  3756. * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
  3757. * with each other, but does not relate to whether those snapshots are in sync
  3758. * with the server. Use SnapshotMetadata in the individual listeners to
  3759. * determine if a snapshot is from the cache or the server.
  3760. *
  3761. * @param firestore - The instance of Firestore for synchronizing snapshots.
  3762. * @param observer - A single object containing `next` and `error` callbacks.
  3763. * @returns An unsubscribe function that can be called to cancel the snapshot
  3764. * listener.
  3765. */
  3766. export declare function onSnapshotsInSync(firestore: Firestore, observer: {
  3767. next?: (value: void) => void;
  3768. error?: (error: FirestoreError) => void;
  3769. complete?: () => void;
  3770. }): Unsubscribe;
  3771. /**
  3772. * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
  3773. * event indicates that all listeners affected by a given change have fired,
  3774. * even if a single server-generated change affects multiple listeners.
  3775. *
  3776. * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
  3777. * with each other, but does not relate to whether those snapshots are in sync
  3778. * with the server. Use `SnapshotMetadata` in the individual listeners to
  3779. * determine if a snapshot is from the cache or the server.
  3780. *
  3781. * @param firestore - The `Firestore` instance for synchronizing snapshots.
  3782. * @param onSync - A callback to be called every time all snapshot listeners are
  3783. * in sync with each other.
  3784. * @returns An unsubscribe function that can be called to cancel the snapshot
  3785. * listener.
  3786. */
  3787. export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe;
  3788. declare const enum Operator {
  3789. LESS_THAN = "<",
  3790. LESS_THAN_OR_EQUAL = "<=",
  3791. EQUAL = "==",
  3792. NOT_EQUAL = "!=",
  3793. GREATER_THAN = ">",
  3794. GREATER_THAN_OR_EQUAL = ">=",
  3795. ARRAY_CONTAINS = "array-contains",
  3796. IN = "in",
  3797. NOT_IN = "not-in",
  3798. ARRAY_CONTAINS_ANY = "array-contains-any"
  3799. }
  3800. /**
  3801. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  3802. * the given filter constraints. A disjunction filter includes a document if it
  3803. * satisfies any of the given filters.
  3804. *
  3805. * @param queryConstraints - Optional. The list of
  3806. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  3807. * created with calls to {@link where}, {@link or}, or {@link and}.
  3808. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  3809. * @internal TODO remove this internal tag with OR Query support in the server
  3810. */
  3811. export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;
  3812. /**
  3813. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  3814. */
  3815. declare class OrderBy {
  3816. readonly field: _FieldPath;
  3817. readonly dir: Direction;
  3818. constructor(field: _FieldPath, dir?: Direction);
  3819. }
  3820. /**
  3821. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  3822. * specified field, optionally in descending order instead of ascending.
  3823. *
  3824. * Note: Documents that do not contain the specified field will not be present
  3825. * in the query result.
  3826. *
  3827. * @param fieldPath - The field to sort by.
  3828. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  3829. * not specified, order will be ascending.
  3830. * @returns The created {@link QueryOrderByConstraint}.
  3831. */
  3832. export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint;
  3833. /**
  3834. * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'
  3835. * (descending or ascending).
  3836. */
  3837. export declare type OrderByDirection = 'desc' | 'asc';
  3838. declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
  3839. /**
  3840. * Representation of an overlay computed by Firestore.
  3841. *
  3842. * Holds information about a mutation and the largest batch id in Firestore when
  3843. * the mutation was created.
  3844. */
  3845. declare class Overlay {
  3846. readonly largestBatchId: number;
  3847. readonly mutation: Mutation;
  3848. constructor(largestBatchId: number, mutation: Mutation);
  3849. getKey(): _DocumentKey;
  3850. isEqual(other: Overlay | null): boolean;
  3851. toString(): string;
  3852. }
  3853. /**
  3854. * Represents a local view (overlay) of a document, and the fields that are
  3855. * locally mutated.
  3856. */
  3857. declare class OverlayedDocument {
  3858. readonly overlayedDocument: Document_2;
  3859. /**
  3860. * The fields that are locally mutated by patch mutations.
  3861. *
  3862. * If the overlayed document is from set or delete mutations, this is `null`.
  3863. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  3864. */
  3865. readonly mutatedFields: FieldMask | null;
  3866. constructor(overlayedDocument: Document_2,
  3867. /**
  3868. * The fields that are locally mutated by patch mutations.
  3869. *
  3870. * If the overlayed document is from set or delete mutations, this is `null`.
  3871. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  3872. */
  3873. mutatedFields: FieldMask | null);
  3874. }
  3875. declare type OverlayedDocumentMap = DocumentKeyMap<OverlayedDocument>;
  3876. declare type OverlayMap = DocumentKeyMap<Overlay>;
  3877. declare interface ParseContext {
  3878. readonly databaseId: _DatabaseId;
  3879. readonly ignoreUndefinedProperties: boolean;
  3880. }
  3881. /** The result of parsing document data (e.g. for a setData call). */
  3882. declare class ParsedSetData {
  3883. readonly data: ObjectValue;
  3884. readonly fieldMask: FieldMask | null;
  3885. readonly fieldTransforms: FieldTransform[];
  3886. constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]);
  3887. toMutation(key: _DocumentKey, precondition: Precondition): Mutation;
  3888. }
  3889. /** The result of parsing "update" data (i.e. for an updateData call). */
  3890. declare class ParsedUpdateData {
  3891. readonly data: ObjectValue;
  3892. readonly fieldMask: FieldMask;
  3893. readonly fieldTransforms: FieldTransform[];
  3894. constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]);
  3895. toMutation(key: _DocumentKey, precondition: Precondition): Mutation;
  3896. }
  3897. /**
  3898. * Similar to Typescript's `Partial<T>`, but allows nested fields to be
  3899. * omitted and FieldValues to be passed in as property values.
  3900. */
  3901. export declare type PartialWithFieldValue<T> = Partial<T> | (T extends Primitive ? T : T extends {} ? {
  3902. [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue;
  3903. } : never);
  3904. /**
  3905. * Persistence is the lowest-level shared interface to persistent storage in
  3906. * Firestore.
  3907. *
  3908. * Persistence is used to create MutationQueue and RemoteDocumentCache
  3909. * instances backed by persistence (which might be in-memory or LevelDB).
  3910. *
  3911. * Persistence also exposes an API to create and run PersistenceTransactions
  3912. * against persistence. All read / write operations must be wrapped in a
  3913. * transaction. Implementations of PersistenceTransaction / Persistence only
  3914. * need to guarantee that writes made against the transaction are not made to
  3915. * durable storage until the transaction resolves its PersistencePromise.
  3916. * Since memory-only storage components do not alter durable storage, they are
  3917. * free to ignore the transaction.
  3918. *
  3919. * This contract is enough to allow the LocalStore be be written
  3920. * independently of whether or not the stored state actually is durably
  3921. * persisted. If persistent storage is enabled, writes are grouped together to
  3922. * avoid inconsistent state that could cause crashes.
  3923. *
  3924. * Concretely, when persistent storage is enabled, the persistent versions of
  3925. * MutationQueue, RemoteDocumentCache, and others (the mutators) will
  3926. * defer their writes into a transaction. Once the local store has completed
  3927. * one logical operation, it commits the transaction.
  3928. *
  3929. * When persistent storage is disabled, the non-persistent versions of the
  3930. * mutators ignore the transaction. This short-cut is allowed because
  3931. * memory-only storage leaves no state so it cannot be inconsistent.
  3932. *
  3933. * This simplifies the implementations of the mutators and allows memory-only
  3934. * implementations to supplement the persistent ones without requiring any
  3935. * special dual-store implementation of Persistence. The cost is that the
  3936. * LocalStore needs to be slightly careful about the order of its reads and
  3937. * writes in order to avoid relying on being able to read back uncommitted
  3938. * writes.
  3939. */
  3940. declare interface Persistence {
  3941. /**
  3942. * Whether or not this persistence instance has been started.
  3943. */
  3944. readonly started: boolean;
  3945. readonly referenceDelegate: ReferenceDelegate;
  3946. /** Starts persistence. */
  3947. start(): Promise<void>;
  3948. /**
  3949. * Releases any resources held during eager shutdown.
  3950. */
  3951. shutdown(): Promise<void>;
  3952. /**
  3953. * Registers a listener that gets called when the database receives a
  3954. * version change event indicating that it has deleted.
  3955. *
  3956. * PORTING NOTE: This is only used for Web multi-tab.
  3957. */
  3958. setDatabaseDeletedListener(databaseDeletedListener: () => Promise<void>): void;
  3959. /**
  3960. * Adjusts the current network state in the client's metadata, potentially
  3961. * affecting the primary lease.
  3962. *
  3963. * PORTING NOTE: This is only used for Web multi-tab.
  3964. */
  3965. setNetworkEnabled(networkEnabled: boolean): void;
  3966. /**
  3967. * Returns a MutationQueue representing the persisted mutations for the
  3968. * given user.
  3969. *
  3970. * Note: The implementation is free to return the same instance every time
  3971. * this is called for a given user. In particular, the memory-backed
  3972. * implementation does this to emulate the persisted implementation to the
  3973. * extent possible (e.g. in the case of uid switching from
  3974. * sally=&gt;jack=&gt;sally, sally's mutation queue will be preserved).
  3975. */
  3976. getMutationQueue(user: User, indexManager: IndexManager): MutationQueue;
  3977. /**
  3978. * Returns a TargetCache representing the persisted cache of targets.
  3979. *
  3980. * Note: The implementation is free to return the same instance every time
  3981. * this is called. In particular, the memory-backed implementation does this
  3982. * to emulate the persisted implementation to the extent possible.
  3983. */
  3984. getTargetCache(): TargetCache;
  3985. /**
  3986. * Returns a RemoteDocumentCache representing the persisted cache of remote
  3987. * documents.
  3988. *
  3989. * Note: The implementation is free to return the same instance every time
  3990. * this is called. In particular, the memory-backed implementation does this
  3991. * to emulate the persisted implementation to the extent possible.
  3992. */
  3993. getRemoteDocumentCache(): RemoteDocumentCache;
  3994. /**
  3995. * Returns a BundleCache representing the persisted cache of loaded bundles.
  3996. *
  3997. * Note: The implementation is free to return the same instance every time
  3998. * this is called. In particular, the memory-backed implementation does this
  3999. * to emulate the persisted implementation to the extent possible.
  4000. */
  4001. getBundleCache(): BundleCache;
  4002. /**
  4003. * Returns an IndexManager instance that manages our persisted query indexes.
  4004. *
  4005. * Note: The implementation is free to return the same instance every time
  4006. * this is called. In particular, the memory-backed implementation does this
  4007. * to emulate the persisted implementation to the extent possible.
  4008. */
  4009. getIndexManager(user: User): IndexManager;
  4010. /**
  4011. * Returns a DocumentOverlayCache representing the documents that are mutated
  4012. * locally.
  4013. */
  4014. getDocumentOverlayCache(user: User): DocumentOverlayCache;
  4015. /**
  4016. * Performs an operation inside a persistence transaction. Any reads or writes
  4017. * against persistence must be performed within a transaction. Writes will be
  4018. * committed atomically once the transaction completes.
  4019. *
  4020. * Persistence operations are asynchronous and therefore the provided
  4021. * transactionOperation must return a PersistencePromise. When it is resolved,
  4022. * the transaction will be committed and the Promise returned by this method
  4023. * will resolve.
  4024. *
  4025. * @param action - A description of the action performed by this transaction,
  4026. * used for logging.
  4027. * @param mode - The underlying mode of the IndexedDb transaction. Can be
  4028. * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked
  4029. * 'readwrite-primary' can only be executed by the primary client. In this
  4030. * mode, the transactionOperation will not be run if the primary lease cannot
  4031. * be acquired and the returned promise will be rejected with a
  4032. * FAILED_PRECONDITION error.
  4033. * @param transactionOperation - The operation to run inside a transaction.
  4034. * @returns A `Promise` that is resolved once the transaction completes.
  4035. */
  4036. runTransaction<T>(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise<T>): Promise<T>;
  4037. }
  4038. /**
  4039. * PersistencePromise is essentially a re-implementation of Promise except
  4040. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  4041. * are executed synchronously when a PersistencePromise resolves rather than
  4042. * asynchronously (Promise implementations use setImmediate() or similar).
  4043. *
  4044. * This is necessary to interoperate with IndexedDB which will automatically
  4045. * commit transactions if control is returned to the event loop without
  4046. * synchronously initiating another operation on the transaction.
  4047. *
  4048. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  4049. * Promises.
  4050. */
  4051. declare class PersistencePromise<T> {
  4052. private nextCallback;
  4053. private catchCallback;
  4054. private result;
  4055. private error;
  4056. private isDone;
  4057. private callbackAttached;
  4058. constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void);
  4059. catch<R>(fn: (error: Error) => R | PersistencePromise<R>): PersistencePromise<R>;
  4060. next<R>(nextFn?: FulfilledHandler<T, R>, catchFn?: RejectedHandler<R>): PersistencePromise<R>;
  4061. toPromise(): Promise<T>;
  4062. private wrapUserFunction;
  4063. private wrapSuccess;
  4064. private wrapFailure;
  4065. static resolve(): PersistencePromise<void>;
  4066. static resolve<R>(result: R): PersistencePromise<R>;
  4067. static reject<R>(error: Error): PersistencePromise<R>;
  4068. static waitFor(all: {
  4069. forEach: (cb: (el: PersistencePromise<any>) => void) => void;
  4070. }): PersistencePromise<void>;
  4071. /**
  4072. * Given an array of predicate functions that asynchronously evaluate to a
  4073. * boolean, implements a short-circuiting `or` between the results. Predicates
  4074. * will be evaluated until one of them returns `true`, then stop. The final
  4075. * result will be whether any of them returned `true`.
  4076. */
  4077. static or(predicates: Array<() => PersistencePromise<boolean>>): PersistencePromise<boolean>;
  4078. /**
  4079. * Given an iterable, call the given function on each element in the
  4080. * collection and wait for all of the resulting concurrent PersistencePromises
  4081. * to resolve.
  4082. */
  4083. static forEach<R, S>(collection: {
  4084. forEach: (cb: (r: R, s: S) => void) => void;
  4085. }, f: ((r: R, s: S) => PersistencePromise<void>) | ((r: R) => PersistencePromise<void>)): PersistencePromise<void>;
  4086. static forEach<R>(collection: {
  4087. forEach: (cb: (r: R) => void) => void;
  4088. }, f: (r: R) => PersistencePromise<void>): PersistencePromise<void>;
  4089. /**
  4090. * Concurrently map all array elements through asynchronous function.
  4091. */
  4092. static mapArray<T, U>(array: T[], f: (t: T) => PersistencePromise<U>): PersistencePromise<U[]>;
  4093. /**
  4094. * An alternative to recursive PersistencePromise calls, that avoids
  4095. * potential memory problems from unbounded chains of promises.
  4096. *
  4097. * The `action` will be called repeatedly while `condition` is true.
  4098. */
  4099. static doWhile(condition: () => boolean, action: () => PersistencePromise<void>): PersistencePromise<void>;
  4100. }
  4101. /**
  4102. * Settings that can be passed to `enableIndexedDbPersistence()` to configure
  4103. * Firestore persistence.
  4104. */
  4105. export declare interface PersistenceSettings {
  4106. /**
  4107. * Whether to force enable persistence for the client. This cannot be used
  4108. * with multi-tab synchronization and is primarily intended for use with Web
  4109. * Workers. Setting this to `true` will enable persistence, but cause other
  4110. * tabs using persistence to fail.
  4111. */
  4112. forceOwnership?: boolean;
  4113. }
  4114. /**
  4115. * A base class representing a persistence transaction, encapsulating both the
  4116. * transaction's sequence numbers as well as a list of onCommitted listeners.
  4117. *
  4118. * When you call Persistence.runTransaction(), it will create a transaction and
  4119. * pass it to your callback. You then pass it to any method that operates
  4120. * on persistence.
  4121. */
  4122. declare abstract class PersistenceTransaction {
  4123. private readonly onCommittedListeners;
  4124. abstract readonly currentSequenceNumber: ListenSequenceNumber;
  4125. addOnCommittedListener(listener: () => void): void;
  4126. raiseOnCommittedEvent(): void;
  4127. }
  4128. /** The different modes supported by `Persistence.runTransaction()`. */
  4129. declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary';
  4130. /**
  4131. * Encodes a precondition for a mutation. This follows the model that the
  4132. * backend accepts with the special case of an explicit "empty" precondition
  4133. * (meaning no precondition).
  4134. */
  4135. declare class Precondition {
  4136. readonly updateTime?: SnapshotVersion | undefined;
  4137. readonly exists?: boolean | undefined;
  4138. private constructor();
  4139. /** Creates a new empty Precondition. */
  4140. static none(): Precondition;
  4141. /** Creates a new Precondition with an exists flag. */
  4142. static exists(exists: boolean): Precondition;
  4143. /** Creates a new Precondition based on a version a document exists at. */
  4144. static updateTime(version: SnapshotVersion): Precondition;
  4145. /** Returns whether this Precondition is empty. */
  4146. get isNone(): boolean;
  4147. isEqual(other: Precondition): boolean;
  4148. }
  4149. /**
  4150. * These types primarily exist to support the `UpdateData`,
  4151. * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed
  4152. * directly by the end developer.
  4153. */
  4154. /** Primitive types. */
  4155. export declare type Primitive = string | number | boolean | undefined | null;
  4156. /** Undocumented, private additional settings not exposed in our public API. */
  4157. declare interface PrivateSettings extends FirestoreSettings_2 {
  4158. credentials?: CredentialsSettings;
  4159. cacheSizeBytes?: number;
  4160. experimentalForceLongPolling?: boolean;
  4161. experimentalAutoDetectLongPolling?: boolean;
  4162. useFetchStreams?: boolean;
  4163. }
  4164. declare interface ProviderCredentialsSettings {
  4165. ['type']: 'provider';
  4166. ['client']: CredentialsProvider<User>;
  4167. }
  4168. /**
  4169. * A `Query` refers to a query which you can read or listen to. You can also
  4170. * construct refined `Query` objects by adding filters and ordering.
  4171. */
  4172. export declare class Query<T = DocumentData> {
  4173. /**
  4174. * If provided, the `FirestoreDataConverter` associated with this instance.
  4175. */
  4176. readonly converter: FirestoreDataConverter_2<T> | null;
  4177. readonly _query: Query_2;
  4178. /** The type of this Firestore reference. */
  4179. readonly type: 'query' | 'collection';
  4180. /**
  4181. * The `Firestore` instance for the Firestore database (useful for performing
  4182. * transactions, etc.).
  4183. */
  4184. readonly firestore: Firestore_2;
  4185. /** @hideconstructor protected */
  4186. constructor(firestore: Firestore_2,
  4187. /**
  4188. * If provided, the `FirestoreDataConverter` associated with this instance.
  4189. */
  4190. converter: FirestoreDataConverter_2<T> | null, _query: Query_2);
  4191. /**
  4192. * Removes the current converter.
  4193. *
  4194. * @param converter - `null` removes the current converter.
  4195. * @returns A `Query<DocumentData>` that does not use a converter.
  4196. */
  4197. withConverter(converter: null): Query<DocumentData>;
  4198. /**
  4199. * Applies a custom data converter to this query, allowing you to use your own
  4200. * custom model objects with Firestore. When you call {@link getDocs} with
  4201. * the returned query, the provided converter will convert between Firestore
  4202. * data and your custom type `U`.
  4203. *
  4204. * @param converter - Converts objects to and from Firestore.
  4205. * @returns A `Query<U>` that uses the provided converter.
  4206. */
  4207. withConverter<U>(converter: FirestoreDataConverter_2<U>): Query<U>;
  4208. }
  4209. /**
  4210. * Creates a new immutable instance of {@link Query} that is extended to also
  4211. * include additional query constraints.
  4212. *
  4213. * @param query - The {@link Query} instance to use as a base for the new
  4214. * constraints.
  4215. * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to
  4216. * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or
  4217. * {@link or}.
  4218. * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to
  4219. * apply (e.g. {@link orderBy}, {@link limit}).
  4220. * @throws if any of the provided query constraints cannot be combined with the
  4221. * existing or new constraints.
  4222. * @internal TODO remove this internal tag with OR Query support in the server
  4223. */
  4224. export declare function query<T>(query: Query<T>, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query<T>;
  4225. /**
  4226. * Creates a new immutable instance of {@link Query} that is extended to also
  4227. * include additional query constraints.
  4228. *
  4229. * @param query - The {@link Query} instance to use as a base for the new
  4230. * constraints.
  4231. * @param queryConstraints - The list of {@link QueryConstraint}s to apply.
  4232. * @throws if any of the provided query constraints cannot be combined with the
  4233. * existing or new constraints.
  4234. */
  4235. export declare function query<T>(query: Query<T>, ...queryConstraints: QueryConstraint[]): Query<T>;
  4236. /**
  4237. * The Query interface defines all external properties of a query.
  4238. *
  4239. * QueryImpl implements this interface to provide memoization for `queryOrderBy`
  4240. * and `queryToTarget`.
  4241. */
  4242. declare interface Query_2 {
  4243. readonly path: _ResourcePath;
  4244. readonly collectionGroup: string | null;
  4245. readonly explicitOrderBy: OrderBy[];
  4246. readonly filters: Filter[];
  4247. readonly limit: number | null;
  4248. readonly limitType: LimitType;
  4249. readonly startAt: Bound | null;
  4250. readonly endAt: Bound | null;
  4251. }
  4252. /**
  4253. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  4254. * returned by a Firestore query by performing the logical OR or AND of multiple
  4255. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  4256. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  4257. * {@link and} and can then be passed to {@link query} to create a new query
  4258. * instance that also contains the `QueryCompositeFilterConstraint`.
  4259. * @internal TODO remove this internal tag with OR Query support in the server
  4260. */
  4261. export declare class QueryCompositeFilterConstraint extends AppliableConstraint {
  4262. /** The type of this query constraint */
  4263. readonly type: 'or' | 'and';
  4264. private readonly _queryConstraints;
  4265. /**
  4266. * @internal
  4267. */
  4268. protected constructor(
  4269. /** The type of this query constraint */
  4270. type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]);
  4271. static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;
  4272. _parse<T>(query: Query<T>): Filter;
  4273. _apply<T>(query: Query<T>): Query<T>;
  4274. _getQueryConstraints(): readonly AppliableConstraint[];
  4275. _getOperator(): CompositeOperator;
  4276. }
  4277. /**
  4278. * A `QueryConstraint` is used to narrow the set of documents returned by a
  4279. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  4280. * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
  4281. * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
  4282. * can then be passed to {@link query} to create a new query instance that
  4283. * also contains this `QueryConstraint`.
  4284. */
  4285. export declare abstract class QueryConstraint extends AppliableConstraint {
  4286. /** The type of this query constraint */
  4287. abstract readonly type: QueryConstraintType;
  4288. /**
  4289. * Takes the provided {@link Query} and returns a copy of the {@link Query} with this
  4290. * {@link AppliableConstraint} applied.
  4291. */
  4292. abstract _apply<T>(query: Query<T>): Query<T>;
  4293. }
  4294. /** Describes the different query constraints available in this SDK. */
  4295. export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore';
  4296. /**
  4297. * A `QueryDocumentSnapshot` contains data read from a document in your
  4298. * Firestore database as part of a query. The document is guaranteed to exist
  4299. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  4300. * specific field.
  4301. *
  4302. * A `QueryDocumentSnapshot` offers the same API surface as a
  4303. * `DocumentSnapshot`. Since query results contain only existing documents, the
  4304. * `exists` property will always be true and `data()` will never return
  4305. * 'undefined'.
  4306. */
  4307. export declare class QueryDocumentSnapshot<T = DocumentData> extends DocumentSnapshot<T> {
  4308. /**
  4309. * Retrieves all fields in the document as an `Object`.
  4310. *
  4311. * By default, `serverTimestamp()` values that have not yet been
  4312. * set to their final value will be returned as `null`. You can override
  4313. * this by passing an options object.
  4314. *
  4315. * @override
  4316. * @param options - An options object to configure how data is retrieved from
  4317. * the snapshot (for example the desired behavior for server timestamps that
  4318. * have not yet been set to their final value).
  4319. * @returns An `Object` containing all fields in the document.
  4320. */
  4321. data(options?: SnapshotOptions): T;
  4322. }
  4323. /**
  4324. * A `QueryDocumentSnapshot` contains data read from a document in your
  4325. * Firestore database as part of a query. The document is guaranteed to exist
  4326. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  4327. * specific field.
  4328. *
  4329. * A `QueryDocumentSnapshot` offers the same API surface as a
  4330. * `DocumentSnapshot`. Since query results contain only existing documents, the
  4331. * `exists` property will always be true and `data()` will never return
  4332. * 'undefined'.
  4333. */
  4334. declare class QueryDocumentSnapshot_2<T = DocumentData> extends DocumentSnapshot_2<T> {
  4335. /**
  4336. * Retrieves all fields in the document as an `Object`.
  4337. *
  4338. * @override
  4339. * @returns An `Object` containing all fields in the document.
  4340. */
  4341. data(): T;
  4342. }
  4343. /**
  4344. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  4345. * result set returned by a Firestore query.
  4346. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  4347. * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
  4348. * query instance that also contains this `QueryEndAtConstraint`.
  4349. */
  4350. export declare class QueryEndAtConstraint extends QueryConstraint {
  4351. /** The type of this query constraint */
  4352. readonly type: 'endBefore' | 'endAt';
  4353. private readonly _docOrFields;
  4354. private readonly _inclusive;
  4355. /**
  4356. * @internal
  4357. */
  4358. protected constructor(
  4359. /** The type of this query constraint */
  4360. type: 'endBefore' | 'endAt', _docOrFields: Array<unknown | DocumentSnapshot_2<unknown>>, _inclusive: boolean);
  4361. static _create(type: 'endBefore' | 'endAt', _docOrFields: Array<unknown | DocumentSnapshot_2<unknown>>, _inclusive: boolean): QueryEndAtConstraint;
  4362. _apply<T>(query: Query<T>): Query<T>;
  4363. }
  4364. /**
  4365. * Returns true if the provided queries point to the same collection and apply
  4366. * the same constraints.
  4367. *
  4368. * @param left - A `Query` to compare.
  4369. * @param right - A `Query` to compare.
  4370. * @returns true if the references point to the same location in the same
  4371. * Firestore database.
  4372. */
  4373. export declare function queryEqual<T>(left: Query<T>, right: Query<T>): boolean;
  4374. /**
  4375. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  4376. * a Firestore query by filtering on one or more document fields.
  4377. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  4378. * be passed to {@link query} to create a new query instance that also contains
  4379. * this `QueryFieldFilterConstraint`.
  4380. */
  4381. export declare class QueryFieldFilterConstraint extends QueryConstraint {
  4382. private readonly _field;
  4383. private _op;
  4384. private _value;
  4385. /** The type of this query constraint */
  4386. readonly type = "where";
  4387. /**
  4388. * @internal
  4389. */
  4390. protected constructor(_field: _FieldPath, _op: Operator, _value: unknown);
  4391. static _create(_field: _FieldPath, _op: Operator, _value: unknown): QueryFieldFilterConstraint;
  4392. _apply<T>(query: Query<T>): Query<T>;
  4393. _parse<T>(query: Query<T>): FieldFilter;
  4394. }
  4395. /**
  4396. * `QueryFilterConstraint` is a helper union type that represents
  4397. * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.
  4398. * `QueryFilterConstraint`s are created by invoking {@link or} or {@link and}
  4399. * and can then be passed to {@link query} to create a new query instance that
  4400. * also contains the `QueryConstraint`.
  4401. * @internal TODO remove this internal tag with OR Query support in the server
  4402. */
  4403. export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint;
  4404. /**
  4405. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  4406. * a Firestore query.
  4407. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  4408. * {@link limitToLast} and can then be passed to {@link query} to create a new
  4409. * query instance that also contains this `QueryLimitConstraint`.
  4410. */
  4411. export declare class QueryLimitConstraint extends QueryConstraint {
  4412. /** The type of this query constraint */
  4413. readonly type: 'limit' | 'limitToLast';
  4414. private readonly _limit;
  4415. private readonly _limitType;
  4416. /**
  4417. * @internal
  4418. */
  4419. protected constructor(
  4420. /** The type of this query constraint */
  4421. type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType);
  4422. static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint;
  4423. _apply<T>(query: Query<T>): Query<T>;
  4424. }
  4425. /**
  4426. * `QueryNonFilterConstraint` is a helper union type that represents
  4427. * QueryConstraints which are used to narrow or order the set of documents,
  4428. * but that do not explicitly filter on a document field.
  4429. * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},
  4430. * {@link startAt}, {@link startAfter}, {@link endBefore}, {@link endAt},
  4431. * {@link limit} or {@link limitToLast} and can then be passed to {@link query}
  4432. * to create a new query instance that also contains the `QueryConstraint`.
  4433. */
  4434. export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint;
  4435. /**
  4436. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  4437. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  4438. * {@link orderBy} and can then be passed to {@link query} to create a new query
  4439. * instance that also contains this `QueryOrderByConstraint`.
  4440. *
  4441. * Note: Documents that do not contain the orderBy field will not be present in
  4442. * the query result.
  4443. */
  4444. export declare class QueryOrderByConstraint extends QueryConstraint {
  4445. private readonly _field;
  4446. private _direction;
  4447. /** The type of this query constraint */
  4448. readonly type = "orderBy";
  4449. /**
  4450. * @internal
  4451. */
  4452. protected constructor(_field: _FieldPath, _direction: Direction);
  4453. static _create(_field: _FieldPath, _direction: Direction): QueryOrderByConstraint;
  4454. _apply<T>(query: Query<T>): Query<T>;
  4455. }
  4456. /**
  4457. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  4458. * representing the results of a query. The documents can be accessed as an
  4459. * array via the `docs` property or enumerated using the `forEach` method. The
  4460. * number of documents can be determined via the `empty` and `size`
  4461. * properties.
  4462. */
  4463. export declare class QuerySnapshot<T = DocumentData> {
  4464. readonly _firestore: Firestore;
  4465. readonly _userDataWriter: AbstractUserDataWriter;
  4466. readonly _snapshot: ViewSnapshot;
  4467. /**
  4468. * Metadata about this snapshot, concerning its source and if it has local
  4469. * modifications.
  4470. */
  4471. readonly metadata: SnapshotMetadata;
  4472. /**
  4473. * The query on which you called `get` or `onSnapshot` in order to get this
  4474. * `QuerySnapshot`.
  4475. */
  4476. readonly query: Query<T>;
  4477. private _cachedChanges?;
  4478. private _cachedChangesIncludeMetadataChanges?;
  4479. /** @hideconstructor */
  4480. constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query<T>, _snapshot: ViewSnapshot);
  4481. /** An array of all the documents in the `QuerySnapshot`. */
  4482. get docs(): Array<QueryDocumentSnapshot<T>>;
  4483. /** The number of documents in the `QuerySnapshot`. */
  4484. get size(): number;
  4485. /** True if there are no documents in the `QuerySnapshot`. */
  4486. get empty(): boolean;
  4487. /**
  4488. * Enumerates all of the documents in the `QuerySnapshot`.
  4489. *
  4490. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  4491. * each document in the snapshot.
  4492. * @param thisArg - The `this` binding for the callback.
  4493. */
  4494. forEach(callback: (result: QueryDocumentSnapshot<T>) => void, thisArg?: unknown): void;
  4495. /**
  4496. * Returns an array of the documents changes since the last snapshot. If this
  4497. * is the first snapshot, all documents will be in the list as 'added'
  4498. * changes.
  4499. *
  4500. * @param options - `SnapshotListenOptions` that control whether metadata-only
  4501. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  4502. * snapshot events.
  4503. */
  4504. docChanges(options?: SnapshotListenOptions): Array<DocumentChange<T>>;
  4505. }
  4506. /**
  4507. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  4508. * result set returned by a Firestore query.
  4509. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  4510. * {@link (startAfter:1)} and can then be passed to {@link query} to create a
  4511. * new query instance that also contains this `QueryStartAtConstraint`.
  4512. */
  4513. export declare class QueryStartAtConstraint extends QueryConstraint {
  4514. /** The type of this query constraint */
  4515. readonly type: 'startAt' | 'startAfter';
  4516. private readonly _docOrFields;
  4517. private readonly _inclusive;
  4518. /**
  4519. * @internal
  4520. */
  4521. protected constructor(
  4522. /** The type of this query constraint */
  4523. type: 'startAt' | 'startAfter', _docOrFields: Array<unknown | DocumentSnapshot_2<unknown>>, _inclusive: boolean);
  4524. static _create(type: 'startAt' | 'startAfter', _docOrFields: Array<unknown | DocumentSnapshot_2<unknown>>, _inclusive: boolean): QueryStartAtConstraint;
  4525. _apply<T>(query: Query<T>): Query<T>;
  4526. }
  4527. /** The different states of a watch target. */
  4528. declare type QueryTargetState = 'not-current' | 'current' | 'rejected';
  4529. /**
  4530. * Returns true if the provided references are equal.
  4531. *
  4532. * @param left - A reference to compare.
  4533. * @param right - A reference to compare.
  4534. * @returns true if the references point to the same location in the same
  4535. * Firestore database.
  4536. */
  4537. export declare function refEqual<T>(left: DocumentReference<T> | CollectionReference<T>, right: DocumentReference<T> | CollectionReference<T>): boolean;
  4538. /**
  4539. * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This
  4540. * includes being added to a target, being removed from a target, being subject to mutation, and
  4541. * being mutated by the user.
  4542. *
  4543. * Different implementations may do different things with each of these events. Not every
  4544. * implementation needs to do something with every lifecycle hook.
  4545. *
  4546. * PORTING NOTE: since sequence numbers are attached to transactions in this
  4547. * client, the ReferenceDelegate does not need to deal in transactional
  4548. * semantics (onTransactionStarted/Committed()), nor does it need to track and
  4549. * generate sequence numbers (getCurrentSequenceNumber()).
  4550. */
  4551. declare interface ReferenceDelegate {
  4552. /** Notify the delegate that the given document was added to a target. */
  4553. addReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise<void>;
  4554. /** Notify the delegate that the given document was removed from a target. */
  4555. removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise<void>;
  4556. /**
  4557. * Notify the delegate that a target was removed. The delegate may, but is not obligated to,
  4558. * actually delete the target and associated data.
  4559. */
  4560. removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  4561. /**
  4562. * Notify the delegate that a document may no longer be part of any views or
  4563. * have any mutations associated.
  4564. */
  4565. markPotentiallyOrphaned(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise<void>;
  4566. /** Notify the delegate that a limbo document was updated. */
  4567. updateLimboDocument(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise<void>;
  4568. }
  4569. declare type RejectedHandler<R> = ((reason: Error) => R | PersistencePromise<R>) | null;
  4570. declare type Rejector = (error: Error) => void;
  4571. /**
  4572. * Represents cached documents received from the remote backend.
  4573. *
  4574. * The cache is keyed by DocumentKey and entries in the cache are
  4575. * MutableDocuments, meaning we can cache both actual documents as well as
  4576. * documents that are known to not exist.
  4577. */
  4578. declare interface RemoteDocumentCache {
  4579. /** Sets the index manager to use for managing the collectionGroup index. */
  4580. setIndexManager(indexManager: IndexManager): void;
  4581. /**
  4582. * Looks up an entry in the cache.
  4583. *
  4584. * @param documentKey - The key of the entry to look up.*
  4585. * @returns The cached document entry. Returns an invalid document if the
  4586. * document is not cached.
  4587. */
  4588. getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
  4589. /**
  4590. * Looks up a set of entries in the cache.
  4591. *
  4592. * @param documentKeys - The keys of the entries to look up.
  4593. * @returns The cached document entries indexed by key. If an entry is not
  4594. * cached, the corresponding key will be mapped to an invalid document.
  4595. */
  4596. getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
  4597. /**
  4598. * Returns the documents from the provided collection.
  4599. *
  4600. * @param collection - The collection to read.
  4601. * @param offset - The offset to start the scan at (exclusive).
  4602. * @returns The set of matching documents.
  4603. */
  4604. getAllFromCollection(transaction: PersistenceTransaction, collection: _ResourcePath, offset: IndexOffset): PersistencePromise<MutableDocumentMap>;
  4605. /**
  4606. * Looks up the next `limit` documents for a collection group based on the
  4607. * provided offset. The ordering is based on the document's read time and key.
  4608. *
  4609. * @param collectionGroup - The collection group to scan.
  4610. * @param offset - The offset to start the scan at (exclusive).
  4611. * @param limit - The maximum number of results to return.
  4612. * @returns The set of matching documents.
  4613. */
  4614. getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise<MutableDocumentMap>;
  4615. /**
  4616. * Provides access to add or update the contents of the cache. The buffer
  4617. * handles proper size accounting for the change.
  4618. *
  4619. * Multi-Tab Note: This should only be called by the primary client.
  4620. *
  4621. * @param options - Specify `trackRemovals` to create sentinel entries for
  4622. * removed documents, which allows removals to be tracked by
  4623. * `getNewDocumentChanges()`.
  4624. */
  4625. newChangeBuffer(options?: {
  4626. trackRemovals: boolean;
  4627. }): RemoteDocumentChangeBuffer;
  4628. /**
  4629. * Get an estimate of the size of the document cache. Note that for eager
  4630. * garbage collection, we don't track sizes so this will return 0.
  4631. */
  4632. getSize(transaction: PersistenceTransaction): PersistencePromise<number>;
  4633. }
  4634. /**
  4635. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  4636. * It can be used to batch up a set of changes to be written to the cache, but
  4637. * additionally supports reading entries back with the `getEntry()` method,
  4638. * falling back to the underlying RemoteDocumentCache if no entry is
  4639. * buffered.
  4640. *
  4641. * Entries added to the cache *must* be read first. This is to facilitate
  4642. * calculating the size delta of the pending changes.
  4643. *
  4644. * PORTING NOTE: This class was implemented then removed from other platforms.
  4645. * If byte-counting ends up being needed on the other platforms, consider
  4646. * porting this class as part of that implementation work.
  4647. */
  4648. declare abstract class RemoteDocumentChangeBuffer {
  4649. protected changes: ObjectMap<_DocumentKey, MutableDocument>;
  4650. private changesApplied;
  4651. protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
  4652. protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
  4653. protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise<void>;
  4654. /**
  4655. * Buffers a `RemoteDocumentCache.addEntry()` call.
  4656. *
  4657. * You can only modify documents that have already been retrieved via
  4658. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  4659. */
  4660. addEntry(document: MutableDocument): void;
  4661. /**
  4662. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  4663. *
  4664. * You can only remove documents that have already been retrieved via
  4665. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  4666. */
  4667. removeEntry(key: _DocumentKey, readTime: SnapshotVersion): void;
  4668. /**
  4669. * Looks up an entry in the cache. The buffered changes will first be checked,
  4670. * and if no buffered change applies, this will forward to
  4671. * `RemoteDocumentCache.getEntry()`.
  4672. *
  4673. * @param transaction - The transaction in which to perform any persistence
  4674. * operations.
  4675. * @param documentKey - The key of the entry to look up.
  4676. * @returns The cached document or an invalid document if we have nothing
  4677. * cached.
  4678. */
  4679. getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
  4680. /**
  4681. * Looks up several entries in the cache, forwarding to
  4682. * `RemoteDocumentCache.getEntry()`.
  4683. *
  4684. * @param transaction - The transaction in which to perform any persistence
  4685. * operations.
  4686. * @param documentKeys - The keys of the entries to look up.
  4687. * @returns A map of cached documents, indexed by key. If an entry cannot be
  4688. * found, the corresponding key will be mapped to an invalid document.
  4689. */
  4690. getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
  4691. /**
  4692. * Applies buffered changes to the underlying RemoteDocumentCache, using
  4693. * the provided transaction.
  4694. */
  4695. apply(transaction: PersistenceTransaction): PersistencePromise<void>;
  4696. /** Helper to assert this.changes is not null */
  4697. protected assertNotApplied(): void;
  4698. }
  4699. /**
  4700. * An event from the RemoteStore. It is split into targetChanges (changes to the
  4701. * state or the set of documents in our watched targets) and documentUpdates
  4702. * (changes to the actual documents).
  4703. */
  4704. declare class RemoteEvent {
  4705. /**
  4706. * The snapshot version this event brings us up to, or MIN if not set.
  4707. */
  4708. readonly snapshotVersion: SnapshotVersion;
  4709. /**
  4710. * A map from target to changes to the target. See TargetChange.
  4711. */
  4712. readonly targetChanges: Map<TargetId, TargetChange>;
  4713. /**
  4714. * A set of targets that is known to be inconsistent. Listens for these
  4715. * targets should be re-established without resume tokens.
  4716. */
  4717. readonly targetMismatches: SortedSet<TargetId>;
  4718. /**
  4719. * A set of which documents have changed or been deleted, along with the
  4720. * doc's new values (if not deleted).
  4721. */
  4722. readonly documentUpdates: MutableDocumentMap;
  4723. /**
  4724. * A set of which document updates are due only to limbo resolution targets.
  4725. */
  4726. readonly resolvedLimboDocuments: DocumentKeySet;
  4727. constructor(
  4728. /**
  4729. * The snapshot version this event brings us up to, or MIN if not set.
  4730. */
  4731. snapshotVersion: SnapshotVersion,
  4732. /**
  4733. * A map from target to changes to the target. See TargetChange.
  4734. */
  4735. targetChanges: Map<TargetId, TargetChange>,
  4736. /**
  4737. * A set of targets that is known to be inconsistent. Listens for these
  4738. * targets should be re-established without resume tokens.
  4739. */
  4740. targetMismatches: SortedSet<TargetId>,
  4741. /**
  4742. * A set of which documents have changed or been deleted, along with the
  4743. * doc's new values (if not deleted).
  4744. */
  4745. documentUpdates: MutableDocumentMap,
  4746. /**
  4747. * A set of which document updates are due only to limbo resolution targets.
  4748. */
  4749. resolvedLimboDocuments: DocumentKeySet);
  4750. /**
  4751. * HACK: Views require RemoteEvents in order to determine whether the view is
  4752. * CURRENT, but secondary tabs don't receive remote events. So this method is
  4753. * used to create a synthesized RemoteEvent that can be used to apply a
  4754. * CURRENT status change to a View, for queries executed in a different tab.
  4755. */
  4756. static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): RemoteEvent;
  4757. }
  4758. /**
  4759. * RemoteStore - An interface to remotely stored data, basically providing a
  4760. * wrapper around the Datastore that is more reliable for the rest of the
  4761. * system.
  4762. *
  4763. * RemoteStore is responsible for maintaining the connection to the server.
  4764. * - maintaining a list of active listens.
  4765. * - reconnecting when the connection is dropped.
  4766. * - resuming all the active listens on reconnect.
  4767. *
  4768. * RemoteStore handles all incoming events from the Datastore.
  4769. * - listening to the watch stream and repackaging the events as RemoteEvents
  4770. * - notifying SyncEngine of any changes to the active listens.
  4771. *
  4772. * RemoteStore takes writes from other components and handles them reliably.
  4773. * - pulling pending mutations from LocalStore and sending them to Datastore.
  4774. * - retrying mutations that failed because of network problems.
  4775. * - acking mutations to the SyncEngine once they are accepted or rejected.
  4776. */
  4777. declare interface RemoteStore {
  4778. /**
  4779. * SyncEngine to notify of watch and write events. This must be set
  4780. * immediately after construction.
  4781. */
  4782. remoteSyncer: RemoteSyncer;
  4783. }
  4784. /**
  4785. * An interface that describes the actions the RemoteStore needs to perform on
  4786. * a cooperating synchronization engine.
  4787. */
  4788. declare interface RemoteSyncer {
  4789. /**
  4790. * Applies one remote event to the sync engine, notifying any views of the
  4791. * changes, and releasing any pending mutation batches that would become
  4792. * visible because of the snapshot version the remote event contains.
  4793. */
  4794. applyRemoteEvent?(remoteEvent: RemoteEvent): Promise<void>;
  4795. /**
  4796. * Rejects the listen for the given targetID. This can be triggered by the
  4797. * backend for any active target.
  4798. *
  4799. * @param targetId - The targetID corresponds to one previously initiated by
  4800. * the user as part of TargetData passed to listen() on RemoteStore.
  4801. * @param error - A description of the condition that has forced the rejection.
  4802. * Nearly always this will be an indication that the user is no longer
  4803. * authorized to see the data matching the target.
  4804. */
  4805. rejectListen?(targetId: TargetId, error: FirestoreError): Promise<void>;
  4806. /**
  4807. * Applies the result of a successful write of a mutation batch to the sync
  4808. * engine, emitting snapshots in any views that the mutation applies to, and
  4809. * removing the batch from the mutation queue.
  4810. */
  4811. applySuccessfulWrite?(result: MutationBatchResult): Promise<void>;
  4812. /**
  4813. * Rejects the batch, removing the batch from the mutation queue, recomputing
  4814. * the local view of any documents affected by the batch and then, emitting
  4815. * snapshots with the reverted value.
  4816. */
  4817. rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise<void>;
  4818. /**
  4819. * Returns the set of remote document keys for the given target ID. This list
  4820. * includes the documents that were assigned to the target when we received
  4821. * the last snapshot.
  4822. */
  4823. getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet;
  4824. /**
  4825. * Updates all local state to match the pending mutations for the given user.
  4826. * May be called repeatedly for the same user.
  4827. */
  4828. handleCredentialChange?(user: User): Promise<void>;
  4829. }
  4830. declare type Resolver<T> = (value?: T) => void;
  4831. /**
  4832. * A slash-separated path for navigating resources (documents and collections)
  4833. * within Firestore.
  4834. *
  4835. * @internal
  4836. */
  4837. export declare class _ResourcePath extends BasePath<_ResourcePath> {
  4838. protected construct(segments: string[], offset?: number, length?: number): _ResourcePath;
  4839. canonicalString(): string;
  4840. toString(): string;
  4841. /**
  4842. * Creates a resource path from the given slash-delimited string. If multiple
  4843. * arguments are provided, all components are combined. Leading and trailing
  4844. * slashes from all components are ignored.
  4845. */
  4846. static fromString(...pathComponents: string[]): _ResourcePath;
  4847. static emptyPath(): _ResourcePath;
  4848. }
  4849. /**
  4850. * Executes the given `updateFunction` and then attempts to commit the changes
  4851. * applied within the transaction. If any document read within the transaction
  4852. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  4853. * commit after 5 attempts, the transaction fails.
  4854. *
  4855. * The maximum number of writes allowed in a single transaction is 500.
  4856. *
  4857. * @param firestore - A reference to the Firestore database to run this
  4858. * transaction against.
  4859. * @param updateFunction - The function to execute within the transaction
  4860. * context.
  4861. * @param options - An options object to configure maximum number of attempts to
  4862. * commit.
  4863. * @returns If the transaction completed successfully or was explicitly aborted
  4864. * (the `updateFunction` returned a failed promise), the promise returned by the
  4865. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  4866. * rejected promise with the corresponding failure error is returned.
  4867. */
  4868. export declare function runTransaction<T>(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
  4869. /**
  4870. * Interface to schedule periodic tasks within SDK.
  4871. */
  4872. declare interface Scheduler {
  4873. readonly started: boolean;
  4874. start(): void;
  4875. stop(): void;
  4876. }
  4877. /**
  4878. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  4879. * include a server-generated timestamp in the written data.
  4880. */
  4881. export declare function serverTimestamp(): FieldValue;
  4882. declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';
  4883. /**
  4884. * Writes to the document referred to by this `DocumentReference`. If the
  4885. * document does not yet exist, it will be created.
  4886. *
  4887. * @param reference - A reference to the document to write.
  4888. * @param data - A map of the fields and values for the document.
  4889. * @returns A `Promise` resolved once the data has been successfully written
  4890. * to the backend (note that it won't resolve while you're offline).
  4891. */
  4892. export declare function setDoc<T>(reference: DocumentReference<T>, data: WithFieldValue<T>): Promise<void>;
  4893. /**
  4894. * Writes to the document referred to by the specified `DocumentReference`. If
  4895. * the document does not yet exist, it will be created. If you provide `merge`
  4896. * or `mergeFields`, the provided data can be merged into an existing document.
  4897. *
  4898. * @param reference - A reference to the document to write.
  4899. * @param data - A map of the fields and values for the document.
  4900. * @param options - An object to configure the set behavior.
  4901. * @returns A Promise resolved once the data has been successfully written
  4902. * to the backend (note that it won't resolve while you're offline).
  4903. */
  4904. export declare function setDoc<T>(reference: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): Promise<void>;
  4905. /**
  4906. * Configures indexing for local query execution. Any previous index
  4907. * configuration is overridden. The `Promise` resolves once the index
  4908. * configuration has been persisted.
  4909. *
  4910. * The index entries themselves are created asynchronously. You can continue to
  4911. * use queries that require indexing even if the indices are not yet available.
  4912. * Query execution will automatically start using the index once the index
  4913. * entries have been written.
  4914. *
  4915. * Indexes are only supported with IndexedDb persistence. Invoke either
  4916. * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`
  4917. * before setting an index configuration. If IndexedDb is not enabled, any
  4918. * index configuration is ignored.
  4919. *
  4920. * @param firestore - The {@link Firestore} instance to configure indexes for.
  4921. * @param configuration -The index definition.
  4922. * @throws FirestoreError if the JSON format is invalid.
  4923. * @returns A `Promise` that resolves once all indices are successfully
  4924. * configured.
  4925. * @beta
  4926. */
  4927. export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise<void>;
  4928. /**
  4929. * Configures indexing for local query execution. Any previous index
  4930. * configuration is overridden. The `Promise` resolves once the index
  4931. * configuration has been persisted.
  4932. *
  4933. * The index entries themselves are created asynchronously. You can continue to
  4934. * use queries that require indexing even if the indices are not yet available.
  4935. * Query execution will automatically start using the index once the index
  4936. * entries have been written.
  4937. *
  4938. * Indexes are only supported with IndexedDb persistence. Invoke either
  4939. * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`
  4940. * before setting an index configuration. If IndexedDb is not enabled, any
  4941. * index configuration is ignored.
  4942. *
  4943. * The method accepts the JSON format exported by the Firebase CLI (`firebase
  4944. * firestore:indexes`). If the JSON format is invalid, this method throws an
  4945. * error.
  4946. *
  4947. * @param firestore - The {@link Firestore} instance to configure indexes for.
  4948. * @param json -The JSON format exported by the Firebase CLI.
  4949. * @throws FirestoreError if the JSON format is invalid.
  4950. * @returns A `Promise` that resolves once all indices are successfully
  4951. * configured.
  4952. * @beta
  4953. */
  4954. export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise<void>;
  4955. /**
  4956. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  4957. *
  4958. * @param logLevel - The verbosity you set for activity and error logging. Can
  4959. * be any of the following values:
  4960. *
  4961. * <ul>
  4962. * <li>`debug` for the most verbose logging level, primarily for
  4963. * debugging.</li>
  4964. * <li>`error` to log errors only.</li>
  4965. * <li><code>`silent` to turn off logging.</li>
  4966. * </ul>
  4967. */
  4968. export declare function setLogLevel(logLevel: LogLevel): void;
  4969. /**
  4970. * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link
  4971. * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be
  4972. * configured to perform granular merges instead of overwriting the target
  4973. * documents in their entirety by providing a `SetOptions` with `merge: true`.
  4974. *
  4975. * @param merge - Changes the behavior of a `setDoc()` call to only replace the
  4976. * values specified in its data argument. Fields omitted from the `setDoc()`
  4977. * call remain untouched. If your input sets any field to an empty map, all
  4978. * nested fields are overwritten.
  4979. * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace
  4980. * the specified field paths. Any field path that is not specified is ignored
  4981. * and remains untouched. If your input sets any field to an empty map, all
  4982. * nested fields are overwritten.
  4983. */
  4984. export declare type SetOptions = {
  4985. readonly merge?: boolean;
  4986. } | {
  4987. readonly mergeFields?: Array<string | FieldPath>;
  4988. };
  4989. /**
  4990. * A `SharedClientState` keeps track of the global state of the mutations
  4991. * and query targets for all active clients with the same persistence key (i.e.
  4992. * project ID and FirebaseApp name). It relays local changes to other clients
  4993. * and updates its local state as new state is observed.
  4994. *
  4995. * `SharedClientState` is primarily used for synchronization in Multi-Tab
  4996. * environments. Each tab is responsible for registering its active query
  4997. * targets and mutations. `SharedClientState` will then notify the listener
  4998. * assigned to `.syncEngine` for updates to mutations and queries that
  4999. * originated in other clients.
  5000. *
  5001. * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be
  5002. * assigned before calling `start()`.
  5003. */
  5004. declare interface SharedClientState {
  5005. onlineStateHandler: ((onlineState: OnlineState) => void) | null;
  5006. sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null;
  5007. /** Registers the Mutation Batch ID of a newly pending mutation. */
  5008. addPendingMutation(batchId: BatchId): void;
  5009. /**
  5010. * Records that a pending mutation has been acknowledged or rejected.
  5011. * Called by the primary client to notify secondary clients of mutation
  5012. * results as they come back from the backend.
  5013. */
  5014. updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void;
  5015. /**
  5016. * Associates a new Query Target ID with the local Firestore client. Returns
  5017. * the new query state for the query (which can be 'current' if the query is
  5018. * already associated with another tab).
  5019. *
  5020. * If the target id is already associated with local client, the method simply
  5021. * returns its `QueryTargetState`.
  5022. */
  5023. addLocalQueryTarget(targetId: TargetId): QueryTargetState;
  5024. /** Removes the Query Target ID association from the local client. */
  5025. removeLocalQueryTarget(targetId: TargetId): void;
  5026. /** Checks whether the target is associated with the local client. */
  5027. isLocalQueryTarget(targetId: TargetId): boolean;
  5028. /**
  5029. * Processes an update to a query target.
  5030. *
  5031. * Called by the primary client to notify secondary clients of document
  5032. * changes or state transitions that affect the provided query target.
  5033. */
  5034. updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void;
  5035. /**
  5036. * Removes the target's metadata entry.
  5037. *
  5038. * Called by the primary client when all clients stopped listening to a query
  5039. * target.
  5040. */
  5041. clearQueryState(targetId: TargetId): void;
  5042. /**
  5043. * Gets the active Query Targets IDs for all active clients.
  5044. *
  5045. * The implementation for this may require O(n) runtime, where 'n' is the size
  5046. * of the result set.
  5047. */
  5048. getAllActiveQueryTargets(): SortedSet<TargetId>;
  5049. /**
  5050. * Checks whether the provided target ID is currently being listened to by
  5051. * any of the active clients.
  5052. *
  5053. * The implementation may require O(n*log m) runtime, where 'n' is the number
  5054. * of clients and 'm' the number of targets.
  5055. */
  5056. isActiveQueryTarget(targetId: TargetId): boolean;
  5057. /**
  5058. * Starts the SharedClientState, reads existing client data and registers
  5059. * listeners for updates to new and existing clients.
  5060. */
  5061. start(): Promise<void>;
  5062. /** Shuts down the `SharedClientState` and its listeners. */
  5063. shutdown(): void;
  5064. /**
  5065. * Changes the active user and removes all existing user-specific data. The
  5066. * user change does not call back into SyncEngine (for example, no mutations
  5067. * will be marked as removed).
  5068. */
  5069. handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void;
  5070. /** Changes the shared online state of all clients. */
  5071. setOnlineState(onlineState: OnlineState): void;
  5072. writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;
  5073. /**
  5074. * Notifies other clients when remote documents have changed due to loading
  5075. * a bundle.
  5076. *
  5077. * @param collectionGroups The collection groups affected by this bundle.
  5078. */
  5079. notifyBundleLoaded(collectionGroups: Set<string>): void;
  5080. }
  5081. /**
  5082. * Returns true if the provided snapshots are equal.
  5083. *
  5084. * @param left - A snapshot to compare.
  5085. * @param right - A snapshot to compare.
  5086. * @returns true if the snapshots are equal.
  5087. */
  5088. export declare function snapshotEqual<T>(left: DocumentSnapshot<T> | QuerySnapshot<T>, right: DocumentSnapshot<T> | QuerySnapshot<T>): boolean;
  5089. /**
  5090. * An options object that can be passed to {@link (onSnapshot:1)} and {@link
  5091. * QuerySnapshot.docChanges} to control which types of changes to include in the
  5092. * result set.
  5093. */
  5094. export declare interface SnapshotListenOptions {
  5095. /**
  5096. * Include a change even if only the metadata of the query or of a document
  5097. * changed. Default is false.
  5098. */
  5099. readonly includeMetadataChanges?: boolean;
  5100. }
  5101. /**
  5102. * Metadata about a snapshot, describing the state of the snapshot.
  5103. */
  5104. export declare class SnapshotMetadata {
  5105. /**
  5106. * True if the snapshot contains the result of local writes (for example
  5107. * `set()` or `update()` calls) that have not yet been committed to the
  5108. * backend. If your listener has opted into metadata updates (via
  5109. * `SnapshotListenOptions`) you will receive another snapshot with
  5110. * `hasPendingWrites` equal to false once the writes have been committed to
  5111. * the backend.
  5112. */
  5113. readonly hasPendingWrites: boolean;
  5114. /**
  5115. * True if the snapshot was created from cached data rather than guaranteed
  5116. * up-to-date server data. If your listener has opted into metadata updates
  5117. * (via `SnapshotListenOptions`) you will receive another snapshot with
  5118. * `fromCache` set to false once the client has received up-to-date data from
  5119. * the backend.
  5120. */
  5121. readonly fromCache: boolean;
  5122. /** @hideconstructor */
  5123. constructor(hasPendingWrites: boolean, fromCache: boolean);
  5124. /**
  5125. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  5126. *
  5127. * @param other - The `SnapshotMetadata` to compare against.
  5128. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  5129. */
  5130. isEqual(other: SnapshotMetadata): boolean;
  5131. }
  5132. /**
  5133. * Options that configure how data is retrieved from a `DocumentSnapshot` (for
  5134. * example the desired behavior for server timestamps that have not yet been set
  5135. * to their final value).
  5136. */
  5137. export declare interface SnapshotOptions {
  5138. /**
  5139. * If set, controls the return value for server timestamps that have not yet
  5140. * been set to their final value.
  5141. *
  5142. * By specifying 'estimate', pending server timestamps return an estimate
  5143. * based on the local clock. This estimate will differ from the final value
  5144. * and cause these values to change once the server result becomes available.
  5145. *
  5146. * By specifying 'previous', pending timestamps will be ignored and return
  5147. * their previous value instead.
  5148. *
  5149. * If omitted or set to 'none', `null` will be returned by default until the
  5150. * server value becomes available.
  5151. */
  5152. readonly serverTimestamps?: 'estimate' | 'previous' | 'none';
  5153. }
  5154. /**
  5155. * A version of a document in Firestore. This corresponds to the version
  5156. * timestamp, such as update_time or read_time.
  5157. */
  5158. declare class SnapshotVersion {
  5159. private timestamp;
  5160. static fromTimestamp(value: Timestamp): SnapshotVersion;
  5161. static min(): SnapshotVersion;
  5162. static max(): SnapshotVersion;
  5163. private constructor();
  5164. compareTo(other: SnapshotVersion): number;
  5165. isEqual(other: SnapshotVersion): boolean;
  5166. /** Returns a number representation of the version for use in spec tests. */
  5167. toMicroseconds(): number;
  5168. toString(): string;
  5169. toTimestamp(): Timestamp;
  5170. }
  5171. declare class SortedMap<K, V> {
  5172. comparator: Comparator<K>;
  5173. root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  5174. constructor(comparator: Comparator<K>, root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>);
  5175. insert(key: K, value: V): SortedMap<K, V>;
  5176. remove(key: K): SortedMap<K, V>;
  5177. get(key: K): V | null;
  5178. indexOf(key: K): number;
  5179. isEmpty(): boolean;
  5180. get size(): number;
  5181. minKey(): K | null;
  5182. maxKey(): K | null;
  5183. inorderTraversal<T>(action: (k: K, v: V) => T): T;
  5184. forEach(fn: (k: K, v: V) => void): void;
  5185. toString(): string;
  5186. reverseTraversal<T>(action: (k: K, v: V) => T): T;
  5187. getIterator(): SortedMapIterator<K, V>;
  5188. getIteratorFrom(key: K): SortedMapIterator<K, V>;
  5189. getReverseIterator(): SortedMapIterator<K, V>;
  5190. getReverseIteratorFrom(key: K): SortedMapIterator<K, V>;
  5191. }
  5192. declare class SortedMapIterator<K, V> {
  5193. private isReverse;
  5194. private nodeStack;
  5195. constructor(node: LLRBNode<K, V> | LLRBEmptyNode<K, V>, startKey: K | null, comparator: Comparator<K>, isReverse: boolean);
  5196. getNext(): Entry<K, V>;
  5197. hasNext(): boolean;
  5198. peek(): Entry<K, V> | null;
  5199. }
  5200. /**
  5201. * SortedSet is an immutable (copy-on-write) collection that holds elements
  5202. * in order specified by the provided comparator.
  5203. *
  5204. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  5205. * be equal!
  5206. */
  5207. declare class SortedSet<T> {
  5208. private comparator;
  5209. private data;
  5210. constructor(comparator: (left: T, right: T) => number);
  5211. has(elem: T): boolean;
  5212. first(): T | null;
  5213. last(): T | null;
  5214. get size(): number;
  5215. indexOf(elem: T): number;
  5216. /** Iterates elements in order defined by "comparator" */
  5217. forEach(cb: (elem: T) => void): void;
  5218. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
  5219. forEachInRange(range: [T, T], cb: (elem: T) => void): void;
  5220. /**
  5221. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  5222. */
  5223. forEachWhile(cb: (elem: T) => boolean, start?: T): void;
  5224. /** Finds the least element greater than or equal to `elem`. */
  5225. firstAfterOrEqual(elem: T): T | null;
  5226. getIterator(): SortedSetIterator<T>;
  5227. getIteratorFrom(key: T): SortedSetIterator<T>;
  5228. /** Inserts or updates an element */
  5229. add(elem: T): SortedSet<T>;
  5230. /** Deletes an element */
  5231. delete(elem: T): SortedSet<T>;
  5232. isEmpty(): boolean;
  5233. unionWith(other: SortedSet<T>): SortedSet<T>;
  5234. isEqual(other: SortedSet<T>): boolean;
  5235. toArray(): T[];
  5236. toString(): string;
  5237. private copy;
  5238. }
  5239. declare class SortedSetIterator<T> {
  5240. private iter;
  5241. constructor(iter: SortedMapIterator<T, boolean>);
  5242. getNext(): T;
  5243. hasNext(): boolean;
  5244. }
  5245. /**
  5246. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5247. * start after the provided document (exclusive). The starting position is
  5248. * relative to the order of the query. The document must contain all of the
  5249. * fields provided in the orderBy of the query.
  5250. *
  5251. * @param snapshot - The snapshot of the document to start after.
  5252. * @returns A {@link QueryStartAtConstraint} to pass to `query()`
  5253. */
  5254. export declare function startAfter(snapshot: DocumentSnapshot_2<unknown>): QueryStartAtConstraint;
  5255. /**
  5256. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5257. * start after the provided fields relative to the order of the query. The order
  5258. * of the field values must match the order of the order by clauses of the query.
  5259. *
  5260. * @param fieldValues - The field values to start this query after, in order
  5261. * of the query's order by.
  5262. * @returns A {@link QueryStartAtConstraint} to pass to `query()`
  5263. */
  5264. export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;
  5265. /**
  5266. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5267. * start at the provided document (inclusive). The starting position is relative
  5268. * to the order of the query. The document must contain all of the fields
  5269. * provided in the `orderBy` of this query.
  5270. *
  5271. * @param snapshot - The snapshot of the document to start at.
  5272. * @returns A {@link QueryStartAtConstraint} to pass to `query()`.
  5273. */
  5274. export declare function startAt(snapshot: DocumentSnapshot_2<unknown>): QueryStartAtConstraint;
  5275. /**
  5276. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5277. * start at the provided fields relative to the order of the query. The order of
  5278. * the field values must match the order of the order by clauses of the query.
  5279. *
  5280. * @param fieldValues - The field values to start this query at, in order
  5281. * of the query's order by.
  5282. * @returns A {@link QueryStartAtConstraint} to pass to `query()`.
  5283. */
  5284. export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;
  5285. declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery;
  5286. /**
  5287. * @license
  5288. * Copyright 2017 Google LLC
  5289. *
  5290. * Licensed under the Apache License, Version 2.0 (the "License");
  5291. * you may not use this file except in compliance with the License.
  5292. * You may obtain a copy of the License at
  5293. *
  5294. * http://www.apache.org/licenses/LICENSE-2.0
  5295. *
  5296. * Unless required by applicable law or agreed to in writing, software
  5297. * distributed under the License is distributed on an "AS IS" BASIS,
  5298. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5299. * See the License for the specific language governing permissions and
  5300. * limitations under the License.
  5301. */
  5302. /**
  5303. * SyncEngine is the central controller in the client SDK architecture. It is
  5304. * the glue code between the EventManager, LocalStore, and RemoteStore. Some of
  5305. * SyncEngine's responsibilities include:
  5306. * 1. Coordinating client requests and remote events between the EventManager
  5307. * and the local and remote data stores.
  5308. * 2. Managing a View object for each query, providing the unified view between
  5309. * the local and remote data stores.
  5310. * 3. Notifying the RemoteStore when the LocalStore has new mutations in its
  5311. * queue that need sending to the backend.
  5312. *
  5313. * The SyncEngine’s methods should only ever be called by methods running in the
  5314. * global async queue.
  5315. *
  5316. * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe()
  5317. * function. Instead, it directly depends on EventManager's tree-shakeable API
  5318. * (via `ensureWatchStream()`).
  5319. */
  5320. declare interface SyncEngine {
  5321. isPrimaryClient: boolean;
  5322. }
  5323. /**
  5324. * A Target represents the WatchTarget representation of a Query, which is used
  5325. * by the LocalStore and the RemoteStore to keep track of and to execute
  5326. * backend queries. While a Query can represent multiple Targets, each Targets
  5327. * maps to a single WatchTarget in RemoteStore and a single TargetData entry
  5328. * in persistence.
  5329. */
  5330. declare interface Target {
  5331. readonly path: _ResourcePath;
  5332. readonly collectionGroup: string | null;
  5333. readonly orderBy: OrderBy[];
  5334. readonly filters: Filter[];
  5335. readonly limit: number | null;
  5336. readonly startAt: Bound | null;
  5337. readonly endAt: Bound | null;
  5338. }
  5339. /**
  5340. * Represents cached targets received from the remote backend.
  5341. *
  5342. * The cache is keyed by `Target` and entries in the cache are `TargetData`
  5343. * instances.
  5344. */
  5345. declare interface TargetCache {
  5346. /**
  5347. * A global snapshot version representing the last consistent snapshot we
  5348. * received from the backend. This is monotonically increasing and any
  5349. * snapshots received from the backend prior to this version (e.g. for targets
  5350. * resumed with a resume_token) should be suppressed (buffered) until the
  5351. * backend has caught up to this snapshot version again. This prevents our
  5352. * cache from ever going backwards in time.
  5353. *
  5354. * This is updated whenever our we get a TargetChange with a read_time and
  5355. * empty target_ids.
  5356. */
  5357. getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise<SnapshotVersion>;
  5358. /**
  5359. * @returns The highest sequence number observed, including any that might be
  5360. * persisted on-disk.
  5361. */
  5362. getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise<ListenSequenceNumber>;
  5363. /**
  5364. * Call provided function with each `TargetData` that we have cached.
  5365. */
  5366. forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise<void>;
  5367. /**
  5368. * Set the highest listen sequence number and optionally updates the
  5369. * snapshot version of the last consistent snapshot received from the backend
  5370. * (see getLastRemoteSnapshotVersion() for more details).
  5371. *
  5372. * @param highestListenSequenceNumber - The new maximum listen sequence number.
  5373. * @param lastRemoteSnapshotVersion - The new snapshot version. Optional.
  5374. */
  5375. setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise<void>;
  5376. /**
  5377. * Adds an entry in the cache.
  5378. *
  5379. * The cache key is extracted from `targetData.target`. The key must not already
  5380. * exist in the cache.
  5381. *
  5382. * @param targetData - A TargetData instance to put in the cache.
  5383. */
  5384. addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  5385. /**
  5386. * Updates an entry in the cache.
  5387. *
  5388. * The cache key is extracted from `targetData.target`. The entry must already
  5389. * exist in the cache, and it will be replaced.
  5390. * @param targetData - The TargetData to be replaced into the cache.
  5391. */
  5392. updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  5393. /**
  5394. * Removes the cached entry for the given target data. It is an error to remove
  5395. * a target data that does not exist.
  5396. *
  5397. * Multi-Tab Note: This operation should only be called by the primary client.
  5398. */
  5399. removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  5400. /**
  5401. * The number of targets currently in the cache.
  5402. */
  5403. getTargetCount(transaction: PersistenceTransaction): PersistencePromise<number>;
  5404. /**
  5405. * Looks up a TargetData entry by target.
  5406. *
  5407. * @param target - The query target corresponding to the entry to look up.
  5408. * @returns The cached TargetData entry, or null if the cache has no entry for
  5409. * the target.
  5410. */
  5411. getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise<TargetData | null>;
  5412. /**
  5413. * Adds the given document keys to cached query results of the given target
  5414. * ID.
  5415. *
  5416. * Multi-Tab Note: This operation should only be called by the primary client.
  5417. */
  5418. addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise<void>;
  5419. /**
  5420. * Removes the given document keys from the cached query results of the
  5421. * given target ID.
  5422. *
  5423. * Multi-Tab Note: This operation should only be called by the primary client.
  5424. */
  5425. removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise<void>;
  5426. /**
  5427. * Removes all the keys in the query results of the given target ID.
  5428. *
  5429. * Multi-Tab Note: This operation should only be called by the primary client.
  5430. */
  5431. removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise<void>;
  5432. /**
  5433. * Returns the document keys that match the provided target ID.
  5434. */
  5435. getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise<DocumentKeySet>;
  5436. /**
  5437. * Returns a new target ID that is higher than any query in the cache. If
  5438. * there are no queries in the cache, returns the first valid target ID.
  5439. * Allocated target IDs are persisted and `allocateTargetId()` will never
  5440. * return the same ID twice.
  5441. */
  5442. allocateTargetId(transaction: PersistenceTransaction): PersistencePromise<TargetId>;
  5443. containsKey(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<boolean>;
  5444. }
  5445. /**
  5446. * A TargetChange specifies the set of changes for a specific target as part of
  5447. * a RemoteEvent. These changes track which documents are added, modified or
  5448. * removed, as well as the target's resume token and whether the target is
  5449. * marked CURRENT.
  5450. * The actual changes *to* documents are not part of the TargetChange since
  5451. * documents may be part of multiple targets.
  5452. */
  5453. declare class TargetChange {
  5454. /**
  5455. * An opaque, server-assigned token that allows watching a query to be resumed
  5456. * after disconnecting without retransmitting all the data that matches the
  5457. * query. The resume token essentially identifies a point in time from which
  5458. * the server should resume sending results.
  5459. */
  5460. readonly resumeToken: _ByteString;
  5461. /**
  5462. * The "current" (synced) status of this target. Note that "current"
  5463. * has special meaning in the RPC protocol that implies that a target is
  5464. * both up-to-date and consistent with the rest of the watch stream.
  5465. */
  5466. readonly current: boolean;
  5467. /**
  5468. * The set of documents that were newly assigned to this target as part of
  5469. * this remote event.
  5470. */
  5471. readonly addedDocuments: DocumentKeySet;
  5472. /**
  5473. * The set of documents that were already assigned to this target but received
  5474. * an update during this remote event.
  5475. */
  5476. readonly modifiedDocuments: DocumentKeySet;
  5477. /**
  5478. * The set of documents that were removed from this target as part of this
  5479. * remote event.
  5480. */
  5481. readonly removedDocuments: DocumentKeySet;
  5482. constructor(
  5483. /**
  5484. * An opaque, server-assigned token that allows watching a query to be resumed
  5485. * after disconnecting without retransmitting all the data that matches the
  5486. * query. The resume token essentially identifies a point in time from which
  5487. * the server should resume sending results.
  5488. */
  5489. resumeToken: _ByteString,
  5490. /**
  5491. * The "current" (synced) status of this target. Note that "current"
  5492. * has special meaning in the RPC protocol that implies that a target is
  5493. * both up-to-date and consistent with the rest of the watch stream.
  5494. */
  5495. current: boolean,
  5496. /**
  5497. * The set of documents that were newly assigned to this target as part of
  5498. * this remote event.
  5499. */
  5500. addedDocuments: DocumentKeySet,
  5501. /**
  5502. * The set of documents that were already assigned to this target but received
  5503. * an update during this remote event.
  5504. */
  5505. modifiedDocuments: DocumentKeySet,
  5506. /**
  5507. * The set of documents that were removed from this target as part of this
  5508. * remote event.
  5509. */
  5510. removedDocuments: DocumentKeySet);
  5511. /**
  5512. * This method is used to create a synthesized TargetChanges that can be used to
  5513. * apply a CURRENT status change to a View (for queries executed in a different
  5514. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5515. */
  5516. static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): TargetChange;
  5517. }
  5518. declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET';
  5519. /**
  5520. * An immutable set of metadata that the local store tracks for each target.
  5521. */
  5522. declare class TargetData {
  5523. /** The target being listened to. */
  5524. readonly target: Target;
  5525. /**
  5526. * The target ID to which the target corresponds; Assigned by the
  5527. * LocalStore for user listens and by the SyncEngine for limbo watches.
  5528. */
  5529. readonly targetId: TargetId;
  5530. /** The purpose of the target. */
  5531. readonly purpose: TargetPurpose;
  5532. /**
  5533. * The sequence number of the last transaction during which this target data
  5534. * was modified.
  5535. */
  5536. readonly sequenceNumber: ListenSequenceNumber;
  5537. /** The latest snapshot version seen for this target. */
  5538. readonly snapshotVersion: SnapshotVersion;
  5539. /**
  5540. * The maximum snapshot version at which the associated view
  5541. * contained no limbo documents.
  5542. */
  5543. readonly lastLimboFreeSnapshotVersion: SnapshotVersion;
  5544. /**
  5545. * An opaque, server-assigned token that allows watching a target to be
  5546. * resumed after disconnecting without retransmitting all the data that
  5547. * matches the target. The resume token essentially identifies a point in
  5548. * time from which the server should resume sending results.
  5549. */
  5550. readonly resumeToken: _ByteString;
  5551. constructor(
  5552. /** The target being listened to. */
  5553. target: Target,
  5554. /**
  5555. * The target ID to which the target corresponds; Assigned by the
  5556. * LocalStore for user listens and by the SyncEngine for limbo watches.
  5557. */
  5558. targetId: TargetId,
  5559. /** The purpose of the target. */
  5560. purpose: TargetPurpose,
  5561. /**
  5562. * The sequence number of the last transaction during which this target data
  5563. * was modified.
  5564. */
  5565. sequenceNumber: ListenSequenceNumber,
  5566. /** The latest snapshot version seen for this target. */
  5567. snapshotVersion?: SnapshotVersion,
  5568. /**
  5569. * The maximum snapshot version at which the associated view
  5570. * contained no limbo documents.
  5571. */
  5572. lastLimboFreeSnapshotVersion?: SnapshotVersion,
  5573. /**
  5574. * An opaque, server-assigned token that allows watching a target to be
  5575. * resumed after disconnecting without retransmitting all the data that
  5576. * matches the target. The resume token essentially identifies a point in
  5577. * time from which the server should resume sending results.
  5578. */
  5579. resumeToken?: _ByteString);
  5580. /** Creates a new target data instance with an updated sequence number. */
  5581. withSequenceNumber(sequenceNumber: number): TargetData;
  5582. /**
  5583. * Creates a new target data instance with an updated resume token and
  5584. * snapshot version.
  5585. */
  5586. withResumeToken(resumeToken: _ByteString, snapshotVersion: SnapshotVersion): TargetData;
  5587. /**
  5588. * Creates a new target data instance with an updated last limbo free
  5589. * snapshot version number.
  5590. */
  5591. withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData;
  5592. }
  5593. /**
  5594. * A locally-assigned ID used to refer to a target being watched via the
  5595. * Watch service.
  5596. */
  5597. declare type TargetId = number;
  5598. /** An enumeration of the different purposes we have for targets. */
  5599. declare const enum TargetPurpose {
  5600. /** A regular, normal query target. */
  5601. Listen = 0,
  5602. /**
  5603. * The query target was used to refill a query after an existence filter mismatch.
  5604. */
  5605. ExistenceFilterMismatch = 1,
  5606. /** The query target was used to resolve a limbo document. */
  5607. LimboResolution = 2
  5608. }
  5609. /**
  5610. * Represents the state of bundle loading tasks.
  5611. *
  5612. * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will
  5613. * be no more updates after they are reported.
  5614. */
  5615. export declare type TaskState = 'Error' | 'Running' | 'Success';
  5616. /**
  5617. * Terminates the provided {@link Firestore} instance.
  5618. *
  5619. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  5620. * may be used. Any other function will throw a `FirestoreError`.
  5621. *
  5622. * To restart after termination, create a new instance of FirebaseFirestore with
  5623. * {@link (getFirestore:1)}.
  5624. *
  5625. * Termination does not cancel any pending writes, and any promises that are
  5626. * awaiting a response from the server will not be resolved. If you have
  5627. * persistence enabled, the next time you start this instance, it will resume
  5628. * sending these writes to the server.
  5629. *
  5630. * Note: Under normal circumstances, calling `terminate()` is not required. This
  5631. * function is useful only when you want to force this instance to release all
  5632. * of its resources or in combination with `clearIndexedDbPersistence()` to
  5633. * ensure that all local state is destroyed between test runs.
  5634. *
  5635. * @returns A `Promise` that is resolved when the instance has been successfully
  5636. * terminated.
  5637. */
  5638. export declare function terminate(firestore: Firestore): Promise<void>;
  5639. /**
  5640. * Wellknown "timer" IDs used when scheduling delayed operations on the
  5641. * AsyncQueue. These IDs can then be used from tests to check for the presence
  5642. * of operations or to run them early.
  5643. *
  5644. * The string values are used when encoding these timer IDs in JSON spec tests.
  5645. */
  5646. declare const enum TimerId {
  5647. /** All can be used with runDelayedOperationsEarly() to run all timers. */
  5648. All = "all",
  5649. /**
  5650. * The following 5 timers are used in persistent_stream.ts for the listen and
  5651. * write streams. The "Idle" timer is used to close the stream due to
  5652. * inactivity. The "ConnectionBackoff" timer is used to restart a stream once
  5653. * the appropriate backoff delay has elapsed. The health check is used to mark
  5654. * a stream healthy if it has not received an error during its initial setup.
  5655. */
  5656. ListenStreamIdle = "listen_stream_idle",
  5657. ListenStreamConnectionBackoff = "listen_stream_connection_backoff",
  5658. WriteStreamIdle = "write_stream_idle",
  5659. WriteStreamConnectionBackoff = "write_stream_connection_backoff",
  5660. HealthCheckTimeout = "health_check_timeout",
  5661. /**
  5662. * A timer used in online_state_tracker.ts to transition from
  5663. * OnlineState.Unknown to Offline after a set timeout, rather than waiting
  5664. * indefinitely for success or failure.
  5665. */
  5666. OnlineStateTimeout = "online_state_timeout",
  5667. /**
  5668. * A timer used to update the client metadata in IndexedDb, which is used
  5669. * to determine the primary leaseholder.
  5670. */
  5671. ClientMetadataRefresh = "client_metadata_refresh",
  5672. /** A timer used to periodically attempt LRU Garbage collection */
  5673. LruGarbageCollection = "lru_garbage_collection",
  5674. /**
  5675. * A timer used to retry transactions. Since there can be multiple concurrent
  5676. * transactions, multiple of these may be in the queue at a given time.
  5677. */
  5678. TransactionRetry = "transaction_retry",
  5679. /**
  5680. * A timer used to retry operations scheduled via retryable AsyncQueue
  5681. * operations.
  5682. */
  5683. AsyncQueueRetry = "async_queue_retry",
  5684. /**
  5685. * A timer used to periodically attempt index backfill.
  5686. */
  5687. IndexBackfill = "index_backfill"
  5688. }
  5689. /**
  5690. * @license
  5691. * Copyright 2017 Google LLC
  5692. *
  5693. * Licensed under the Apache License, Version 2.0 (the "License");
  5694. * you may not use this file except in compliance with the License.
  5695. * You may obtain a copy of the License at
  5696. *
  5697. * http://www.apache.org/licenses/LICENSE-2.0
  5698. *
  5699. * Unless required by applicable law or agreed to in writing, software
  5700. * distributed under the License is distributed on an "AS IS" BASIS,
  5701. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5702. * See the License for the specific language governing permissions and
  5703. * limitations under the License.
  5704. */
  5705. /**
  5706. * A `Timestamp` represents a point in time independent of any time zone or
  5707. * calendar, represented as seconds and fractions of seconds at nanosecond
  5708. * resolution in UTC Epoch time.
  5709. *
  5710. * It is encoded using the Proleptic Gregorian Calendar which extends the
  5711. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  5712. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  5713. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  5714. * 9999-12-31T23:59:59.999999999Z.
  5715. *
  5716. * For examples and further specifications, refer to the
  5717. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  5718. */
  5719. export declare class Timestamp {
  5720. /**
  5721. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  5722. */
  5723. readonly seconds: number;
  5724. /**
  5725. * The fractions of a second at nanosecond resolution.*
  5726. */
  5727. readonly nanoseconds: number;
  5728. /**
  5729. * Creates a new timestamp with the current date, with millisecond precision.
  5730. *
  5731. * @returns a new timestamp representing the current date.
  5732. */
  5733. static now(): Timestamp;
  5734. /**
  5735. * Creates a new timestamp from the given date.
  5736. *
  5737. * @param date - The date to initialize the `Timestamp` from.
  5738. * @returns A new `Timestamp` representing the same point in time as the given
  5739. * date.
  5740. */
  5741. static fromDate(date: Date): Timestamp;
  5742. /**
  5743. * Creates a new timestamp from the given number of milliseconds.
  5744. *
  5745. * @param milliseconds - Number of milliseconds since Unix epoch
  5746. * 1970-01-01T00:00:00Z.
  5747. * @returns A new `Timestamp` representing the same point in time as the given
  5748. * number of milliseconds.
  5749. */
  5750. static fromMillis(milliseconds: number): Timestamp;
  5751. /**
  5752. * Creates a new timestamp.
  5753. *
  5754. * @param seconds - The number of seconds of UTC time since Unix epoch
  5755. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  5756. * 9999-12-31T23:59:59Z inclusive.
  5757. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  5758. * resolution. Negative second values with fractions must still have
  5759. * non-negative nanoseconds values that count forward in time. Must be
  5760. * from 0 to 999,999,999 inclusive.
  5761. */
  5762. constructor(
  5763. /**
  5764. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  5765. */
  5766. seconds: number,
  5767. /**
  5768. * The fractions of a second at nanosecond resolution.*
  5769. */
  5770. nanoseconds: number);
  5771. /**
  5772. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  5773. * causes a loss of precision since `Date` objects only support millisecond
  5774. * precision.
  5775. *
  5776. * @returns JavaScript `Date` object representing the same point in time as
  5777. * this `Timestamp`, with millisecond precision.
  5778. */
  5779. toDate(): Date;
  5780. /**
  5781. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  5782. * epoch). This operation causes a loss of precision.
  5783. *
  5784. * @returns The point in time corresponding to this timestamp, represented as
  5785. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  5786. */
  5787. toMillis(): number;
  5788. _compareTo(other: Timestamp): number;
  5789. /**
  5790. * Returns true if this `Timestamp` is equal to the provided one.
  5791. *
  5792. * @param other - The `Timestamp` to compare against.
  5793. * @returns true if this `Timestamp` is equal to the provided one.
  5794. */
  5795. isEqual(other: Timestamp): boolean;
  5796. /** Returns a textual representation of this `Timestamp`. */
  5797. toString(): string;
  5798. /** Returns a JSON-serializable representation of this `Timestamp`. */
  5799. toJSON(): {
  5800. seconds: number;
  5801. nanoseconds: number;
  5802. };
  5803. /**
  5804. * Converts this object to a primitive string, which allows `Timestamp` objects
  5805. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  5806. */
  5807. valueOf(): string;
  5808. }
  5809. declare type Timestamp_2 = string | {
  5810. seconds?: string | number;
  5811. nanos?: number;
  5812. };
  5813. declare interface Token {
  5814. /** Type of token. */
  5815. type: TokenType;
  5816. /**
  5817. * The user with which the token is associated (used for persisting user
  5818. * state on disk, etc.).
  5819. * This will be null for Tokens of the type 'AppCheck'.
  5820. */
  5821. user?: User;
  5822. /** Header values to set for this token */
  5823. headers: Map<string, string>;
  5824. }
  5825. declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';
  5826. /**
  5827. * A reference to a transaction.
  5828. *
  5829. * The `Transaction` object passed to a transaction's `updateFunction` provides
  5830. * the methods to read and write data within the transaction context. See
  5831. * {@link runTransaction}.
  5832. */
  5833. export declare class Transaction extends Transaction_2 {
  5834. protected readonly _firestore: Firestore;
  5835. /** @hideconstructor */
  5836. constructor(_firestore: Firestore, _transaction: Transaction_3);
  5837. /**
  5838. * Reads the document referenced by the provided {@link DocumentReference}.
  5839. *
  5840. * @param documentRef - A reference to the document to be read.
  5841. * @returns A `DocumentSnapshot` with the read data.
  5842. */
  5843. get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  5844. }
  5845. /**
  5846. * A reference to a transaction.
  5847. *
  5848. * The `Transaction` object passed to a transaction's `updateFunction` provides
  5849. * the methods to read and write data within the transaction context. See
  5850. * {@link runTransaction}.
  5851. */
  5852. declare class Transaction_2 {
  5853. protected readonly _firestore: Firestore_2;
  5854. private readonly _transaction;
  5855. private readonly _dataReader;
  5856. /** @hideconstructor */
  5857. constructor(_firestore: Firestore_2, _transaction: Transaction_3);
  5858. /**
  5859. * Reads the document referenced by the provided {@link DocumentReference}.
  5860. *
  5861. * @param documentRef - A reference to the document to be read.
  5862. * @returns A `DocumentSnapshot` with the read data.
  5863. */
  5864. get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot_2<T>>;
  5865. /**
  5866. * Writes to the document referred to by the provided {@link
  5867. * DocumentReference}. If the document does not exist yet, it will be created.
  5868. *
  5869. * @param documentRef - A reference to the document to be set.
  5870. * @param data - An object of the fields and values for the document.
  5871. * @throws Error - If the provided input is not a valid Firestore document.
  5872. * @returns This `Transaction` instance. Used for chaining method calls.
  5873. */
  5874. set<T>(documentRef: DocumentReference<T>, data: WithFieldValue<T>): this;
  5875. /**
  5876. * Writes to the document referred to by the provided {@link
  5877. * DocumentReference}. If the document does not exist yet, it will be created.
  5878. * If you provide `merge` or `mergeFields`, the provided data can be merged
  5879. * into an existing document.
  5880. *
  5881. * @param documentRef - A reference to the document to be set.
  5882. * @param data - An object of the fields and values for the document.
  5883. * @param options - An object to configure the set behavior.
  5884. * @throws Error - If the provided input is not a valid Firestore document.
  5885. * @returns This `Transaction` instance. Used for chaining method calls.
  5886. */
  5887. set<T>(documentRef: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): this;
  5888. /**
  5889. * Updates fields in the document referred to by the provided {@link
  5890. * DocumentReference}. The update will fail if applied to a document that does
  5891. * not exist.
  5892. *
  5893. * @param documentRef - A reference to the document to be updated.
  5894. * @param data - An object containing the fields and values with which to
  5895. * update the document. Fields can contain dots to reference nested fields
  5896. * within the document.
  5897. * @throws Error - If the provided input is not valid Firestore data.
  5898. * @returns This `Transaction` instance. Used for chaining method calls.
  5899. */
  5900. update<T>(documentRef: DocumentReference<T>, data: UpdateData<T>): this;
  5901. /**
  5902. * Updates fields in the document referred to by the provided {@link
  5903. * DocumentReference}. The update will fail if applied to a document that does
  5904. * not exist.
  5905. *
  5906. * Nested fields can be updated by providing dot-separated field path
  5907. * strings or by providing `FieldPath` objects.
  5908. *
  5909. * @param documentRef - A reference to the document to be updated.
  5910. * @param field - The first field to update.
  5911. * @param value - The first value.
  5912. * @param moreFieldsAndValues - Additional key/value pairs.
  5913. * @throws Error - If the provided input is not valid Firestore data.
  5914. * @returns This `Transaction` instance. Used for chaining method calls.
  5915. */
  5916. update(documentRef: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this;
  5917. /**
  5918. * Deletes the document referred to by the provided {@link DocumentReference}.
  5919. *
  5920. * @param documentRef - A reference to the document to be deleted.
  5921. * @returns This `Transaction` instance. Used for chaining method calls.
  5922. */
  5923. delete(documentRef: DocumentReference<unknown>): this;
  5924. }
  5925. /**
  5926. * Internal transaction object responsible for accumulating the mutations to
  5927. * perform and the base versions for any documents read.
  5928. */
  5929. declare class Transaction_3 {
  5930. private datastore;
  5931. private readVersions;
  5932. private mutations;
  5933. private committed;
  5934. /**
  5935. * A deferred usage error that occurred previously in this transaction that
  5936. * will cause the transaction to fail once it actually commits.
  5937. */
  5938. private lastWriteError;
  5939. /**
  5940. * Set of documents that have been written in the transaction.
  5941. *
  5942. * When there's more than one write to the same key in a transaction, any
  5943. * writes after the first are handled differently.
  5944. */
  5945. private writtenDocs;
  5946. constructor(datastore: Datastore);
  5947. lookup(keys: _DocumentKey[]): Promise<Document_2[]>;
  5948. set(key: _DocumentKey, data: ParsedSetData): void;
  5949. update(key: _DocumentKey, data: ParsedUpdateData): void;
  5950. delete(key: _DocumentKey): void;
  5951. commit(): Promise<void>;
  5952. private recordVersion;
  5953. /**
  5954. * Returns the version of this document when it was read in this transaction,
  5955. * as a precondition, or no precondition if it was not read.
  5956. */
  5957. private precondition;
  5958. /**
  5959. * Returns the precondition for a document if the operation is an update.
  5960. */
  5961. private preconditionForUpdate;
  5962. private write;
  5963. private ensureCommitNotCalled;
  5964. }
  5965. /**
  5966. * @license
  5967. * Copyright 2022 Google LLC
  5968. *
  5969. * Licensed under the Apache License, Version 2.0 (the "License");
  5970. * you may not use this file except in compliance with the License.
  5971. * You may obtain a copy of the License at
  5972. *
  5973. * http://www.apache.org/licenses/LICENSE-2.0
  5974. *
  5975. * Unless required by applicable law or agreed to in writing, software
  5976. * distributed under the License is distributed on an "AS IS" BASIS,
  5977. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5978. * See the License for the specific language governing permissions and
  5979. * limitations under the License.
  5980. */
  5981. /**
  5982. * Options to customize transaction behavior.
  5983. */
  5984. export declare interface TransactionOptions {
  5985. /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */
  5986. readonly maxAttempts?: number;
  5987. }
  5988. /** Used to represent a field transform on a mutation. */
  5989. declare class TransformOperation {
  5990. private _;
  5991. }
  5992. declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL';
  5993. /**
  5994. * Given a union type `U = T1 | T2 | ...`, returns an intersected type
  5995. * `(T1 & T2 & ...)`.
  5996. *
  5997. * Uses distributive conditional types and inference from conditional types.
  5998. * This works because multiple candidates for the same type variable in
  5999. * contra-variant positions causes an intersection type to be inferred.
  6000. * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types
  6001. * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type
  6002. */
  6003. export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
  6004. /**
  6005. * A function returned by `onSnapshot()` that removes the listener when invoked.
  6006. */
  6007. export declare interface Unsubscribe {
  6008. /** Removes the listener when invoked. */
  6009. (): void;
  6010. }
  6011. /**
  6012. * An untyped Firestore Data Converter interface that is shared between the
  6013. * lite, firestore-exp and classic SDK.
  6014. */
  6015. declare interface UntypedFirestoreDataConverter<T> {
  6016. toFirestore(modelObject: WithFieldValue<T>): DocumentData_2;
  6017. toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions_2): DocumentData_2;
  6018. fromFirestore(snapshot: unknown, options?: unknown): T;
  6019. }
  6020. /**
  6021. * Update data (for use with {@link (updateDoc:1)}) that consists of field paths
  6022. * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots
  6023. * reference nested fields within the document. FieldValues can be passed in
  6024. * as property values.
  6025. */
  6026. export declare type UpdateData<T> = T extends Primitive ? T : T extends {} ? {
  6027. [K in keyof T]?: UpdateData<T[K]> | FieldValue;
  6028. } & NestedUpdateFields<T> : Partial<T>;
  6029. /**
  6030. * Updates fields in the document referred to by the specified
  6031. * `DocumentReference`. The update will fail if applied to a document that does
  6032. * not exist.
  6033. *
  6034. * @param reference - A reference to the document to update.
  6035. * @param data - An object containing the fields and values with which to
  6036. * update the document. Fields can contain dots to reference nested fields
  6037. * within the document.
  6038. * @returns A `Promise` resolved once the data has been successfully written
  6039. * to the backend (note that it won't resolve while you're offline).
  6040. */
  6041. export declare function updateDoc<T>(reference: DocumentReference<T>, data: UpdateData<T>): Promise<void>;
  6042. /**
  6043. * Updates fields in the document referred to by the specified
  6044. * `DocumentReference` The update will fail if applied to a document that does
  6045. * not exist.
  6046. *
  6047. * Nested fields can be updated by providing dot-separated field path
  6048. * strings or by providing `FieldPath` objects.
  6049. *
  6050. * @param reference - A reference to the document to update.
  6051. * @param field - The first field to update.
  6052. * @param value - The first value.
  6053. * @param moreFieldsAndValues - Additional key value pairs.
  6054. * @returns A `Promise` resolved once the data has been successfully written
  6055. * to the backend (note that it won't resolve while you're offline).
  6056. */
  6057. export declare function updateDoc(reference: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise<void>;
  6058. /**
  6059. * @license
  6060. * Copyright 2017 Google LLC
  6061. *
  6062. * Licensed under the Apache License, Version 2.0 (the "License");
  6063. * you may not use this file except in compliance with the License.
  6064. * You may obtain a copy of the License at
  6065. *
  6066. * http://www.apache.org/licenses/LICENSE-2.0
  6067. *
  6068. * Unless required by applicable law or agreed to in writing, software
  6069. * distributed under the License is distributed on an "AS IS" BASIS,
  6070. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6071. * See the License for the specific language governing permissions and
  6072. * limitations under the License.
  6073. */
  6074. /**
  6075. * Simple wrapper around a nullable UID. Mostly exists to make code more
  6076. * readable.
  6077. */
  6078. declare class User {
  6079. readonly uid: string | null;
  6080. /** A user with a null UID. */
  6081. static readonly UNAUTHENTICATED: User;
  6082. static readonly GOOGLE_CREDENTIALS: User;
  6083. static readonly FIRST_PARTY: User;
  6084. static readonly MOCK_USER: User;
  6085. constructor(uid: string | null);
  6086. isAuthenticated(): boolean;
  6087. /**
  6088. * Returns a key representing this user, suitable for inclusion in a
  6089. * dictionary.
  6090. */
  6091. toKey(): string;
  6092. isEqual(otherUser: User): boolean;
  6093. }
  6094. /**
  6095. * Validates that two boolean options are not set at the same time.
  6096. * @internal
  6097. */
  6098. export declare function _validateIsNotUsedTogether(optionName1: string, argument1: boolean | undefined, optionName2: string, argument2: boolean | undefined): void;
  6099. declare type Value = firestoreV1ApiClientInterfaces.Value;
  6100. declare type ValueNullValue = 'NULL_VALUE';
  6101. declare class ViewSnapshot {
  6102. readonly query: Query_2;
  6103. readonly docs: DocumentSet;
  6104. readonly oldDocs: DocumentSet;
  6105. readonly docChanges: DocumentViewChange[];
  6106. readonly mutatedKeys: DocumentKeySet;
  6107. readonly fromCache: boolean;
  6108. readonly syncStateChanged: boolean;
  6109. readonly excludesMetadataChanges: boolean;
  6110. readonly hasCachedResults: boolean;
  6111. constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean);
  6112. /** Returns a view snapshot as if all documents in the snapshot were added. */
  6113. static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot;
  6114. get hasPendingWrites(): boolean;
  6115. isEqual(other: ViewSnapshot): boolean;
  6116. }
  6117. /**
  6118. * Waits until all currently pending writes for the active user have been
  6119. * acknowledged by the backend.
  6120. *
  6121. * The returned promise resolves immediately if there are no outstanding writes.
  6122. * Otherwise, the promise waits for all previously issued writes (including
  6123. * those written in a previous app session), but it does not wait for writes
  6124. * that were added after the function is called. If you want to wait for
  6125. * additional writes, call `waitForPendingWrites()` again.
  6126. *
  6127. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  6128. * changes.
  6129. *
  6130. * @returns A `Promise` which resolves when all currently pending writes have been
  6131. * acknowledged by the backend.
  6132. */
  6133. export declare function waitForPendingWrites(firestore: Firestore): Promise<void>;
  6134. /**
  6135. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  6136. * must contain the specified field and that the value should satisfy the
  6137. * relation constraint provided.
  6138. *
  6139. * @param fieldPath - The path to compare
  6140. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  6141. * "&lt;=", "!=").
  6142. * @param value - The value for comparison
  6143. * @returns The created {@link QueryFieldFilterConstraint}.
  6144. */
  6145. export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint;
  6146. /**
  6147. * Filter conditions in a {@link where} clause are specified using the
  6148. * strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in',
  6149. * 'array-contains-any', and 'not-in'.
  6150. */
  6151. export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in';
  6152. /**
  6153. * Allows FieldValues to be passed in as a property value while maintaining
  6154. * type safety.
  6155. */
  6156. export declare type WithFieldValue<T> = T | (T extends Primitive ? T : T extends {} ? {
  6157. [K in keyof T]: WithFieldValue<T[K]> | FieldValue;
  6158. } : never);
  6159. /**
  6160. * A write batch, used to perform multiple writes as a single atomic unit.
  6161. *
  6162. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  6163. * provides methods for adding writes to the write batch. None of the writes
  6164. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  6165. * called.
  6166. */
  6167. export declare class WriteBatch {
  6168. private readonly _firestore;
  6169. private readonly _commitHandler;
  6170. private readonly _dataReader;
  6171. private _mutations;
  6172. private _committed;
  6173. /** @hideconstructor */
  6174. constructor(_firestore: Firestore_2, _commitHandler: (m: Mutation[]) => Promise<void>);
  6175. /**
  6176. * Writes to the document referred to by the provided {@link
  6177. * DocumentReference}. If the document does not exist yet, it will be created.
  6178. *
  6179. * @param documentRef - A reference to the document to be set.
  6180. * @param data - An object of the fields and values for the document.
  6181. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6182. */
  6183. set<T>(documentRef: DocumentReference<T>, data: WithFieldValue<T>): WriteBatch;
  6184. /**
  6185. * Writes to the document referred to by the provided {@link
  6186. * DocumentReference}. If the document does not exist yet, it will be created.
  6187. * If you provide `merge` or `mergeFields`, the provided data can be merged
  6188. * into an existing document.
  6189. *
  6190. * @param documentRef - A reference to the document to be set.
  6191. * @param data - An object of the fields and values for the document.
  6192. * @param options - An object to configure the set behavior.
  6193. * @throws Error - If the provided input is not a valid Firestore document.
  6194. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6195. */
  6196. set<T>(documentRef: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): WriteBatch;
  6197. /**
  6198. * Updates fields in the document referred to by the provided {@link
  6199. * DocumentReference}. The update will fail if applied to a document that does
  6200. * not exist.
  6201. *
  6202. * @param documentRef - A reference to the document to be updated.
  6203. * @param data - An object containing the fields and values with which to
  6204. * update the document. Fields can contain dots to reference nested fields
  6205. * within the document.
  6206. * @throws Error - If the provided input is not valid Firestore data.
  6207. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6208. */
  6209. update<T>(documentRef: DocumentReference<T>, data: UpdateData<T>): WriteBatch;
  6210. /**
  6211. * Updates fields in the document referred to by this {@link
  6212. * DocumentReference}. The update will fail if applied to a document that does
  6213. * not exist.
  6214. *
  6215. * Nested fields can be update by providing dot-separated field path strings
  6216. * or by providing `FieldPath` objects.
  6217. *
  6218. * @param documentRef - A reference to the document to be updated.
  6219. * @param field - The first field to update.
  6220. * @param value - The first value.
  6221. * @param moreFieldsAndValues - Additional key value pairs.
  6222. * @throws Error - If the provided input is not valid Firestore data.
  6223. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6224. */
  6225. update(documentRef: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch;
  6226. /**
  6227. * Deletes the document referred to by the provided {@link DocumentReference}.
  6228. *
  6229. * @param documentRef - A reference to the document to be deleted.
  6230. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6231. */
  6232. delete(documentRef: DocumentReference<unknown>): WriteBatch;
  6233. /**
  6234. * Commits all of the writes in this write batch as a single atomic unit.
  6235. *
  6236. * The result of these writes will only be reflected in document reads that
  6237. * occur after the returned promise resolves. If the client is offline, the
  6238. * write fails. If you would like to see local modifications or buffer writes
  6239. * until the client is online, use the full Firestore SDK.
  6240. *
  6241. * @returns A `Promise` resolved once all of the writes in the batch have been
  6242. * successfully written to the backend as an atomic unit (note that it won't
  6243. * resolve while you're offline).
  6244. */
  6245. commit(): Promise<void>;
  6246. private _verifyNotCommitted;
  6247. }
  6248. /**
  6249. * Creates a write batch, used for performing multiple writes as a single
  6250. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  6251. * is 500.
  6252. *
  6253. * Unlike transactions, write batches are persisted offline and therefore are
  6254. * preferable when you don't need to condition your writes on read data.
  6255. *
  6256. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  6257. * writes.
  6258. */
  6259. export declare function writeBatch(firestore: Firestore): WriteBatch;
  6260. export { }