internal.d.ts 229 KB

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