private.d.ts 221 KB

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