internal.d.ts 283 KB

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