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

private.d.ts 249KB

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