index.node.mjs 351 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290
  1. import { _getProvider, getApp, _removeServiceInstance, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app';
  2. import { Component } from '@firebase/component';
  3. import { Logger, LogLevel } from '@firebase/logger';
  4. import { inspect } from 'util';
  5. import { FirebaseError, getDefaultEmulatorHostnameAndPort, createMockUserToken, getModularInstance, deepEqual } from '@firebase/util';
  6. import nodeFetch from 'node-fetch';
  7. import { randomBytes as randomBytes$1 } from 'crypto';
  8. const version$1 = "3.13.0";
  9. /**
  10. * @license
  11. * Copyright 2017 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. /**
  26. * Simple wrapper around a nullable UID. Mostly exists to make code more
  27. * readable.
  28. */
  29. class User {
  30. constructor(uid) {
  31. this.uid = uid;
  32. }
  33. isAuthenticated() {
  34. return this.uid != null;
  35. }
  36. /**
  37. * Returns a key representing this user, suitable for inclusion in a
  38. * dictionary.
  39. */
  40. toKey() {
  41. if (this.isAuthenticated()) {
  42. return 'uid:' + this.uid;
  43. }
  44. else {
  45. return 'anonymous-user';
  46. }
  47. }
  48. isEqual(otherUser) {
  49. return otherUser.uid === this.uid;
  50. }
  51. }
  52. /** A user with a null UID. */
  53. User.UNAUTHENTICATED = new User(null);
  54. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  55. // non-FirebaseAuth providers.
  56. User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
  57. User.FIRST_PARTY = new User('first-party-uid');
  58. User.MOCK_USER = new User('mock-user');
  59. const version = "9.23.0";
  60. /**
  61. * @license
  62. * Copyright 2017 Google LLC
  63. *
  64. * Licensed under the Apache License, Version 2.0 (the "License");
  65. * you may not use this file except in compliance with the License.
  66. * You may obtain a copy of the License at
  67. *
  68. * http://www.apache.org/licenses/LICENSE-2.0
  69. *
  70. * Unless required by applicable law or agreed to in writing, software
  71. * distributed under the License is distributed on an "AS IS" BASIS,
  72. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  73. * See the License for the specific language governing permissions and
  74. * limitations under the License.
  75. */
  76. let SDK_VERSION = version;
  77. function setSDKVersion(version) {
  78. SDK_VERSION = version;
  79. }
  80. /**
  81. * @license
  82. * Copyright 2020 Google LLC
  83. *
  84. * Licensed under the Apache License, Version 2.0 (the "License");
  85. * you may not use this file except in compliance with the License.
  86. * You may obtain a copy of the License at
  87. *
  88. * http://www.apache.org/licenses/LICENSE-2.0
  89. *
  90. * Unless required by applicable law or agreed to in writing, software
  91. * distributed under the License is distributed on an "AS IS" BASIS,
  92. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  93. * See the License for the specific language governing permissions and
  94. * limitations under the License.
  95. */
  96. /** Formats an object as a JSON string, suitable for logging. */
  97. function formatJSON(value) {
  98. // util.inspect() results in much more readable output than JSON.stringify()
  99. return inspect(value, { depth: 100 });
  100. }
  101. /**
  102. * @license
  103. * Copyright 2017 Google LLC
  104. *
  105. * Licensed under the Apache License, Version 2.0 (the "License");
  106. * you may not use this file except in compliance with the License.
  107. * You may obtain a copy of the License at
  108. *
  109. * http://www.apache.org/licenses/LICENSE-2.0
  110. *
  111. * Unless required by applicable law or agreed to in writing, software
  112. * distributed under the License is distributed on an "AS IS" BASIS,
  113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  114. * See the License for the specific language governing permissions and
  115. * limitations under the License.
  116. */
  117. const logClient = new Logger('@firebase/firestore');
  118. /**
  119. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  120. *
  121. * @param logLevel - The verbosity you set for activity and error logging. Can
  122. * be any of the following values:
  123. *
  124. * <ul>
  125. * <li>`debug` for the most verbose logging level, primarily for
  126. * debugging.</li>
  127. * <li>`error` to log errors only.</li>
  128. * <li><code>`silent` to turn off logging.</li>
  129. * </ul>
  130. */
  131. function setLogLevel(logLevel) {
  132. logClient.setLogLevel(logLevel);
  133. }
  134. function logDebug(msg, ...obj) {
  135. if (logClient.logLevel <= LogLevel.DEBUG) {
  136. const args = obj.map(argToString);
  137. logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);
  138. }
  139. }
  140. function logError(msg, ...obj) {
  141. if (logClient.logLevel <= LogLevel.ERROR) {
  142. const args = obj.map(argToString);
  143. logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);
  144. }
  145. }
  146. /**
  147. * @internal
  148. */
  149. function logWarn(msg, ...obj) {
  150. if (logClient.logLevel <= LogLevel.WARN) {
  151. const args = obj.map(argToString);
  152. logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);
  153. }
  154. }
  155. /**
  156. * Converts an additional log parameter to a string representation.
  157. */
  158. function argToString(obj) {
  159. if (typeof obj === 'string') {
  160. return obj;
  161. }
  162. else {
  163. try {
  164. return formatJSON(obj);
  165. }
  166. catch (e) {
  167. // Converting to JSON failed, just log the object directly
  168. return obj;
  169. }
  170. }
  171. }
  172. /**
  173. * @license
  174. * Copyright 2017 Google LLC
  175. *
  176. * Licensed under the Apache License, Version 2.0 (the "License");
  177. * you may not use this file except in compliance with the License.
  178. * You may obtain a copy of the License at
  179. *
  180. * http://www.apache.org/licenses/LICENSE-2.0
  181. *
  182. * Unless required by applicable law or agreed to in writing, software
  183. * distributed under the License is distributed on an "AS IS" BASIS,
  184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  185. * See the License for the specific language governing permissions and
  186. * limitations under the License.
  187. */
  188. /**
  189. * Unconditionally fails, throwing an Error with the given message.
  190. * Messages are stripped in production builds.
  191. *
  192. * Returns `never` and can be used in expressions:
  193. * @example
  194. * let futureVar = fail('not implemented yet');
  195. */
  196. function fail(failure = 'Unexpected state') {
  197. // Log the failure in addition to throw an exception, just in case the
  198. // exception is swallowed.
  199. const message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;
  200. logError(message);
  201. // NOTE: We don't use FirestoreError here because these are internal failures
  202. // that cannot be handled by the user. (Also it would create a circular
  203. // dependency between the error and assert modules which doesn't work.)
  204. throw new Error(message);
  205. }
  206. /**
  207. * Fails if the given assertion condition is false, throwing an Error with the
  208. * given message if it did.
  209. *
  210. * Messages are stripped in production builds.
  211. */
  212. function hardAssert(assertion, message) {
  213. if (!assertion) {
  214. fail();
  215. }
  216. }
  217. /**
  218. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  219. * instance of `T` before casting.
  220. */
  221. function debugCast(obj,
  222. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  223. constructor) {
  224. return obj;
  225. }
  226. /**
  227. * @license
  228. * Copyright 2017 Google LLC
  229. *
  230. * Licensed under the Apache License, Version 2.0 (the "License");
  231. * you may not use this file except in compliance with the License.
  232. * You may obtain a copy of the License at
  233. *
  234. * http://www.apache.org/licenses/LICENSE-2.0
  235. *
  236. * Unless required by applicable law or agreed to in writing, software
  237. * distributed under the License is distributed on an "AS IS" BASIS,
  238. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  239. * See the License for the specific language governing permissions and
  240. * limitations under the License.
  241. */
  242. const Code = {
  243. // Causes are copied from:
  244. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  245. /** Not an error; returned on success. */
  246. OK: 'ok',
  247. /** The operation was cancelled (typically by the caller). */
  248. CANCELLED: 'cancelled',
  249. /** Unknown error or an error from a different error domain. */
  250. UNKNOWN: 'unknown',
  251. /**
  252. * Client specified an invalid argument. Note that this differs from
  253. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  254. * problematic regardless of the state of the system (e.g., a malformed file
  255. * name).
  256. */
  257. INVALID_ARGUMENT: 'invalid-argument',
  258. /**
  259. * Deadline expired before operation could complete. For operations that
  260. * change the state of the system, this error may be returned even if the
  261. * operation has completed successfully. For example, a successful response
  262. * from a server could have been delayed long enough for the deadline to
  263. * expire.
  264. */
  265. DEADLINE_EXCEEDED: 'deadline-exceeded',
  266. /** Some requested entity (e.g., file or directory) was not found. */
  267. NOT_FOUND: 'not-found',
  268. /**
  269. * Some entity that we attempted to create (e.g., file or directory) already
  270. * exists.
  271. */
  272. ALREADY_EXISTS: 'already-exists',
  273. /**
  274. * The caller does not have permission to execute the specified operation.
  275. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  276. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  277. * PERMISSION_DENIED must not be used if the caller can not be identified
  278. * (use UNAUTHENTICATED instead for those errors).
  279. */
  280. PERMISSION_DENIED: 'permission-denied',
  281. /**
  282. * The request does not have valid authentication credentials for the
  283. * operation.
  284. */
  285. UNAUTHENTICATED: 'unauthenticated',
  286. /**
  287. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  288. * entire file system is out of space.
  289. */
  290. RESOURCE_EXHAUSTED: 'resource-exhausted',
  291. /**
  292. * Operation was rejected because the system is not in a state required for
  293. * the operation's execution. For example, directory to be deleted may be
  294. * non-empty, an rmdir operation is applied to a non-directory, etc.
  295. *
  296. * A litmus test that may help a service implementor in deciding
  297. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  298. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  299. * (b) Use ABORTED if the client should retry at a higher-level
  300. * (e.g., restarting a read-modify-write sequence).
  301. * (c) Use FAILED_PRECONDITION if the client should not retry until
  302. * the system state has been explicitly fixed. E.g., if an "rmdir"
  303. * fails because the directory is non-empty, FAILED_PRECONDITION
  304. * should be returned since the client should not retry unless
  305. * they have first fixed up the directory by deleting files from it.
  306. * (d) Use FAILED_PRECONDITION if the client performs conditional
  307. * REST Get/Update/Delete on a resource and the resource on the
  308. * server does not match the condition. E.g., conflicting
  309. * read-modify-write on the same resource.
  310. */
  311. FAILED_PRECONDITION: 'failed-precondition',
  312. /**
  313. * The operation was aborted, typically due to a concurrency issue like
  314. * sequencer check failures, transaction aborts, etc.
  315. *
  316. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  317. * and UNAVAILABLE.
  318. */
  319. ABORTED: 'aborted',
  320. /**
  321. * Operation was attempted past the valid range. E.g., seeking or reading
  322. * past end of file.
  323. *
  324. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  325. * if the system state changes. For example, a 32-bit file system will
  326. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  327. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  328. * an offset past the current file size.
  329. *
  330. * There is a fair bit of overlap between FAILED_PRECONDITION and
  331. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  332. * when it applies so that callers who are iterating through a space can
  333. * easily look for an OUT_OF_RANGE error to detect when they are done.
  334. */
  335. OUT_OF_RANGE: 'out-of-range',
  336. /** Operation is not implemented or not supported/enabled in this service. */
  337. UNIMPLEMENTED: 'unimplemented',
  338. /**
  339. * Internal errors. Means some invariants expected by underlying System has
  340. * been broken. If you see one of these errors, Something is very broken.
  341. */
  342. INTERNAL: 'internal',
  343. /**
  344. * The service is currently unavailable. This is a most likely a transient
  345. * condition and may be corrected by retrying with a backoff.
  346. *
  347. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  348. * and UNAVAILABLE.
  349. */
  350. UNAVAILABLE: 'unavailable',
  351. /** Unrecoverable data loss or corruption. */
  352. DATA_LOSS: 'data-loss'
  353. };
  354. /** An error returned by a Firestore operation. */
  355. class FirestoreError extends FirebaseError {
  356. /** @hideconstructor */
  357. constructor(
  358. /**
  359. * The backend error code associated with this error.
  360. */
  361. code,
  362. /**
  363. * A custom error description.
  364. */
  365. message) {
  366. super(code, message);
  367. this.code = code;
  368. this.message = message;
  369. // HACK: We write a toString property directly because Error is not a real
  370. // class and so inheritance does not work correctly. We could alternatively
  371. // do the same "back-door inheritance" trick that FirebaseError does.
  372. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  373. }
  374. }
  375. /**
  376. * @license
  377. * Copyright 2017 Google LLC
  378. *
  379. * Licensed under the Apache License, Version 2.0 (the "License");
  380. * you may not use this file except in compliance with the License.
  381. * You may obtain a copy of the License at
  382. *
  383. * http://www.apache.org/licenses/LICENSE-2.0
  384. *
  385. * Unless required by applicable law or agreed to in writing, software
  386. * distributed under the License is distributed on an "AS IS" BASIS,
  387. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  388. * See the License for the specific language governing permissions and
  389. * limitations under the License.
  390. */
  391. class Deferred {
  392. constructor() {
  393. this.promise = new Promise((resolve, reject) => {
  394. this.resolve = resolve;
  395. this.reject = reject;
  396. });
  397. }
  398. }
  399. /**
  400. * @license
  401. * Copyright 2017 Google LLC
  402. *
  403. * Licensed under the Apache License, Version 2.0 (the "License");
  404. * you may not use this file except in compliance with the License.
  405. * You may obtain a copy of the License at
  406. *
  407. * http://www.apache.org/licenses/LICENSE-2.0
  408. *
  409. * Unless required by applicable law or agreed to in writing, software
  410. * distributed under the License is distributed on an "AS IS" BASIS,
  411. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  412. * See the License for the specific language governing permissions and
  413. * limitations under the License.
  414. */
  415. class OAuthToken {
  416. constructor(value, user) {
  417. this.user = user;
  418. this.type = 'OAuth';
  419. this.headers = new Map();
  420. this.headers.set('Authorization', `Bearer ${value}`);
  421. }
  422. }
  423. /**
  424. * A CredentialsProvider that always yields an empty token.
  425. * @internal
  426. */
  427. class EmptyAuthCredentialsProvider {
  428. getToken() {
  429. return Promise.resolve(null);
  430. }
  431. invalidateToken() { }
  432. start(asyncQueue, changeListener) {
  433. // Fire with initial user.
  434. asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));
  435. }
  436. shutdown() { }
  437. }
  438. /**
  439. * A CredentialsProvider that always returns a constant token. Used for
  440. * emulator token mocking.
  441. */
  442. class EmulatorAuthCredentialsProvider {
  443. constructor(token) {
  444. this.token = token;
  445. /**
  446. * Stores the listener registered with setChangeListener()
  447. * This isn't actually necessary since the UID never changes, but we use this
  448. * to verify the listen contract is adhered to in tests.
  449. */
  450. this.changeListener = null;
  451. }
  452. getToken() {
  453. return Promise.resolve(this.token);
  454. }
  455. invalidateToken() { }
  456. start(asyncQueue, changeListener) {
  457. this.changeListener = changeListener;
  458. // Fire with initial user.
  459. asyncQueue.enqueueRetryable(() => changeListener(this.token.user));
  460. }
  461. shutdown() {
  462. this.changeListener = null;
  463. }
  464. }
  465. /** Credential provider for the Lite SDK. */
  466. class LiteAuthCredentialsProvider {
  467. constructor(authProvider) {
  468. this.auth = null;
  469. authProvider.onInit(auth => {
  470. this.auth = auth;
  471. });
  472. }
  473. getToken() {
  474. if (!this.auth) {
  475. return Promise.resolve(null);
  476. }
  477. return this.auth.getToken().then(tokenData => {
  478. if (tokenData) {
  479. hardAssert(typeof tokenData.accessToken === 'string');
  480. return new OAuthToken(tokenData.accessToken, new User(this.auth.getUid()));
  481. }
  482. else {
  483. return null;
  484. }
  485. });
  486. }
  487. invalidateToken() { }
  488. start(asyncQueue, changeListener) { }
  489. shutdown() { }
  490. }
  491. /*
  492. * FirstPartyToken provides a fresh token each time its value
  493. * is requested, because if the token is too old, requests will be rejected.
  494. * Technically this may no longer be necessary since the SDK should gracefully
  495. * recover from unauthenticated errors (see b/33147818 for context), but it's
  496. * safer to keep the implementation as-is.
  497. */
  498. class FirstPartyToken {
  499. constructor(sessionIndex, iamToken, authTokenFactory) {
  500. this.sessionIndex = sessionIndex;
  501. this.iamToken = iamToken;
  502. this.authTokenFactory = authTokenFactory;
  503. this.type = 'FirstParty';
  504. this.user = User.FIRST_PARTY;
  505. this._headers = new Map();
  506. }
  507. /**
  508. * Gets an authorization token, using a provided factory function, or return
  509. * null.
  510. */
  511. getAuthToken() {
  512. if (this.authTokenFactory) {
  513. return this.authTokenFactory();
  514. }
  515. else {
  516. return null;
  517. }
  518. }
  519. get headers() {
  520. this._headers.set('X-Goog-AuthUser', this.sessionIndex);
  521. // Use array notation to prevent minification
  522. const authHeaderTokenValue = this.getAuthToken();
  523. if (authHeaderTokenValue) {
  524. this._headers.set('Authorization', authHeaderTokenValue);
  525. }
  526. if (this.iamToken) {
  527. this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);
  528. }
  529. return this._headers;
  530. }
  531. }
  532. /*
  533. * Provides user credentials required for the Firestore JavaScript SDK
  534. * to authenticate the user, using technique that is only available
  535. * to applications hosted by Google.
  536. */
  537. class FirstPartyAuthCredentialsProvider {
  538. constructor(sessionIndex, iamToken, authTokenFactory) {
  539. this.sessionIndex = sessionIndex;
  540. this.iamToken = iamToken;
  541. this.authTokenFactory = authTokenFactory;
  542. }
  543. getToken() {
  544. return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory));
  545. }
  546. start(asyncQueue, changeListener) {
  547. // Fire with initial uid.
  548. asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));
  549. }
  550. shutdown() { }
  551. invalidateToken() { }
  552. }
  553. class AppCheckToken {
  554. constructor(value) {
  555. this.value = value;
  556. this.type = 'AppCheck';
  557. this.headers = new Map();
  558. if (value && value.length > 0) {
  559. this.headers.set('x-firebase-appcheck', this.value);
  560. }
  561. }
  562. }
  563. /** AppCheck token provider for the Lite SDK. */
  564. class LiteAppCheckTokenProvider {
  565. constructor(appCheckProvider) {
  566. this.appCheckProvider = appCheckProvider;
  567. this.appCheck = null;
  568. appCheckProvider.onInit(appCheck => {
  569. this.appCheck = appCheck;
  570. });
  571. }
  572. getToken() {
  573. if (!this.appCheck) {
  574. return Promise.resolve(null);
  575. }
  576. return this.appCheck.getToken().then(tokenResult => {
  577. if (tokenResult) {
  578. hardAssert(typeof tokenResult.token === 'string');
  579. return new AppCheckToken(tokenResult.token);
  580. }
  581. else {
  582. return null;
  583. }
  584. });
  585. }
  586. invalidateToken() { }
  587. start(asyncQueue, changeListener) { }
  588. shutdown() { }
  589. }
  590. /**
  591. * Builds a CredentialsProvider depending on the type of
  592. * the credentials passed in.
  593. */
  594. function makeAuthCredentialsProvider(credentials) {
  595. if (!credentials) {
  596. return new EmptyAuthCredentialsProvider();
  597. }
  598. switch (credentials['type']) {
  599. case 'firstParty':
  600. return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null);
  601. case 'provider':
  602. return credentials['client'];
  603. default:
  604. throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type');
  605. }
  606. }
  607. /**
  608. * @license
  609. * Copyright 2017 Google LLC
  610. *
  611. * Licensed under the Apache License, Version 2.0 (the "License");
  612. * you may not use this file except in compliance with the License.
  613. * You may obtain a copy of the License at
  614. *
  615. * http://www.apache.org/licenses/LICENSE-2.0
  616. *
  617. * Unless required by applicable law or agreed to in writing, software
  618. * distributed under the License is distributed on an "AS IS" BASIS,
  619. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  620. * See the License for the specific language governing permissions and
  621. * limitations under the License.
  622. */
  623. class DatabaseInfo {
  624. /**
  625. * Constructs a DatabaseInfo using the provided host, databaseId and
  626. * persistenceKey.
  627. *
  628. * @param databaseId - The database to use.
  629. * @param appId - The Firebase App Id.
  630. * @param persistenceKey - A unique identifier for this Firestore's local
  631. * storage (used in conjunction with the databaseId).
  632. * @param host - The Firestore backend host to connect to.
  633. * @param ssl - Whether to use SSL when connecting.
  634. * @param forceLongPolling - Whether to use the forceLongPolling option
  635. * when using WebChannel as the network transport.
  636. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  637. * option when using WebChannel as the network transport.
  638. * @param longPollingOptions Options that configure long-polling.
  639. * @param useFetchStreams Whether to use the Fetch API instead of
  640. * XMLHTTPRequest
  641. */
  642. constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams) {
  643. this.databaseId = databaseId;
  644. this.appId = appId;
  645. this.persistenceKey = persistenceKey;
  646. this.host = host;
  647. this.ssl = ssl;
  648. this.forceLongPolling = forceLongPolling;
  649. this.autoDetectLongPolling = autoDetectLongPolling;
  650. this.longPollingOptions = longPollingOptions;
  651. this.useFetchStreams = useFetchStreams;
  652. }
  653. }
  654. /** The default database name for a project. */
  655. const DEFAULT_DATABASE_NAME = '(default)';
  656. /**
  657. * Represents the database ID a Firestore client is associated with.
  658. * @internal
  659. */
  660. class DatabaseId {
  661. constructor(projectId, database) {
  662. this.projectId = projectId;
  663. this.database = database ? database : DEFAULT_DATABASE_NAME;
  664. }
  665. static empty() {
  666. return new DatabaseId('', '');
  667. }
  668. get isDefaultDatabase() {
  669. return this.database === DEFAULT_DATABASE_NAME;
  670. }
  671. isEqual(other) {
  672. return (other instanceof DatabaseId &&
  673. other.projectId === this.projectId &&
  674. other.database === this.database);
  675. }
  676. }
  677. function databaseIdFromApp(app, database) {
  678. if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {
  679. throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  680. }
  681. return new DatabaseId(app.options.projectId, database);
  682. }
  683. /**
  684. * @license
  685. * Copyright 2017 Google LLC
  686. *
  687. * Licensed under the Apache License, Version 2.0 (the "License");
  688. * you may not use this file except in compliance with the License.
  689. * You may obtain a copy of the License at
  690. *
  691. * http://www.apache.org/licenses/LICENSE-2.0
  692. *
  693. * Unless required by applicable law or agreed to in writing, software
  694. * distributed under the License is distributed on an "AS IS" BASIS,
  695. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  696. * See the License for the specific language governing permissions and
  697. * limitations under the License.
  698. */
  699. const DOCUMENT_KEY_NAME = '__name__';
  700. /**
  701. * Path represents an ordered sequence of string segments.
  702. */
  703. class BasePath {
  704. constructor(segments, offset, length) {
  705. if (offset === undefined) {
  706. offset = 0;
  707. }
  708. else if (offset > segments.length) {
  709. fail();
  710. }
  711. if (length === undefined) {
  712. length = segments.length - offset;
  713. }
  714. else if (length > segments.length - offset) {
  715. fail();
  716. }
  717. this.segments = segments;
  718. this.offset = offset;
  719. this.len = length;
  720. }
  721. get length() {
  722. return this.len;
  723. }
  724. isEqual(other) {
  725. return BasePath.comparator(this, other) === 0;
  726. }
  727. child(nameOrPath) {
  728. const segments = this.segments.slice(this.offset, this.limit());
  729. if (nameOrPath instanceof BasePath) {
  730. nameOrPath.forEach(segment => {
  731. segments.push(segment);
  732. });
  733. }
  734. else {
  735. segments.push(nameOrPath);
  736. }
  737. return this.construct(segments);
  738. }
  739. /** The index of one past the last segment of the path. */
  740. limit() {
  741. return this.offset + this.length;
  742. }
  743. popFirst(size) {
  744. size = size === undefined ? 1 : size;
  745. return this.construct(this.segments, this.offset + size, this.length - size);
  746. }
  747. popLast() {
  748. return this.construct(this.segments, this.offset, this.length - 1);
  749. }
  750. firstSegment() {
  751. return this.segments[this.offset];
  752. }
  753. lastSegment() {
  754. return this.get(this.length - 1);
  755. }
  756. get(index) {
  757. return this.segments[this.offset + index];
  758. }
  759. isEmpty() {
  760. return this.length === 0;
  761. }
  762. isPrefixOf(other) {
  763. if (other.length < this.length) {
  764. return false;
  765. }
  766. for (let i = 0; i < this.length; i++) {
  767. if (this.get(i) !== other.get(i)) {
  768. return false;
  769. }
  770. }
  771. return true;
  772. }
  773. isImmediateParentOf(potentialChild) {
  774. if (this.length + 1 !== potentialChild.length) {
  775. return false;
  776. }
  777. for (let i = 0; i < this.length; i++) {
  778. if (this.get(i) !== potentialChild.get(i)) {
  779. return false;
  780. }
  781. }
  782. return true;
  783. }
  784. forEach(fn) {
  785. for (let i = this.offset, end = this.limit(); i < end; i++) {
  786. fn(this.segments[i]);
  787. }
  788. }
  789. toArray() {
  790. return this.segments.slice(this.offset, this.limit());
  791. }
  792. static comparator(p1, p2) {
  793. const len = Math.min(p1.length, p2.length);
  794. for (let i = 0; i < len; i++) {
  795. const left = p1.get(i);
  796. const right = p2.get(i);
  797. if (left < right) {
  798. return -1;
  799. }
  800. if (left > right) {
  801. return 1;
  802. }
  803. }
  804. if (p1.length < p2.length) {
  805. return -1;
  806. }
  807. if (p1.length > p2.length) {
  808. return 1;
  809. }
  810. return 0;
  811. }
  812. }
  813. /**
  814. * A slash-separated path for navigating resources (documents and collections)
  815. * within Firestore.
  816. *
  817. * @internal
  818. */
  819. class ResourcePath extends BasePath {
  820. construct(segments, offset, length) {
  821. return new ResourcePath(segments, offset, length);
  822. }
  823. canonicalString() {
  824. // NOTE: The client is ignorant of any path segments containing escape
  825. // sequences (e.g. __id123__) and just passes them through raw (they exist
  826. // for legacy reasons and should not be used frequently).
  827. return this.toArray().join('/');
  828. }
  829. toString() {
  830. return this.canonicalString();
  831. }
  832. /**
  833. * Creates a resource path from the given slash-delimited string. If multiple
  834. * arguments are provided, all components are combined. Leading and trailing
  835. * slashes from all components are ignored.
  836. */
  837. static fromString(...pathComponents) {
  838. // NOTE: The client is ignorant of any path segments containing escape
  839. // sequences (e.g. __id123__) and just passes them through raw (they exist
  840. // for legacy reasons and should not be used frequently).
  841. const segments = [];
  842. for (const path of pathComponents) {
  843. if (path.indexOf('//') >= 0) {
  844. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`);
  845. }
  846. // Strip leading and traling slashed.
  847. segments.push(...path.split('/').filter(segment => segment.length > 0));
  848. }
  849. return new ResourcePath(segments);
  850. }
  851. static emptyPath() {
  852. return new ResourcePath([]);
  853. }
  854. }
  855. const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  856. /**
  857. * A dot-separated path for navigating sub-objects within a document.
  858. * @internal
  859. */
  860. class FieldPath$1 extends BasePath {
  861. construct(segments, offset, length) {
  862. return new FieldPath$1(segments, offset, length);
  863. }
  864. /**
  865. * Returns true if the string could be used as a segment in a field path
  866. * without escaping.
  867. */
  868. static isValidIdentifier(segment) {
  869. return identifierRegExp.test(segment);
  870. }
  871. canonicalString() {
  872. return this.toArray()
  873. .map(str => {
  874. str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`');
  875. if (!FieldPath$1.isValidIdentifier(str)) {
  876. str = '`' + str + '`';
  877. }
  878. return str;
  879. })
  880. .join('.');
  881. }
  882. toString() {
  883. return this.canonicalString();
  884. }
  885. /**
  886. * Returns true if this field references the key of a document.
  887. */
  888. isKeyField() {
  889. return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;
  890. }
  891. /**
  892. * The field designating the key of a document.
  893. */
  894. static keyField() {
  895. return new FieldPath$1([DOCUMENT_KEY_NAME]);
  896. }
  897. /**
  898. * Parses a field string from the given server-formatted string.
  899. *
  900. * - Splitting the empty string is not allowed (for now at least).
  901. * - Empty segments within the string (e.g. if there are two consecutive
  902. * separators) are not allowed.
  903. *
  904. * TODO(b/37244157): we should make this more strict. Right now, it allows
  905. * non-identifier path components, even if they aren't escaped.
  906. */
  907. static fromServerFormat(path) {
  908. const segments = [];
  909. let current = '';
  910. let i = 0;
  911. const addCurrentSegment = () => {
  912. if (current.length === 0) {
  913. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` +
  914. `with '.', end with '.', or contain '..'`);
  915. }
  916. segments.push(current);
  917. current = '';
  918. };
  919. let inBackticks = false;
  920. while (i < path.length) {
  921. const c = path[i];
  922. if (c === '\\') {
  923. if (i + 1 === path.length) {
  924. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);
  925. }
  926. const next = path[i + 1];
  927. if (!(next === '\\' || next === '.' || next === '`')) {
  928. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);
  929. }
  930. current += next;
  931. i += 2;
  932. }
  933. else if (c === '`') {
  934. inBackticks = !inBackticks;
  935. i++;
  936. }
  937. else if (c === '.' && !inBackticks) {
  938. addCurrentSegment();
  939. i++;
  940. }
  941. else {
  942. current += c;
  943. i++;
  944. }
  945. }
  946. addCurrentSegment();
  947. if (inBackticks) {
  948. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);
  949. }
  950. return new FieldPath$1(segments);
  951. }
  952. static emptyPath() {
  953. return new FieldPath$1([]);
  954. }
  955. }
  956. /**
  957. * @license
  958. * Copyright 2017 Google LLC
  959. *
  960. * Licensed under the Apache License, Version 2.0 (the "License");
  961. * you may not use this file except in compliance with the License.
  962. * You may obtain a copy of the License at
  963. *
  964. * http://www.apache.org/licenses/LICENSE-2.0
  965. *
  966. * Unless required by applicable law or agreed to in writing, software
  967. * distributed under the License is distributed on an "AS IS" BASIS,
  968. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  969. * See the License for the specific language governing permissions and
  970. * limitations under the License.
  971. */
  972. /**
  973. * @internal
  974. */
  975. class DocumentKey {
  976. constructor(path) {
  977. this.path = path;
  978. }
  979. static fromPath(path) {
  980. return new DocumentKey(ResourcePath.fromString(path));
  981. }
  982. static fromName(name) {
  983. return new DocumentKey(ResourcePath.fromString(name).popFirst(5));
  984. }
  985. static empty() {
  986. return new DocumentKey(ResourcePath.emptyPath());
  987. }
  988. get collectionGroup() {
  989. return this.path.popLast().lastSegment();
  990. }
  991. /** Returns true if the document is in the specified collectionId. */
  992. hasCollectionId(collectionId) {
  993. return (this.path.length >= 2 &&
  994. this.path.get(this.path.length - 2) === collectionId);
  995. }
  996. /** Returns the collection group (i.e. the name of the parent collection) for this key. */
  997. getCollectionGroup() {
  998. return this.path.get(this.path.length - 2);
  999. }
  1000. /** Returns the fully qualified path to the parent collection. */
  1001. getCollectionPath() {
  1002. return this.path.popLast();
  1003. }
  1004. isEqual(other) {
  1005. return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);
  1006. }
  1007. toString() {
  1008. return this.path.toString();
  1009. }
  1010. static comparator(k1, k2) {
  1011. return ResourcePath.comparator(k1.path, k2.path);
  1012. }
  1013. static isDocumentKey(path) {
  1014. return path.length % 2 === 0;
  1015. }
  1016. /**
  1017. * Creates and returns a new document key with the given segments.
  1018. *
  1019. * @param segments - The segments of the path to the document
  1020. * @returns A new instance of DocumentKey
  1021. */
  1022. static fromSegments(segments) {
  1023. return new DocumentKey(new ResourcePath(segments.slice()));
  1024. }
  1025. }
  1026. /**
  1027. * @license
  1028. * Copyright 2017 Google LLC
  1029. *
  1030. * Licensed under the Apache License, Version 2.0 (the "License");
  1031. * you may not use this file except in compliance with the License.
  1032. * You may obtain a copy of the License at
  1033. *
  1034. * http://www.apache.org/licenses/LICENSE-2.0
  1035. *
  1036. * Unless required by applicable law or agreed to in writing, software
  1037. * distributed under the License is distributed on an "AS IS" BASIS,
  1038. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1039. * See the License for the specific language governing permissions and
  1040. * limitations under the License.
  1041. */
  1042. function validateNonEmptyArgument(functionName, argumentName, argument) {
  1043. if (!argument) {
  1044. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`);
  1045. }
  1046. }
  1047. /**
  1048. * Validates that two boolean options are not set at the same time.
  1049. * @internal
  1050. */
  1051. function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) {
  1052. if (argument1 === true && argument2 === true) {
  1053. throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`);
  1054. }
  1055. }
  1056. /**
  1057. * Validates that `path` refers to a document (indicated by the fact it contains
  1058. * an even numbers of segments).
  1059. */
  1060. function validateDocumentPath(path) {
  1061. if (!DocumentKey.isDocumentKey(path)) {
  1062. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`);
  1063. }
  1064. }
  1065. /**
  1066. * Validates that `path` refers to a collection (indicated by the fact it
  1067. * contains an odd numbers of segments).
  1068. */
  1069. function validateCollectionPath(path) {
  1070. if (DocumentKey.isDocumentKey(path)) {
  1071. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`);
  1072. }
  1073. }
  1074. /**
  1075. * Returns true if it's a non-null object without a custom prototype
  1076. * (i.e. excludes Array, Date, etc.).
  1077. */
  1078. function isPlainObject(input) {
  1079. return (typeof input === 'object' &&
  1080. input !== null &&
  1081. (Object.getPrototypeOf(input) === Object.prototype ||
  1082. Object.getPrototypeOf(input) === null));
  1083. }
  1084. /** Returns a string describing the type / value of the provided input. */
  1085. function valueDescription(input) {
  1086. if (input === undefined) {
  1087. return 'undefined';
  1088. }
  1089. else if (input === null) {
  1090. return 'null';
  1091. }
  1092. else if (typeof input === 'string') {
  1093. if (input.length > 20) {
  1094. input = `${input.substring(0, 20)}...`;
  1095. }
  1096. return JSON.stringify(input);
  1097. }
  1098. else if (typeof input === 'number' || typeof input === 'boolean') {
  1099. return '' + input;
  1100. }
  1101. else if (typeof input === 'object') {
  1102. if (input instanceof Array) {
  1103. return 'an array';
  1104. }
  1105. else {
  1106. const customObjectName = tryGetCustomObjectType(input);
  1107. if (customObjectName) {
  1108. return `a custom ${customObjectName} object`;
  1109. }
  1110. else {
  1111. return 'an object';
  1112. }
  1113. }
  1114. }
  1115. else if (typeof input === 'function') {
  1116. return 'a function';
  1117. }
  1118. else {
  1119. return fail();
  1120. }
  1121. }
  1122. /** try to get the constructor name for an object. */
  1123. function tryGetCustomObjectType(input) {
  1124. if (input.constructor) {
  1125. return input.constructor.name;
  1126. }
  1127. return null;
  1128. }
  1129. /**
  1130. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  1131. * underlying instance. Throws if `obj` is not an instance of `T`.
  1132. *
  1133. * This cast is used in the Lite and Full SDK to verify instance types for
  1134. * arguments passed to the public API.
  1135. * @internal
  1136. */
  1137. function cast(obj,
  1138. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1139. constructor) {
  1140. if ('_delegate' in obj) {
  1141. // Unwrap Compat types
  1142. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1143. obj = obj._delegate;
  1144. }
  1145. if (!(obj instanceof constructor)) {
  1146. if (constructor.name === obj.constructor.name) {
  1147. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' +
  1148. `reference from a different Firestore SDK?`);
  1149. }
  1150. else {
  1151. const description = valueDescription(obj);
  1152. throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`);
  1153. }
  1154. }
  1155. return obj;
  1156. }
  1157. function validatePositiveNumber(functionName, n) {
  1158. if (n <= 0) {
  1159. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`);
  1160. }
  1161. }
  1162. /**
  1163. * @license
  1164. * Copyright 2023 Google LLC
  1165. *
  1166. * Licensed under the Apache License, Version 2.0 (the "License");
  1167. * you may not use this file except in compliance with the License.
  1168. * You may obtain a copy of the License at
  1169. *
  1170. * http://www.apache.org/licenses/LICENSE-2.0
  1171. *
  1172. * Unless required by applicable law or agreed to in writing, software
  1173. * distributed under the License is distributed on an "AS IS" BASIS,
  1174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1175. * See the License for the specific language governing permissions and
  1176. * limitations under the License.
  1177. */
  1178. /**
  1179. * Compares two `ExperimentalLongPollingOptions` objects for equality.
  1180. */
  1181. function longPollingOptionsEqual(options1, options2) {
  1182. return options1.timeoutSeconds === options2.timeoutSeconds;
  1183. }
  1184. /**
  1185. * Creates and returns a new `ExperimentalLongPollingOptions` with the same
  1186. * option values as the given instance.
  1187. */
  1188. function cloneLongPollingOptions(options) {
  1189. const clone = {};
  1190. if (options.timeoutSeconds !== undefined) {
  1191. clone.timeoutSeconds = options.timeoutSeconds;
  1192. }
  1193. return clone;
  1194. }
  1195. /**
  1196. * @license
  1197. * Copyright 2023 Google LLC
  1198. *
  1199. * Licensed under the Apache License, Version 2.0 (the "License");
  1200. * you may not use this file except in compliance with the License.
  1201. * You may obtain a copy of the License at
  1202. *
  1203. * http://www.apache.org/licenses/LICENSE-2.0
  1204. *
  1205. * Unless required by applicable law or agreed to in writing, software
  1206. * distributed under the License is distributed on an "AS IS" BASIS,
  1207. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1208. * See the License for the specific language governing permissions and
  1209. * limitations under the License.
  1210. */
  1211. /**
  1212. * The value returned from the most recent invocation of
  1213. * `generateUniqueDebugId()`, or null if it has never been invoked.
  1214. */
  1215. let lastUniqueDebugId = null;
  1216. /**
  1217. * Generates and returns an initial value for `lastUniqueDebugId`.
  1218. *
  1219. * The returned value is randomly selected from a range of integers that are
  1220. * represented as 8 hexadecimal digits. This means that (within reason) any
  1221. * numbers generated by incrementing the returned number by 1 will also be
  1222. * represented by 8 hexadecimal digits. This leads to all "IDs" having the same
  1223. * length when converted to a hexadecimal string, making reading logs containing
  1224. * these IDs easier to follow. And since the return value is randomly selected
  1225. * it will help to differentiate between logs from different executions.
  1226. */
  1227. function generateInitialUniqueDebugId() {
  1228. const minResult = 0x10000000;
  1229. const maxResult = 0x90000000;
  1230. const resultRange = maxResult - minResult;
  1231. const resultOffset = Math.round(resultRange * Math.random());
  1232. return minResult + resultOffset;
  1233. }
  1234. /**
  1235. * Generates and returns a unique ID as a hexadecimal string.
  1236. *
  1237. * The returned ID is intended to be used in debug logging messages to help
  1238. * correlate log messages that may be spatially separated in the logs, but
  1239. * logically related. For example, a network connection could include the same
  1240. * "debug ID" string in all of its log messages to help trace a specific
  1241. * connection over time.
  1242. *
  1243. * @return the 10-character generated ID (e.g. "0xa1b2c3d4").
  1244. */
  1245. function generateUniqueDebugId() {
  1246. if (lastUniqueDebugId === null) {
  1247. lastUniqueDebugId = generateInitialUniqueDebugId();
  1248. }
  1249. else {
  1250. lastUniqueDebugId++;
  1251. }
  1252. return '0x' + lastUniqueDebugId.toString(16);
  1253. }
  1254. /**
  1255. * @license
  1256. * Copyright 2020 Google LLC
  1257. *
  1258. * Licensed under the Apache License, Version 2.0 (the "License");
  1259. * you may not use this file except in compliance with the License.
  1260. * You may obtain a copy of the License at
  1261. *
  1262. * http://www.apache.org/licenses/LICENSE-2.0
  1263. *
  1264. * Unless required by applicable law or agreed to in writing, software
  1265. * distributed under the License is distributed on an "AS IS" BASIS,
  1266. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1267. * See the License for the specific language governing permissions and
  1268. * limitations under the License.
  1269. */
  1270. const LOG_TAG$3 = 'RestConnection';
  1271. /**
  1272. * Maps RPC names to the corresponding REST endpoint name.
  1273. *
  1274. * We use array notation to avoid mangling.
  1275. */
  1276. const RPC_NAME_URL_MAPPING = {};
  1277. RPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';
  1278. RPC_NAME_URL_MAPPING['Commit'] = 'commit';
  1279. RPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';
  1280. RPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';
  1281. const RPC_URL_VERSION = 'v1';
  1282. // SDK_VERSION is updated to different value at runtime depending on the entry point,
  1283. // so we need to get its value when we need it in a function.
  1284. function getGoogApiClientValue() {
  1285. return 'gl-js/ fire/' + SDK_VERSION;
  1286. }
  1287. /**
  1288. * Base class for all Rest-based connections to the backend (WebChannel and
  1289. * HTTP).
  1290. */
  1291. class RestConnection {
  1292. constructor(databaseInfo) {
  1293. this.databaseInfo = databaseInfo;
  1294. this.databaseId = databaseInfo.databaseId;
  1295. const proto = databaseInfo.ssl ? 'https' : 'http';
  1296. this.baseUrl = proto + '://' + databaseInfo.host;
  1297. this.databaseRoot =
  1298. 'projects/' +
  1299. this.databaseId.projectId +
  1300. '/databases/' +
  1301. this.databaseId.database +
  1302. '/documents';
  1303. }
  1304. get shouldResourcePathBeIncludedInRequest() {
  1305. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  1306. // where to run the query, and expect the `request` to NOT specify the "path".
  1307. return false;
  1308. }
  1309. invokeRPC(rpcName, path, req, authToken, appCheckToken) {
  1310. const streamId = generateUniqueDebugId();
  1311. const url = this.makeUrl(rpcName, path);
  1312. logDebug(LOG_TAG$3, `Sending RPC '${rpcName}' ${streamId}:`, url, req);
  1313. const headers = {};
  1314. this.modifyHeadersForRequest(headers, authToken, appCheckToken);
  1315. return this.performRPCRequest(rpcName, url, headers, req).then(response => {
  1316. logDebug(LOG_TAG$3, `Received RPC '${rpcName}' ${streamId}: `, response);
  1317. return response;
  1318. }, (err) => {
  1319. logWarn(LOG_TAG$3, `RPC '${rpcName}' ${streamId} failed with error: `, err, 'url: ', url, 'request:', req);
  1320. throw err;
  1321. });
  1322. }
  1323. invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) {
  1324. // The REST API automatically aggregates all of the streamed results, so we
  1325. // can just use the normal invoke() method.
  1326. return this.invokeRPC(rpcName, path, request, authToken, appCheckToken);
  1327. }
  1328. /**
  1329. * Modifies the headers for a request, adding any authorization token if
  1330. * present and any additional headers for the request.
  1331. */
  1332. modifyHeadersForRequest(headers, authToken, appCheckToken) {
  1333. headers['X-Goog-Api-Client'] = getGoogApiClientValue();
  1334. // Content-Type: text/plain will avoid preflight requests which might
  1335. // mess with CORS and redirects by proxies. If we add custom headers
  1336. // we will need to change this code to potentially use the $httpOverwrite
  1337. // parameter supported by ESF to avoid triggering preflight requests.
  1338. headers['Content-Type'] = 'text/plain';
  1339. if (this.databaseInfo.appId) {
  1340. headers['X-Firebase-GMPID'] = this.databaseInfo.appId;
  1341. }
  1342. if (authToken) {
  1343. authToken.headers.forEach((value, key) => (headers[key] = value));
  1344. }
  1345. if (appCheckToken) {
  1346. appCheckToken.headers.forEach((value, key) => (headers[key] = value));
  1347. }
  1348. }
  1349. makeUrl(rpcName, path) {
  1350. const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];
  1351. return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;
  1352. }
  1353. }
  1354. /**
  1355. * @license
  1356. * Copyright 2017 Google LLC
  1357. *
  1358. * Licensed under the Apache License, Version 2.0 (the "License");
  1359. * you may not use this file except in compliance with the License.
  1360. * You may obtain a copy of the License at
  1361. *
  1362. * http://www.apache.org/licenses/LICENSE-2.0
  1363. *
  1364. * Unless required by applicable law or agreed to in writing, software
  1365. * distributed under the License is distributed on an "AS IS" BASIS,
  1366. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1367. * See the License for the specific language governing permissions and
  1368. * limitations under the License.
  1369. */
  1370. /**
  1371. * Error Codes describing the different ways GRPC can fail. These are copied
  1372. * directly from GRPC's sources here:
  1373. *
  1374. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  1375. *
  1376. * Important! The names of these identifiers matter because the string forms
  1377. * are used for reverse lookups from the webchannel stream. Do NOT change the
  1378. * names of these identifiers or change this into a const enum.
  1379. */
  1380. var RpcCode;
  1381. (function (RpcCode) {
  1382. RpcCode[RpcCode["OK"] = 0] = "OK";
  1383. RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED";
  1384. RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN";
  1385. RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
  1386. RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
  1387. RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND";
  1388. RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
  1389. RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
  1390. RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
  1391. RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
  1392. RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
  1393. RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED";
  1394. RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
  1395. RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
  1396. RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL";
  1397. RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE";
  1398. RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS";
  1399. })(RpcCode || (RpcCode = {}));
  1400. /**
  1401. * Determines whether an error code represents a permanent error when received
  1402. * in response to a non-write operation.
  1403. *
  1404. * See isPermanentWriteError for classifying write errors.
  1405. */
  1406. function isPermanentError(code) {
  1407. switch (code) {
  1408. case Code.OK:
  1409. return fail();
  1410. case Code.CANCELLED:
  1411. case Code.UNKNOWN:
  1412. case Code.DEADLINE_EXCEEDED:
  1413. case Code.RESOURCE_EXHAUSTED:
  1414. case Code.INTERNAL:
  1415. case Code.UNAVAILABLE:
  1416. // Unauthenticated means something went wrong with our token and we need
  1417. // to retry with new credentials which will happen automatically.
  1418. case Code.UNAUTHENTICATED:
  1419. return false;
  1420. case Code.INVALID_ARGUMENT:
  1421. case Code.NOT_FOUND:
  1422. case Code.ALREADY_EXISTS:
  1423. case Code.PERMISSION_DENIED:
  1424. case Code.FAILED_PRECONDITION:
  1425. // Aborted might be retried in some scenarios, but that is dependant on
  1426. // the context and should handled individually by the calling code.
  1427. // See https://cloud.google.com/apis/design/errors.
  1428. case Code.ABORTED:
  1429. case Code.OUT_OF_RANGE:
  1430. case Code.UNIMPLEMENTED:
  1431. case Code.DATA_LOSS:
  1432. return true;
  1433. default:
  1434. return fail();
  1435. }
  1436. }
  1437. /**
  1438. * Converts an HTTP Status Code to the equivalent error code.
  1439. *
  1440. * @param status - An HTTP Status Code, like 200, 404, 503, etc.
  1441. * @returns The equivalent Code. Unknown status codes are mapped to
  1442. * Code.UNKNOWN.
  1443. */
  1444. function mapCodeFromHttpStatus(status) {
  1445. if (status === undefined) {
  1446. logError('RPC_ERROR', 'HTTP error has no status');
  1447. return Code.UNKNOWN;
  1448. }
  1449. // The canonical error codes for Google APIs [1] specify mapping onto HTTP
  1450. // status codes but the mapping is not bijective. In each case of ambiguity
  1451. // this function chooses a primary error.
  1452. //
  1453. // [1]
  1454. // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  1455. switch (status) {
  1456. case 200: // OK
  1457. return Code.OK;
  1458. case 400: // Bad Request
  1459. return Code.FAILED_PRECONDITION;
  1460. // Other possibilities based on the forward mapping
  1461. // return Code.INVALID_ARGUMENT;
  1462. // return Code.OUT_OF_RANGE;
  1463. case 401: // Unauthorized
  1464. return Code.UNAUTHENTICATED;
  1465. case 403: // Forbidden
  1466. return Code.PERMISSION_DENIED;
  1467. case 404: // Not Found
  1468. return Code.NOT_FOUND;
  1469. case 409: // Conflict
  1470. return Code.ABORTED;
  1471. // Other possibilities:
  1472. // return Code.ALREADY_EXISTS;
  1473. case 416: // Range Not Satisfiable
  1474. return Code.OUT_OF_RANGE;
  1475. case 429: // Too Many Requests
  1476. return Code.RESOURCE_EXHAUSTED;
  1477. case 499: // Client Closed Request
  1478. return Code.CANCELLED;
  1479. case 500: // Internal Server Error
  1480. return Code.UNKNOWN;
  1481. // Other possibilities:
  1482. // return Code.INTERNAL;
  1483. // return Code.DATA_LOSS;
  1484. case 501: // Unimplemented
  1485. return Code.UNIMPLEMENTED;
  1486. case 503: // Service Unavailable
  1487. return Code.UNAVAILABLE;
  1488. case 504: // Gateway Timeout
  1489. return Code.DEADLINE_EXCEEDED;
  1490. default:
  1491. if (status >= 200 && status < 300) {
  1492. return Code.OK;
  1493. }
  1494. if (status >= 400 && status < 500) {
  1495. return Code.FAILED_PRECONDITION;
  1496. }
  1497. if (status >= 500 && status < 600) {
  1498. return Code.INTERNAL;
  1499. }
  1500. return Code.UNKNOWN;
  1501. }
  1502. }
  1503. /**
  1504. * @license
  1505. * Copyright 2020 Google LLC
  1506. *
  1507. * Licensed under the Apache License, Version 2.0 (the "License");
  1508. * you may not use this file except in compliance with the License.
  1509. * You may obtain a copy of the License at
  1510. *
  1511. * http://www.apache.org/licenses/LICENSE-2.0
  1512. *
  1513. * Unless required by applicable law or agreed to in writing, software
  1514. * distributed under the License is distributed on an "AS IS" BASIS,
  1515. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1516. * See the License for the specific language governing permissions and
  1517. * limitations under the License.
  1518. */
  1519. /**
  1520. * A Rest-based connection that relies on the native HTTP stack
  1521. * (e.g. `fetch` or a polyfill).
  1522. */
  1523. class FetchConnection extends RestConnection {
  1524. /**
  1525. * @param databaseInfo - The connection info.
  1526. * @param fetchImpl - `fetch` or a Polyfill that implements the fetch API.
  1527. */
  1528. constructor(databaseInfo, fetchImpl) {
  1529. super(databaseInfo);
  1530. this.fetchImpl = fetchImpl;
  1531. }
  1532. openStream(rpcName, token) {
  1533. throw new Error('Not supported by FetchConnection');
  1534. }
  1535. async performRPCRequest(rpcName, url, headers, body) {
  1536. var _a;
  1537. const requestJson = JSON.stringify(body);
  1538. let response;
  1539. try {
  1540. response = await this.fetchImpl(url, {
  1541. method: 'POST',
  1542. headers,
  1543. body: requestJson
  1544. });
  1545. }
  1546. catch (e) {
  1547. const err = e;
  1548. throw new FirestoreError(mapCodeFromHttpStatus(err.status), 'Request failed with error: ' + err.statusText);
  1549. }
  1550. if (!response.ok) {
  1551. let errorResponse = await response.json();
  1552. if (Array.isArray(errorResponse)) {
  1553. errorResponse = errorResponse[0];
  1554. }
  1555. const errorMessage = (_a = errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.error) === null || _a === void 0 ? void 0 : _a.message;
  1556. throw new FirestoreError(mapCodeFromHttpStatus(response.status), `Request failed with error: ${errorMessage !== null && errorMessage !== void 0 ? errorMessage : response.statusText}`);
  1557. }
  1558. return response.json();
  1559. }
  1560. }
  1561. /**
  1562. * @license
  1563. * Copyright 2020 Google LLC
  1564. *
  1565. * Licensed under the Apache License, Version 2.0 (the "License");
  1566. * you may not use this file except in compliance with the License.
  1567. * You may obtain a copy of the License at
  1568. *
  1569. * http://www.apache.org/licenses/LICENSE-2.0
  1570. *
  1571. * Unless required by applicable law or agreed to in writing, software
  1572. * distributed under the License is distributed on an "AS IS" BASIS,
  1573. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1574. * See the License for the specific language governing permissions and
  1575. * limitations under the License.
  1576. */
  1577. /** Initializes the HTTP connection for the REST API. */
  1578. function newConnection(databaseInfo) {
  1579. // node-fetch is meant to be API compatible with `fetch`, but its type doesn't
  1580. // match 100%.
  1581. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1582. return new FetchConnection(databaseInfo, nodeFetch);
  1583. }
  1584. /**
  1585. * @license
  1586. * Copyright 2020 Google LLC
  1587. *
  1588. * Licensed under the Apache License, Version 2.0 (the "License");
  1589. * you may not use this file except in compliance with the License.
  1590. * You may obtain a copy of the License at
  1591. *
  1592. * http://www.apache.org/licenses/LICENSE-2.0
  1593. *
  1594. * Unless required by applicable law or agreed to in writing, software
  1595. * distributed under the License is distributed on an "AS IS" BASIS,
  1596. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1597. * See the License for the specific language governing permissions and
  1598. * limitations under the License.
  1599. */
  1600. /**
  1601. * Generates `nBytes` of random bytes.
  1602. *
  1603. * If `nBytes < 0` , an error will be thrown.
  1604. */
  1605. function randomBytes(nBytes) {
  1606. return randomBytes$1(nBytes);
  1607. }
  1608. /**
  1609. * @license
  1610. * Copyright 2017 Google LLC
  1611. *
  1612. * Licensed under the Apache License, Version 2.0 (the "License");
  1613. * you may not use this file except in compliance with the License.
  1614. * You may obtain a copy of the License at
  1615. *
  1616. * http://www.apache.org/licenses/LICENSE-2.0
  1617. *
  1618. * Unless required by applicable law or agreed to in writing, software
  1619. * distributed under the License is distributed on an "AS IS" BASIS,
  1620. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1621. * See the License for the specific language governing permissions and
  1622. * limitations under the License.
  1623. */
  1624. class AutoId {
  1625. static newId() {
  1626. // Alphanumeric characters
  1627. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  1628. // The largest byte value that is a multiple of `char.length`.
  1629. const maxMultiple = Math.floor(256 / chars.length) * chars.length;
  1630. let autoId = '';
  1631. const targetLength = 20;
  1632. while (autoId.length < targetLength) {
  1633. const bytes = randomBytes(40);
  1634. for (let i = 0; i < bytes.length; ++i) {
  1635. // Only accept values that are [0, maxMultiple), this ensures they can
  1636. // be evenly mapped to indices of `chars` via a modulo operation.
  1637. if (autoId.length < targetLength && bytes[i] < maxMultiple) {
  1638. autoId += chars.charAt(bytes[i] % chars.length);
  1639. }
  1640. }
  1641. }
  1642. return autoId;
  1643. }
  1644. }
  1645. function primitiveComparator(left, right) {
  1646. if (left < right) {
  1647. return -1;
  1648. }
  1649. if (left > right) {
  1650. return 1;
  1651. }
  1652. return 0;
  1653. }
  1654. /** Helper to compare arrays using isEqual(). */
  1655. function arrayEquals(left, right, comparator) {
  1656. if (left.length !== right.length) {
  1657. return false;
  1658. }
  1659. return left.every((value, index) => comparator(value, right[index]));
  1660. }
  1661. /**
  1662. * @license
  1663. * Copyright 2017 Google LLC
  1664. *
  1665. * Licensed under the Apache License, Version 2.0 (the "License");
  1666. * you may not use this file except in compliance with the License.
  1667. * You may obtain a copy of the License at
  1668. *
  1669. * http://www.apache.org/licenses/LICENSE-2.0
  1670. *
  1671. * Unless required by applicable law or agreed to in writing, software
  1672. * distributed under the License is distributed on an "AS IS" BASIS,
  1673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1674. * See the License for the specific language governing permissions and
  1675. * limitations under the License.
  1676. */
  1677. function objectSize(obj) {
  1678. let count = 0;
  1679. for (const key in obj) {
  1680. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1681. count++;
  1682. }
  1683. }
  1684. return count;
  1685. }
  1686. function forEach(obj, fn) {
  1687. for (const key in obj) {
  1688. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1689. fn(key, obj[key]);
  1690. }
  1691. }
  1692. }
  1693. function mapToArray(obj, fn) {
  1694. const result = [];
  1695. for (const key in obj) {
  1696. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1697. result.push(fn(obj[key], key, obj));
  1698. }
  1699. }
  1700. return result;
  1701. }
  1702. function isEmpty(obj) {
  1703. for (const key in obj) {
  1704. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1705. return false;
  1706. }
  1707. }
  1708. return true;
  1709. }
  1710. /**
  1711. * @license
  1712. * Copyright 2017 Google LLC
  1713. *
  1714. * Licensed under the Apache License, Version 2.0 (the "License");
  1715. * you may not use this file except in compliance with the License.
  1716. * You may obtain a copy of the License at
  1717. *
  1718. * http://www.apache.org/licenses/LICENSE-2.0
  1719. *
  1720. * Unless required by applicable law or agreed to in writing, software
  1721. * distributed under the License is distributed on an "AS IS" BASIS,
  1722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1723. * See the License for the specific language governing permissions and
  1724. * limitations under the License.
  1725. */
  1726. /**
  1727. * Returns whether a variable is either undefined or null.
  1728. */
  1729. function isNullOrUndefined(value) {
  1730. return value === null || value === undefined;
  1731. }
  1732. /** Returns whether the value represents -0. */
  1733. function isNegativeZero(value) {
  1734. // Detect if the value is -0.0. Based on polyfill from
  1735. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  1736. return value === 0 && 1 / value === 1 / -0;
  1737. }
  1738. /**
  1739. * Returns whether a value is an integer and in the safe integer range
  1740. * @param value - The value to test for being an integer and in the safe range
  1741. */
  1742. function isSafeInteger(value) {
  1743. return (typeof value === 'number' &&
  1744. Number.isInteger(value) &&
  1745. !isNegativeZero(value) &&
  1746. value <= Number.MAX_SAFE_INTEGER &&
  1747. value >= Number.MIN_SAFE_INTEGER);
  1748. }
  1749. /**
  1750. * @license
  1751. * Copyright 2020 Google LLC
  1752. *
  1753. * Licensed under the Apache License, Version 2.0 (the "License");
  1754. * you may not use this file except in compliance with the License.
  1755. * You may obtain a copy of the License at
  1756. *
  1757. * http://www.apache.org/licenses/LICENSE-2.0
  1758. *
  1759. * Unless required by applicable law or agreed to in writing, software
  1760. * distributed under the License is distributed on an "AS IS" BASIS,
  1761. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1762. * See the License for the specific language governing permissions and
  1763. * limitations under the License.
  1764. */
  1765. /** Converts a Base64 encoded string to a binary string. */
  1766. function decodeBase64(encoded) {
  1767. // Note: We used to validate the base64 string here via a regular expression.
  1768. // This was removed to improve the performance of indexing.
  1769. return Buffer.from(encoded, 'base64').toString('binary');
  1770. }
  1771. /** Converts a binary string to a Base64 encoded string. */
  1772. function encodeBase64(raw) {
  1773. return Buffer.from(raw, 'binary').toString('base64');
  1774. }
  1775. /**
  1776. * @license
  1777. * Copyright 2020 Google LLC
  1778. *
  1779. * Licensed under the Apache License, Version 2.0 (the "License");
  1780. * you may not use this file except in compliance with the License.
  1781. * You may obtain a copy of the License at
  1782. *
  1783. * http://www.apache.org/licenses/LICENSE-2.0
  1784. *
  1785. * Unless required by applicable law or agreed to in writing, software
  1786. * distributed under the License is distributed on an "AS IS" BASIS,
  1787. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1788. * See the License for the specific language governing permissions and
  1789. * limitations under the License.
  1790. */
  1791. /**
  1792. * Immutable class that represents a "proto" byte string.
  1793. *
  1794. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  1795. * sent on the wire. This class abstracts away this differentiation by holding
  1796. * the proto byte string in a common class that must be converted into a string
  1797. * before being sent as a proto.
  1798. * @internal
  1799. */
  1800. class ByteString {
  1801. constructor(binaryString) {
  1802. this.binaryString = binaryString;
  1803. }
  1804. static fromBase64String(base64) {
  1805. const binaryString = decodeBase64(base64);
  1806. return new ByteString(binaryString);
  1807. }
  1808. static fromUint8Array(array) {
  1809. // TODO(indexing); Remove the copy of the byte string here as this method
  1810. // is frequently called during indexing.
  1811. const binaryString = binaryStringFromUint8Array(array);
  1812. return new ByteString(binaryString);
  1813. }
  1814. [Symbol.iterator]() {
  1815. let i = 0;
  1816. return {
  1817. next: () => {
  1818. if (i < this.binaryString.length) {
  1819. return { value: this.binaryString.charCodeAt(i++), done: false };
  1820. }
  1821. else {
  1822. return { value: undefined, done: true };
  1823. }
  1824. }
  1825. };
  1826. }
  1827. toBase64() {
  1828. return encodeBase64(this.binaryString);
  1829. }
  1830. toUint8Array() {
  1831. return uint8ArrayFromBinaryString(this.binaryString);
  1832. }
  1833. approximateByteSize() {
  1834. return this.binaryString.length * 2;
  1835. }
  1836. compareTo(other) {
  1837. return primitiveComparator(this.binaryString, other.binaryString);
  1838. }
  1839. isEqual(other) {
  1840. return this.binaryString === other.binaryString;
  1841. }
  1842. }
  1843. ByteString.EMPTY_BYTE_STRING = new ByteString('');
  1844. /**
  1845. * Helper function to convert an Uint8array to a binary string.
  1846. */
  1847. function binaryStringFromUint8Array(array) {
  1848. let binaryString = '';
  1849. for (let i = 0; i < array.length; ++i) {
  1850. binaryString += String.fromCharCode(array[i]);
  1851. }
  1852. return binaryString;
  1853. }
  1854. /**
  1855. * Helper function to convert a binary string to an Uint8Array.
  1856. */
  1857. function uint8ArrayFromBinaryString(binaryString) {
  1858. const buffer = new Uint8Array(binaryString.length);
  1859. for (let i = 0; i < binaryString.length; i++) {
  1860. buffer[i] = binaryString.charCodeAt(i);
  1861. }
  1862. return buffer;
  1863. }
  1864. /**
  1865. * @license
  1866. * Copyright 2020 Google LLC
  1867. *
  1868. * Licensed under the Apache License, Version 2.0 (the "License");
  1869. * you may not use this file except in compliance with the License.
  1870. * You may obtain a copy of the License at
  1871. *
  1872. * http://www.apache.org/licenses/LICENSE-2.0
  1873. *
  1874. * Unless required by applicable law or agreed to in writing, software
  1875. * distributed under the License is distributed on an "AS IS" BASIS,
  1876. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1877. * See the License for the specific language governing permissions and
  1878. * limitations under the License.
  1879. */
  1880. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  1881. const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  1882. /**
  1883. * Converts the possible Proto values for a timestamp value into a "seconds and
  1884. * nanos" representation.
  1885. */
  1886. function normalizeTimestamp(date) {
  1887. hardAssert(!!date);
  1888. // The json interface (for the browser) will return an iso timestamp string,
  1889. // while the proto js library (for node) will return a
  1890. // google.protobuf.Timestamp instance.
  1891. if (typeof date === 'string') {
  1892. // The date string can have higher precision (nanos) than the Date class
  1893. // (millis), so we do some custom parsing here.
  1894. // Parse the nanos right out of the string.
  1895. let nanos = 0;
  1896. const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);
  1897. hardAssert(!!fraction);
  1898. if (fraction[1]) {
  1899. // Pad the fraction out to 9 digits (nanos).
  1900. let nanoStr = fraction[1];
  1901. nanoStr = (nanoStr + '000000000').substr(0, 9);
  1902. nanos = Number(nanoStr);
  1903. }
  1904. // Parse the date to get the seconds.
  1905. const parsedDate = new Date(date);
  1906. const seconds = Math.floor(parsedDate.getTime() / 1000);
  1907. return { seconds, nanos };
  1908. }
  1909. else {
  1910. // TODO(b/37282237): Use strings for Proto3 timestamps
  1911. // assert(!this.options.useProto3Json,
  1912. // 'The timestamp instance format requires Proto JS.');
  1913. const seconds = normalizeNumber(date.seconds);
  1914. const nanos = normalizeNumber(date.nanos);
  1915. return { seconds, nanos };
  1916. }
  1917. }
  1918. /**
  1919. * Converts the possible Proto types for numbers into a JavaScript number.
  1920. * Returns 0 if the value is not numeric.
  1921. */
  1922. function normalizeNumber(value) {
  1923. // TODO(bjornick): Handle int64 greater than 53 bits.
  1924. if (typeof value === 'number') {
  1925. return value;
  1926. }
  1927. else if (typeof value === 'string') {
  1928. return Number(value);
  1929. }
  1930. else {
  1931. return 0;
  1932. }
  1933. }
  1934. /** Converts the possible Proto types for Blobs into a ByteString. */
  1935. function normalizeByteString(blob) {
  1936. if (typeof blob === 'string') {
  1937. return ByteString.fromBase64String(blob);
  1938. }
  1939. else {
  1940. return ByteString.fromUint8Array(blob);
  1941. }
  1942. }
  1943. /**
  1944. * @license
  1945. * Copyright 2017 Google LLC
  1946. *
  1947. * Licensed under the Apache License, Version 2.0 (the "License");
  1948. * you may not use this file except in compliance with the License.
  1949. * You may obtain a copy of the License at
  1950. *
  1951. * http://www.apache.org/licenses/LICENSE-2.0
  1952. *
  1953. * Unless required by applicable law or agreed to in writing, software
  1954. * distributed under the License is distributed on an "AS IS" BASIS,
  1955. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1956. * See the License for the specific language governing permissions and
  1957. * limitations under the License.
  1958. */
  1959. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  1960. const MIN_SECONDS = -62135596800;
  1961. // Number of nanoseconds in a millisecond.
  1962. const MS_TO_NANOS = 1e6;
  1963. /**
  1964. * A `Timestamp` represents a point in time independent of any time zone or
  1965. * calendar, represented as seconds and fractions of seconds at nanosecond
  1966. * resolution in UTC Epoch time.
  1967. *
  1968. * It is encoded using the Proleptic Gregorian Calendar which extends the
  1969. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  1970. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  1971. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  1972. * 9999-12-31T23:59:59.999999999Z.
  1973. *
  1974. * For examples and further specifications, refer to the
  1975. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  1976. */
  1977. class Timestamp {
  1978. /**
  1979. * Creates a new timestamp.
  1980. *
  1981. * @param seconds - The number of seconds of UTC time since Unix epoch
  1982. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  1983. * 9999-12-31T23:59:59Z inclusive.
  1984. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  1985. * resolution. Negative second values with fractions must still have
  1986. * non-negative nanoseconds values that count forward in time. Must be
  1987. * from 0 to 999,999,999 inclusive.
  1988. */
  1989. constructor(
  1990. /**
  1991. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  1992. */
  1993. seconds,
  1994. /**
  1995. * The fractions of a second at nanosecond resolution.*
  1996. */
  1997. nanoseconds) {
  1998. this.seconds = seconds;
  1999. this.nanoseconds = nanoseconds;
  2000. if (nanoseconds < 0) {
  2001. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
  2002. }
  2003. if (nanoseconds >= 1e9) {
  2004. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
  2005. }
  2006. if (seconds < MIN_SECONDS) {
  2007. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
  2008. }
  2009. // This will break in the year 10,000.
  2010. if (seconds >= 253402300800) {
  2011. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
  2012. }
  2013. }
  2014. /**
  2015. * Creates a new timestamp with the current date, with millisecond precision.
  2016. *
  2017. * @returns a new timestamp representing the current date.
  2018. */
  2019. static now() {
  2020. return Timestamp.fromMillis(Date.now());
  2021. }
  2022. /**
  2023. * Creates a new timestamp from the given date.
  2024. *
  2025. * @param date - The date to initialize the `Timestamp` from.
  2026. * @returns A new `Timestamp` representing the same point in time as the given
  2027. * date.
  2028. */
  2029. static fromDate(date) {
  2030. return Timestamp.fromMillis(date.getTime());
  2031. }
  2032. /**
  2033. * Creates a new timestamp from the given number of milliseconds.
  2034. *
  2035. * @param milliseconds - Number of milliseconds since Unix epoch
  2036. * 1970-01-01T00:00:00Z.
  2037. * @returns A new `Timestamp` representing the same point in time as the given
  2038. * number of milliseconds.
  2039. */
  2040. static fromMillis(milliseconds) {
  2041. const seconds = Math.floor(milliseconds / 1000);
  2042. const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);
  2043. return new Timestamp(seconds, nanos);
  2044. }
  2045. /**
  2046. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  2047. * causes a loss of precision since `Date` objects only support millisecond
  2048. * precision.
  2049. *
  2050. * @returns JavaScript `Date` object representing the same point in time as
  2051. * this `Timestamp`, with millisecond precision.
  2052. */
  2053. toDate() {
  2054. return new Date(this.toMillis());
  2055. }
  2056. /**
  2057. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  2058. * epoch). This operation causes a loss of precision.
  2059. *
  2060. * @returns The point in time corresponding to this timestamp, represented as
  2061. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  2062. */
  2063. toMillis() {
  2064. return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;
  2065. }
  2066. _compareTo(other) {
  2067. if (this.seconds === other.seconds) {
  2068. return primitiveComparator(this.nanoseconds, other.nanoseconds);
  2069. }
  2070. return primitiveComparator(this.seconds, other.seconds);
  2071. }
  2072. /**
  2073. * Returns true if this `Timestamp` is equal to the provided one.
  2074. *
  2075. * @param other - The `Timestamp` to compare against.
  2076. * @returns true if this `Timestamp` is equal to the provided one.
  2077. */
  2078. isEqual(other) {
  2079. return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds);
  2080. }
  2081. /** Returns a textual representation of this `Timestamp`. */
  2082. toString() {
  2083. return ('Timestamp(seconds=' +
  2084. this.seconds +
  2085. ', nanoseconds=' +
  2086. this.nanoseconds +
  2087. ')');
  2088. }
  2089. /** Returns a JSON-serializable representation of this `Timestamp`. */
  2090. toJSON() {
  2091. return { seconds: this.seconds, nanoseconds: this.nanoseconds };
  2092. }
  2093. /**
  2094. * Converts this object to a primitive string, which allows `Timestamp` objects
  2095. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  2096. */
  2097. valueOf() {
  2098. // This method returns a string of the form <seconds>.<nanoseconds> where
  2099. // <seconds> is translated to have a non-negative value and both <seconds>
  2100. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  2101. // Strings with this format then have a lexiographical ordering that matches
  2102. // the expected ordering. The <seconds> translation is done to avoid having
  2103. // a leading negative sign (i.e. a leading '-' character) in its string
  2104. // representation, which would affect its lexiographical ordering.
  2105. const adjustedSeconds = this.seconds - MIN_SECONDS;
  2106. // Note: Up to 12 decimal digits are required to represent all valid
  2107. // 'seconds' values.
  2108. const formattedSeconds = String(adjustedSeconds).padStart(12, '0');
  2109. const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');
  2110. return formattedSeconds + '.' + formattedNanoseconds;
  2111. }
  2112. }
  2113. /**
  2114. * @license
  2115. * Copyright 2020 Google LLC
  2116. *
  2117. * Licensed under the Apache License, Version 2.0 (the "License");
  2118. * you may not use this file except in compliance with the License.
  2119. * You may obtain a copy of the License at
  2120. *
  2121. * http://www.apache.org/licenses/LICENSE-2.0
  2122. *
  2123. * Unless required by applicable law or agreed to in writing, software
  2124. * distributed under the License is distributed on an "AS IS" BASIS,
  2125. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2126. * See the License for the specific language governing permissions and
  2127. * limitations under the License.
  2128. */
  2129. /**
  2130. * Represents a locally-applied ServerTimestamp.
  2131. *
  2132. * Server Timestamps are backed by MapValues that contain an internal field
  2133. * `__type__` with a value of `server_timestamp`. The previous value and local
  2134. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2135. * fields respectively.
  2136. *
  2137. * Notes:
  2138. * - ServerTimestampValue instances are created as the result of applying a
  2139. * transform. They can only exist in the local view of a document. Therefore
  2140. * they do not need to be parsed or serialized.
  2141. * - When evaluated locally (e.g. for snapshot.data()), they by default
  2142. * evaluate to `null`. This behavior can be configured by passing custom
  2143. * FieldValueOptions to value().
  2144. * - With respect to other ServerTimestampValues, they sort by their
  2145. * localWriteTime.
  2146. */
  2147. const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';
  2148. const TYPE_KEY = '__type__';
  2149. const PREVIOUS_VALUE_KEY = '__previous_value__';
  2150. const LOCAL_WRITE_TIME_KEY = '__local_write_time__';
  2151. function isServerTimestamp(value) {
  2152. var _a, _b;
  2153. const type = (_b = (((_a = value === null || value === void 0 ? void 0 : value.mapValue) === null || _a === void 0 ? void 0 : _a.fields) || {})[TYPE_KEY]) === null || _b === void 0 ? void 0 : _b.stringValue;
  2154. return type === SERVER_TIMESTAMP_SENTINEL;
  2155. }
  2156. /**
  2157. * Returns the value of the field before this ServerTimestamp was set.
  2158. *
  2159. * Preserving the previous values allows the user to display the last resoled
  2160. * value until the backend responds with the timestamp.
  2161. */
  2162. function getPreviousValue(value) {
  2163. const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY];
  2164. if (isServerTimestamp(previousValue)) {
  2165. return getPreviousValue(previousValue);
  2166. }
  2167. return previousValue;
  2168. }
  2169. /**
  2170. * Returns the local time at which this timestamp was first set.
  2171. */
  2172. function getLocalWriteTime(value) {
  2173. const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue);
  2174. return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);
  2175. }
  2176. /**
  2177. * @license
  2178. * Copyright 2020 Google LLC
  2179. *
  2180. * Licensed under the Apache License, Version 2.0 (the "License");
  2181. * you may not use this file except in compliance with the License.
  2182. * You may obtain a copy of the License at
  2183. *
  2184. * http://www.apache.org/licenses/LICENSE-2.0
  2185. *
  2186. * Unless required by applicable law or agreed to in writing, software
  2187. * distributed under the License is distributed on an "AS IS" BASIS,
  2188. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2189. * See the License for the specific language governing permissions and
  2190. * limitations under the License.
  2191. */
  2192. const MAX_VALUE_TYPE = '__max__';
  2193. const MAX_VALUE = {
  2194. mapValue: {
  2195. fields: {
  2196. '__type__': { stringValue: MAX_VALUE_TYPE }
  2197. }
  2198. }
  2199. };
  2200. /** Extracts the backend's type order for the provided value. */
  2201. function typeOrder(value) {
  2202. if ('nullValue' in value) {
  2203. return 0 /* TypeOrder.NullValue */;
  2204. }
  2205. else if ('booleanValue' in value) {
  2206. return 1 /* TypeOrder.BooleanValue */;
  2207. }
  2208. else if ('integerValue' in value || 'doubleValue' in value) {
  2209. return 2 /* TypeOrder.NumberValue */;
  2210. }
  2211. else if ('timestampValue' in value) {
  2212. return 3 /* TypeOrder.TimestampValue */;
  2213. }
  2214. else if ('stringValue' in value) {
  2215. return 5 /* TypeOrder.StringValue */;
  2216. }
  2217. else if ('bytesValue' in value) {
  2218. return 6 /* TypeOrder.BlobValue */;
  2219. }
  2220. else if ('referenceValue' in value) {
  2221. return 7 /* TypeOrder.RefValue */;
  2222. }
  2223. else if ('geoPointValue' in value) {
  2224. return 8 /* TypeOrder.GeoPointValue */;
  2225. }
  2226. else if ('arrayValue' in value) {
  2227. return 9 /* TypeOrder.ArrayValue */;
  2228. }
  2229. else if ('mapValue' in value) {
  2230. if (isServerTimestamp(value)) {
  2231. return 4 /* TypeOrder.ServerTimestampValue */;
  2232. }
  2233. else if (isMaxValue(value)) {
  2234. return 9007199254740991 /* TypeOrder.MaxValue */;
  2235. }
  2236. return 10 /* TypeOrder.ObjectValue */;
  2237. }
  2238. else {
  2239. return fail();
  2240. }
  2241. }
  2242. /** Tests `left` and `right` for equality based on the backend semantics. */
  2243. function valueEquals(left, right) {
  2244. if (left === right) {
  2245. return true;
  2246. }
  2247. const leftType = typeOrder(left);
  2248. const rightType = typeOrder(right);
  2249. if (leftType !== rightType) {
  2250. return false;
  2251. }
  2252. switch (leftType) {
  2253. case 0 /* TypeOrder.NullValue */:
  2254. return true;
  2255. case 1 /* TypeOrder.BooleanValue */:
  2256. return left.booleanValue === right.booleanValue;
  2257. case 4 /* TypeOrder.ServerTimestampValue */:
  2258. return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));
  2259. case 3 /* TypeOrder.TimestampValue */:
  2260. return timestampEquals(left, right);
  2261. case 5 /* TypeOrder.StringValue */:
  2262. return left.stringValue === right.stringValue;
  2263. case 6 /* TypeOrder.BlobValue */:
  2264. return blobEquals(left, right);
  2265. case 7 /* TypeOrder.RefValue */:
  2266. return left.referenceValue === right.referenceValue;
  2267. case 8 /* TypeOrder.GeoPointValue */:
  2268. return geoPointEquals(left, right);
  2269. case 2 /* TypeOrder.NumberValue */:
  2270. return numberEquals(left, right);
  2271. case 9 /* TypeOrder.ArrayValue */:
  2272. return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals);
  2273. case 10 /* TypeOrder.ObjectValue */:
  2274. return objectEquals(left, right);
  2275. case 9007199254740991 /* TypeOrder.MaxValue */:
  2276. return true;
  2277. default:
  2278. return fail();
  2279. }
  2280. }
  2281. function timestampEquals(left, right) {
  2282. if (typeof left.timestampValue === 'string' &&
  2283. typeof right.timestampValue === 'string' &&
  2284. left.timestampValue.length === right.timestampValue.length) {
  2285. // Use string equality for ISO 8601 timestamps
  2286. return left.timestampValue === right.timestampValue;
  2287. }
  2288. const leftTimestamp = normalizeTimestamp(left.timestampValue);
  2289. const rightTimestamp = normalizeTimestamp(right.timestampValue);
  2290. return (leftTimestamp.seconds === rightTimestamp.seconds &&
  2291. leftTimestamp.nanos === rightTimestamp.nanos);
  2292. }
  2293. function geoPointEquals(left, right) {
  2294. return (normalizeNumber(left.geoPointValue.latitude) ===
  2295. normalizeNumber(right.geoPointValue.latitude) &&
  2296. normalizeNumber(left.geoPointValue.longitude) ===
  2297. normalizeNumber(right.geoPointValue.longitude));
  2298. }
  2299. function blobEquals(left, right) {
  2300. return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue));
  2301. }
  2302. function numberEquals(left, right) {
  2303. if ('integerValue' in left && 'integerValue' in right) {
  2304. return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue));
  2305. }
  2306. else if ('doubleValue' in left && 'doubleValue' in right) {
  2307. const n1 = normalizeNumber(left.doubleValue);
  2308. const n2 = normalizeNumber(right.doubleValue);
  2309. if (n1 === n2) {
  2310. return isNegativeZero(n1) === isNegativeZero(n2);
  2311. }
  2312. else {
  2313. return isNaN(n1) && isNaN(n2);
  2314. }
  2315. }
  2316. return false;
  2317. }
  2318. function objectEquals(left, right) {
  2319. const leftMap = left.mapValue.fields || {};
  2320. const rightMap = right.mapValue.fields || {};
  2321. if (objectSize(leftMap) !== objectSize(rightMap)) {
  2322. return false;
  2323. }
  2324. for (const key in leftMap) {
  2325. if (leftMap.hasOwnProperty(key)) {
  2326. if (rightMap[key] === undefined ||
  2327. !valueEquals(leftMap[key], rightMap[key])) {
  2328. return false;
  2329. }
  2330. }
  2331. }
  2332. return true;
  2333. }
  2334. /** Returns true if the ArrayValue contains the specified element. */
  2335. function arrayValueContains(haystack, needle) {
  2336. return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined);
  2337. }
  2338. function valueCompare(left, right) {
  2339. if (left === right) {
  2340. return 0;
  2341. }
  2342. const leftType = typeOrder(left);
  2343. const rightType = typeOrder(right);
  2344. if (leftType !== rightType) {
  2345. return primitiveComparator(leftType, rightType);
  2346. }
  2347. switch (leftType) {
  2348. case 0 /* TypeOrder.NullValue */:
  2349. case 9007199254740991 /* TypeOrder.MaxValue */:
  2350. return 0;
  2351. case 1 /* TypeOrder.BooleanValue */:
  2352. return primitiveComparator(left.booleanValue, right.booleanValue);
  2353. case 2 /* TypeOrder.NumberValue */:
  2354. return compareNumbers(left, right);
  2355. case 3 /* TypeOrder.TimestampValue */:
  2356. return compareTimestamps(left.timestampValue, right.timestampValue);
  2357. case 4 /* TypeOrder.ServerTimestampValue */:
  2358. return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right));
  2359. case 5 /* TypeOrder.StringValue */:
  2360. return primitiveComparator(left.stringValue, right.stringValue);
  2361. case 6 /* TypeOrder.BlobValue */:
  2362. return compareBlobs(left.bytesValue, right.bytesValue);
  2363. case 7 /* TypeOrder.RefValue */:
  2364. return compareReferences(left.referenceValue, right.referenceValue);
  2365. case 8 /* TypeOrder.GeoPointValue */:
  2366. return compareGeoPoints(left.geoPointValue, right.geoPointValue);
  2367. case 9 /* TypeOrder.ArrayValue */:
  2368. return compareArrays(left.arrayValue, right.arrayValue);
  2369. case 10 /* TypeOrder.ObjectValue */:
  2370. return compareMaps(left.mapValue, right.mapValue);
  2371. default:
  2372. throw fail();
  2373. }
  2374. }
  2375. function compareNumbers(left, right) {
  2376. const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);
  2377. const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);
  2378. if (leftNumber < rightNumber) {
  2379. return -1;
  2380. }
  2381. else if (leftNumber > rightNumber) {
  2382. return 1;
  2383. }
  2384. else if (leftNumber === rightNumber) {
  2385. return 0;
  2386. }
  2387. else {
  2388. // one or both are NaN.
  2389. if (isNaN(leftNumber)) {
  2390. return isNaN(rightNumber) ? 0 : -1;
  2391. }
  2392. else {
  2393. return 1;
  2394. }
  2395. }
  2396. }
  2397. function compareTimestamps(left, right) {
  2398. if (typeof left === 'string' &&
  2399. typeof right === 'string' &&
  2400. left.length === right.length) {
  2401. return primitiveComparator(left, right);
  2402. }
  2403. const leftTimestamp = normalizeTimestamp(left);
  2404. const rightTimestamp = normalizeTimestamp(right);
  2405. const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds);
  2406. if (comparison !== 0) {
  2407. return comparison;
  2408. }
  2409. return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);
  2410. }
  2411. function compareReferences(leftPath, rightPath) {
  2412. const leftSegments = leftPath.split('/');
  2413. const rightSegments = rightPath.split('/');
  2414. for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {
  2415. const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);
  2416. if (comparison !== 0) {
  2417. return comparison;
  2418. }
  2419. }
  2420. return primitiveComparator(leftSegments.length, rightSegments.length);
  2421. }
  2422. function compareGeoPoints(left, right) {
  2423. const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude));
  2424. if (comparison !== 0) {
  2425. return comparison;
  2426. }
  2427. return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude));
  2428. }
  2429. function compareBlobs(left, right) {
  2430. const leftBytes = normalizeByteString(left);
  2431. const rightBytes = normalizeByteString(right);
  2432. return leftBytes.compareTo(rightBytes);
  2433. }
  2434. function compareArrays(left, right) {
  2435. const leftArray = left.values || [];
  2436. const rightArray = right.values || [];
  2437. for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {
  2438. const compare = valueCompare(leftArray[i], rightArray[i]);
  2439. if (compare) {
  2440. return compare;
  2441. }
  2442. }
  2443. return primitiveComparator(leftArray.length, rightArray.length);
  2444. }
  2445. function compareMaps(left, right) {
  2446. if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {
  2447. return 0;
  2448. }
  2449. else if (left === MAX_VALUE.mapValue) {
  2450. return 1;
  2451. }
  2452. else if (right === MAX_VALUE.mapValue) {
  2453. return -1;
  2454. }
  2455. const leftMap = left.fields || {};
  2456. const leftKeys = Object.keys(leftMap);
  2457. const rightMap = right.fields || {};
  2458. const rightKeys = Object.keys(rightMap);
  2459. // Even though MapValues are likely sorted correctly based on their insertion
  2460. // order (e.g. when received from the backend), local modifications can bring
  2461. // elements out of order. We need to re-sort the elements to ensure that
  2462. // canonical IDs are independent of insertion order.
  2463. leftKeys.sort();
  2464. rightKeys.sort();
  2465. for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {
  2466. const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);
  2467. if (keyCompare !== 0) {
  2468. return keyCompare;
  2469. }
  2470. const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);
  2471. if (compare !== 0) {
  2472. return compare;
  2473. }
  2474. }
  2475. return primitiveComparator(leftKeys.length, rightKeys.length);
  2476. }
  2477. /** Returns a reference value for the provided database and key. */
  2478. function refValue(databaseId, key) {
  2479. return {
  2480. referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}`
  2481. };
  2482. }
  2483. /** Returns true if `value` is an ArrayValue. */
  2484. function isArray(value) {
  2485. return !!value && 'arrayValue' in value;
  2486. }
  2487. /** Returns true if `value` is a NullValue. */
  2488. function isNullValue(value) {
  2489. return !!value && 'nullValue' in value;
  2490. }
  2491. /** Returns true if `value` is NaN. */
  2492. function isNanValue(value) {
  2493. return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));
  2494. }
  2495. /** Returns true if `value` is a MapValue. */
  2496. function isMapValue(value) {
  2497. return !!value && 'mapValue' in value;
  2498. }
  2499. /** Creates a deep copy of `source`. */
  2500. function deepClone(source) {
  2501. if (source.geoPointValue) {
  2502. return { geoPointValue: Object.assign({}, source.geoPointValue) };
  2503. }
  2504. else if (source.timestampValue &&
  2505. typeof source.timestampValue === 'object') {
  2506. return { timestampValue: Object.assign({}, source.timestampValue) };
  2507. }
  2508. else if (source.mapValue) {
  2509. const target = { mapValue: { fields: {} } };
  2510. forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val)));
  2511. return target;
  2512. }
  2513. else if (source.arrayValue) {
  2514. const target = { arrayValue: { values: [] } };
  2515. for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {
  2516. target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]);
  2517. }
  2518. return target;
  2519. }
  2520. else {
  2521. return Object.assign({}, source);
  2522. }
  2523. }
  2524. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */
  2525. function isMaxValue(value) {
  2526. return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===
  2527. MAX_VALUE_TYPE);
  2528. }
  2529. /**
  2530. * @license
  2531. * Copyright 2022 Google LLC
  2532. *
  2533. * Licensed under the Apache License, Version 2.0 (the "License");
  2534. * you may not use this file except in compliance with the License.
  2535. * You may obtain a copy of the License at
  2536. *
  2537. * http://www.apache.org/licenses/LICENSE-2.0
  2538. *
  2539. * Unless required by applicable law or agreed to in writing, software
  2540. * distributed under the License is distributed on an "AS IS" BASIS,
  2541. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2542. * See the License for the specific language governing permissions and
  2543. * limitations under the License.
  2544. */
  2545. /**
  2546. * Represents a bound of a query.
  2547. *
  2548. * The bound is specified with the given components representing a position and
  2549. * whether it's just before or just after the position (relative to whatever the
  2550. * query order is).
  2551. *
  2552. * The position represents a logical index position for a query. It's a prefix
  2553. * of values for the (potentially implicit) order by clauses of a query.
  2554. *
  2555. * Bound provides a function to determine whether a document comes before or
  2556. * after a bound. This is influenced by whether the position is just before or
  2557. * just after the provided values.
  2558. */
  2559. class Bound {
  2560. constructor(position, inclusive) {
  2561. this.position = position;
  2562. this.inclusive = inclusive;
  2563. }
  2564. }
  2565. function boundEquals(left, right) {
  2566. if (left === null) {
  2567. return right === null;
  2568. }
  2569. else if (right === null) {
  2570. return false;
  2571. }
  2572. if (left.inclusive !== right.inclusive ||
  2573. left.position.length !== right.position.length) {
  2574. return false;
  2575. }
  2576. for (let i = 0; i < left.position.length; i++) {
  2577. const leftPosition = left.position[i];
  2578. const rightPosition = right.position[i];
  2579. if (!valueEquals(leftPosition, rightPosition)) {
  2580. return false;
  2581. }
  2582. }
  2583. return true;
  2584. }
  2585. /**
  2586. * @license
  2587. * Copyright 2022 Google LLC
  2588. *
  2589. * Licensed under the Apache License, Version 2.0 (the "License");
  2590. * you may not use this file except in compliance with the License.
  2591. * You may obtain a copy of the License at
  2592. *
  2593. * http://www.apache.org/licenses/LICENSE-2.0
  2594. *
  2595. * Unless required by applicable law or agreed to in writing, software
  2596. * distributed under the License is distributed on an "AS IS" BASIS,
  2597. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2598. * See the License for the specific language governing permissions and
  2599. * limitations under the License.
  2600. */
  2601. class Filter {
  2602. }
  2603. class FieldFilter extends Filter {
  2604. constructor(field, op, value) {
  2605. super();
  2606. this.field = field;
  2607. this.op = op;
  2608. this.value = value;
  2609. }
  2610. /**
  2611. * Creates a filter based on the provided arguments.
  2612. */
  2613. static create(field, op, value) {
  2614. if (field.isKeyField()) {
  2615. if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
  2616. return this.createKeyFieldInFilter(field, op, value);
  2617. }
  2618. else {
  2619. return new KeyFieldFilter(field, op, value);
  2620. }
  2621. }
  2622. else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) {
  2623. return new ArrayContainsFilter(field, value);
  2624. }
  2625. else if (op === "in" /* Operator.IN */) {
  2626. return new InFilter(field, value);
  2627. }
  2628. else if (op === "not-in" /* Operator.NOT_IN */) {
  2629. return new NotInFilter(field, value);
  2630. }
  2631. else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
  2632. return new ArrayContainsAnyFilter(field, value);
  2633. }
  2634. else {
  2635. return new FieldFilter(field, op, value);
  2636. }
  2637. }
  2638. static createKeyFieldInFilter(field, op, value) {
  2639. return op === "in" /* Operator.IN */
  2640. ? new KeyFieldInFilter(field, value)
  2641. : new KeyFieldNotInFilter(field, value);
  2642. }
  2643. matches(doc) {
  2644. const other = doc.data.field(this.field);
  2645. // Types do not have to match in NOT_EQUAL filters.
  2646. if (this.op === "!=" /* Operator.NOT_EQUAL */) {
  2647. return (other !== null &&
  2648. this.matchesComparison(valueCompare(other, this.value)));
  2649. }
  2650. // Only compare types with matching backend order (such as double and int).
  2651. return (other !== null &&
  2652. typeOrder(this.value) === typeOrder(other) &&
  2653. this.matchesComparison(valueCompare(other, this.value)));
  2654. }
  2655. matchesComparison(comparison) {
  2656. switch (this.op) {
  2657. case "<" /* Operator.LESS_THAN */:
  2658. return comparison < 0;
  2659. case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
  2660. return comparison <= 0;
  2661. case "==" /* Operator.EQUAL */:
  2662. return comparison === 0;
  2663. case "!=" /* Operator.NOT_EQUAL */:
  2664. return comparison !== 0;
  2665. case ">" /* Operator.GREATER_THAN */:
  2666. return comparison > 0;
  2667. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
  2668. return comparison >= 0;
  2669. default:
  2670. return fail();
  2671. }
  2672. }
  2673. isInequality() {
  2674. return ([
  2675. "<" /* Operator.LESS_THAN */,
  2676. "<=" /* Operator.LESS_THAN_OR_EQUAL */,
  2677. ">" /* Operator.GREATER_THAN */,
  2678. ">=" /* Operator.GREATER_THAN_OR_EQUAL */,
  2679. "!=" /* Operator.NOT_EQUAL */,
  2680. "not-in" /* Operator.NOT_IN */
  2681. ].indexOf(this.op) >= 0);
  2682. }
  2683. getFlattenedFilters() {
  2684. return [this];
  2685. }
  2686. getFilters() {
  2687. return [this];
  2688. }
  2689. getFirstInequalityField() {
  2690. if (this.isInequality()) {
  2691. return this.field;
  2692. }
  2693. return null;
  2694. }
  2695. }
  2696. class CompositeFilter extends Filter {
  2697. constructor(filters, op) {
  2698. super();
  2699. this.filters = filters;
  2700. this.op = op;
  2701. this.memoizedFlattenedFilters = null;
  2702. }
  2703. /**
  2704. * Creates a filter based on the provided arguments.
  2705. */
  2706. static create(filters, op) {
  2707. return new CompositeFilter(filters, op);
  2708. }
  2709. matches(doc) {
  2710. if (compositeFilterIsConjunction(this)) {
  2711. // For conjunctions, all filters must match, so return false if any filter doesn't match.
  2712. return this.filters.find(filter => !filter.matches(doc)) === undefined;
  2713. }
  2714. else {
  2715. // For disjunctions, at least one filter should match.
  2716. return this.filters.find(filter => filter.matches(doc)) !== undefined;
  2717. }
  2718. }
  2719. getFlattenedFilters() {
  2720. if (this.memoizedFlattenedFilters !== null) {
  2721. return this.memoizedFlattenedFilters;
  2722. }
  2723. this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {
  2724. return result.concat(subfilter.getFlattenedFilters());
  2725. }, []);
  2726. return this.memoizedFlattenedFilters;
  2727. }
  2728. // Returns a mutable copy of `this.filters`
  2729. getFilters() {
  2730. return Object.assign([], this.filters);
  2731. }
  2732. getFirstInequalityField() {
  2733. const found = this.findFirstMatchingFilter(filter => filter.isInequality());
  2734. if (found !== null) {
  2735. return found.field;
  2736. }
  2737. return null;
  2738. }
  2739. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  2740. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  2741. // predicate.
  2742. findFirstMatchingFilter(predicate) {
  2743. for (const fieldFilter of this.getFlattenedFilters()) {
  2744. if (predicate(fieldFilter)) {
  2745. return fieldFilter;
  2746. }
  2747. }
  2748. return null;
  2749. }
  2750. }
  2751. function compositeFilterIsConjunction(compositeFilter) {
  2752. return compositeFilter.op === "and" /* CompositeOperator.AND */;
  2753. }
  2754. function filterEquals(f1, f2) {
  2755. if (f1 instanceof FieldFilter) {
  2756. return fieldFilterEquals(f1, f2);
  2757. }
  2758. else if (f1 instanceof CompositeFilter) {
  2759. return compositeFilterEquals(f1, f2);
  2760. }
  2761. else {
  2762. fail();
  2763. }
  2764. }
  2765. function fieldFilterEquals(f1, f2) {
  2766. return (f2 instanceof FieldFilter &&
  2767. f1.op === f2.op &&
  2768. f1.field.isEqual(f2.field) &&
  2769. valueEquals(f1.value, f2.value));
  2770. }
  2771. function compositeFilterEquals(f1, f2) {
  2772. if (f2 instanceof CompositeFilter &&
  2773. f1.op === f2.op &&
  2774. f1.filters.length === f2.filters.length) {
  2775. const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true);
  2776. return subFiltersMatch;
  2777. }
  2778. return false;
  2779. }
  2780. /** Filter that matches on key fields (i.e. '__name__'). */
  2781. class KeyFieldFilter extends FieldFilter {
  2782. constructor(field, op, value) {
  2783. super(field, op, value);
  2784. this.key = DocumentKey.fromName(value.referenceValue);
  2785. }
  2786. matches(doc) {
  2787. const comparison = DocumentKey.comparator(doc.key, this.key);
  2788. return this.matchesComparison(comparison);
  2789. }
  2790. }
  2791. /** Filter that matches on key fields within an array. */
  2792. class KeyFieldInFilter extends FieldFilter {
  2793. constructor(field, value) {
  2794. super(field, "in" /* Operator.IN */, value);
  2795. this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value);
  2796. }
  2797. matches(doc) {
  2798. return this.keys.some(key => key.isEqual(doc.key));
  2799. }
  2800. }
  2801. /** Filter that matches on key fields not present within an array. */
  2802. class KeyFieldNotInFilter extends FieldFilter {
  2803. constructor(field, value) {
  2804. super(field, "not-in" /* Operator.NOT_IN */, value);
  2805. this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value);
  2806. }
  2807. matches(doc) {
  2808. return !this.keys.some(key => key.isEqual(doc.key));
  2809. }
  2810. }
  2811. function extractDocumentKeysFromArrayValue(op, value) {
  2812. var _a;
  2813. return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
  2814. return DocumentKey.fromName(v.referenceValue);
  2815. });
  2816. }
  2817. /** A Filter that implements the array-contains operator. */
  2818. class ArrayContainsFilter extends FieldFilter {
  2819. constructor(field, value) {
  2820. super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value);
  2821. }
  2822. matches(doc) {
  2823. const other = doc.data.field(this.field);
  2824. return isArray(other) && arrayValueContains(other.arrayValue, this.value);
  2825. }
  2826. }
  2827. /** A Filter that implements the IN operator. */
  2828. class InFilter extends FieldFilter {
  2829. constructor(field, value) {
  2830. super(field, "in" /* Operator.IN */, value);
  2831. }
  2832. matches(doc) {
  2833. const other = doc.data.field(this.field);
  2834. return other !== null && arrayValueContains(this.value.arrayValue, other);
  2835. }
  2836. }
  2837. /** A Filter that implements the not-in operator. */
  2838. class NotInFilter extends FieldFilter {
  2839. constructor(field, value) {
  2840. super(field, "not-in" /* Operator.NOT_IN */, value);
  2841. }
  2842. matches(doc) {
  2843. if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
  2844. return false;
  2845. }
  2846. const other = doc.data.field(this.field);
  2847. return other !== null && !arrayValueContains(this.value.arrayValue, other);
  2848. }
  2849. }
  2850. /** A Filter that implements the array-contains-any operator. */
  2851. class ArrayContainsAnyFilter extends FieldFilter {
  2852. constructor(field, value) {
  2853. super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value);
  2854. }
  2855. matches(doc) {
  2856. const other = doc.data.field(this.field);
  2857. if (!isArray(other) || !other.arrayValue.values) {
  2858. return false;
  2859. }
  2860. return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
  2861. }
  2862. }
  2863. /**
  2864. * @license
  2865. * Copyright 2022 Google LLC
  2866. *
  2867. * Licensed under the Apache License, Version 2.0 (the "License");
  2868. * you may not use this file except in compliance with the License.
  2869. * You may obtain a copy of the License at
  2870. *
  2871. * http://www.apache.org/licenses/LICENSE-2.0
  2872. *
  2873. * Unless required by applicable law or agreed to in writing, software
  2874. * distributed under the License is distributed on an "AS IS" BASIS,
  2875. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2876. * See the License for the specific language governing permissions and
  2877. * limitations under the License.
  2878. */
  2879. /**
  2880. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  2881. */
  2882. class OrderBy {
  2883. constructor(field, dir = "asc" /* Direction.ASCENDING */) {
  2884. this.field = field;
  2885. this.dir = dir;
  2886. }
  2887. }
  2888. function orderByEquals(left, right) {
  2889. return left.dir === right.dir && left.field.isEqual(right.field);
  2890. }
  2891. /**
  2892. * @license
  2893. * Copyright 2017 Google LLC
  2894. *
  2895. * Licensed under the Apache License, Version 2.0 (the "License");
  2896. * you may not use this file except in compliance with the License.
  2897. * You may obtain a copy of the License at
  2898. *
  2899. * http://www.apache.org/licenses/LICENSE-2.0
  2900. *
  2901. * Unless required by applicable law or agreed to in writing, software
  2902. * distributed under the License is distributed on an "AS IS" BASIS,
  2903. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2904. * See the License for the specific language governing permissions and
  2905. * limitations under the License.
  2906. */
  2907. /**
  2908. * A version of a document in Firestore. This corresponds to the version
  2909. * timestamp, such as update_time or read_time.
  2910. */
  2911. class SnapshotVersion {
  2912. constructor(timestamp) {
  2913. this.timestamp = timestamp;
  2914. }
  2915. static fromTimestamp(value) {
  2916. return new SnapshotVersion(value);
  2917. }
  2918. static min() {
  2919. return new SnapshotVersion(new Timestamp(0, 0));
  2920. }
  2921. static max() {
  2922. return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));
  2923. }
  2924. compareTo(other) {
  2925. return this.timestamp._compareTo(other.timestamp);
  2926. }
  2927. isEqual(other) {
  2928. return this.timestamp.isEqual(other.timestamp);
  2929. }
  2930. /** Returns a number representation of the version for use in spec tests. */
  2931. toMicroseconds() {
  2932. // Convert to microseconds.
  2933. return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;
  2934. }
  2935. toString() {
  2936. return 'SnapshotVersion(' + this.timestamp.toString() + ')';
  2937. }
  2938. toTimestamp() {
  2939. return this.timestamp;
  2940. }
  2941. }
  2942. /**
  2943. * @license
  2944. * Copyright 2017 Google LLC
  2945. *
  2946. * Licensed under the Apache License, Version 2.0 (the "License");
  2947. * you may not use this file except in compliance with the License.
  2948. * You may obtain a copy of the License at
  2949. *
  2950. * http://www.apache.org/licenses/LICENSE-2.0
  2951. *
  2952. * Unless required by applicable law or agreed to in writing, software
  2953. * distributed under the License is distributed on an "AS IS" BASIS,
  2954. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2955. * See the License for the specific language governing permissions and
  2956. * limitations under the License.
  2957. */
  2958. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2959. // tree.
  2960. class SortedMap {
  2961. constructor(comparator, root) {
  2962. this.comparator = comparator;
  2963. this.root = root ? root : LLRBNode.EMPTY;
  2964. }
  2965. // Returns a copy of the map, with the specified key/value added or replaced.
  2966. insert(key, value) {
  2967. return new SortedMap(this.comparator, this.root
  2968. .insert(key, value, this.comparator)
  2969. .copy(null, null, LLRBNode.BLACK, null, null));
  2970. }
  2971. // Returns a copy of the map, with the specified key removed.
  2972. remove(key) {
  2973. return new SortedMap(this.comparator, this.root
  2974. .remove(key, this.comparator)
  2975. .copy(null, null, LLRBNode.BLACK, null, null));
  2976. }
  2977. // Returns the value of the node with the given key, or null.
  2978. get(key) {
  2979. let node = this.root;
  2980. while (!node.isEmpty()) {
  2981. const cmp = this.comparator(key, node.key);
  2982. if (cmp === 0) {
  2983. return node.value;
  2984. }
  2985. else if (cmp < 0) {
  2986. node = node.left;
  2987. }
  2988. else if (cmp > 0) {
  2989. node = node.right;
  2990. }
  2991. }
  2992. return null;
  2993. }
  2994. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2995. // exist.
  2996. indexOf(key) {
  2997. // Number of nodes that were pruned when descending right
  2998. let prunedNodes = 0;
  2999. let node = this.root;
  3000. while (!node.isEmpty()) {
  3001. const cmp = this.comparator(key, node.key);
  3002. if (cmp === 0) {
  3003. return prunedNodes + node.left.size;
  3004. }
  3005. else if (cmp < 0) {
  3006. node = node.left;
  3007. }
  3008. else {
  3009. // Count all nodes left of the node plus the node itself
  3010. prunedNodes += node.left.size + 1;
  3011. node = node.right;
  3012. }
  3013. }
  3014. // Node not found
  3015. return -1;
  3016. }
  3017. isEmpty() {
  3018. return this.root.isEmpty();
  3019. }
  3020. // Returns the total number of nodes in the map.
  3021. get size() {
  3022. return this.root.size;
  3023. }
  3024. // Returns the minimum key in the map.
  3025. minKey() {
  3026. return this.root.minKey();
  3027. }
  3028. // Returns the maximum key in the map.
  3029. maxKey() {
  3030. return this.root.maxKey();
  3031. }
  3032. // Traverses the map in key order and calls the specified action function
  3033. // for each key/value pair. If action returns true, traversal is aborted.
  3034. // Returns the first truthy value returned by action, or the last falsey
  3035. // value returned by action.
  3036. inorderTraversal(action) {
  3037. return this.root.inorderTraversal(action);
  3038. }
  3039. forEach(fn) {
  3040. this.inorderTraversal((k, v) => {
  3041. fn(k, v);
  3042. return false;
  3043. });
  3044. }
  3045. toString() {
  3046. const descriptions = [];
  3047. this.inorderTraversal((k, v) => {
  3048. descriptions.push(`${k}:${v}`);
  3049. return false;
  3050. });
  3051. return `{${descriptions.join(', ')}}`;
  3052. }
  3053. // Traverses the map in reverse key order and calls the specified action
  3054. // function for each key/value pair. If action returns true, traversal is
  3055. // aborted.
  3056. // Returns the first truthy value returned by action, or the last falsey
  3057. // value returned by action.
  3058. reverseTraversal(action) {
  3059. return this.root.reverseTraversal(action);
  3060. }
  3061. // Returns an iterator over the SortedMap.
  3062. getIterator() {
  3063. return new SortedMapIterator(this.root, null, this.comparator, false);
  3064. }
  3065. getIteratorFrom(key) {
  3066. return new SortedMapIterator(this.root, key, this.comparator, false);
  3067. }
  3068. getReverseIterator() {
  3069. return new SortedMapIterator(this.root, null, this.comparator, true);
  3070. }
  3071. getReverseIteratorFrom(key) {
  3072. return new SortedMapIterator(this.root, key, this.comparator, true);
  3073. }
  3074. } // end SortedMap
  3075. // An iterator over an LLRBNode.
  3076. class SortedMapIterator {
  3077. constructor(node, startKey, comparator, isReverse) {
  3078. this.isReverse = isReverse;
  3079. this.nodeStack = [];
  3080. let cmp = 1;
  3081. while (!node.isEmpty()) {
  3082. cmp = startKey ? comparator(node.key, startKey) : 1;
  3083. // flip the comparison if we're going in reverse
  3084. if (startKey && isReverse) {
  3085. cmp *= -1;
  3086. }
  3087. if (cmp < 0) {
  3088. // This node is less than our start key. ignore it
  3089. if (this.isReverse) {
  3090. node = node.left;
  3091. }
  3092. else {
  3093. node = node.right;
  3094. }
  3095. }
  3096. else if (cmp === 0) {
  3097. // This node is exactly equal to our start key. Push it on the stack,
  3098. // but stop iterating;
  3099. this.nodeStack.push(node);
  3100. break;
  3101. }
  3102. else {
  3103. // This node is greater than our start key, add it to the stack and move
  3104. // to the next one
  3105. this.nodeStack.push(node);
  3106. if (this.isReverse) {
  3107. node = node.right;
  3108. }
  3109. else {
  3110. node = node.left;
  3111. }
  3112. }
  3113. }
  3114. }
  3115. getNext() {
  3116. let node = this.nodeStack.pop();
  3117. const result = { key: node.key, value: node.value };
  3118. if (this.isReverse) {
  3119. node = node.left;
  3120. while (!node.isEmpty()) {
  3121. this.nodeStack.push(node);
  3122. node = node.right;
  3123. }
  3124. }
  3125. else {
  3126. node = node.right;
  3127. while (!node.isEmpty()) {
  3128. this.nodeStack.push(node);
  3129. node = node.left;
  3130. }
  3131. }
  3132. return result;
  3133. }
  3134. hasNext() {
  3135. return this.nodeStack.length > 0;
  3136. }
  3137. peek() {
  3138. if (this.nodeStack.length === 0) {
  3139. return null;
  3140. }
  3141. const node = this.nodeStack[this.nodeStack.length - 1];
  3142. return { key: node.key, value: node.value };
  3143. }
  3144. } // end SortedMapIterator
  3145. // Represents a node in a Left-leaning Red-Black tree.
  3146. class LLRBNode {
  3147. constructor(key, value, color, left, right) {
  3148. this.key = key;
  3149. this.value = value;
  3150. this.color = color != null ? color : LLRBNode.RED;
  3151. this.left = left != null ? left : LLRBNode.EMPTY;
  3152. this.right = right != null ? right : LLRBNode.EMPTY;
  3153. this.size = this.left.size + 1 + this.right.size;
  3154. }
  3155. // Returns a copy of the current node, optionally replacing pieces of it.
  3156. copy(key, value, color, left, right) {
  3157. return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  3158. }
  3159. isEmpty() {
  3160. return false;
  3161. }
  3162. // Traverses the tree in key order and calls the specified action function
  3163. // for each node. If action returns true, traversal is aborted.
  3164. // Returns the first truthy value returned by action, or the last falsey
  3165. // value returned by action.
  3166. inorderTraversal(action) {
  3167. return (this.left.inorderTraversal(action) ||
  3168. action(this.key, this.value) ||
  3169. this.right.inorderTraversal(action));
  3170. }
  3171. // Traverses the tree in reverse key order and calls the specified action
  3172. // function for each node. If action returns true, traversal is aborted.
  3173. // Returns the first truthy value returned by action, or the last falsey
  3174. // value returned by action.
  3175. reverseTraversal(action) {
  3176. return (this.right.reverseTraversal(action) ||
  3177. action(this.key, this.value) ||
  3178. this.left.reverseTraversal(action));
  3179. }
  3180. // Returns the minimum node in the tree.
  3181. min() {
  3182. if (this.left.isEmpty()) {
  3183. return this;
  3184. }
  3185. else {
  3186. return this.left.min();
  3187. }
  3188. }
  3189. // Returns the maximum key in the tree.
  3190. minKey() {
  3191. return this.min().key;
  3192. }
  3193. // Returns the maximum key in the tree.
  3194. maxKey() {
  3195. if (this.right.isEmpty()) {
  3196. return this.key;
  3197. }
  3198. else {
  3199. return this.right.maxKey();
  3200. }
  3201. }
  3202. // Returns new tree, with the key/value added.
  3203. insert(key, value, comparator) {
  3204. let n = this;
  3205. const cmp = comparator(key, n.key);
  3206. if (cmp < 0) {
  3207. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  3208. }
  3209. else if (cmp === 0) {
  3210. n = n.copy(null, value, null, null, null);
  3211. }
  3212. else {
  3213. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  3214. }
  3215. return n.fixUp();
  3216. }
  3217. removeMin() {
  3218. if (this.left.isEmpty()) {
  3219. return LLRBNode.EMPTY;
  3220. }
  3221. let n = this;
  3222. if (!n.left.isRed() && !n.left.left.isRed()) {
  3223. n = n.moveRedLeft();
  3224. }
  3225. n = n.copy(null, null, null, n.left.removeMin(), null);
  3226. return n.fixUp();
  3227. }
  3228. // Returns new tree, with the specified item removed.
  3229. remove(key, comparator) {
  3230. let smallest;
  3231. let n = this;
  3232. if (comparator(key, n.key) < 0) {
  3233. if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
  3234. n = n.moveRedLeft();
  3235. }
  3236. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  3237. }
  3238. else {
  3239. if (n.left.isRed()) {
  3240. n = n.rotateRight();
  3241. }
  3242. if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
  3243. n = n.moveRedRight();
  3244. }
  3245. if (comparator(key, n.key) === 0) {
  3246. if (n.right.isEmpty()) {
  3247. return LLRBNode.EMPTY;
  3248. }
  3249. else {
  3250. smallest = n.right.min();
  3251. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
  3252. }
  3253. }
  3254. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  3255. }
  3256. return n.fixUp();
  3257. }
  3258. isRed() {
  3259. return this.color;
  3260. }
  3261. // Returns new tree after performing any needed rotations.
  3262. fixUp() {
  3263. let n = this;
  3264. if (n.right.isRed() && !n.left.isRed()) {
  3265. n = n.rotateLeft();
  3266. }
  3267. if (n.left.isRed() && n.left.left.isRed()) {
  3268. n = n.rotateRight();
  3269. }
  3270. if (n.left.isRed() && n.right.isRed()) {
  3271. n = n.colorFlip();
  3272. }
  3273. return n;
  3274. }
  3275. moveRedLeft() {
  3276. let n = this.colorFlip();
  3277. if (n.right.left.isRed()) {
  3278. n = n.copy(null, null, null, null, n.right.rotateRight());
  3279. n = n.rotateLeft();
  3280. n = n.colorFlip();
  3281. }
  3282. return n;
  3283. }
  3284. moveRedRight() {
  3285. let n = this.colorFlip();
  3286. if (n.left.left.isRed()) {
  3287. n = n.rotateRight();
  3288. n = n.colorFlip();
  3289. }
  3290. return n;
  3291. }
  3292. rotateLeft() {
  3293. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  3294. return this.right.copy(null, null, this.color, nl, null);
  3295. }
  3296. rotateRight() {
  3297. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  3298. return this.left.copy(null, null, this.color, null, nr);
  3299. }
  3300. colorFlip() {
  3301. const left = this.left.copy(null, null, !this.left.color, null, null);
  3302. const right = this.right.copy(null, null, !this.right.color, null, null);
  3303. return this.copy(null, null, !this.color, left, right);
  3304. }
  3305. // For testing.
  3306. checkMaxDepth() {
  3307. const blackDepth = this.check();
  3308. if (Math.pow(2.0, blackDepth) <= this.size + 1) {
  3309. return true;
  3310. }
  3311. else {
  3312. return false;
  3313. }
  3314. }
  3315. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  3316. // leaves is equal on both sides. This function verifies that or asserts.
  3317. check() {
  3318. if (this.isRed() && this.left.isRed()) {
  3319. throw fail();
  3320. }
  3321. if (this.right.isRed()) {
  3322. throw fail();
  3323. }
  3324. const blackDepth = this.left.check();
  3325. if (blackDepth !== this.right.check()) {
  3326. throw fail();
  3327. }
  3328. else {
  3329. return blackDepth + (this.isRed() ? 0 : 1);
  3330. }
  3331. }
  3332. } // end LLRBNode
  3333. // Empty node is shared between all LLRB trees.
  3334. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3335. LLRBNode.EMPTY = null;
  3336. LLRBNode.RED = true;
  3337. LLRBNode.BLACK = false;
  3338. // Represents an empty node (a leaf node in the Red-Black Tree).
  3339. class LLRBEmptyNode {
  3340. constructor() {
  3341. this.size = 0;
  3342. }
  3343. get key() {
  3344. throw fail();
  3345. }
  3346. get value() {
  3347. throw fail();
  3348. }
  3349. get color() {
  3350. throw fail();
  3351. }
  3352. get left() {
  3353. throw fail();
  3354. }
  3355. get right() {
  3356. throw fail();
  3357. }
  3358. // Returns a copy of the current node.
  3359. copy(key, value, color, left, right) {
  3360. return this;
  3361. }
  3362. // Returns a copy of the tree, with the specified key/value added.
  3363. insert(key, value, comparator) {
  3364. return new LLRBNode(key, value);
  3365. }
  3366. // Returns a copy of the tree, with the specified key removed.
  3367. remove(key, comparator) {
  3368. return this;
  3369. }
  3370. isEmpty() {
  3371. return true;
  3372. }
  3373. inorderTraversal(action) {
  3374. return false;
  3375. }
  3376. reverseTraversal(action) {
  3377. return false;
  3378. }
  3379. minKey() {
  3380. return null;
  3381. }
  3382. maxKey() {
  3383. return null;
  3384. }
  3385. isRed() {
  3386. return false;
  3387. }
  3388. // For testing.
  3389. checkMaxDepth() {
  3390. return true;
  3391. }
  3392. check() {
  3393. return 0;
  3394. }
  3395. } // end LLRBEmptyNode
  3396. LLRBNode.EMPTY = new LLRBEmptyNode();
  3397. /**
  3398. * @license
  3399. * Copyright 2017 Google LLC
  3400. *
  3401. * Licensed under the Apache License, Version 2.0 (the "License");
  3402. * you may not use this file except in compliance with the License.
  3403. * You may obtain a copy of the License at
  3404. *
  3405. * http://www.apache.org/licenses/LICENSE-2.0
  3406. *
  3407. * Unless required by applicable law or agreed to in writing, software
  3408. * distributed under the License is distributed on an "AS IS" BASIS,
  3409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3410. * See the License for the specific language governing permissions and
  3411. * limitations under the License.
  3412. */
  3413. /**
  3414. * SortedSet is an immutable (copy-on-write) collection that holds elements
  3415. * in order specified by the provided comparator.
  3416. *
  3417. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  3418. * be equal!
  3419. */
  3420. class SortedSet {
  3421. constructor(comparator) {
  3422. this.comparator = comparator;
  3423. this.data = new SortedMap(this.comparator);
  3424. }
  3425. has(elem) {
  3426. return this.data.get(elem) !== null;
  3427. }
  3428. first() {
  3429. return this.data.minKey();
  3430. }
  3431. last() {
  3432. return this.data.maxKey();
  3433. }
  3434. get size() {
  3435. return this.data.size;
  3436. }
  3437. indexOf(elem) {
  3438. return this.data.indexOf(elem);
  3439. }
  3440. /** Iterates elements in order defined by "comparator" */
  3441. forEach(cb) {
  3442. this.data.inorderTraversal((k, v) => {
  3443. cb(k);
  3444. return false;
  3445. });
  3446. }
  3447. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
  3448. forEachInRange(range, cb) {
  3449. const iter = this.data.getIteratorFrom(range[0]);
  3450. while (iter.hasNext()) {
  3451. const elem = iter.getNext();
  3452. if (this.comparator(elem.key, range[1]) >= 0) {
  3453. return;
  3454. }
  3455. cb(elem.key);
  3456. }
  3457. }
  3458. /**
  3459. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  3460. */
  3461. forEachWhile(cb, start) {
  3462. let iter;
  3463. if (start !== undefined) {
  3464. iter = this.data.getIteratorFrom(start);
  3465. }
  3466. else {
  3467. iter = this.data.getIterator();
  3468. }
  3469. while (iter.hasNext()) {
  3470. const elem = iter.getNext();
  3471. const result = cb(elem.key);
  3472. if (!result) {
  3473. return;
  3474. }
  3475. }
  3476. }
  3477. /** Finds the least element greater than or equal to `elem`. */
  3478. firstAfterOrEqual(elem) {
  3479. const iter = this.data.getIteratorFrom(elem);
  3480. return iter.hasNext() ? iter.getNext().key : null;
  3481. }
  3482. getIterator() {
  3483. return new SortedSetIterator(this.data.getIterator());
  3484. }
  3485. getIteratorFrom(key) {
  3486. return new SortedSetIterator(this.data.getIteratorFrom(key));
  3487. }
  3488. /** Inserts or updates an element */
  3489. add(elem) {
  3490. return this.copy(this.data.remove(elem).insert(elem, true));
  3491. }
  3492. /** Deletes an element */
  3493. delete(elem) {
  3494. if (!this.has(elem)) {
  3495. return this;
  3496. }
  3497. return this.copy(this.data.remove(elem));
  3498. }
  3499. isEmpty() {
  3500. return this.data.isEmpty();
  3501. }
  3502. unionWith(other) {
  3503. let result = this;
  3504. // Make sure `result` always refers to the larger one of the two sets.
  3505. if (result.size < other.size) {
  3506. result = other;
  3507. other = this;
  3508. }
  3509. other.forEach(elem => {
  3510. result = result.add(elem);
  3511. });
  3512. return result;
  3513. }
  3514. isEqual(other) {
  3515. if (!(other instanceof SortedSet)) {
  3516. return false;
  3517. }
  3518. if (this.size !== other.size) {
  3519. return false;
  3520. }
  3521. const thisIt = this.data.getIterator();
  3522. const otherIt = other.data.getIterator();
  3523. while (thisIt.hasNext()) {
  3524. const thisElem = thisIt.getNext().key;
  3525. const otherElem = otherIt.getNext().key;
  3526. if (this.comparator(thisElem, otherElem) !== 0) {
  3527. return false;
  3528. }
  3529. }
  3530. return true;
  3531. }
  3532. toArray() {
  3533. const res = [];
  3534. this.forEach(targetId => {
  3535. res.push(targetId);
  3536. });
  3537. return res;
  3538. }
  3539. toString() {
  3540. const result = [];
  3541. this.forEach(elem => result.push(elem));
  3542. return 'SortedSet(' + result.toString() + ')';
  3543. }
  3544. copy(data) {
  3545. const result = new SortedSet(this.comparator);
  3546. result.data = data;
  3547. return result;
  3548. }
  3549. }
  3550. class SortedSetIterator {
  3551. constructor(iter) {
  3552. this.iter = iter;
  3553. }
  3554. getNext() {
  3555. return this.iter.getNext().key;
  3556. }
  3557. hasNext() {
  3558. return this.iter.hasNext();
  3559. }
  3560. }
  3561. /**
  3562. * @license
  3563. * Copyright 2020 Google LLC
  3564. *
  3565. * Licensed under the Apache License, Version 2.0 (the "License");
  3566. * you may not use this file except in compliance with the License.
  3567. * You may obtain a copy of the License at
  3568. *
  3569. * http://www.apache.org/licenses/LICENSE-2.0
  3570. *
  3571. * Unless required by applicable law or agreed to in writing, software
  3572. * distributed under the License is distributed on an "AS IS" BASIS,
  3573. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3574. * See the License for the specific language governing permissions and
  3575. * limitations under the License.
  3576. */
  3577. /**
  3578. * Provides a set of fields that can be used to partially patch a document.
  3579. * FieldMask is used in conjunction with ObjectValue.
  3580. * Examples:
  3581. * foo - Overwrites foo entirely with the provided value. If foo is not
  3582. * present in the companion ObjectValue, the field is deleted.
  3583. * foo.bar - Overwrites only the field bar of the object foo.
  3584. * If foo is not an object, foo is replaced with an object
  3585. * containing foo
  3586. */
  3587. class FieldMask {
  3588. constructor(fields) {
  3589. this.fields = fields;
  3590. // TODO(dimond): validation of FieldMask
  3591. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  3592. fields.sort(FieldPath$1.comparator);
  3593. }
  3594. static empty() {
  3595. return new FieldMask([]);
  3596. }
  3597. /**
  3598. * Returns a new FieldMask object that is the result of adding all the given
  3599. * fields paths to this field mask.
  3600. */
  3601. unionWith(extraFields) {
  3602. let mergedMaskSet = new SortedSet(FieldPath$1.comparator);
  3603. for (const fieldPath of this.fields) {
  3604. mergedMaskSet = mergedMaskSet.add(fieldPath);
  3605. }
  3606. for (const fieldPath of extraFields) {
  3607. mergedMaskSet = mergedMaskSet.add(fieldPath);
  3608. }
  3609. return new FieldMask(mergedMaskSet.toArray());
  3610. }
  3611. /**
  3612. * Verifies that `fieldPath` is included by at least one field in this field
  3613. * mask.
  3614. *
  3615. * This is an O(n) operation, where `n` is the size of the field mask.
  3616. */
  3617. covers(fieldPath) {
  3618. for (const fieldMaskPath of this.fields) {
  3619. if (fieldMaskPath.isPrefixOf(fieldPath)) {
  3620. return true;
  3621. }
  3622. }
  3623. return false;
  3624. }
  3625. isEqual(other) {
  3626. return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));
  3627. }
  3628. }
  3629. /**
  3630. * @license
  3631. * Copyright 2017 Google LLC
  3632. *
  3633. * Licensed under the Apache License, Version 2.0 (the "License");
  3634. * you may not use this file except in compliance with the License.
  3635. * You may obtain a copy of the License at
  3636. *
  3637. * http://www.apache.org/licenses/LICENSE-2.0
  3638. *
  3639. * Unless required by applicable law or agreed to in writing, software
  3640. * distributed under the License is distributed on an "AS IS" BASIS,
  3641. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3642. * See the License for the specific language governing permissions and
  3643. * limitations under the License.
  3644. */
  3645. /**
  3646. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3647. * ability to add and remove fields (via the ObjectValueBuilder).
  3648. */
  3649. class ObjectValue {
  3650. constructor(value) {
  3651. this.value = value;
  3652. }
  3653. static empty() {
  3654. return new ObjectValue({ mapValue: {} });
  3655. }
  3656. /**
  3657. * Returns the value at the given path or null.
  3658. *
  3659. * @param path - the path to search
  3660. * @returns The value at the path or null if the path is not set.
  3661. */
  3662. field(path) {
  3663. if (path.isEmpty()) {
  3664. return this.value;
  3665. }
  3666. else {
  3667. let currentLevel = this.value;
  3668. for (let i = 0; i < path.length - 1; ++i) {
  3669. currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)];
  3670. if (!isMapValue(currentLevel)) {
  3671. return null;
  3672. }
  3673. }
  3674. currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()];
  3675. return currentLevel || null;
  3676. }
  3677. }
  3678. /**
  3679. * Sets the field to the provided value.
  3680. *
  3681. * @param path - The field path to set.
  3682. * @param value - The value to set.
  3683. */
  3684. set(path, value) {
  3685. const fieldsMap = this.getFieldsMap(path.popLast());
  3686. fieldsMap[path.lastSegment()] = deepClone(value);
  3687. }
  3688. /**
  3689. * Sets the provided fields to the provided values.
  3690. *
  3691. * @param data - A map of fields to values (or null for deletes).
  3692. */
  3693. setAll(data) {
  3694. let parent = FieldPath$1.emptyPath();
  3695. let upserts = {};
  3696. let deletes = [];
  3697. data.forEach((value, path) => {
  3698. if (!parent.isImmediateParentOf(path)) {
  3699. // Insert the accumulated changes at this parent location
  3700. const fieldsMap = this.getFieldsMap(parent);
  3701. this.applyChanges(fieldsMap, upserts, deletes);
  3702. upserts = {};
  3703. deletes = [];
  3704. parent = path.popLast();
  3705. }
  3706. if (value) {
  3707. upserts[path.lastSegment()] = deepClone(value);
  3708. }
  3709. else {
  3710. deletes.push(path.lastSegment());
  3711. }
  3712. });
  3713. const fieldsMap = this.getFieldsMap(parent);
  3714. this.applyChanges(fieldsMap, upserts, deletes);
  3715. }
  3716. /**
  3717. * Removes the field at the specified path. If there is no field at the
  3718. * specified path, nothing is changed.
  3719. *
  3720. * @param path - The field path to remove.
  3721. */
  3722. delete(path) {
  3723. const nestedValue = this.field(path.popLast());
  3724. if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {
  3725. delete nestedValue.mapValue.fields[path.lastSegment()];
  3726. }
  3727. }
  3728. isEqual(other) {
  3729. return valueEquals(this.value, other.value);
  3730. }
  3731. /**
  3732. * Returns the map that contains the leaf element of `path`. If the parent
  3733. * entry does not yet exist, or if it is not a map, a new map will be created.
  3734. */
  3735. getFieldsMap(path) {
  3736. let current = this.value;
  3737. if (!current.mapValue.fields) {
  3738. current.mapValue = { fields: {} };
  3739. }
  3740. for (let i = 0; i < path.length; ++i) {
  3741. let next = current.mapValue.fields[path.get(i)];
  3742. if (!isMapValue(next) || !next.mapValue.fields) {
  3743. next = { mapValue: { fields: {} } };
  3744. current.mapValue.fields[path.get(i)] = next;
  3745. }
  3746. current = next;
  3747. }
  3748. return current.mapValue.fields;
  3749. }
  3750. /**
  3751. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3752. * entries.
  3753. */
  3754. applyChanges(fieldsMap, inserts, deletes) {
  3755. forEach(inserts, (key, val) => (fieldsMap[key] = val));
  3756. for (const field of deletes) {
  3757. delete fieldsMap[field];
  3758. }
  3759. }
  3760. clone() {
  3761. return new ObjectValue(deepClone(this.value));
  3762. }
  3763. }
  3764. /**
  3765. * @license
  3766. * Copyright 2017 Google LLC
  3767. *
  3768. * Licensed under the Apache License, Version 2.0 (the "License");
  3769. * you may not use this file except in compliance with the License.
  3770. * You may obtain a copy of the License at
  3771. *
  3772. * http://www.apache.org/licenses/LICENSE-2.0
  3773. *
  3774. * Unless required by applicable law or agreed to in writing, software
  3775. * distributed under the License is distributed on an "AS IS" BASIS,
  3776. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3777. * See the License for the specific language governing permissions and
  3778. * limitations under the License.
  3779. */
  3780. /**
  3781. * Represents a document in Firestore with a key, version, data and whether it
  3782. * has local mutations applied to it.
  3783. *
  3784. * Documents can transition between states via `convertToFoundDocument()`,
  3785. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3786. * not transition to one of these states even after all mutations have been
  3787. * applied, `isValidDocument()` returns false and the document should be removed
  3788. * from all views.
  3789. */
  3790. class MutableDocument {
  3791. constructor(key, documentType, version, readTime, createTime, data, documentState) {
  3792. this.key = key;
  3793. this.documentType = documentType;
  3794. this.version = version;
  3795. this.readTime = readTime;
  3796. this.createTime = createTime;
  3797. this.data = data;
  3798. this.documentState = documentState;
  3799. }
  3800. /**
  3801. * Creates a document with no known version or data, but which can serve as
  3802. * base document for mutations.
  3803. */
  3804. static newInvalidDocument(documentKey) {
  3805. return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */,
  3806. /* version */ SnapshotVersion.min(),
  3807. /* readTime */ SnapshotVersion.min(),
  3808. /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);
  3809. }
  3810. /**
  3811. * Creates a new document that is known to exist with the given data at the
  3812. * given version.
  3813. */
  3814. static newFoundDocument(documentKey, version, createTime, value) {
  3815. return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */,
  3816. /* version */ version,
  3817. /* readTime */ SnapshotVersion.min(),
  3818. /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */);
  3819. }
  3820. /** Creates a new document that is known to not exist at the given version. */
  3821. static newNoDocument(documentKey, version) {
  3822. return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */,
  3823. /* version */ version,
  3824. /* readTime */ SnapshotVersion.min(),
  3825. /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);
  3826. }
  3827. /**
  3828. * Creates a new document that is known to exist at the given version but
  3829. * whose data is not known (e.g. a document that was updated without a known
  3830. * base document).
  3831. */
  3832. static newUnknownDocument(documentKey, version) {
  3833. return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */,
  3834. /* version */ version,
  3835. /* readTime */ SnapshotVersion.min(),
  3836. /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3837. }
  3838. /**
  3839. * Changes the document type to indicate that it exists and that its version
  3840. * and data are known.
  3841. */
  3842. convertToFoundDocument(version, value) {
  3843. // If a document is switching state from being an invalid or deleted
  3844. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3845. // update from Watch or due to applying a local set mutation on top
  3846. // of a deleted document, our best guess about its createTime would be the
  3847. // version at which the document transitioned to a FOUND_DOCUMENT.
  3848. if (this.createTime.isEqual(SnapshotVersion.min()) &&
  3849. (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ ||
  3850. this.documentType === 0 /* DocumentType.INVALID */)) {
  3851. this.createTime = version;
  3852. }
  3853. this.version = version;
  3854. this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */;
  3855. this.data = value;
  3856. this.documentState = 0 /* DocumentState.SYNCED */;
  3857. return this;
  3858. }
  3859. /**
  3860. * Changes the document type to indicate that it doesn't exist at the given
  3861. * version.
  3862. */
  3863. convertToNoDocument(version) {
  3864. this.version = version;
  3865. this.documentType = 2 /* DocumentType.NO_DOCUMENT */;
  3866. this.data = ObjectValue.empty();
  3867. this.documentState = 0 /* DocumentState.SYNCED */;
  3868. return this;
  3869. }
  3870. /**
  3871. * Changes the document type to indicate that it exists at a given version but
  3872. * that its data is not known (e.g. a document that was updated without a known
  3873. * base document).
  3874. */
  3875. convertToUnknownDocument(version) {
  3876. this.version = version;
  3877. this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */;
  3878. this.data = ObjectValue.empty();
  3879. this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
  3880. return this;
  3881. }
  3882. setHasCommittedMutations() {
  3883. this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
  3884. return this;
  3885. }
  3886. setHasLocalMutations() {
  3887. this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */;
  3888. this.version = SnapshotVersion.min();
  3889. return this;
  3890. }
  3891. setReadTime(readTime) {
  3892. this.readTime = readTime;
  3893. return this;
  3894. }
  3895. get hasLocalMutations() {
  3896. return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */;
  3897. }
  3898. get hasCommittedMutations() {
  3899. return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
  3900. }
  3901. get hasPendingWrites() {
  3902. return this.hasLocalMutations || this.hasCommittedMutations;
  3903. }
  3904. isValidDocument() {
  3905. return this.documentType !== 0 /* DocumentType.INVALID */;
  3906. }
  3907. isFoundDocument() {
  3908. return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */;
  3909. }
  3910. isNoDocument() {
  3911. return this.documentType === 2 /* DocumentType.NO_DOCUMENT */;
  3912. }
  3913. isUnknownDocument() {
  3914. return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */;
  3915. }
  3916. isEqual(other) {
  3917. return (other instanceof MutableDocument &&
  3918. this.key.isEqual(other.key) &&
  3919. this.version.isEqual(other.version) &&
  3920. this.documentType === other.documentType &&
  3921. this.documentState === other.documentState &&
  3922. this.data.isEqual(other.data));
  3923. }
  3924. mutableCopy() {
  3925. return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3926. }
  3927. toString() {
  3928. return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` +
  3929. `{createTime: ${this.createTime}}), ` +
  3930. `{documentType: ${this.documentType}}), ` +
  3931. `{documentState: ${this.documentState}})`);
  3932. }
  3933. }
  3934. /**
  3935. * @license
  3936. * Copyright 2019 Google LLC
  3937. *
  3938. * Licensed under the Apache License, Version 2.0 (the "License");
  3939. * you may not use this file except in compliance with the License.
  3940. * You may obtain a copy of the License at
  3941. *
  3942. * http://www.apache.org/licenses/LICENSE-2.0
  3943. *
  3944. * Unless required by applicable law or agreed to in writing, software
  3945. * distributed under the License is distributed on an "AS IS" BASIS,
  3946. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3947. * See the License for the specific language governing permissions and
  3948. * limitations under the License.
  3949. */
  3950. // Visible for testing
  3951. class TargetImpl {
  3952. constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
  3953. this.path = path;
  3954. this.collectionGroup = collectionGroup;
  3955. this.orderBy = orderBy;
  3956. this.filters = filters;
  3957. this.limit = limit;
  3958. this.startAt = startAt;
  3959. this.endAt = endAt;
  3960. this.memoizedCanonicalId = null;
  3961. }
  3962. }
  3963. /**
  3964. * Initializes a Target with a path and optional additional query constraints.
  3965. * Path must currently be empty if this is a collection group query.
  3966. *
  3967. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  3968. * using this factory method, because `Query` provides an implicit `orderBy`
  3969. * property.
  3970. */
  3971. function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
  3972. return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
  3973. }
  3974. function targetEquals(left, right) {
  3975. if (left.limit !== right.limit) {
  3976. return false;
  3977. }
  3978. if (left.orderBy.length !== right.orderBy.length) {
  3979. return false;
  3980. }
  3981. for (let i = 0; i < left.orderBy.length; i++) {
  3982. if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
  3983. return false;
  3984. }
  3985. }
  3986. if (left.filters.length !== right.filters.length) {
  3987. return false;
  3988. }
  3989. for (let i = 0; i < left.filters.length; i++) {
  3990. if (!filterEquals(left.filters[i], right.filters[i])) {
  3991. return false;
  3992. }
  3993. }
  3994. if (left.collectionGroup !== right.collectionGroup) {
  3995. return false;
  3996. }
  3997. if (!left.path.isEqual(right.path)) {
  3998. return false;
  3999. }
  4000. if (!boundEquals(left.startAt, right.startAt)) {
  4001. return false;
  4002. }
  4003. return boundEquals(left.endAt, right.endAt);
  4004. }
  4005. /**
  4006. * @license
  4007. * Copyright 2017 Google LLC
  4008. *
  4009. * Licensed under the Apache License, Version 2.0 (the "License");
  4010. * you may not use this file except in compliance with the License.
  4011. * You may obtain a copy of the License at
  4012. *
  4013. * http://www.apache.org/licenses/LICENSE-2.0
  4014. *
  4015. * Unless required by applicable law or agreed to in writing, software
  4016. * distributed under the License is distributed on an "AS IS" BASIS,
  4017. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4018. * See the License for the specific language governing permissions and
  4019. * limitations under the License.
  4020. */
  4021. /**
  4022. * Query encapsulates all the query attributes we support in the SDK. It can
  4023. * be run against the LocalStore, as well as be converted to a `Target` to
  4024. * query the RemoteStore results.
  4025. *
  4026. * Visible for testing.
  4027. */
  4028. class QueryImpl {
  4029. /**
  4030. * Initializes a Query with a path and optional additional query constraints.
  4031. * Path must currently be empty if this is a collection group query.
  4032. */
  4033. constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) {
  4034. this.path = path;
  4035. this.collectionGroup = collectionGroup;
  4036. this.explicitOrderBy = explicitOrderBy;
  4037. this.filters = filters;
  4038. this.limit = limit;
  4039. this.limitType = limitType;
  4040. this.startAt = startAt;
  4041. this.endAt = endAt;
  4042. this.memoizedOrderBy = null;
  4043. // The corresponding `Target` of this `Query` instance.
  4044. this.memoizedTarget = null;
  4045. if (this.startAt) ;
  4046. if (this.endAt) ;
  4047. }
  4048. }
  4049. /** Creates a new Query for a query that matches all documents at `path` */
  4050. function newQueryForPath(path) {
  4051. return new QueryImpl(path);
  4052. }
  4053. function getFirstOrderByField(query) {
  4054. return query.explicitOrderBy.length > 0
  4055. ? query.explicitOrderBy[0].field
  4056. : null;
  4057. }
  4058. function getInequalityFilterField(query) {
  4059. for (const filter of query.filters) {
  4060. const result = filter.getFirstInequalityField();
  4061. if (result !== null) {
  4062. return result;
  4063. }
  4064. }
  4065. return null;
  4066. }
  4067. /**
  4068. * Creates a new Query for a collection group query that matches all documents
  4069. * within the provided collection group.
  4070. */
  4071. function newQueryForCollectionGroup(collectionId) {
  4072. return new QueryImpl(ResourcePath.emptyPath(), collectionId);
  4073. }
  4074. /**
  4075. * Returns whether the query matches a collection group rather than a specific
  4076. * collection.
  4077. */
  4078. function isCollectionGroupQuery(query) {
  4079. return query.collectionGroup !== null;
  4080. }
  4081. /**
  4082. * Returns the implicit order by constraint that is used to execute the Query,
  4083. * which can be different from the order by constraints the user provided (e.g.
  4084. * the SDK and backend always orders by `__name__`).
  4085. */
  4086. function queryOrderBy(query) {
  4087. const queryImpl = debugCast(query);
  4088. if (queryImpl.memoizedOrderBy === null) {
  4089. queryImpl.memoizedOrderBy = [];
  4090. const inequalityField = getInequalityFilterField(queryImpl);
  4091. const firstOrderByField = getFirstOrderByField(queryImpl);
  4092. if (inequalityField !== null && firstOrderByField === null) {
  4093. // In order to implicitly add key ordering, we must also add the
  4094. // inequality filter field for it to be a valid query.
  4095. // Note that the default inequality field and key ordering is ascending.
  4096. if (!inequalityField.isKeyField()) {
  4097. queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
  4098. }
  4099. queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* Direction.ASCENDING */));
  4100. }
  4101. else {
  4102. let foundKeyOrdering = false;
  4103. for (const orderBy of queryImpl.explicitOrderBy) {
  4104. queryImpl.memoizedOrderBy.push(orderBy);
  4105. if (orderBy.field.isKeyField()) {
  4106. foundKeyOrdering = true;
  4107. }
  4108. }
  4109. if (!foundKeyOrdering) {
  4110. // The order of the implicit key ordering always matches the last
  4111. // explicit order by
  4112. const lastDirection = queryImpl.explicitOrderBy.length > 0
  4113. ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
  4114. .dir
  4115. : "asc" /* Direction.ASCENDING */;
  4116. queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
  4117. }
  4118. }
  4119. }
  4120. return queryImpl.memoizedOrderBy;
  4121. }
  4122. /**
  4123. * Converts this `Query` instance to it's corresponding `Target` representation.
  4124. */
  4125. function queryToTarget(query) {
  4126. const queryImpl = debugCast(query);
  4127. if (!queryImpl.memoizedTarget) {
  4128. if (queryImpl.limitType === "F" /* LimitType.First */) {
  4129. queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
  4130. }
  4131. else {
  4132. // Flip the orderBy directions since we want the last results
  4133. const orderBys = [];
  4134. for (const orderBy of queryOrderBy(queryImpl)) {
  4135. const dir = orderBy.dir === "desc" /* Direction.DESCENDING */
  4136. ? "asc" /* Direction.ASCENDING */
  4137. : "desc" /* Direction.DESCENDING */;
  4138. orderBys.push(new OrderBy(orderBy.field, dir));
  4139. }
  4140. // We need to swap the cursors to match the now-flipped query ordering.
  4141. const startAt = queryImpl.endAt
  4142. ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)
  4143. : null;
  4144. const endAt = queryImpl.startAt
  4145. ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)
  4146. : null;
  4147. // Now return as a LimitType.First query.
  4148. queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
  4149. }
  4150. }
  4151. return queryImpl.memoizedTarget;
  4152. }
  4153. function queryWithAddedFilter(query, filter) {
  4154. filter.getFirstInequalityField();
  4155. getInequalityFilterField(query);
  4156. const newFilters = query.filters.concat([filter]);
  4157. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
  4158. }
  4159. function queryWithAddedOrderBy(query, orderBy) {
  4160. // TODO(dimond): validate that orderBy does not list the same key twice.
  4161. const newOrderBy = query.explicitOrderBy.concat([orderBy]);
  4162. return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
  4163. }
  4164. function queryWithLimit(query, limit, limitType) {
  4165. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
  4166. }
  4167. function queryWithStartAt(query, bound) {
  4168. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
  4169. }
  4170. function queryWithEndAt(query, bound) {
  4171. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
  4172. }
  4173. function queryEquals(left, right) {
  4174. return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
  4175. left.limitType === right.limitType);
  4176. }
  4177. /**
  4178. * @license
  4179. * Copyright 2020 Google LLC
  4180. *
  4181. * Licensed under the Apache License, Version 2.0 (the "License");
  4182. * you may not use this file except in compliance with the License.
  4183. * You may obtain a copy of the License at
  4184. *
  4185. * http://www.apache.org/licenses/LICENSE-2.0
  4186. *
  4187. * Unless required by applicable law or agreed to in writing, software
  4188. * distributed under the License is distributed on an "AS IS" BASIS,
  4189. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4190. * See the License for the specific language governing permissions and
  4191. * limitations under the License.
  4192. */
  4193. /**
  4194. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4195. * `useProto3Json` setting.
  4196. */
  4197. function toDouble(serializer, value) {
  4198. if (serializer.useProto3Json) {
  4199. if (isNaN(value)) {
  4200. return { doubleValue: 'NaN' };
  4201. }
  4202. else if (value === Infinity) {
  4203. return { doubleValue: 'Infinity' };
  4204. }
  4205. else if (value === -Infinity) {
  4206. return { doubleValue: '-Infinity' };
  4207. }
  4208. }
  4209. return { doubleValue: isNegativeZero(value) ? '-0' : value };
  4210. }
  4211. /**
  4212. * Returns an IntegerValue for `value`.
  4213. */
  4214. function toInteger(value) {
  4215. return { integerValue: '' + value };
  4216. }
  4217. /**
  4218. * Returns a value for a number that's appropriate to put into a proto.
  4219. * The return value is an IntegerValue if it can safely represent the value,
  4220. * otherwise a DoubleValue is returned.
  4221. */
  4222. function toNumber(serializer, value) {
  4223. return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);
  4224. }
  4225. /**
  4226. * @license
  4227. * Copyright 2018 Google LLC
  4228. *
  4229. * Licensed under the Apache License, Version 2.0 (the "License");
  4230. * you may not use this file except in compliance with the License.
  4231. * You may obtain a copy of the License at
  4232. *
  4233. * http://www.apache.org/licenses/LICENSE-2.0
  4234. *
  4235. * Unless required by applicable law or agreed to in writing, software
  4236. * distributed under the License is distributed on an "AS IS" BASIS,
  4237. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4238. * See the License for the specific language governing permissions and
  4239. * limitations under the License.
  4240. */
  4241. /** Used to represent a field transform on a mutation. */
  4242. class TransformOperation {
  4243. constructor() {
  4244. // Make sure that the structural type of `TransformOperation` is unique.
  4245. // See https://github.com/microsoft/TypeScript/issues/5451
  4246. this._ = undefined;
  4247. }
  4248. }
  4249. /** Transforms a value into a server-generated timestamp. */
  4250. class ServerTimestampTransform extends TransformOperation {
  4251. }
  4252. /** Transforms an array value via a union operation. */
  4253. class ArrayUnionTransformOperation extends TransformOperation {
  4254. constructor(elements) {
  4255. super();
  4256. this.elements = elements;
  4257. }
  4258. }
  4259. /** Transforms an array value via a remove operation. */
  4260. class ArrayRemoveTransformOperation extends TransformOperation {
  4261. constructor(elements) {
  4262. super();
  4263. this.elements = elements;
  4264. }
  4265. }
  4266. /**
  4267. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4268. * transforms. Converts all field values to integers or doubles, but unlike the
  4269. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4270. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4271. */
  4272. class NumericIncrementTransformOperation extends TransformOperation {
  4273. constructor(serializer, operand) {
  4274. super();
  4275. this.serializer = serializer;
  4276. this.operand = operand;
  4277. }
  4278. }
  4279. /**
  4280. * @license
  4281. * Copyright 2017 Google LLC
  4282. *
  4283. * Licensed under the Apache License, Version 2.0 (the "License");
  4284. * you may not use this file except in compliance with the License.
  4285. * You may obtain a copy of the License at
  4286. *
  4287. * http://www.apache.org/licenses/LICENSE-2.0
  4288. *
  4289. * Unless required by applicable law or agreed to in writing, software
  4290. * distributed under the License is distributed on an "AS IS" BASIS,
  4291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4292. * See the License for the specific language governing permissions and
  4293. * limitations under the License.
  4294. */
  4295. /** A field path and the TransformOperation to perform upon it. */
  4296. class FieldTransform {
  4297. constructor(field, transform) {
  4298. this.field = field;
  4299. this.transform = transform;
  4300. }
  4301. }
  4302. /**
  4303. * Encodes a precondition for a mutation. This follows the model that the
  4304. * backend accepts with the special case of an explicit "empty" precondition
  4305. * (meaning no precondition).
  4306. */
  4307. class Precondition {
  4308. constructor(updateTime, exists) {
  4309. this.updateTime = updateTime;
  4310. this.exists = exists;
  4311. }
  4312. /** Creates a new empty Precondition. */
  4313. static none() {
  4314. return new Precondition();
  4315. }
  4316. /** Creates a new Precondition with an exists flag. */
  4317. static exists(exists) {
  4318. return new Precondition(undefined, exists);
  4319. }
  4320. /** Creates a new Precondition based on a version a document exists at. */
  4321. static updateTime(version) {
  4322. return new Precondition(version);
  4323. }
  4324. /** Returns whether this Precondition is empty. */
  4325. get isNone() {
  4326. return this.updateTime === undefined && this.exists === undefined;
  4327. }
  4328. isEqual(other) {
  4329. return (this.exists === other.exists &&
  4330. (this.updateTime
  4331. ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)
  4332. : !other.updateTime));
  4333. }
  4334. }
  4335. /**
  4336. * A mutation describes a self-contained change to a document. Mutations can
  4337. * create, replace, delete, and update subsets of documents.
  4338. *
  4339. * Mutations not only act on the value of the document but also its version.
  4340. *
  4341. * For local mutations (mutations that haven't been committed yet), we preserve
  4342. * the existing version for Set and Patch mutations. For Delete mutations, we
  4343. * reset the version to 0.
  4344. *
  4345. * Here's the expected transition table.
  4346. *
  4347. * MUTATION APPLIED TO RESULTS IN
  4348. *
  4349. * SetMutation Document(v3) Document(v3)
  4350. * SetMutation NoDocument(v3) Document(v0)
  4351. * SetMutation InvalidDocument(v0) Document(v0)
  4352. * PatchMutation Document(v3) Document(v3)
  4353. * PatchMutation NoDocument(v3) NoDocument(v3)
  4354. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4355. * DeleteMutation Document(v3) NoDocument(v0)
  4356. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4357. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4358. *
  4359. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4360. * the resulting version for Set and Patch mutations. As deletes have no
  4361. * explicit update time, we use the commitTime of the WriteResponse for
  4362. * Delete mutations.
  4363. *
  4364. * If a mutation is acknowledged by the backend but fails the precondition check
  4365. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4366. * the updated version.
  4367. *
  4368. * Field transforms are used only with Patch and Set Mutations. We use the
  4369. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4370. * messages.
  4371. *
  4372. * ## Subclassing Notes
  4373. *
  4374. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4375. * applyToLocalView() to implement the actual behavior of applying the mutation
  4376. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4377. * example).
  4378. */
  4379. class Mutation {
  4380. }
  4381. /**
  4382. * A mutation that creates or replaces the document at the given key with the
  4383. * object value contents.
  4384. */
  4385. class SetMutation extends Mutation {
  4386. constructor(key, value, precondition, fieldTransforms = []) {
  4387. super();
  4388. this.key = key;
  4389. this.value = value;
  4390. this.precondition = precondition;
  4391. this.fieldTransforms = fieldTransforms;
  4392. this.type = 0 /* MutationType.Set */;
  4393. }
  4394. getFieldMask() {
  4395. return null;
  4396. }
  4397. }
  4398. /**
  4399. * A mutation that modifies fields of the document at the given key with the
  4400. * given values. The values are applied through a field mask:
  4401. *
  4402. * * When a field is in both the mask and the values, the corresponding field
  4403. * is updated.
  4404. * * When a field is in neither the mask nor the values, the corresponding
  4405. * field is unmodified.
  4406. * * When a field is in the mask but not in the values, the corresponding field
  4407. * is deleted.
  4408. * * When a field is not in the mask but is in the values, the values map is
  4409. * ignored.
  4410. */
  4411. class PatchMutation extends Mutation {
  4412. constructor(key, data, fieldMask, precondition, fieldTransforms = []) {
  4413. super();
  4414. this.key = key;
  4415. this.data = data;
  4416. this.fieldMask = fieldMask;
  4417. this.precondition = precondition;
  4418. this.fieldTransforms = fieldTransforms;
  4419. this.type = 1 /* MutationType.Patch */;
  4420. }
  4421. getFieldMask() {
  4422. return this.fieldMask;
  4423. }
  4424. }
  4425. /** A mutation that deletes the document at the given key. */
  4426. class DeleteMutation extends Mutation {
  4427. constructor(key, precondition) {
  4428. super();
  4429. this.key = key;
  4430. this.precondition = precondition;
  4431. this.type = 2 /* MutationType.Delete */;
  4432. this.fieldTransforms = [];
  4433. }
  4434. getFieldMask() {
  4435. return null;
  4436. }
  4437. }
  4438. /**
  4439. * A mutation that verifies the existence of the document at the given key with
  4440. * the provided precondition.
  4441. *
  4442. * The `verify` operation is only used in Transactions, and this class serves
  4443. * primarily to facilitate serialization into protos.
  4444. */
  4445. class VerifyMutation extends Mutation {
  4446. constructor(key, precondition) {
  4447. super();
  4448. this.key = key;
  4449. this.precondition = precondition;
  4450. this.type = 3 /* MutationType.Verify */;
  4451. this.fieldTransforms = [];
  4452. }
  4453. getFieldMask() {
  4454. return null;
  4455. }
  4456. }
  4457. /**
  4458. * @license
  4459. * Copyright 2017 Google LLC
  4460. *
  4461. * Licensed under the Apache License, Version 2.0 (the "License");
  4462. * you may not use this file except in compliance with the License.
  4463. * You may obtain a copy of the License at
  4464. *
  4465. * http://www.apache.org/licenses/LICENSE-2.0
  4466. *
  4467. * Unless required by applicable law or agreed to in writing, software
  4468. * distributed under the License is distributed on an "AS IS" BASIS,
  4469. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4470. * See the License for the specific language governing permissions and
  4471. * limitations under the License.
  4472. */
  4473. const DIRECTIONS = (() => {
  4474. const dirs = {};
  4475. dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING';
  4476. dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING';
  4477. return dirs;
  4478. })();
  4479. const OPERATORS = (() => {
  4480. const ops = {};
  4481. ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN';
  4482. ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL';
  4483. ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN';
  4484. ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL';
  4485. ops["==" /* Operator.EQUAL */] = 'EQUAL';
  4486. ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL';
  4487. ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS';
  4488. ops["in" /* Operator.IN */] = 'IN';
  4489. ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN';
  4490. ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY';
  4491. return ops;
  4492. })();
  4493. const COMPOSITE_OPERATORS = (() => {
  4494. const ops = {};
  4495. ops["and" /* CompositeOperator.AND */] = 'AND';
  4496. ops["or" /* CompositeOperator.OR */] = 'OR';
  4497. return ops;
  4498. })();
  4499. function assertPresent(value, description) {
  4500. }
  4501. /**
  4502. * This class generates JsonObject values for the Datastore API suitable for
  4503. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  4504. *
  4505. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  4506. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  4507. * format.
  4508. *
  4509. * For a description of the Proto3 JSON format check
  4510. * https://developers.google.com/protocol-buffers/docs/proto3#json
  4511. *
  4512. * TODO(klimt): We can remove the databaseId argument if we keep the full
  4513. * resource name in documents.
  4514. */
  4515. class JsonProtoSerializer {
  4516. constructor(databaseId, useProto3Json) {
  4517. this.databaseId = databaseId;
  4518. this.useProto3Json = useProto3Json;
  4519. }
  4520. }
  4521. /**
  4522. * Returns a value for a number (or null) that's appropriate to put into
  4523. * a google.protobuf.Int32Value proto.
  4524. * DO NOT USE THIS FOR ANYTHING ELSE.
  4525. * This method cheats. It's typed as returning "number" because that's what
  4526. * our generated proto interfaces say Int32Value must be. But GRPC actually
  4527. * expects a { value: <number> } struct.
  4528. */
  4529. function toInt32Proto(serializer, val) {
  4530. if (serializer.useProto3Json || isNullOrUndefined(val)) {
  4531. return val;
  4532. }
  4533. else {
  4534. return { value: val };
  4535. }
  4536. }
  4537. /**
  4538. * Returns a value for a Date that's appropriate to put into a proto.
  4539. */
  4540. function toTimestamp(serializer, timestamp) {
  4541. if (serializer.useProto3Json) {
  4542. // Serialize to ISO-8601 date format, but with full nano resolution.
  4543. // Since JS Date has only millis, let's only use it for the seconds and
  4544. // then manually add the fractions to the end.
  4545. const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();
  4546. // Remove .xxx frac part and Z in the end.
  4547. const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', '');
  4548. // Pad the fraction out to 9 digits (nanos).
  4549. const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);
  4550. return `${strUntilSeconds}.${nanoStr}Z`;
  4551. }
  4552. else {
  4553. return {
  4554. seconds: '' + timestamp.seconds,
  4555. nanos: timestamp.nanoseconds
  4556. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4557. };
  4558. }
  4559. }
  4560. function fromTimestamp(date) {
  4561. const timestamp = normalizeTimestamp(date);
  4562. return new Timestamp(timestamp.seconds, timestamp.nanos);
  4563. }
  4564. /**
  4565. * Returns a value for bytes that's appropriate to put in a proto.
  4566. *
  4567. * Visible for testing.
  4568. */
  4569. function toBytes(serializer, bytes) {
  4570. if (serializer.useProto3Json) {
  4571. return bytes.toBase64();
  4572. }
  4573. else {
  4574. return bytes.toUint8Array();
  4575. }
  4576. }
  4577. function toVersion(serializer, version) {
  4578. return toTimestamp(serializer, version.toTimestamp());
  4579. }
  4580. function fromVersion(version) {
  4581. hardAssert(!!version);
  4582. return SnapshotVersion.fromTimestamp(fromTimestamp(version));
  4583. }
  4584. function toResourceName(databaseId, path) {
  4585. return fullyQualifiedPrefixPath(databaseId)
  4586. .child('documents')
  4587. .child(path)
  4588. .canonicalString();
  4589. }
  4590. function fromResourceName(name) {
  4591. const resource = ResourcePath.fromString(name);
  4592. hardAssert(isValidResourceName(resource));
  4593. return resource;
  4594. }
  4595. function toName(serializer, key) {
  4596. return toResourceName(serializer.databaseId, key.path);
  4597. }
  4598. function fromName(serializer, name) {
  4599. const resource = fromResourceName(name);
  4600. if (resource.get(1) !== serializer.databaseId.projectId) {
  4601. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' +
  4602. resource.get(1) +
  4603. ' vs ' +
  4604. serializer.databaseId.projectId);
  4605. }
  4606. if (resource.get(3) !== serializer.databaseId.database) {
  4607. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' +
  4608. resource.get(3) +
  4609. ' vs ' +
  4610. serializer.databaseId.database);
  4611. }
  4612. return new DocumentKey(extractLocalPathFromResourceName(resource));
  4613. }
  4614. function toQueryPath(serializer, path) {
  4615. return toResourceName(serializer.databaseId, path);
  4616. }
  4617. function getEncodedDatabaseId(serializer) {
  4618. const path = new ResourcePath([
  4619. 'projects',
  4620. serializer.databaseId.projectId,
  4621. 'databases',
  4622. serializer.databaseId.database
  4623. ]);
  4624. return path.canonicalString();
  4625. }
  4626. function fullyQualifiedPrefixPath(databaseId) {
  4627. return new ResourcePath([
  4628. 'projects',
  4629. databaseId.projectId,
  4630. 'databases',
  4631. databaseId.database
  4632. ]);
  4633. }
  4634. function extractLocalPathFromResourceName(resourceName) {
  4635. hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents');
  4636. return resourceName.popFirst(5);
  4637. }
  4638. /** Creates a Document proto from key and fields (but no create/update time) */
  4639. function toMutationDocument(serializer, key, fields) {
  4640. return {
  4641. name: toName(serializer, key),
  4642. fields: fields.value.mapValue.fields
  4643. };
  4644. }
  4645. function fromDocument(serializer, document, hasCommittedMutations) {
  4646. const key = fromName(serializer, document.name);
  4647. const version = fromVersion(document.updateTime);
  4648. // If we read a document from persistence that is missing createTime, it's due
  4649. // to older SDK versions not storing this information. In such cases, we'll
  4650. // set the createTime to zero. This can be removed in the long term.
  4651. const createTime = document.createTime
  4652. ? fromVersion(document.createTime)
  4653. : SnapshotVersion.min();
  4654. const data = new ObjectValue({ mapValue: { fields: document.fields } });
  4655. const result = MutableDocument.newFoundDocument(key, version, createTime, data);
  4656. if (hasCommittedMutations) {
  4657. result.setHasCommittedMutations();
  4658. }
  4659. return hasCommittedMutations ? result.setHasCommittedMutations() : result;
  4660. }
  4661. function fromFound(serializer, doc) {
  4662. hardAssert(!!doc.found);
  4663. assertPresent(doc.found.name);
  4664. assertPresent(doc.found.updateTime);
  4665. const key = fromName(serializer, doc.found.name);
  4666. const version = fromVersion(doc.found.updateTime);
  4667. const createTime = doc.found.createTime
  4668. ? fromVersion(doc.found.createTime)
  4669. : SnapshotVersion.min();
  4670. const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });
  4671. return MutableDocument.newFoundDocument(key, version, createTime, data);
  4672. }
  4673. function fromMissing(serializer, result) {
  4674. hardAssert(!!result.missing);
  4675. hardAssert(!!result.readTime);
  4676. const key = fromName(serializer, result.missing);
  4677. const version = fromVersion(result.readTime);
  4678. return MutableDocument.newNoDocument(key, version);
  4679. }
  4680. function fromBatchGetDocumentsResponse(serializer, result) {
  4681. if ('found' in result) {
  4682. return fromFound(serializer, result);
  4683. }
  4684. else if ('missing' in result) {
  4685. return fromMissing(serializer, result);
  4686. }
  4687. return fail();
  4688. }
  4689. function toMutation(serializer, mutation) {
  4690. let result;
  4691. if (mutation instanceof SetMutation) {
  4692. result = {
  4693. update: toMutationDocument(serializer, mutation.key, mutation.value)
  4694. };
  4695. }
  4696. else if (mutation instanceof DeleteMutation) {
  4697. result = { delete: toName(serializer, mutation.key) };
  4698. }
  4699. else if (mutation instanceof PatchMutation) {
  4700. result = {
  4701. update: toMutationDocument(serializer, mutation.key, mutation.data),
  4702. updateMask: toDocumentMask(mutation.fieldMask)
  4703. };
  4704. }
  4705. else if (mutation instanceof VerifyMutation) {
  4706. result = {
  4707. verify: toName(serializer, mutation.key)
  4708. };
  4709. }
  4710. else {
  4711. return fail();
  4712. }
  4713. if (mutation.fieldTransforms.length > 0) {
  4714. result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform));
  4715. }
  4716. if (!mutation.precondition.isNone) {
  4717. result.currentDocument = toPrecondition(serializer, mutation.precondition);
  4718. }
  4719. return result;
  4720. }
  4721. function toPrecondition(serializer, precondition) {
  4722. if (precondition.updateTime !== undefined) {
  4723. return {
  4724. updateTime: toVersion(serializer, precondition.updateTime)
  4725. };
  4726. }
  4727. else if (precondition.exists !== undefined) {
  4728. return { exists: precondition.exists };
  4729. }
  4730. else {
  4731. return fail();
  4732. }
  4733. }
  4734. function toFieldTransform(serializer, fieldTransform) {
  4735. const transform = fieldTransform.transform;
  4736. if (transform instanceof ServerTimestampTransform) {
  4737. return {
  4738. fieldPath: fieldTransform.field.canonicalString(),
  4739. setToServerValue: 'REQUEST_TIME'
  4740. };
  4741. }
  4742. else if (transform instanceof ArrayUnionTransformOperation) {
  4743. return {
  4744. fieldPath: fieldTransform.field.canonicalString(),
  4745. appendMissingElements: {
  4746. values: transform.elements
  4747. }
  4748. };
  4749. }
  4750. else if (transform instanceof ArrayRemoveTransformOperation) {
  4751. return {
  4752. fieldPath: fieldTransform.field.canonicalString(),
  4753. removeAllFromArray: {
  4754. values: transform.elements
  4755. }
  4756. };
  4757. }
  4758. else if (transform instanceof NumericIncrementTransformOperation) {
  4759. return {
  4760. fieldPath: fieldTransform.field.canonicalString(),
  4761. increment: transform.operand
  4762. };
  4763. }
  4764. else {
  4765. throw fail();
  4766. }
  4767. }
  4768. function toQueryTarget(serializer, target) {
  4769. // Dissect the path into parent, collectionId, and optional key filter.
  4770. const result = { structuredQuery: {} };
  4771. const path = target.path;
  4772. if (target.collectionGroup !== null) {
  4773. result.parent = toQueryPath(serializer, path);
  4774. result.structuredQuery.from = [
  4775. {
  4776. collectionId: target.collectionGroup,
  4777. allDescendants: true
  4778. }
  4779. ];
  4780. }
  4781. else {
  4782. result.parent = toQueryPath(serializer, path.popLast());
  4783. result.structuredQuery.from = [{ collectionId: path.lastSegment() }];
  4784. }
  4785. const where = toFilters(target.filters);
  4786. if (where) {
  4787. result.structuredQuery.where = where;
  4788. }
  4789. const orderBy = toOrder(target.orderBy);
  4790. if (orderBy) {
  4791. result.structuredQuery.orderBy = orderBy;
  4792. }
  4793. const limit = toInt32Proto(serializer, target.limit);
  4794. if (limit !== null) {
  4795. result.structuredQuery.limit = limit;
  4796. }
  4797. if (target.startAt) {
  4798. result.structuredQuery.startAt = toStartAtCursor(target.startAt);
  4799. }
  4800. if (target.endAt) {
  4801. result.structuredQuery.endAt = toEndAtCursor(target.endAt);
  4802. }
  4803. return result;
  4804. }
  4805. function toRunAggregationQueryRequest(serializer, target, aggregates) {
  4806. const queryTarget = toQueryTarget(serializer, target);
  4807. const aliasMap = {};
  4808. const aggregations = [];
  4809. let aggregationNum = 0;
  4810. aggregates.forEach(aggregate => {
  4811. // Map all client-side aliases to a unique short-form
  4812. // alias. This avoids issues with client-side aliases that
  4813. // exceed the 1500-byte string size limit.
  4814. const serverAlias = `aggregate_${aggregationNum++}`;
  4815. aliasMap[serverAlias] = aggregate.alias;
  4816. if (aggregate.aggregateType === 'count') {
  4817. aggregations.push({
  4818. alias: serverAlias,
  4819. count: {}
  4820. });
  4821. }
  4822. else if (aggregate.aggregateType === 'avg') {
  4823. aggregations.push({
  4824. alias: serverAlias,
  4825. avg: {
  4826. field: toFieldPathReference(aggregate.fieldPath)
  4827. }
  4828. });
  4829. }
  4830. else if (aggregate.aggregateType === 'sum') {
  4831. aggregations.push({
  4832. alias: serverAlias,
  4833. sum: {
  4834. field: toFieldPathReference(aggregate.fieldPath)
  4835. }
  4836. });
  4837. }
  4838. });
  4839. return {
  4840. request: {
  4841. structuredAggregationQuery: {
  4842. aggregations,
  4843. structuredQuery: queryTarget.structuredQuery
  4844. },
  4845. parent: queryTarget.parent
  4846. },
  4847. aliasMap
  4848. };
  4849. }
  4850. function toFilters(filters) {
  4851. if (filters.length === 0) {
  4852. return;
  4853. }
  4854. return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */));
  4855. }
  4856. function toOrder(orderBys) {
  4857. if (orderBys.length === 0) {
  4858. return;
  4859. }
  4860. return orderBys.map(order => toPropertyOrder(order));
  4861. }
  4862. function toStartAtCursor(cursor) {
  4863. return {
  4864. before: cursor.inclusive,
  4865. values: cursor.position
  4866. };
  4867. }
  4868. function toEndAtCursor(cursor) {
  4869. return {
  4870. before: !cursor.inclusive,
  4871. values: cursor.position
  4872. };
  4873. }
  4874. // visible for testing
  4875. function toDirection(dir) {
  4876. return DIRECTIONS[dir];
  4877. }
  4878. // visible for testing
  4879. function toOperatorName(op) {
  4880. return OPERATORS[op];
  4881. }
  4882. function toCompositeOperatorName(op) {
  4883. return COMPOSITE_OPERATORS[op];
  4884. }
  4885. function toFieldPathReference(path) {
  4886. return { fieldPath: path.canonicalString() };
  4887. }
  4888. // visible for testing
  4889. function toPropertyOrder(orderBy) {
  4890. return {
  4891. field: toFieldPathReference(orderBy.field),
  4892. direction: toDirection(orderBy.dir)
  4893. };
  4894. }
  4895. // visible for testing
  4896. function toFilter(filter) {
  4897. if (filter instanceof FieldFilter) {
  4898. return toUnaryOrFieldFilter(filter);
  4899. }
  4900. else if (filter instanceof CompositeFilter) {
  4901. return toCompositeFilter(filter);
  4902. }
  4903. else {
  4904. return fail();
  4905. }
  4906. }
  4907. function toCompositeFilter(filter) {
  4908. const protos = filter.getFilters().map(filter => toFilter(filter));
  4909. if (protos.length === 1) {
  4910. return protos[0];
  4911. }
  4912. return {
  4913. compositeFilter: {
  4914. op: toCompositeOperatorName(filter.op),
  4915. filters: protos
  4916. }
  4917. };
  4918. }
  4919. function toUnaryOrFieldFilter(filter) {
  4920. if (filter.op === "==" /* Operator.EQUAL */) {
  4921. if (isNanValue(filter.value)) {
  4922. return {
  4923. unaryFilter: {
  4924. field: toFieldPathReference(filter.field),
  4925. op: 'IS_NAN'
  4926. }
  4927. };
  4928. }
  4929. else if (isNullValue(filter.value)) {
  4930. return {
  4931. unaryFilter: {
  4932. field: toFieldPathReference(filter.field),
  4933. op: 'IS_NULL'
  4934. }
  4935. };
  4936. }
  4937. }
  4938. else if (filter.op === "!=" /* Operator.NOT_EQUAL */) {
  4939. if (isNanValue(filter.value)) {
  4940. return {
  4941. unaryFilter: {
  4942. field: toFieldPathReference(filter.field),
  4943. op: 'IS_NOT_NAN'
  4944. }
  4945. };
  4946. }
  4947. else if (isNullValue(filter.value)) {
  4948. return {
  4949. unaryFilter: {
  4950. field: toFieldPathReference(filter.field),
  4951. op: 'IS_NOT_NULL'
  4952. }
  4953. };
  4954. }
  4955. }
  4956. return {
  4957. fieldFilter: {
  4958. field: toFieldPathReference(filter.field),
  4959. op: toOperatorName(filter.op),
  4960. value: filter.value
  4961. }
  4962. };
  4963. }
  4964. function toDocumentMask(fieldMask) {
  4965. const canonicalFields = [];
  4966. fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString()));
  4967. return {
  4968. fieldPaths: canonicalFields
  4969. };
  4970. }
  4971. function isValidResourceName(path) {
  4972. // Resource names have at least 4 components (project ID, database ID)
  4973. return (path.length >= 4 &&
  4974. path.get(0) === 'projects' &&
  4975. path.get(2) === 'databases');
  4976. }
  4977. /**
  4978. * @license
  4979. * Copyright 2020 Google LLC
  4980. *
  4981. * Licensed under the Apache License, Version 2.0 (the "License");
  4982. * you may not use this file except in compliance with the License.
  4983. * You may obtain a copy of the License at
  4984. *
  4985. * http://www.apache.org/licenses/LICENSE-2.0
  4986. *
  4987. * Unless required by applicable law or agreed to in writing, software
  4988. * distributed under the License is distributed on an "AS IS" BASIS,
  4989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4990. * See the License for the specific language governing permissions and
  4991. * limitations under the License.
  4992. */
  4993. function newSerializer(databaseId) {
  4994. return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);
  4995. }
  4996. /**
  4997. * @license
  4998. * Copyright 2017 Google LLC
  4999. *
  5000. * Licensed under the Apache License, Version 2.0 (the "License");
  5001. * you may not use this file except in compliance with the License.
  5002. * You may obtain a copy of the License at
  5003. *
  5004. * http://www.apache.org/licenses/LICENSE-2.0
  5005. *
  5006. * Unless required by applicable law or agreed to in writing, software
  5007. * distributed under the License is distributed on an "AS IS" BASIS,
  5008. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5009. * See the License for the specific language governing permissions and
  5010. * limitations under the License.
  5011. */
  5012. const LOG_TAG$2 = 'ExponentialBackoff';
  5013. /**
  5014. * Initial backoff time in milliseconds after an error.
  5015. * Set to 1s according to https://cloud.google.com/apis/design/errors.
  5016. */
  5017. const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;
  5018. const DEFAULT_BACKOFF_FACTOR = 1.5;
  5019. /** Maximum backoff time in milliseconds */
  5020. const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;
  5021. /**
  5022. * A helper for running delayed tasks following an exponential backoff curve
  5023. * between attempts.
  5024. *
  5025. * Each delay is made up of a "base" delay which follows the exponential
  5026. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  5027. * base delay. This prevents clients from accidentally synchronizing their
  5028. * delays causing spikes of load to the backend.
  5029. */
  5030. class ExponentialBackoff {
  5031. constructor(
  5032. /**
  5033. * The AsyncQueue to run backoff operations on.
  5034. */
  5035. queue,
  5036. /**
  5037. * The ID to use when scheduling backoff operations on the AsyncQueue.
  5038. */
  5039. timerId,
  5040. /**
  5041. * The initial delay (used as the base delay on the first retry attempt).
  5042. * Note that jitter will still be applied, so the actual delay could be as
  5043. * little as 0.5*initialDelayMs.
  5044. */
  5045. initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS,
  5046. /**
  5047. * The multiplier to use to determine the extended base delay after each
  5048. * attempt.
  5049. */
  5050. backoffFactor = DEFAULT_BACKOFF_FACTOR,
  5051. /**
  5052. * The maximum base delay after which no further backoff is performed.
  5053. * Note that jitter will still be applied, so the actual delay could be as
  5054. * much as 1.5*maxDelayMs.
  5055. */
  5056. maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) {
  5057. this.queue = queue;
  5058. this.timerId = timerId;
  5059. this.initialDelayMs = initialDelayMs;
  5060. this.backoffFactor = backoffFactor;
  5061. this.maxDelayMs = maxDelayMs;
  5062. this.currentBaseMs = 0;
  5063. this.timerPromise = null;
  5064. /** The last backoff attempt, as epoch milliseconds. */
  5065. this.lastAttemptTime = Date.now();
  5066. this.reset();
  5067. }
  5068. /**
  5069. * Resets the backoff delay.
  5070. *
  5071. * The very next backoffAndWait() will have no delay. If it is called again
  5072. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  5073. * subsequent ones will increase according to the backoffFactor.
  5074. */
  5075. reset() {
  5076. this.currentBaseMs = 0;
  5077. }
  5078. /**
  5079. * Resets the backoff delay to the maximum delay (e.g. for use after a
  5080. * RESOURCE_EXHAUSTED error).
  5081. */
  5082. resetToMax() {
  5083. this.currentBaseMs = this.maxDelayMs;
  5084. }
  5085. /**
  5086. * Returns a promise that resolves after currentDelayMs, and increases the
  5087. * delay for any subsequent attempts. If there was a pending backoff operation
  5088. * already, it will be canceled.
  5089. */
  5090. backoffAndRun(op) {
  5091. // Cancel any pending backoff operation.
  5092. this.cancel();
  5093. // First schedule using the current base (which may be 0 and should be
  5094. // honored as such).
  5095. const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs());
  5096. // Guard against lastAttemptTime being in the future due to a clock change.
  5097. const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);
  5098. // Guard against the backoff delay already being past.
  5099. const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs);
  5100. if (remainingDelayMs > 0) {
  5101. logDebug(LOG_TAG$2, `Backing off for ${remainingDelayMs} ms ` +
  5102. `(base delay: ${this.currentBaseMs} ms, ` +
  5103. `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +
  5104. `last attempt: ${delaySoFarMs} ms ago)`);
  5105. }
  5106. this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => {
  5107. this.lastAttemptTime = Date.now();
  5108. return op();
  5109. });
  5110. // Apply backoff factor to determine next delay and ensure it is within
  5111. // bounds.
  5112. this.currentBaseMs *= this.backoffFactor;
  5113. if (this.currentBaseMs < this.initialDelayMs) {
  5114. this.currentBaseMs = this.initialDelayMs;
  5115. }
  5116. if (this.currentBaseMs > this.maxDelayMs) {
  5117. this.currentBaseMs = this.maxDelayMs;
  5118. }
  5119. }
  5120. skipBackoff() {
  5121. if (this.timerPromise !== null) {
  5122. this.timerPromise.skipDelay();
  5123. this.timerPromise = null;
  5124. }
  5125. }
  5126. cancel() {
  5127. if (this.timerPromise !== null) {
  5128. this.timerPromise.cancel();
  5129. this.timerPromise = null;
  5130. }
  5131. }
  5132. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */
  5133. jitterDelayMs() {
  5134. return (Math.random() - 0.5) * this.currentBaseMs;
  5135. }
  5136. }
  5137. /**
  5138. * @license
  5139. * Copyright 2017 Google LLC
  5140. *
  5141. * Licensed under the Apache License, Version 2.0 (the "License");
  5142. * you may not use this file except in compliance with the License.
  5143. * You may obtain a copy of the License at
  5144. *
  5145. * http://www.apache.org/licenses/LICENSE-2.0
  5146. *
  5147. * Unless required by applicable law or agreed to in writing, software
  5148. * distributed under the License is distributed on an "AS IS" BASIS,
  5149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5150. * See the License for the specific language governing permissions and
  5151. * limitations under the License.
  5152. */
  5153. /**
  5154. * Datastore and its related methods are a wrapper around the external Google
  5155. * Cloud Datastore grpc API, which provides an interface that is more convenient
  5156. * for the rest of the client SDK architecture to consume.
  5157. */
  5158. class Datastore {
  5159. }
  5160. /**
  5161. * An implementation of Datastore that exposes additional state for internal
  5162. * consumption.
  5163. */
  5164. class DatastoreImpl extends Datastore {
  5165. constructor(authCredentials, appCheckCredentials, connection, serializer) {
  5166. super();
  5167. this.authCredentials = authCredentials;
  5168. this.appCheckCredentials = appCheckCredentials;
  5169. this.connection = connection;
  5170. this.serializer = serializer;
  5171. this.terminated = false;
  5172. }
  5173. verifyInitialized() {
  5174. if (this.terminated) {
  5175. throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.');
  5176. }
  5177. }
  5178. /** Invokes the provided RPC with auth and AppCheck tokens. */
  5179. invokeRPC(rpcName, path, request) {
  5180. this.verifyInitialized();
  5181. return Promise.all([
  5182. this.authCredentials.getToken(),
  5183. this.appCheckCredentials.getToken()
  5184. ])
  5185. .then(([authToken, appCheckToken]) => {
  5186. return this.connection.invokeRPC(rpcName, path, request, authToken, appCheckToken);
  5187. })
  5188. .catch((error) => {
  5189. if (error.name === 'FirebaseError') {
  5190. if (error.code === Code.UNAUTHENTICATED) {
  5191. this.authCredentials.invalidateToken();
  5192. this.appCheckCredentials.invalidateToken();
  5193. }
  5194. throw error;
  5195. }
  5196. else {
  5197. throw new FirestoreError(Code.UNKNOWN, error.toString());
  5198. }
  5199. });
  5200. }
  5201. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */
  5202. invokeStreamingRPC(rpcName, path, request, expectedResponseCount) {
  5203. this.verifyInitialized();
  5204. return Promise.all([
  5205. this.authCredentials.getToken(),
  5206. this.appCheckCredentials.getToken()
  5207. ])
  5208. .then(([authToken, appCheckToken]) => {
  5209. return this.connection.invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount);
  5210. })
  5211. .catch((error) => {
  5212. if (error.name === 'FirebaseError') {
  5213. if (error.code === Code.UNAUTHENTICATED) {
  5214. this.authCredentials.invalidateToken();
  5215. this.appCheckCredentials.invalidateToken();
  5216. }
  5217. throw error;
  5218. }
  5219. else {
  5220. throw new FirestoreError(Code.UNKNOWN, error.toString());
  5221. }
  5222. });
  5223. }
  5224. terminate() {
  5225. this.terminated = true;
  5226. }
  5227. }
  5228. // TODO(firestorexp): Make sure there is only one Datastore instance per
  5229. // firestore-exp client.
  5230. function newDatastore(authCredentials, appCheckCredentials, connection, serializer) {
  5231. return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer);
  5232. }
  5233. async function invokeCommitRpc(datastore, mutations) {
  5234. const datastoreImpl = debugCast(datastore);
  5235. const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';
  5236. const request = {
  5237. writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))
  5238. };
  5239. await datastoreImpl.invokeRPC('Commit', path, request);
  5240. }
  5241. async function invokeBatchGetDocumentsRpc(datastore, keys) {
  5242. const datastoreImpl = debugCast(datastore);
  5243. const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';
  5244. const request = {
  5245. documents: keys.map(k => toName(datastoreImpl.serializer, k))
  5246. };
  5247. const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', path, request, keys.length);
  5248. const docs = new Map();
  5249. response.forEach(proto => {
  5250. const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);
  5251. docs.set(doc.key.toString(), doc);
  5252. });
  5253. const result = [];
  5254. keys.forEach(key => {
  5255. const doc = docs.get(key.toString());
  5256. hardAssert(!!doc);
  5257. result.push(doc);
  5258. });
  5259. return result;
  5260. }
  5261. async function invokeRunQueryRpc(datastore, query) {
  5262. const datastoreImpl = debugCast(datastore);
  5263. const request = toQueryTarget(datastoreImpl.serializer, queryToTarget(query));
  5264. const response = await datastoreImpl.invokeStreamingRPC('RunQuery', request.parent, { structuredQuery: request.structuredQuery });
  5265. return (response
  5266. // Omit RunQueryResponses that only contain readTimes.
  5267. .filter(proto => !!proto.document)
  5268. .map(proto => fromDocument(datastoreImpl.serializer, proto.document, undefined)));
  5269. }
  5270. async function invokeRunAggregationQueryRpc(datastore, query, aggregates) {
  5271. var _a;
  5272. const datastoreImpl = debugCast(datastore);
  5273. const { request, aliasMap } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToTarget(query), aggregates);
  5274. const parent = request.parent;
  5275. if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {
  5276. delete request.parent;
  5277. }
  5278. const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', parent, request, /*expectedResponseCount=*/ 1);
  5279. // Omit RunAggregationQueryResponse that only contain readTimes.
  5280. const filteredResult = response.filter(proto => !!proto.result);
  5281. hardAssert(filteredResult.length === 1);
  5282. // Remap the short-form aliases that were sent to the server
  5283. // to the client-side aliases. Users will access the results
  5284. // using the client-side alias.
  5285. const unmappedAggregateFields = (_a = filteredResult[0].result) === null || _a === void 0 ? void 0 : _a.aggregateFields;
  5286. const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => {
  5287. accumulator[aliasMap[key]] = unmappedAggregateFields[key];
  5288. return accumulator;
  5289. }, {});
  5290. return remappedFields;
  5291. }
  5292. /**
  5293. * @license
  5294. * Copyright 2020 Google LLC
  5295. *
  5296. * Licensed under the Apache License, Version 2.0 (the "License");
  5297. * you may not use this file except in compliance with the License.
  5298. * You may obtain a copy of the License at
  5299. *
  5300. * http://www.apache.org/licenses/LICENSE-2.0
  5301. *
  5302. * Unless required by applicable law or agreed to in writing, software
  5303. * distributed under the License is distributed on an "AS IS" BASIS,
  5304. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5305. * See the License for the specific language governing permissions and
  5306. * limitations under the License.
  5307. */
  5308. const LOG_TAG$1 = 'ComponentProvider';
  5309. /**
  5310. * An instance map that ensures only one Datastore exists per Firestore
  5311. * instance.
  5312. */
  5313. const datastoreInstances = new Map();
  5314. /**
  5315. * Returns an initialized and started Datastore for the given Firestore
  5316. * instance. Callers must invoke removeComponents() when the Firestore
  5317. * instance is terminated.
  5318. */
  5319. function getDatastore(firestore) {
  5320. if (firestore._terminated) {
  5321. throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.');
  5322. }
  5323. if (!datastoreInstances.has(firestore)) {
  5324. logDebug(LOG_TAG$1, 'Initializing Datastore');
  5325. const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore.app.options.appId || '', firestore._persistenceKey, firestore._freezeSettings());
  5326. const connection = newConnection(databaseInfo);
  5327. const serializer = newSerializer(firestore._databaseId);
  5328. const datastore = newDatastore(firestore._authCredentials, firestore._appCheckCredentials, connection, serializer);
  5329. datastoreInstances.set(firestore, datastore);
  5330. }
  5331. return datastoreInstances.get(firestore);
  5332. }
  5333. /**
  5334. * Removes all components associated with the provided instance. Must be called
  5335. * when the `Firestore` instance is terminated.
  5336. */
  5337. function removeComponents(firestore) {
  5338. const datastore = datastoreInstances.get(firestore);
  5339. if (datastore) {
  5340. logDebug(LOG_TAG$1, 'Removing Datastore');
  5341. datastoreInstances.delete(firestore);
  5342. datastore.terminate();
  5343. }
  5344. }
  5345. function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) {
  5346. return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams);
  5347. }
  5348. /**
  5349. * @license
  5350. * Copyright 2018 Google LLC
  5351. *
  5352. * Licensed under the Apache License, Version 2.0 (the "License");
  5353. * you may not use this file except in compliance with the License.
  5354. * You may obtain a copy of the License at
  5355. *
  5356. * http://www.apache.org/licenses/LICENSE-2.0
  5357. *
  5358. * Unless required by applicable law or agreed to in writing, software
  5359. * distributed under the License is distributed on an "AS IS" BASIS,
  5360. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5361. * See the License for the specific language governing permissions and
  5362. * limitations under the License.
  5363. */
  5364. const LRU_COLLECTION_DISABLED = -1;
  5365. const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;
  5366. /**
  5367. * @license
  5368. * Copyright 2017 Google LLC
  5369. *
  5370. * Licensed under the Apache License, Version 2.0 (the "License");
  5371. * you may not use this file except in compliance with the License.
  5372. * You may obtain a copy of the License at
  5373. *
  5374. * http://www.apache.org/licenses/LICENSE-2.0
  5375. *
  5376. * Unless required by applicable law or agreed to in writing, software
  5377. * distributed under the License is distributed on an "AS IS" BASIS,
  5378. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5379. * See the License for the specific language governing permissions and
  5380. * limitations under the License.
  5381. */
  5382. /** Verifies whether `e` is an IndexedDbTransactionError. */
  5383. function isIndexedDbTransactionError(e) {
  5384. // Use name equality, as instanceof checks on errors don't work with errors
  5385. // that wrap other errors.
  5386. return e.name === 'IndexedDbTransactionError';
  5387. }
  5388. /**
  5389. * @license
  5390. * Copyright 2020 Google LLC
  5391. *
  5392. * Licensed under the Apache License, Version 2.0 (the "License");
  5393. * you may not use this file except in compliance with the License.
  5394. * You may obtain a copy of the License at
  5395. *
  5396. * http://www.apache.org/licenses/LICENSE-2.0
  5397. *
  5398. * Unless required by applicable law or agreed to in writing, software
  5399. * distributed under the License is distributed on an "AS IS" BASIS,
  5400. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5401. * See the License for the specific language governing permissions and
  5402. * limitations under the License.
  5403. */
  5404. const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;
  5405. /**
  5406. * @license
  5407. * Copyright 2020 Google LLC
  5408. *
  5409. * Licensed under the Apache License, Version 2.0 (the "License");
  5410. * you may not use this file except in compliance with the License.
  5411. * You may obtain a copy of the License at
  5412. *
  5413. * http://www.apache.org/licenses/LICENSE-2.0
  5414. *
  5415. * Unless required by applicable law or agreed to in writing, software
  5416. * distributed under the License is distributed on an "AS IS" BASIS,
  5417. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5418. * See the License for the specific language governing permissions and
  5419. * limitations under the License.
  5420. */
  5421. // settings() defaults:
  5422. const DEFAULT_HOST = 'firestore.googleapis.com';
  5423. const DEFAULT_SSL = true;
  5424. // The minimum long-polling timeout is hardcoded on the server. The value here
  5425. // should be kept in sync with the value used by the server, as the server will
  5426. // silently ignore a value below the minimum and fall back to the default.
  5427. // Googlers see b/266868871 for relevant discussion.
  5428. const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;
  5429. // No maximum long-polling timeout is configured in the server, and defaults to
  5430. // 30 seconds, which is what Watch appears to use.
  5431. // Googlers see b/266868871 for relevant discussion.
  5432. const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;
  5433. // Whether long-polling auto-detected is enabled by default.
  5434. const DEFAULT_AUTO_DETECT_LONG_POLLING = true;
  5435. /**
  5436. * A concrete type describing all the values that can be applied via a
  5437. * user-supplied `FirestoreSettings` object. This is a separate type so that
  5438. * defaults can be supplied and the value can be checked for equality.
  5439. */
  5440. class FirestoreSettingsImpl {
  5441. constructor(settings) {
  5442. var _a, _b;
  5443. if (settings.host === undefined) {
  5444. if (settings.ssl !== undefined) {
  5445. throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  5446. }
  5447. this.host = DEFAULT_HOST;
  5448. this.ssl = DEFAULT_SSL;
  5449. }
  5450. else {
  5451. this.host = settings.host;
  5452. this.ssl = (_a = settings.ssl) !== null && _a !== void 0 ? _a : DEFAULT_SSL;
  5453. }
  5454. this.credentials = settings.credentials;
  5455. this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;
  5456. this.cache = settings.localCache;
  5457. if (settings.cacheSizeBytes === undefined) {
  5458. this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;
  5459. }
  5460. else {
  5461. if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&
  5462. settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) {
  5463. throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`);
  5464. }
  5465. else {
  5466. this.cacheSizeBytes = settings.cacheSizeBytes;
  5467. }
  5468. }
  5469. validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling);
  5470. this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;
  5471. if (this.experimentalForceLongPolling) {
  5472. this.experimentalAutoDetectLongPolling = false;
  5473. }
  5474. else if (settings.experimentalAutoDetectLongPolling === undefined) {
  5475. this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;
  5476. }
  5477. else {
  5478. // For backwards compatibility, coerce the value to boolean even though
  5479. // the TypeScript compiler has narrowed the type to boolean already.
  5480. // noinspection PointlessBooleanExpressionJS
  5481. this.experimentalAutoDetectLongPolling =
  5482. !!settings.experimentalAutoDetectLongPolling;
  5483. }
  5484. this.experimentalLongPollingOptions = cloneLongPollingOptions((_b = settings.experimentalLongPollingOptions) !== null && _b !== void 0 ? _b : {});
  5485. validateLongPollingOptions(this.experimentalLongPollingOptions);
  5486. this.useFetchStreams = !!settings.useFetchStreams;
  5487. }
  5488. isEqual(other) {
  5489. return (this.host === other.host &&
  5490. this.ssl === other.ssl &&
  5491. this.credentials === other.credentials &&
  5492. this.cacheSizeBytes === other.cacheSizeBytes &&
  5493. this.experimentalForceLongPolling ===
  5494. other.experimentalForceLongPolling &&
  5495. this.experimentalAutoDetectLongPolling ===
  5496. other.experimentalAutoDetectLongPolling &&
  5497. longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) &&
  5498. this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&
  5499. this.useFetchStreams === other.useFetchStreams);
  5500. }
  5501. }
  5502. function validateLongPollingOptions(options) {
  5503. if (options.timeoutSeconds !== undefined) {
  5504. if (isNaN(options.timeoutSeconds)) {
  5505. throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` +
  5506. `${options.timeoutSeconds} (must not be NaN)`);
  5507. }
  5508. if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {
  5509. throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` +
  5510. `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`);
  5511. }
  5512. if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {
  5513. throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` +
  5514. `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`);
  5515. }
  5516. }
  5517. }
  5518. /**
  5519. * @license
  5520. * Copyright 2020 Google LLC
  5521. *
  5522. * Licensed under the Apache License, Version 2.0 (the "License");
  5523. * you may not use this file except in compliance with the License.
  5524. * You may obtain a copy of the License at
  5525. *
  5526. * http://www.apache.org/licenses/LICENSE-2.0
  5527. *
  5528. * Unless required by applicable law or agreed to in writing, software
  5529. * distributed under the License is distributed on an "AS IS" BASIS,
  5530. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5531. * See the License for the specific language governing permissions and
  5532. * limitations under the License.
  5533. */
  5534. /**
  5535. * The Cloud Firestore service interface.
  5536. *
  5537. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  5538. */
  5539. class Firestore {
  5540. /** @hideconstructor */
  5541. constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) {
  5542. this._authCredentials = _authCredentials;
  5543. this._appCheckCredentials = _appCheckCredentials;
  5544. this._databaseId = _databaseId;
  5545. this._app = _app;
  5546. /**
  5547. * Whether it's a Firestore or Firestore Lite instance.
  5548. */
  5549. this.type = 'firestore-lite';
  5550. this._persistenceKey = '(lite)';
  5551. this._settings = new FirestoreSettingsImpl({});
  5552. this._settingsFrozen = false;
  5553. }
  5554. /**
  5555. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  5556. * instance.
  5557. */
  5558. get app() {
  5559. if (!this._app) {
  5560. throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " +
  5561. 'not available');
  5562. }
  5563. return this._app;
  5564. }
  5565. get _initialized() {
  5566. return this._settingsFrozen;
  5567. }
  5568. get _terminated() {
  5569. return this._terminateTask !== undefined;
  5570. }
  5571. _setSettings(settings) {
  5572. if (this._settingsFrozen) {
  5573. throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +
  5574. 'be changed. You can only modify settings before calling any other ' +
  5575. 'methods on a Firestore object.');
  5576. }
  5577. this._settings = new FirestoreSettingsImpl(settings);
  5578. if (settings.credentials !== undefined) {
  5579. this._authCredentials = makeAuthCredentialsProvider(settings.credentials);
  5580. }
  5581. }
  5582. _getSettings() {
  5583. return this._settings;
  5584. }
  5585. _freezeSettings() {
  5586. this._settingsFrozen = true;
  5587. return this._settings;
  5588. }
  5589. _delete() {
  5590. if (!this._terminateTask) {
  5591. this._terminateTask = this._terminate();
  5592. }
  5593. return this._terminateTask;
  5594. }
  5595. /** Returns a JSON-serializable representation of this `Firestore` instance. */
  5596. toJSON() {
  5597. return {
  5598. app: this._app,
  5599. databaseId: this._databaseId,
  5600. settings: this._settings
  5601. };
  5602. }
  5603. /**
  5604. * Terminates all components used by this client. Subclasses can override
  5605. * this method to clean up their own dependencies, but must also call this
  5606. * method.
  5607. *
  5608. * Only ever called once.
  5609. */
  5610. _terminate() {
  5611. removeComponents(this);
  5612. return Promise.resolve();
  5613. }
  5614. }
  5615. function initializeFirestore(app, settings, databaseId) {
  5616. if (!databaseId) {
  5617. databaseId = DEFAULT_DATABASE_NAME;
  5618. }
  5619. const provider = _getProvider(app, 'firestore/lite');
  5620. if (provider.isInitialized(databaseId)) {
  5621. throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore can only be initialized once per app.');
  5622. }
  5623. return provider.initialize({
  5624. options: settings,
  5625. instanceIdentifier: databaseId
  5626. });
  5627. }
  5628. function getFirestore(appOrDatabaseId, optionalDatabaseId) {
  5629. const app = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();
  5630. const databaseId = typeof appOrDatabaseId === 'string'
  5631. ? appOrDatabaseId
  5632. : optionalDatabaseId || '(default)';
  5633. const db = _getProvider(app, 'firestore/lite').getImmediate({
  5634. identifier: databaseId
  5635. });
  5636. if (!db._initialized) {
  5637. const emulator = getDefaultEmulatorHostnameAndPort('firestore');
  5638. if (emulator) {
  5639. connectFirestoreEmulator(db, ...emulator);
  5640. }
  5641. }
  5642. return db;
  5643. }
  5644. /**
  5645. * Modify this instance to communicate with the Cloud Firestore emulator.
  5646. *
  5647. * Note: This must be called before this instance has been used to do any
  5648. * operations.
  5649. *
  5650. * @param firestore - The `Firestore` instance to configure to connect to the
  5651. * emulator.
  5652. * @param host - the emulator host (ex: localhost).
  5653. * @param port - the emulator port (ex: 9000).
  5654. * @param options.mockUserToken - the mock auth token to use for unit testing
  5655. * Security Rules.
  5656. */
  5657. function connectFirestoreEmulator(firestore, host, port, options = {}) {
  5658. var _a;
  5659. firestore = cast(firestore, Firestore);
  5660. const settings = firestore._getSettings();
  5661. const newHostSetting = `${host}:${port}`;
  5662. if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {
  5663. logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +
  5664. 'will be used.');
  5665. }
  5666. firestore._setSettings(Object.assign(Object.assign({}, settings), { host: newHostSetting, ssl: false }));
  5667. if (options.mockUserToken) {
  5668. let token;
  5669. let user;
  5670. if (typeof options.mockUserToken === 'string') {
  5671. token = options.mockUserToken;
  5672. user = User.MOCK_USER;
  5673. }
  5674. else {
  5675. // Let createMockUserToken validate first (catches common mistakes like
  5676. // invalid field "uid" and missing field "sub" / "user_id".)
  5677. token = createMockUserToken(options.mockUserToken, (_a = firestore._app) === null || _a === void 0 ? void 0 : _a.options.projectId);
  5678. const uid = options.mockUserToken.sub || options.mockUserToken.user_id;
  5679. if (!uid) {
  5680. throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  5681. }
  5682. user = new User(uid);
  5683. }
  5684. firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user));
  5685. }
  5686. }
  5687. /**
  5688. * Terminates the provided `Firestore` instance.
  5689. *
  5690. * After calling `terminate()` only the `clearIndexedDbPersistence()` functions
  5691. * may be used. Any other function will throw a `FirestoreError`. Termination
  5692. * does not cancel any pending writes, and any promises that are awaiting a
  5693. * response from the server will not be resolved.
  5694. *
  5695. * To restart after termination, create a new instance of `Firestore` with
  5696. * {@link (getFirestore:1)}.
  5697. *
  5698. * Note: Under normal circumstances, calling `terminate()` is not required. This
  5699. * function is useful only when you want to force this instance to release all of
  5700. * its resources or in combination with {@link clearIndexedDbPersistence} to
  5701. * ensure that all local state is destroyed between test runs.
  5702. *
  5703. * @param firestore - The `Firestore` instance to terminate.
  5704. * @returns A `Promise` that is resolved when the instance has been successfully
  5705. * terminated.
  5706. */
  5707. function terminate(firestore) {
  5708. firestore = cast(firestore, Firestore);
  5709. _removeServiceInstance(firestore.app, 'firestore/lite');
  5710. return firestore._delete();
  5711. }
  5712. /**
  5713. * @license
  5714. * Copyright 2020 Google LLC
  5715. *
  5716. * Licensed under the Apache License, Version 2.0 (the "License");
  5717. * you may not use this file except in compliance with the License.
  5718. * You may obtain a copy of the License at
  5719. *
  5720. * http://www.apache.org/licenses/LICENSE-2.0
  5721. *
  5722. * Unless required by applicable law or agreed to in writing, software
  5723. * distributed under the License is distributed on an "AS IS" BASIS,
  5724. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5725. * See the License for the specific language governing permissions and
  5726. * limitations under the License.
  5727. */
  5728. function registerFirestore() {
  5729. setSDKVersion(`${SDK_VERSION$1}_lite`);
  5730. _registerComponent(new Component('firestore/lite', (container, { instanceIdentifier: databaseId, options: settings }) => {
  5731. const app = container.getProvider('app').getImmediate();
  5732. const firestoreInstance = new Firestore(new LiteAuthCredentialsProvider(container.getProvider('auth-internal')), new LiteAppCheckTokenProvider(container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app);
  5733. if (settings) {
  5734. firestoreInstance._setSettings(settings);
  5735. }
  5736. return firestoreInstance;
  5737. }, 'PUBLIC').setMultipleInstances(true));
  5738. // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation
  5739. registerVersion('firestore-lite', version$1, 'node');
  5740. registerVersion('firestore-lite', version$1, 'esm2017');
  5741. }
  5742. /**
  5743. * @license
  5744. * Copyright 2023 Google LLC
  5745. *
  5746. * Licensed under the Apache License, Version 2.0 (the "License");
  5747. * you may not use this file except in compliance with the License.
  5748. * You may obtain a copy of the License at
  5749. *
  5750. * http://www.apache.org/licenses/LICENSE-2.0
  5751. *
  5752. * Unless required by applicable law or agreed to in writing, software
  5753. * distributed under the License is distributed on an "AS IS" BASIS,
  5754. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5755. * See the License for the specific language governing permissions and
  5756. * limitations under the License.
  5757. */
  5758. /**
  5759. * Concrete implementation of the Aggregate type.
  5760. */
  5761. class AggregateImpl {
  5762. constructor(alias, aggregateType, fieldPath) {
  5763. this.alias = alias;
  5764. this.aggregateType = aggregateType;
  5765. this.fieldPath = fieldPath;
  5766. }
  5767. }
  5768. /**
  5769. * @license
  5770. * Copyright 2022 Google LLC
  5771. *
  5772. * Licensed under the Apache License, Version 2.0 (the "License");
  5773. * you may not use this file except in compliance with the License.
  5774. * You may obtain a copy of the License at
  5775. *
  5776. * http://www.apache.org/licenses/LICENSE-2.0
  5777. *
  5778. * Unless required by applicable law or agreed to in writing, software
  5779. * distributed under the License is distributed on an "AS IS" BASIS,
  5780. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5781. * See the License for the specific language governing permissions and
  5782. * limitations under the License.
  5783. */
  5784. /**
  5785. * Represents an aggregation that can be performed by Firestore.
  5786. */
  5787. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  5788. class AggregateField {
  5789. /**
  5790. * Create a new AggregateField<T>
  5791. * @param _aggregateType Specifies the type of aggregation operation to perform.
  5792. * @param _internalFieldPath Optionally specifies the field that is aggregated.
  5793. * @internal
  5794. */
  5795. constructor(
  5796. // TODO (sum/avg) make aggregateType public when the feature is supported
  5797. _aggregateType = 'count', _internalFieldPath) {
  5798. this._aggregateType = _aggregateType;
  5799. this._internalFieldPath = _internalFieldPath;
  5800. /** A type string to uniquely identify instances of this class. */
  5801. this.type = 'AggregateField';
  5802. }
  5803. }
  5804. /**
  5805. * The results of executing an aggregation query.
  5806. */
  5807. class AggregateQuerySnapshot {
  5808. /** @hideconstructor */
  5809. constructor(query, _userDataWriter, _data) {
  5810. this._userDataWriter = _userDataWriter;
  5811. this._data = _data;
  5812. /** A type string to uniquely identify instances of this class. */
  5813. this.type = 'AggregateQuerySnapshot';
  5814. this.query = query;
  5815. }
  5816. /**
  5817. * Returns the results of the aggregations performed over the underlying
  5818. * query.
  5819. *
  5820. * The keys of the returned object will be the same as those of the
  5821. * `AggregateSpec` object specified to the aggregation method, and the values
  5822. * will be the corresponding aggregation result.
  5823. *
  5824. * @returns The results of the aggregations performed over the underlying
  5825. * query.
  5826. */
  5827. data() {
  5828. return this._userDataWriter.convertObjectMap(this._data);
  5829. }
  5830. }
  5831. /**
  5832. * @license
  5833. * Copyright 2020 Google LLC
  5834. *
  5835. * Licensed under the Apache License, Version 2.0 (the "License");
  5836. * you may not use this file except in compliance with the License.
  5837. * You may obtain a copy of the License at
  5838. *
  5839. * http://www.apache.org/licenses/LICENSE-2.0
  5840. *
  5841. * Unless required by applicable law or agreed to in writing, software
  5842. * distributed under the License is distributed on an "AS IS" BASIS,
  5843. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5844. * See the License for the specific language governing permissions and
  5845. * limitations under the License.
  5846. */
  5847. /**
  5848. * A `DocumentReference` refers to a document location in a Firestore database
  5849. * and can be used to write, read, or listen to the location. The document at
  5850. * the referenced location may or may not exist.
  5851. */
  5852. class DocumentReference {
  5853. /** @hideconstructor */
  5854. constructor(firestore,
  5855. /**
  5856. * If provided, the `FirestoreDataConverter` associated with this instance.
  5857. */
  5858. converter, _key) {
  5859. this.converter = converter;
  5860. this._key = _key;
  5861. /** The type of this Firestore reference. */
  5862. this.type = 'document';
  5863. this.firestore = firestore;
  5864. }
  5865. get _path() {
  5866. return this._key.path;
  5867. }
  5868. /**
  5869. * The document's identifier within its collection.
  5870. */
  5871. get id() {
  5872. return this._key.path.lastSegment();
  5873. }
  5874. /**
  5875. * A string representing the path of the referenced document (relative
  5876. * to the root of the database).
  5877. */
  5878. get path() {
  5879. return this._key.path.canonicalString();
  5880. }
  5881. /**
  5882. * The collection this `DocumentReference` belongs to.
  5883. */
  5884. get parent() {
  5885. return new CollectionReference(this.firestore, this.converter, this._key.path.popLast());
  5886. }
  5887. withConverter(converter) {
  5888. return new DocumentReference(this.firestore, converter, this._key);
  5889. }
  5890. }
  5891. /**
  5892. * A `Query` refers to a query which you can read or listen to. You can also
  5893. * construct refined `Query` objects by adding filters and ordering.
  5894. */
  5895. class Query {
  5896. // This is the lite version of the Query class in the main SDK.
  5897. /** @hideconstructor protected */
  5898. constructor(firestore,
  5899. /**
  5900. * If provided, the `FirestoreDataConverter` associated with this instance.
  5901. */
  5902. converter, _query) {
  5903. this.converter = converter;
  5904. this._query = _query;
  5905. /** The type of this Firestore reference. */
  5906. this.type = 'query';
  5907. this.firestore = firestore;
  5908. }
  5909. withConverter(converter) {
  5910. return new Query(this.firestore, converter, this._query);
  5911. }
  5912. }
  5913. /**
  5914. * A `CollectionReference` object can be used for adding documents, getting
  5915. * document references, and querying for documents (using {@link (query:1)}).
  5916. */
  5917. class CollectionReference extends Query {
  5918. /** @hideconstructor */
  5919. constructor(firestore, converter, _path) {
  5920. super(firestore, converter, newQueryForPath(_path));
  5921. this._path = _path;
  5922. /** The type of this Firestore reference. */
  5923. this.type = 'collection';
  5924. }
  5925. /** The collection's identifier. */
  5926. get id() {
  5927. return this._query.path.lastSegment();
  5928. }
  5929. /**
  5930. * A string representing the path of the referenced collection (relative
  5931. * to the root of the database).
  5932. */
  5933. get path() {
  5934. return this._query.path.canonicalString();
  5935. }
  5936. /**
  5937. * A reference to the containing `DocumentReference` if this is a
  5938. * subcollection. If this isn't a subcollection, the reference is null.
  5939. */
  5940. get parent() {
  5941. const parentPath = this._path.popLast();
  5942. if (parentPath.isEmpty()) {
  5943. return null;
  5944. }
  5945. else {
  5946. return new DocumentReference(this.firestore,
  5947. /* converter= */ null, new DocumentKey(parentPath));
  5948. }
  5949. }
  5950. withConverter(converter) {
  5951. return new CollectionReference(this.firestore, converter, this._path);
  5952. }
  5953. }
  5954. function collection(parent, path, ...pathSegments) {
  5955. parent = getModularInstance(parent);
  5956. validateNonEmptyArgument('collection', 'path', path);
  5957. if (parent instanceof Firestore) {
  5958. const absolutePath = ResourcePath.fromString(path, ...pathSegments);
  5959. validateCollectionPath(absolutePath);
  5960. return new CollectionReference(parent, /* converter= */ null, absolutePath);
  5961. }
  5962. else {
  5963. if (!(parent instanceof DocumentReference) &&
  5964. !(parent instanceof CollectionReference)) {
  5965. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' +
  5966. 'a DocumentReference or FirebaseFirestore');
  5967. }
  5968. const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments));
  5969. validateCollectionPath(absolutePath);
  5970. return new CollectionReference(parent.firestore,
  5971. /* converter= */ null, absolutePath);
  5972. }
  5973. }
  5974. // TODO(firestorelite): Consider using ErrorFactory -
  5975. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  5976. /**
  5977. * Creates and returns a new `Query` instance that includes all documents in the
  5978. * database that are contained in a collection or subcollection with the
  5979. * given `collectionId`.
  5980. *
  5981. * @param firestore - A reference to the root `Firestore` instance.
  5982. * @param collectionId - Identifies the collections to query over. Every
  5983. * collection or subcollection with this ID as the last segment of its path
  5984. * will be included. Cannot contain a slash.
  5985. * @returns The created `Query`.
  5986. */
  5987. function collectionGroup(firestore, collectionId) {
  5988. firestore = cast(firestore, Firestore);
  5989. validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);
  5990. if (collectionId.indexOf('/') >= 0) {
  5991. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` +
  5992. `collectionGroup(). Collection IDs must not contain '/'.`);
  5993. }
  5994. return new Query(firestore,
  5995. /* converter= */ null, newQueryForCollectionGroup(collectionId));
  5996. }
  5997. function doc(parent, path, ...pathSegments) {
  5998. parent = getModularInstance(parent);
  5999. // We allow omission of 'pathString' but explicitly prohibit passing in both
  6000. // 'undefined' and 'null'.
  6001. if (arguments.length === 1) {
  6002. path = AutoId.newId();
  6003. }
  6004. validateNonEmptyArgument('doc', 'path', path);
  6005. if (parent instanceof Firestore) {
  6006. const absolutePath = ResourcePath.fromString(path, ...pathSegments);
  6007. validateDocumentPath(absolutePath);
  6008. return new DocumentReference(parent,
  6009. /* converter= */ null, new DocumentKey(absolutePath));
  6010. }
  6011. else {
  6012. if (!(parent instanceof DocumentReference) &&
  6013. !(parent instanceof CollectionReference)) {
  6014. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' +
  6015. 'a DocumentReference or FirebaseFirestore');
  6016. }
  6017. const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments));
  6018. validateDocumentPath(absolutePath);
  6019. return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath));
  6020. }
  6021. }
  6022. /**
  6023. * Returns true if the provided references are equal.
  6024. *
  6025. * @param left - A reference to compare.
  6026. * @param right - A reference to compare.
  6027. * @returns true if the references point to the same location in the same
  6028. * Firestore database.
  6029. */
  6030. function refEqual(left, right) {
  6031. left = getModularInstance(left);
  6032. right = getModularInstance(right);
  6033. if ((left instanceof DocumentReference ||
  6034. left instanceof CollectionReference) &&
  6035. (right instanceof DocumentReference || right instanceof CollectionReference)) {
  6036. return (left.firestore === right.firestore &&
  6037. left.path === right.path &&
  6038. left.converter === right.converter);
  6039. }
  6040. return false;
  6041. }
  6042. /**
  6043. * Returns true if the provided queries point to the same collection and apply
  6044. * the same constraints.
  6045. *
  6046. * @param left - A `Query` to compare.
  6047. * @param right - A `Query` to compare.
  6048. * @returns true if the references point to the same location in the same
  6049. * Firestore database.
  6050. */
  6051. function queryEqual(left, right) {
  6052. left = getModularInstance(left);
  6053. right = getModularInstance(right);
  6054. if (left instanceof Query && right instanceof Query) {
  6055. return (left.firestore === right.firestore &&
  6056. queryEquals(left._query, right._query) &&
  6057. left.converter === right.converter);
  6058. }
  6059. return false;
  6060. }
  6061. /**
  6062. * @license
  6063. * Copyright 2020 Google LLC
  6064. *
  6065. * Licensed under the Apache License, Version 2.0 (the "License");
  6066. * you may not use this file except in compliance with the License.
  6067. * You may obtain a copy of the License at
  6068. *
  6069. * http://www.apache.org/licenses/LICENSE-2.0
  6070. *
  6071. * Unless required by applicable law or agreed to in writing, software
  6072. * distributed under the License is distributed on an "AS IS" BASIS,
  6073. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6074. * See the License for the specific language governing permissions and
  6075. * limitations under the License.
  6076. */
  6077. /**
  6078. * An immutable object representing an array of bytes.
  6079. */
  6080. class Bytes {
  6081. /** @hideconstructor */
  6082. constructor(byteString) {
  6083. this._byteString = byteString;
  6084. }
  6085. /**
  6086. * Creates a new `Bytes` object from the given Base64 string, converting it to
  6087. * bytes.
  6088. *
  6089. * @param base64 - The Base64 string used to create the `Bytes` object.
  6090. */
  6091. static fromBase64String(base64) {
  6092. try {
  6093. return new Bytes(ByteString.fromBase64String(base64));
  6094. }
  6095. catch (e) {
  6096. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e);
  6097. }
  6098. }
  6099. /**
  6100. * Creates a new `Bytes` object from the given Uint8Array.
  6101. *
  6102. * @param array - The Uint8Array used to create the `Bytes` object.
  6103. */
  6104. static fromUint8Array(array) {
  6105. return new Bytes(ByteString.fromUint8Array(array));
  6106. }
  6107. /**
  6108. * Returns the underlying bytes as a Base64-encoded string.
  6109. *
  6110. * @returns The Base64-encoded string created from the `Bytes` object.
  6111. */
  6112. toBase64() {
  6113. return this._byteString.toBase64();
  6114. }
  6115. /**
  6116. * Returns the underlying bytes in a new `Uint8Array`.
  6117. *
  6118. * @returns The Uint8Array created from the `Bytes` object.
  6119. */
  6120. toUint8Array() {
  6121. return this._byteString.toUint8Array();
  6122. }
  6123. /**
  6124. * Returns a string representation of the `Bytes` object.
  6125. *
  6126. * @returns A string representation of the `Bytes` object.
  6127. */
  6128. toString() {
  6129. return 'Bytes(base64: ' + this.toBase64() + ')';
  6130. }
  6131. /**
  6132. * Returns true if this `Bytes` object is equal to the provided one.
  6133. *
  6134. * @param other - The `Bytes` object to compare against.
  6135. * @returns true if this `Bytes` object is equal to the provided one.
  6136. */
  6137. isEqual(other) {
  6138. return this._byteString.isEqual(other._byteString);
  6139. }
  6140. }
  6141. /**
  6142. * @license
  6143. * Copyright 2020 Google LLC
  6144. *
  6145. * Licensed under the Apache License, Version 2.0 (the "License");
  6146. * you may not use this file except in compliance with the License.
  6147. * You may obtain a copy of the License at
  6148. *
  6149. * http://www.apache.org/licenses/LICENSE-2.0
  6150. *
  6151. * Unless required by applicable law or agreed to in writing, software
  6152. * distributed under the License is distributed on an "AS IS" BASIS,
  6153. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6154. * See the License for the specific language governing permissions and
  6155. * limitations under the License.
  6156. */
  6157. /**
  6158. * A `FieldPath` refers to a field in a document. The path may consist of a
  6159. * single field name (referring to a top-level field in the document), or a
  6160. * list of field names (referring to a nested field in the document).
  6161. *
  6162. * Create a `FieldPath` by providing field names. If more than one field
  6163. * name is provided, the path will point to a nested field in a document.
  6164. */
  6165. class FieldPath {
  6166. /**
  6167. * Creates a `FieldPath` from the provided field names. If more than one field
  6168. * name is provided, the path will point to a nested field in a document.
  6169. *
  6170. * @param fieldNames - A list of field names.
  6171. */
  6172. constructor(...fieldNames) {
  6173. for (let i = 0; i < fieldNames.length; ++i) {
  6174. if (fieldNames[i].length === 0) {
  6175. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` +
  6176. 'Field names must not be empty.');
  6177. }
  6178. }
  6179. this._internalPath = new FieldPath$1(fieldNames);
  6180. }
  6181. /**
  6182. * Returns true if this `FieldPath` is equal to the provided one.
  6183. *
  6184. * @param other - The `FieldPath` to compare against.
  6185. * @returns true if this `FieldPath` is equal to the provided one.
  6186. */
  6187. isEqual(other) {
  6188. return this._internalPath.isEqual(other._internalPath);
  6189. }
  6190. }
  6191. /**
  6192. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  6193. * It can be used in queries to sort or filter by the document ID.
  6194. */
  6195. function documentId() {
  6196. return new FieldPath(DOCUMENT_KEY_NAME);
  6197. }
  6198. /**
  6199. * @license
  6200. * Copyright 2020 Google LLC
  6201. *
  6202. * Licensed under the Apache License, Version 2.0 (the "License");
  6203. * you may not use this file except in compliance with the License.
  6204. * You may obtain a copy of the License at
  6205. *
  6206. * http://www.apache.org/licenses/LICENSE-2.0
  6207. *
  6208. * Unless required by applicable law or agreed to in writing, software
  6209. * distributed under the License is distributed on an "AS IS" BASIS,
  6210. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6211. * See the License for the specific language governing permissions and
  6212. * limitations under the License.
  6213. */
  6214. /**
  6215. * Sentinel values that can be used when writing document fields with `set()`
  6216. * or `update()`.
  6217. */
  6218. class FieldValue {
  6219. /**
  6220. * @param _methodName - The public API endpoint that returns this class.
  6221. * @hideconstructor
  6222. */
  6223. constructor(_methodName) {
  6224. this._methodName = _methodName;
  6225. }
  6226. }
  6227. /**
  6228. * @license
  6229. * Copyright 2017 Google LLC
  6230. *
  6231. * Licensed under the Apache License, Version 2.0 (the "License");
  6232. * you may not use this file except in compliance with the License.
  6233. * You may obtain a copy of the License at
  6234. *
  6235. * http://www.apache.org/licenses/LICENSE-2.0
  6236. *
  6237. * Unless required by applicable law or agreed to in writing, software
  6238. * distributed under the License is distributed on an "AS IS" BASIS,
  6239. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6240. * See the License for the specific language governing permissions and
  6241. * limitations under the License.
  6242. */
  6243. /**
  6244. * An immutable object representing a geographic location in Firestore. The
  6245. * location is represented as latitude/longitude pair.
  6246. *
  6247. * Latitude values are in the range of [-90, 90].
  6248. * Longitude values are in the range of [-180, 180].
  6249. */
  6250. class GeoPoint {
  6251. /**
  6252. * Creates a new immutable `GeoPoint` object with the provided latitude and
  6253. * longitude values.
  6254. * @param latitude - The latitude as number between -90 and 90.
  6255. * @param longitude - The longitude as number between -180 and 180.
  6256. */
  6257. constructor(latitude, longitude) {
  6258. if (!isFinite(latitude) || latitude < -90 || latitude > 90) {
  6259. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);
  6260. }
  6261. if (!isFinite(longitude) || longitude < -180 || longitude > 180) {
  6262. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);
  6263. }
  6264. this._lat = latitude;
  6265. this._long = longitude;
  6266. }
  6267. /**
  6268. * The latitude of this `GeoPoint` instance.
  6269. */
  6270. get latitude() {
  6271. return this._lat;
  6272. }
  6273. /**
  6274. * The longitude of this `GeoPoint` instance.
  6275. */
  6276. get longitude() {
  6277. return this._long;
  6278. }
  6279. /**
  6280. * Returns true if this `GeoPoint` is equal to the provided one.
  6281. *
  6282. * @param other - The `GeoPoint` to compare against.
  6283. * @returns true if this `GeoPoint` is equal to the provided one.
  6284. */
  6285. isEqual(other) {
  6286. return this._lat === other._lat && this._long === other._long;
  6287. }
  6288. /** Returns a JSON-serializable representation of this GeoPoint. */
  6289. toJSON() {
  6290. return { latitude: this._lat, longitude: this._long };
  6291. }
  6292. /**
  6293. * Actually private to JS consumers of our API, so this function is prefixed
  6294. * with an underscore.
  6295. */
  6296. _compareTo(other) {
  6297. return (primitiveComparator(this._lat, other._lat) ||
  6298. primitiveComparator(this._long, other._long));
  6299. }
  6300. }
  6301. /**
  6302. * @license
  6303. * Copyright 2017 Google LLC
  6304. *
  6305. * Licensed under the Apache License, Version 2.0 (the "License");
  6306. * you may not use this file except in compliance with the License.
  6307. * You may obtain a copy of the License at
  6308. *
  6309. * http://www.apache.org/licenses/LICENSE-2.0
  6310. *
  6311. * Unless required by applicable law or agreed to in writing, software
  6312. * distributed under the License is distributed on an "AS IS" BASIS,
  6313. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6314. * See the License for the specific language governing permissions and
  6315. * limitations under the License.
  6316. */
  6317. const RESERVED_FIELD_REGEX = /^__.*__$/;
  6318. /** The result of parsing document data (e.g. for a setData call). */
  6319. class ParsedSetData {
  6320. constructor(data, fieldMask, fieldTransforms) {
  6321. this.data = data;
  6322. this.fieldMask = fieldMask;
  6323. this.fieldTransforms = fieldTransforms;
  6324. }
  6325. toMutation(key, precondition) {
  6326. if (this.fieldMask !== null) {
  6327. return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms);
  6328. }
  6329. else {
  6330. return new SetMutation(key, this.data, precondition, this.fieldTransforms);
  6331. }
  6332. }
  6333. }
  6334. /** The result of parsing "update" data (i.e. for an updateData call). */
  6335. class ParsedUpdateData {
  6336. constructor(data,
  6337. // The fieldMask does not include document transforms.
  6338. fieldMask, fieldTransforms) {
  6339. this.data = data;
  6340. this.fieldMask = fieldMask;
  6341. this.fieldTransforms = fieldTransforms;
  6342. }
  6343. toMutation(key, precondition) {
  6344. return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms);
  6345. }
  6346. }
  6347. function isWrite(dataSource) {
  6348. switch (dataSource) {
  6349. case 0 /* UserDataSource.Set */: // fall through
  6350. case 2 /* UserDataSource.MergeSet */: // fall through
  6351. case 1 /* UserDataSource.Update */:
  6352. return true;
  6353. case 3 /* UserDataSource.Argument */:
  6354. case 4 /* UserDataSource.ArrayArgument */:
  6355. return false;
  6356. default:
  6357. throw fail();
  6358. }
  6359. }
  6360. /** A "context" object passed around while parsing user data. */
  6361. class ParseContextImpl {
  6362. /**
  6363. * Initializes a ParseContext with the given source and path.
  6364. *
  6365. * @param settings - The settings for the parser.
  6366. * @param databaseId - The database ID of the Firestore instance.
  6367. * @param serializer - The serializer to use to generate the Value proto.
  6368. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  6369. * rather than throw.
  6370. * @param fieldTransforms - A mutable list of field transforms encountered
  6371. * while parsing the data.
  6372. * @param fieldMask - A mutable list of field paths encountered while parsing
  6373. * the data.
  6374. *
  6375. * TODO(b/34871131): We don't support array paths right now, so path can be
  6376. * null to indicate the context represents any location within an array (in
  6377. * which case certain features will not work and errors will be somewhat
  6378. * compromised).
  6379. */
  6380. constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) {
  6381. this.settings = settings;
  6382. this.databaseId = databaseId;
  6383. this.serializer = serializer;
  6384. this.ignoreUndefinedProperties = ignoreUndefinedProperties;
  6385. // Minor hack: If fieldTransforms is undefined, we assume this is an
  6386. // external call and we need to validate the entire path.
  6387. if (fieldTransforms === undefined) {
  6388. this.validatePath();
  6389. }
  6390. this.fieldTransforms = fieldTransforms || [];
  6391. this.fieldMask = fieldMask || [];
  6392. }
  6393. get path() {
  6394. return this.settings.path;
  6395. }
  6396. get dataSource() {
  6397. return this.settings.dataSource;
  6398. }
  6399. /** Returns a new context with the specified settings overwritten. */
  6400. contextWith(configuration) {
  6401. return new ParseContextImpl(Object.assign(Object.assign({}, this.settings), configuration), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  6402. }
  6403. childContextForField(field) {
  6404. var _a;
  6405. const childPath = (_a = this.path) === null || _a === void 0 ? void 0 : _a.child(field);
  6406. const context = this.contextWith({ path: childPath, arrayElement: false });
  6407. context.validatePathSegment(field);
  6408. return context;
  6409. }
  6410. childContextForFieldPath(field) {
  6411. var _a;
  6412. const childPath = (_a = this.path) === null || _a === void 0 ? void 0 : _a.child(field);
  6413. const context = this.contextWith({ path: childPath, arrayElement: false });
  6414. context.validatePath();
  6415. return context;
  6416. }
  6417. childContextForArray(index) {
  6418. // TODO(b/34871131): We don't support array paths right now; so make path
  6419. // undefined.
  6420. return this.contextWith({ path: undefined, arrayElement: true });
  6421. }
  6422. createError(reason) {
  6423. return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc);
  6424. }
  6425. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */
  6426. contains(fieldPath) {
  6427. return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||
  6428. this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined);
  6429. }
  6430. validatePath() {
  6431. // TODO(b/34871131): Remove null check once we have proper paths for fields
  6432. // within arrays.
  6433. if (!this.path) {
  6434. return;
  6435. }
  6436. for (let i = 0; i < this.path.length; i++) {
  6437. this.validatePathSegment(this.path.get(i));
  6438. }
  6439. }
  6440. validatePathSegment(segment) {
  6441. if (segment.length === 0) {
  6442. throw this.createError('Document fields must not be empty');
  6443. }
  6444. if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {
  6445. throw this.createError('Document fields cannot begin and end with "__"');
  6446. }
  6447. }
  6448. }
  6449. /**
  6450. * Helper for parsing raw user input (provided via the API) into internal model
  6451. * classes.
  6452. */
  6453. class UserDataReader {
  6454. constructor(databaseId, ignoreUndefinedProperties, serializer) {
  6455. this.databaseId = databaseId;
  6456. this.ignoreUndefinedProperties = ignoreUndefinedProperties;
  6457. this.serializer = serializer || newSerializer(databaseId);
  6458. }
  6459. /** Creates a new top-level parse context. */
  6460. createContext(dataSource, methodName, targetDoc, hasConverter = false) {
  6461. return new ParseContextImpl({
  6462. dataSource,
  6463. methodName,
  6464. targetDoc,
  6465. path: FieldPath$1.emptyPath(),
  6466. arrayElement: false,
  6467. hasConverter
  6468. }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  6469. }
  6470. }
  6471. function newUserDataReader(firestore) {
  6472. const settings = firestore._freezeSettings();
  6473. const serializer = newSerializer(firestore._databaseId);
  6474. return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer);
  6475. }
  6476. /** Parse document data from a set() call. */
  6477. function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) {
  6478. const context = userDataReader.createContext(options.merge || options.mergeFields
  6479. ? 2 /* UserDataSource.MergeSet */
  6480. : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter);
  6481. validatePlainObject('Data must be an object, but it was:', context, input);
  6482. const updateData = parseObject(input, context);
  6483. let fieldMask;
  6484. let fieldTransforms;
  6485. if (options.merge) {
  6486. fieldMask = new FieldMask(context.fieldMask);
  6487. fieldTransforms = context.fieldTransforms;
  6488. }
  6489. else if (options.mergeFields) {
  6490. const validatedFieldPaths = [];
  6491. for (const stringOrFieldPath of options.mergeFields) {
  6492. const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc);
  6493. if (!context.contains(fieldPath)) {
  6494. throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`);
  6495. }
  6496. if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {
  6497. validatedFieldPaths.push(fieldPath);
  6498. }
  6499. }
  6500. fieldMask = new FieldMask(validatedFieldPaths);
  6501. fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field));
  6502. }
  6503. else {
  6504. fieldMask = null;
  6505. fieldTransforms = context.fieldTransforms;
  6506. }
  6507. return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms);
  6508. }
  6509. class DeleteFieldValueImpl extends FieldValue {
  6510. _toFieldTransform(context) {
  6511. if (context.dataSource === 2 /* UserDataSource.MergeSet */) {
  6512. // No transform to add for a delete, but we need to add it to our
  6513. // fieldMask so it gets deleted.
  6514. context.fieldMask.push(context.path);
  6515. }
  6516. else if (context.dataSource === 1 /* UserDataSource.Update */) {
  6517. throw context.createError(`${this._methodName}() can only appear at the top level ` +
  6518. 'of your update data');
  6519. }
  6520. else {
  6521. // We shouldn't encounter delete sentinels for queries or non-merge set() calls.
  6522. throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` +
  6523. '{merge:true}');
  6524. }
  6525. return null;
  6526. }
  6527. isEqual(other) {
  6528. return other instanceof DeleteFieldValueImpl;
  6529. }
  6530. }
  6531. /**
  6532. * Creates a child context for parsing SerializableFieldValues.
  6533. *
  6534. * This is different than calling `ParseContext.contextWith` because it keeps
  6535. * the fieldTransforms and fieldMask separate.
  6536. *
  6537. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  6538. * Although these values are used with writes, any elements in these FieldValues
  6539. * are not considered writes since they cannot contain any FieldValue sentinels,
  6540. * etc.
  6541. *
  6542. * @param fieldValue - The sentinel FieldValue for which to create a child
  6543. * context.
  6544. * @param context - The parent context.
  6545. * @param arrayElement - Whether or not the FieldValue has an array.
  6546. */
  6547. function createSentinelChildContext(fieldValue, context, arrayElement) {
  6548. return new ParseContextImpl({
  6549. dataSource: 3 /* UserDataSource.Argument */,
  6550. targetDoc: context.settings.targetDoc,
  6551. methodName: fieldValue._methodName,
  6552. arrayElement
  6553. }, context.databaseId, context.serializer, context.ignoreUndefinedProperties);
  6554. }
  6555. class ServerTimestampFieldValueImpl extends FieldValue {
  6556. _toFieldTransform(context) {
  6557. return new FieldTransform(context.path, new ServerTimestampTransform());
  6558. }
  6559. isEqual(other) {
  6560. return other instanceof ServerTimestampFieldValueImpl;
  6561. }
  6562. }
  6563. class ArrayUnionFieldValueImpl extends FieldValue {
  6564. constructor(methodName, _elements) {
  6565. super(methodName);
  6566. this._elements = _elements;
  6567. }
  6568. _toFieldTransform(context) {
  6569. const parseContext = createSentinelChildContext(this, context,
  6570. /*array=*/ true);
  6571. const parsedElements = this._elements.map(element => parseData(element, parseContext));
  6572. const arrayUnion = new ArrayUnionTransformOperation(parsedElements);
  6573. return new FieldTransform(context.path, arrayUnion);
  6574. }
  6575. isEqual(other) {
  6576. // TODO(mrschmidt): Implement isEquals
  6577. return this === other;
  6578. }
  6579. }
  6580. class ArrayRemoveFieldValueImpl extends FieldValue {
  6581. constructor(methodName, _elements) {
  6582. super(methodName);
  6583. this._elements = _elements;
  6584. }
  6585. _toFieldTransform(context) {
  6586. const parseContext = createSentinelChildContext(this, context,
  6587. /*array=*/ true);
  6588. const parsedElements = this._elements.map(element => parseData(element, parseContext));
  6589. const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);
  6590. return new FieldTransform(context.path, arrayUnion);
  6591. }
  6592. isEqual(other) {
  6593. // TODO(mrschmidt): Implement isEquals
  6594. return this === other;
  6595. }
  6596. }
  6597. class NumericIncrementFieldValueImpl extends FieldValue {
  6598. constructor(methodName, _operand) {
  6599. super(methodName);
  6600. this._operand = _operand;
  6601. }
  6602. _toFieldTransform(context) {
  6603. const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand));
  6604. return new FieldTransform(context.path, numericIncrement);
  6605. }
  6606. isEqual(other) {
  6607. // TODO(mrschmidt): Implement isEquals
  6608. return this === other;
  6609. }
  6610. }
  6611. /** Parse update data from an update() call. */
  6612. function parseUpdateData(userDataReader, methodName, targetDoc, input) {
  6613. const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc);
  6614. validatePlainObject('Data must be an object, but it was:', context, input);
  6615. const fieldMaskPaths = [];
  6616. const updateData = ObjectValue.empty();
  6617. forEach(input, (key, value) => {
  6618. const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);
  6619. // For Compat types, we have to "extract" the underlying types before
  6620. // performing validation.
  6621. value = getModularInstance(value);
  6622. const childContext = context.childContextForFieldPath(path);
  6623. if (value instanceof DeleteFieldValueImpl) {
  6624. // Add it to the field mask, but don't add anything to updateData.
  6625. fieldMaskPaths.push(path);
  6626. }
  6627. else {
  6628. const parsedValue = parseData(value, childContext);
  6629. if (parsedValue != null) {
  6630. fieldMaskPaths.push(path);
  6631. updateData.set(path, parsedValue);
  6632. }
  6633. }
  6634. });
  6635. const mask = new FieldMask(fieldMaskPaths);
  6636. return new ParsedUpdateData(updateData, mask, context.fieldTransforms);
  6637. }
  6638. /** Parse update data from a list of field/value arguments. */
  6639. function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) {
  6640. const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc);
  6641. const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)];
  6642. const values = [value];
  6643. if (moreFieldsAndValues.length % 2 !== 0) {
  6644. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` +
  6645. 'of arguments that alternate between field names and values.');
  6646. }
  6647. for (let i = 0; i < moreFieldsAndValues.length; i += 2) {
  6648. keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i]));
  6649. values.push(moreFieldsAndValues[i + 1]);
  6650. }
  6651. const fieldMaskPaths = [];
  6652. const updateData = ObjectValue.empty();
  6653. // We iterate in reverse order to pick the last value for a field if the
  6654. // user specified the field multiple times.
  6655. for (let i = keys.length - 1; i >= 0; --i) {
  6656. if (!fieldMaskContains(fieldMaskPaths, keys[i])) {
  6657. const path = keys[i];
  6658. let value = values[i];
  6659. // For Compat types, we have to "extract" the underlying types before
  6660. // performing validation.
  6661. value = getModularInstance(value);
  6662. const childContext = context.childContextForFieldPath(path);
  6663. if (value instanceof DeleteFieldValueImpl) {
  6664. // Add it to the field mask, but don't add anything to updateData.
  6665. fieldMaskPaths.push(path);
  6666. }
  6667. else {
  6668. const parsedValue = parseData(value, childContext);
  6669. if (parsedValue != null) {
  6670. fieldMaskPaths.push(path);
  6671. updateData.set(path, parsedValue);
  6672. }
  6673. }
  6674. }
  6675. }
  6676. const mask = new FieldMask(fieldMaskPaths);
  6677. return new ParsedUpdateData(updateData, mask, context.fieldTransforms);
  6678. }
  6679. /**
  6680. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  6681. * bound).
  6682. *
  6683. * @param allowArrays - Whether the query value is an array that may directly
  6684. * contain additional arrays (e.g. the operand of an `in` query).
  6685. */
  6686. function parseQueryValue(userDataReader, methodName, input, allowArrays = false) {
  6687. const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName);
  6688. const parsed = parseData(input, context);
  6689. return parsed;
  6690. }
  6691. /**
  6692. * Parses user data to Protobuf Values.
  6693. *
  6694. * @param input - Data to be parsed.
  6695. * @param context - A context object representing the current path being parsed,
  6696. * the source of the data being parsed, etc.
  6697. * @returns The parsed value, or null if the value was a FieldValue sentinel
  6698. * that should not be included in the resulting parsed data.
  6699. */
  6700. function parseData(input, context) {
  6701. // Unwrap the API type from the Compat SDK. This will return the API type
  6702. // from firestore-exp.
  6703. input = getModularInstance(input);
  6704. if (looksLikeJsonObject(input)) {
  6705. validatePlainObject('Unsupported field value:', context, input);
  6706. return parseObject(input, context);
  6707. }
  6708. else if (input instanceof FieldValue) {
  6709. // FieldValues usually parse into transforms (except deleteField())
  6710. // in which case we do not want to include this field in our parsed data
  6711. // (as doing so will overwrite the field directly prior to the transform
  6712. // trying to transform it). So we don't add this location to
  6713. // context.fieldMask and we return null as our parsing result.
  6714. parseSentinelFieldValue(input, context);
  6715. return null;
  6716. }
  6717. else if (input === undefined && context.ignoreUndefinedProperties) {
  6718. // If the input is undefined it can never participate in the fieldMask, so
  6719. // don't handle this below. If `ignoreUndefinedProperties` is false,
  6720. // `parseScalarValue` will reject an undefined value.
  6721. return null;
  6722. }
  6723. else {
  6724. // If context.path is null we are inside an array and we don't support
  6725. // field mask paths more granular than the top-level array.
  6726. if (context.path) {
  6727. context.fieldMask.push(context.path);
  6728. }
  6729. if (input instanceof Array) {
  6730. // TODO(b/34871131): Include the path containing the array in the error
  6731. // message.
  6732. // In the case of IN queries, the parsed data is an array (representing
  6733. // the set of values to be included for the IN query) that may directly
  6734. // contain additional arrays (each representing an individual field
  6735. // value), so we disable this validation.
  6736. if (context.settings.arrayElement &&
  6737. context.dataSource !== 4 /* UserDataSource.ArrayArgument */) {
  6738. throw context.createError('Nested arrays are not supported');
  6739. }
  6740. return parseArray(input, context);
  6741. }
  6742. else {
  6743. return parseScalarValue(input, context);
  6744. }
  6745. }
  6746. }
  6747. function parseObject(obj, context) {
  6748. const fields = {};
  6749. if (isEmpty(obj)) {
  6750. // If we encounter an empty object, we explicitly add it to the update
  6751. // mask to ensure that the server creates a map entry.
  6752. if (context.path && context.path.length > 0) {
  6753. context.fieldMask.push(context.path);
  6754. }
  6755. }
  6756. else {
  6757. forEach(obj, (key, val) => {
  6758. const parsedValue = parseData(val, context.childContextForField(key));
  6759. if (parsedValue != null) {
  6760. fields[key] = parsedValue;
  6761. }
  6762. });
  6763. }
  6764. return { mapValue: { fields } };
  6765. }
  6766. function parseArray(array, context) {
  6767. const values = [];
  6768. let entryIndex = 0;
  6769. for (const entry of array) {
  6770. let parsedEntry = parseData(entry, context.childContextForArray(entryIndex));
  6771. if (parsedEntry == null) {
  6772. // Just include nulls in the array for fields being replaced with a
  6773. // sentinel.
  6774. parsedEntry = { nullValue: 'NULL_VALUE' };
  6775. }
  6776. values.push(parsedEntry);
  6777. entryIndex++;
  6778. }
  6779. return { arrayValue: { values } };
  6780. }
  6781. /**
  6782. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  6783. * context.fieldTransforms.
  6784. */
  6785. function parseSentinelFieldValue(value, context) {
  6786. // Sentinels are only supported with writes, and not within arrays.
  6787. if (!isWrite(context.dataSource)) {
  6788. throw context.createError(`${value._methodName}() can only be used with update() and set()`);
  6789. }
  6790. if (!context.path) {
  6791. throw context.createError(`${value._methodName}() is not currently supported inside arrays`);
  6792. }
  6793. const fieldTransform = value._toFieldTransform(context);
  6794. if (fieldTransform) {
  6795. context.fieldTransforms.push(fieldTransform);
  6796. }
  6797. }
  6798. /**
  6799. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  6800. *
  6801. * @returns The parsed value
  6802. */
  6803. function parseScalarValue(value, context) {
  6804. value = getModularInstance(value);
  6805. if (value === null) {
  6806. return { nullValue: 'NULL_VALUE' };
  6807. }
  6808. else if (typeof value === 'number') {
  6809. return toNumber(context.serializer, value);
  6810. }
  6811. else if (typeof value === 'boolean') {
  6812. return { booleanValue: value };
  6813. }
  6814. else if (typeof value === 'string') {
  6815. return { stringValue: value };
  6816. }
  6817. else if (value instanceof Date) {
  6818. const timestamp = Timestamp.fromDate(value);
  6819. return {
  6820. timestampValue: toTimestamp(context.serializer, timestamp)
  6821. };
  6822. }
  6823. else if (value instanceof Timestamp) {
  6824. // Firestore backend truncates precision down to microseconds. To ensure
  6825. // offline mode works the same with regards to truncation, perform the
  6826. // truncation immediately without waiting for the backend to do that.
  6827. const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000);
  6828. return {
  6829. timestampValue: toTimestamp(context.serializer, timestamp)
  6830. };
  6831. }
  6832. else if (value instanceof GeoPoint) {
  6833. return {
  6834. geoPointValue: {
  6835. latitude: value.latitude,
  6836. longitude: value.longitude
  6837. }
  6838. };
  6839. }
  6840. else if (value instanceof Bytes) {
  6841. return { bytesValue: toBytes(context.serializer, value._byteString) };
  6842. }
  6843. else if (value instanceof DocumentReference) {
  6844. const thisDb = context.databaseId;
  6845. const otherDb = value.firestore._databaseId;
  6846. if (!otherDb.isEqual(thisDb)) {
  6847. throw context.createError('Document reference is for database ' +
  6848. `${otherDb.projectId}/${otherDb.database} but should be ` +
  6849. `for database ${thisDb.projectId}/${thisDb.database}`);
  6850. }
  6851. return {
  6852. referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path)
  6853. };
  6854. }
  6855. else {
  6856. throw context.createError(`Unsupported field value: ${valueDescription(value)}`);
  6857. }
  6858. }
  6859. /**
  6860. * Checks whether an object looks like a JSON object that should be converted
  6861. * into a struct. Normal class/prototype instances are considered to look like
  6862. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  6863. * GeoPoints, etc. are not considered to look like JSON objects since they map
  6864. * to specific FieldValue types other than ObjectValue.
  6865. */
  6866. function looksLikeJsonObject(input) {
  6867. return (typeof input === 'object' &&
  6868. input !== null &&
  6869. !(input instanceof Array) &&
  6870. !(input instanceof Date) &&
  6871. !(input instanceof Timestamp) &&
  6872. !(input instanceof GeoPoint) &&
  6873. !(input instanceof Bytes) &&
  6874. !(input instanceof DocumentReference) &&
  6875. !(input instanceof FieldValue));
  6876. }
  6877. function validatePlainObject(message, context, input) {
  6878. if (!looksLikeJsonObject(input) || !isPlainObject(input)) {
  6879. const description = valueDescription(input);
  6880. if (description === 'an object') {
  6881. // Massage the error if it was an object.
  6882. throw context.createError(message + ' a custom object');
  6883. }
  6884. else {
  6885. throw context.createError(message + ' ' + description);
  6886. }
  6887. }
  6888. }
  6889. /**
  6890. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  6891. */
  6892. function fieldPathFromArgument$1(methodName, path, targetDoc) {
  6893. // If required, replace the FieldPath Compat class with with the firestore-exp
  6894. // FieldPath.
  6895. path = getModularInstance(path);
  6896. if (path instanceof FieldPath) {
  6897. return path._internalPath;
  6898. }
  6899. else if (typeof path === 'string') {
  6900. return fieldPathFromDotSeparatedString(methodName, path);
  6901. }
  6902. else {
  6903. const message = 'Field path arguments must be of type string or ';
  6904. throw createError(message, methodName,
  6905. /* hasConverter= */ false,
  6906. /* path= */ undefined, targetDoc);
  6907. }
  6908. }
  6909. /**
  6910. * Matches any characters in a field path string that are reserved.
  6911. */
  6912. const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]');
  6913. /**
  6914. * Wraps fromDotSeparatedString with an error message about the method that
  6915. * was thrown.
  6916. * @param methodName - The publicly visible method name
  6917. * @param path - The dot-separated string form of a field path which will be
  6918. * split on dots.
  6919. * @param targetDoc - The document against which the field path will be
  6920. * evaluated.
  6921. */
  6922. function fieldPathFromDotSeparatedString(methodName, path, targetDoc) {
  6923. const found = path.search(FIELD_PATH_RESERVED);
  6924. if (found >= 0) {
  6925. throw createError(`Invalid field path (${path}). Paths must not contain ` +
  6926. `'~', '*', '/', '[', or ']'`, methodName,
  6927. /* hasConverter= */ false,
  6928. /* path= */ undefined, targetDoc);
  6929. }
  6930. try {
  6931. return new FieldPath(...path.split('.'))._internalPath;
  6932. }
  6933. catch (e) {
  6934. throw createError(`Invalid field path (${path}). Paths must not be empty, ` +
  6935. `begin with '.', end with '.', or contain '..'`, methodName,
  6936. /* hasConverter= */ false,
  6937. /* path= */ undefined, targetDoc);
  6938. }
  6939. }
  6940. function createError(reason, methodName, hasConverter, path, targetDoc) {
  6941. const hasPath = path && !path.isEmpty();
  6942. const hasDocument = targetDoc !== undefined;
  6943. let message = `Function ${methodName}() called with invalid data`;
  6944. if (hasConverter) {
  6945. message += ' (via `toFirestore()`)';
  6946. }
  6947. message += '. ';
  6948. let description = '';
  6949. if (hasPath || hasDocument) {
  6950. description += ' (found';
  6951. if (hasPath) {
  6952. description += ` in field ${path}`;
  6953. }
  6954. if (hasDocument) {
  6955. description += ` in document ${targetDoc}`;
  6956. }
  6957. description += ')';
  6958. }
  6959. return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description);
  6960. }
  6961. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */
  6962. function fieldMaskContains(haystack, needle) {
  6963. return haystack.some(v => v.isEqual(needle));
  6964. }
  6965. /**
  6966. * @license
  6967. * Copyright 2020 Google LLC
  6968. *
  6969. * Licensed under the Apache License, Version 2.0 (the "License");
  6970. * you may not use this file except in compliance with the License.
  6971. * You may obtain a copy of the License at
  6972. *
  6973. * http://www.apache.org/licenses/LICENSE-2.0
  6974. *
  6975. * Unless required by applicable law or agreed to in writing, software
  6976. * distributed under the License is distributed on an "AS IS" BASIS,
  6977. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6978. * See the License for the specific language governing permissions and
  6979. * limitations under the License.
  6980. */
  6981. /**
  6982. * A `DocumentSnapshot` contains data read from a document in your Firestore
  6983. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  6984. * get a specific field.
  6985. *
  6986. * For a `DocumentSnapshot` that points to a non-existing document, any data
  6987. * access will return 'undefined'. You can use the `exists()` method to
  6988. * explicitly verify a document's existence.
  6989. */
  6990. class DocumentSnapshot {
  6991. // Note: This class is stripped down version of the DocumentSnapshot in
  6992. // the legacy SDK. The changes are:
  6993. // - No support for SnapshotMetadata.
  6994. // - No support for SnapshotOptions.
  6995. /** @hideconstructor protected */
  6996. constructor(_firestore, _userDataWriter, _key, _document, _converter) {
  6997. this._firestore = _firestore;
  6998. this._userDataWriter = _userDataWriter;
  6999. this._key = _key;
  7000. this._document = _document;
  7001. this._converter = _converter;
  7002. }
  7003. /** Property of the `DocumentSnapshot` that provides the document's ID. */
  7004. get id() {
  7005. return this._key.path.lastSegment();
  7006. }
  7007. /**
  7008. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  7009. */
  7010. get ref() {
  7011. return new DocumentReference(this._firestore, this._converter, this._key);
  7012. }
  7013. /**
  7014. * Signals whether or not the document at the snapshot's location exists.
  7015. *
  7016. * @returns true if the document exists.
  7017. */
  7018. exists() {
  7019. return this._document !== null;
  7020. }
  7021. /**
  7022. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  7023. * the document doesn't exist.
  7024. *
  7025. * @returns An `Object` containing all fields in the document or `undefined`
  7026. * if the document doesn't exist.
  7027. */
  7028. data() {
  7029. if (!this._document) {
  7030. return undefined;
  7031. }
  7032. else if (this._converter) {
  7033. // We only want to use the converter and create a new DocumentSnapshot
  7034. // if a converter has been provided.
  7035. const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document,
  7036. /* converter= */ null);
  7037. return this._converter.fromFirestore(snapshot);
  7038. }
  7039. else {
  7040. return this._userDataWriter.convertValue(this._document.data.value);
  7041. }
  7042. }
  7043. /**
  7044. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  7045. * document or field doesn't exist.
  7046. *
  7047. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  7048. * field.
  7049. * @returns The data at the specified field location or undefined if no such
  7050. * field exists in the document.
  7051. */
  7052. // We are using `any` here to avoid an explicit cast by our users.
  7053. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7054. get(fieldPath) {
  7055. if (this._document) {
  7056. const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));
  7057. if (value !== null) {
  7058. return this._userDataWriter.convertValue(value);
  7059. }
  7060. }
  7061. return undefined;
  7062. }
  7063. }
  7064. /**
  7065. * A `QueryDocumentSnapshot` contains data read from a document in your
  7066. * Firestore database as part of a query. The document is guaranteed to exist
  7067. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  7068. * specific field.
  7069. *
  7070. * A `QueryDocumentSnapshot` offers the same API surface as a
  7071. * `DocumentSnapshot`. Since query results contain only existing documents, the
  7072. * `exists` property will always be true and `data()` will never return
  7073. * 'undefined'.
  7074. */
  7075. class QueryDocumentSnapshot extends DocumentSnapshot {
  7076. /**
  7077. * Retrieves all fields in the document as an `Object`.
  7078. *
  7079. * @override
  7080. * @returns An `Object` containing all fields in the document.
  7081. */
  7082. data() {
  7083. return super.data();
  7084. }
  7085. }
  7086. /**
  7087. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  7088. * representing the results of a query. The documents can be accessed as an
  7089. * array via the `docs` property or enumerated using the `forEach` method. The
  7090. * number of documents can be determined via the `empty` and `size`
  7091. * properties.
  7092. */
  7093. class QuerySnapshot {
  7094. /** @hideconstructor */
  7095. constructor(_query, _docs) {
  7096. this._docs = _docs;
  7097. this.query = _query;
  7098. }
  7099. /** An array of all the documents in the `QuerySnapshot`. */
  7100. get docs() {
  7101. return [...this._docs];
  7102. }
  7103. /** The number of documents in the `QuerySnapshot`. */
  7104. get size() {
  7105. return this.docs.length;
  7106. }
  7107. /** True if there are no documents in the `QuerySnapshot`. */
  7108. get empty() {
  7109. return this.docs.length === 0;
  7110. }
  7111. /**
  7112. * Enumerates all of the documents in the `QuerySnapshot`.
  7113. *
  7114. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  7115. * each document in the snapshot.
  7116. * @param thisArg - The `this` binding for the callback.
  7117. */
  7118. forEach(callback, thisArg) {
  7119. this._docs.forEach(callback, thisArg);
  7120. }
  7121. }
  7122. /**
  7123. * Returns true if the provided snapshots are equal.
  7124. *
  7125. * @param left - A snapshot to compare.
  7126. * @param right - A snapshot to compare.
  7127. * @returns true if the snapshots are equal.
  7128. */
  7129. function snapshotEqual(left, right) {
  7130. left = getModularInstance(left);
  7131. right = getModularInstance(right);
  7132. if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {
  7133. return (left._firestore === right._firestore &&
  7134. left._key.isEqual(right._key) &&
  7135. (left._document === null
  7136. ? right._document === null
  7137. : left._document.isEqual(right._document)) &&
  7138. left._converter === right._converter);
  7139. }
  7140. else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {
  7141. return (queryEqual(left.query, right.query) &&
  7142. arrayEquals(left.docs, right.docs, snapshotEqual));
  7143. }
  7144. return false;
  7145. }
  7146. /**
  7147. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  7148. */
  7149. function fieldPathFromArgument(methodName, arg) {
  7150. if (typeof arg === 'string') {
  7151. return fieldPathFromDotSeparatedString(methodName, arg);
  7152. }
  7153. else if (arg instanceof FieldPath) {
  7154. return arg._internalPath;
  7155. }
  7156. else {
  7157. return arg._delegate._internalPath;
  7158. }
  7159. }
  7160. /**
  7161. * @license
  7162. * Copyright 2020 Google LLC
  7163. *
  7164. * Licensed under the Apache License, Version 2.0 (the "License");
  7165. * you may not use this file except in compliance with the License.
  7166. * You may obtain a copy of the License at
  7167. *
  7168. * http://www.apache.org/licenses/LICENSE-2.0
  7169. *
  7170. * Unless required by applicable law or agreed to in writing, software
  7171. * distributed under the License is distributed on an "AS IS" BASIS,
  7172. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7173. * See the License for the specific language governing permissions and
  7174. * limitations under the License.
  7175. */
  7176. function validateHasExplicitOrderByForLimitToLast(query) {
  7177. if (query.limitType === "L" /* LimitType.Last */ &&
  7178. query.explicitOrderBy.length === 0) {
  7179. throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
  7180. }
  7181. }
  7182. /**
  7183. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  7184. * to a Firestore query.
  7185. */
  7186. class AppliableConstraint {
  7187. }
  7188. /**
  7189. * A `QueryConstraint` is used to narrow the set of documents returned by a
  7190. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  7191. * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
  7192. * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and
  7193. * can then be passed to {@link (query:1)} to create a new query instance that
  7194. * also contains this `QueryConstraint`.
  7195. */
  7196. class QueryConstraint extends AppliableConstraint {
  7197. }
  7198. function query(query, queryConstraint, ...additionalQueryConstraints) {
  7199. let queryConstraints = [];
  7200. if (queryConstraint instanceof AppliableConstraint) {
  7201. queryConstraints.push(queryConstraint);
  7202. }
  7203. queryConstraints = queryConstraints.concat(additionalQueryConstraints);
  7204. validateQueryConstraintArray(queryConstraints);
  7205. for (const constraint of queryConstraints) {
  7206. query = constraint._apply(query);
  7207. }
  7208. return query;
  7209. }
  7210. /**
  7211. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  7212. * a Firestore query by filtering on one or more document fields.
  7213. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  7214. * be passed to {@link (query:1)} to create a new query instance that also contains
  7215. * this `QueryFieldFilterConstraint`.
  7216. */
  7217. class QueryFieldFilterConstraint extends QueryConstraint {
  7218. /**
  7219. * @internal
  7220. */
  7221. constructor(_field, _op, _value) {
  7222. super();
  7223. this._field = _field;
  7224. this._op = _op;
  7225. this._value = _value;
  7226. /** The type of this query constraint */
  7227. this.type = 'where';
  7228. }
  7229. static _create(_field, _op, _value) {
  7230. return new QueryFieldFilterConstraint(_field, _op, _value);
  7231. }
  7232. _apply(query) {
  7233. const filter = this._parse(query);
  7234. validateNewFieldFilter(query._query, filter);
  7235. return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
  7236. }
  7237. _parse(query) {
  7238. const reader = newUserDataReader(query.firestore);
  7239. const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value);
  7240. return filter;
  7241. }
  7242. }
  7243. /**
  7244. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  7245. * must contain the specified field and that the value should satisfy the
  7246. * relation constraint provided.
  7247. *
  7248. * @param fieldPath - The path to compare
  7249. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  7250. * "&lt;=", "!=").
  7251. * @param value - The value for comparison
  7252. * @returns The created {@link QueryFieldFilterConstraint}.
  7253. */
  7254. function where(fieldPath, opStr, value) {
  7255. const op = opStr;
  7256. const field = fieldPathFromArgument('where', fieldPath);
  7257. return QueryFieldFilterConstraint._create(field, op, value);
  7258. }
  7259. /**
  7260. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  7261. * returned by a Firestore query by performing the logical OR or AND of multiple
  7262. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  7263. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  7264. * {@link and} and can then be passed to {@link (query:1)} to create a new query
  7265. * instance that also contains the `QueryCompositeFilterConstraint`.
  7266. */
  7267. class QueryCompositeFilterConstraint extends AppliableConstraint {
  7268. /**
  7269. * @internal
  7270. */
  7271. constructor(
  7272. /** The type of this query constraint */
  7273. type, _queryConstraints) {
  7274. super();
  7275. this.type = type;
  7276. this._queryConstraints = _queryConstraints;
  7277. }
  7278. static _create(type, _queryConstraints) {
  7279. return new QueryCompositeFilterConstraint(type, _queryConstraints);
  7280. }
  7281. _parse(query) {
  7282. const parsedFilters = this._queryConstraints
  7283. .map(queryConstraint => {
  7284. return queryConstraint._parse(query);
  7285. })
  7286. .filter(parsedFilter => parsedFilter.getFilters().length > 0);
  7287. if (parsedFilters.length === 1) {
  7288. return parsedFilters[0];
  7289. }
  7290. return CompositeFilter.create(parsedFilters, this._getOperator());
  7291. }
  7292. _apply(query) {
  7293. const parsedFilter = this._parse(query);
  7294. if (parsedFilter.getFilters().length === 0) {
  7295. // Return the existing query if not adding any more filters (e.g. an empty
  7296. // composite filter).
  7297. return query;
  7298. }
  7299. validateNewFilter(query._query, parsedFilter);
  7300. return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter));
  7301. }
  7302. _getQueryConstraints() {
  7303. return this._queryConstraints;
  7304. }
  7305. _getOperator() {
  7306. return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  7307. }
  7308. }
  7309. /**
  7310. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  7311. * the given filter constraints. A disjunction filter includes a document if it
  7312. * satisfies any of the given filters.
  7313. *
  7314. * @param queryConstraints - Optional. The list of
  7315. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  7316. * created with calls to {@link where}, {@link or}, or {@link and}.
  7317. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  7318. */
  7319. function or(...queryConstraints) {
  7320. // Only support QueryFilterConstraints
  7321. queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint));
  7322. return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints);
  7323. }
  7324. /**
  7325. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  7326. * the given filter constraints. A conjunction filter includes a document if it
  7327. * satisfies all of the given filters.
  7328. *
  7329. * @param queryConstraints - Optional. The list of
  7330. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  7331. * created with calls to {@link where}, {@link or}, or {@link and}.
  7332. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  7333. */
  7334. function and(...queryConstraints) {
  7335. // Only support QueryFilterConstraints
  7336. queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint));
  7337. return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints);
  7338. }
  7339. /**
  7340. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  7341. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  7342. * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query
  7343. * instance that also contains this `QueryOrderByConstraint`.
  7344. *
  7345. * Note: Documents that do not contain the orderBy field will not be present in
  7346. * the query result.
  7347. */
  7348. class QueryOrderByConstraint extends QueryConstraint {
  7349. /**
  7350. * @internal
  7351. */
  7352. constructor(_field, _direction) {
  7353. super();
  7354. this._field = _field;
  7355. this._direction = _direction;
  7356. /** The type of this query constraint */
  7357. this.type = 'orderBy';
  7358. }
  7359. static _create(_field, _direction) {
  7360. return new QueryOrderByConstraint(_field, _direction);
  7361. }
  7362. _apply(query) {
  7363. const orderBy = newQueryOrderBy(query._query, this._field, this._direction);
  7364. return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy));
  7365. }
  7366. }
  7367. /**
  7368. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  7369. * specified field, optionally in descending order instead of ascending.
  7370. *
  7371. * Note: Documents that do not contain the specified field will not be present
  7372. * in the query result.
  7373. *
  7374. * @param fieldPath - The field to sort by.
  7375. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  7376. * not specified, order will be ascending.
  7377. * @returns The created {@link QueryOrderByConstraint}.
  7378. */
  7379. function orderBy(fieldPath, directionStr = 'asc') {
  7380. const direction = directionStr;
  7381. const path = fieldPathFromArgument('orderBy', fieldPath);
  7382. return QueryOrderByConstraint._create(path, direction);
  7383. }
  7384. /**
  7385. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  7386. * a Firestore query.
  7387. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  7388. * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new
  7389. * query instance that also contains this `QueryLimitConstraint`.
  7390. */
  7391. class QueryLimitConstraint extends QueryConstraint {
  7392. /**
  7393. * @internal
  7394. */
  7395. constructor(
  7396. /** The type of this query constraint */
  7397. type, _limit, _limitType) {
  7398. super();
  7399. this.type = type;
  7400. this._limit = _limit;
  7401. this._limitType = _limitType;
  7402. }
  7403. static _create(type, _limit, _limitType) {
  7404. return new QueryLimitConstraint(type, _limit, _limitType);
  7405. }
  7406. _apply(query) {
  7407. return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType));
  7408. }
  7409. }
  7410. /**
  7411. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  7412. * documents.
  7413. *
  7414. * @param limit - The maximum number of items to return.
  7415. * @returns The created {@link QueryLimitConstraint}.
  7416. */
  7417. function limit(limit) {
  7418. validatePositiveNumber('limit', limit);
  7419. return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */);
  7420. }
  7421. /**
  7422. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  7423. * documents.
  7424. *
  7425. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  7426. * otherwise an exception will be thrown during execution.
  7427. *
  7428. * @param limit - The maximum number of items to return.
  7429. * @returns The created {@link QueryLimitConstraint}.
  7430. */
  7431. function limitToLast(limit) {
  7432. validatePositiveNumber('limitToLast', limit);
  7433. return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */);
  7434. }
  7435. /**
  7436. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  7437. * result set returned by a Firestore query.
  7438. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  7439. * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a
  7440. * new query instance that also contains this `QueryStartAtConstraint`.
  7441. */
  7442. class QueryStartAtConstraint extends QueryConstraint {
  7443. /**
  7444. * @internal
  7445. */
  7446. constructor(
  7447. /** The type of this query constraint */
  7448. type, _docOrFields, _inclusive) {
  7449. super();
  7450. this.type = type;
  7451. this._docOrFields = _docOrFields;
  7452. this._inclusive = _inclusive;
  7453. }
  7454. static _create(type, _docOrFields, _inclusive) {
  7455. return new QueryStartAtConstraint(type, _docOrFields, _inclusive);
  7456. }
  7457. _apply(query) {
  7458. const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
  7459. return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound));
  7460. }
  7461. }
  7462. function startAt(...docOrFields) {
  7463. return QueryStartAtConstraint._create('startAt', docOrFields,
  7464. /*inclusive=*/ true);
  7465. }
  7466. function startAfter(...docOrFields) {
  7467. return QueryStartAtConstraint._create('startAfter', docOrFields,
  7468. /*inclusive=*/ false);
  7469. }
  7470. /**
  7471. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  7472. * result set returned by a Firestore query.
  7473. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  7474. * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new
  7475. * query instance that also contains this `QueryEndAtConstraint`.
  7476. */
  7477. class QueryEndAtConstraint extends QueryConstraint {
  7478. /**
  7479. * @internal
  7480. */
  7481. constructor(
  7482. /** The type of this query constraint */
  7483. type, _docOrFields, _inclusive) {
  7484. super();
  7485. this.type = type;
  7486. this._docOrFields = _docOrFields;
  7487. this._inclusive = _inclusive;
  7488. }
  7489. static _create(type, _docOrFields, _inclusive) {
  7490. return new QueryEndAtConstraint(type, _docOrFields, _inclusive);
  7491. }
  7492. _apply(query) {
  7493. const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
  7494. return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound));
  7495. }
  7496. }
  7497. function endBefore(...docOrFields) {
  7498. return QueryEndAtConstraint._create('endBefore', docOrFields,
  7499. /*inclusive=*/ false);
  7500. }
  7501. function endAt(...docOrFields) {
  7502. return QueryEndAtConstraint._create('endAt', docOrFields,
  7503. /*inclusive=*/ true);
  7504. }
  7505. /** Helper function to create a bound from a document or fields */
  7506. function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) {
  7507. docOrFields[0] = getModularInstance(docOrFields[0]);
  7508. if (docOrFields[0] instanceof DocumentSnapshot) {
  7509. return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive);
  7510. }
  7511. else {
  7512. const reader = newUserDataReader(query.firestore);
  7513. return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive);
  7514. }
  7515. }
  7516. function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) {
  7517. let fieldValue;
  7518. if (fieldPath.isKeyField()) {
  7519. if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
  7520. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`);
  7521. }
  7522. else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
  7523. validateDisjunctiveFilterElements(value, op);
  7524. const referenceList = [];
  7525. for (const arrayValue of value) {
  7526. referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));
  7527. }
  7528. fieldValue = { arrayValue: { values: referenceList } };
  7529. }
  7530. else {
  7531. fieldValue = parseDocumentIdValue(databaseId, query, value);
  7532. }
  7533. }
  7534. else {
  7535. if (op === "in" /* Operator.IN */ ||
  7536. op === "not-in" /* Operator.NOT_IN */ ||
  7537. op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
  7538. validateDisjunctiveFilterElements(value, op);
  7539. }
  7540. fieldValue = parseQueryValue(dataReader, methodName, value,
  7541. /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */);
  7542. }
  7543. const filter = FieldFilter.create(fieldPath, op, fieldValue);
  7544. return filter;
  7545. }
  7546. function newQueryOrderBy(query, fieldPath, direction) {
  7547. if (query.startAt !== null) {
  7548. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' +
  7549. 'calling orderBy().');
  7550. }
  7551. if (query.endAt !== null) {
  7552. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' +
  7553. 'calling orderBy().');
  7554. }
  7555. const orderBy = new OrderBy(fieldPath, direction);
  7556. validateNewOrderBy(query, orderBy);
  7557. return orderBy;
  7558. }
  7559. /**
  7560. * Create a `Bound` from a query and a document.
  7561. *
  7562. * Note that the `Bound` will always include the key of the document
  7563. * and so only the provided document will compare equal to the returned
  7564. * position.
  7565. *
  7566. * Will throw if the document does not contain all fields of the order by
  7567. * of the query or if any of the fields in the order by are an uncommitted
  7568. * server timestamp.
  7569. */
  7570. function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) {
  7571. if (!doc) {
  7572. throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` +
  7573. `${methodName}().`);
  7574. }
  7575. const components = [];
  7576. // Because people expect to continue/end a query at the exact document
  7577. // provided, we need to use the implicit sort order rather than the explicit
  7578. // sort order, because it's guaranteed to contain the document key. That way
  7579. // the position becomes unambiguous and the query continues/ends exactly at
  7580. // the provided document. Without the key (by using the explicit sort
  7581. // orders), multiple documents could match the position, yielding duplicate
  7582. // results.
  7583. for (const orderBy of queryOrderBy(query)) {
  7584. if (orderBy.field.isKeyField()) {
  7585. components.push(refValue(databaseId, doc.key));
  7586. }
  7587. else {
  7588. const value = doc.data.field(orderBy.field);
  7589. if (isServerTimestamp(value)) {
  7590. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' +
  7591. 'document for which the field "' +
  7592. orderBy.field +
  7593. '" is an uncommitted server timestamp. (Since the value of ' +
  7594. 'this field is unknown, you cannot start/end a query with it.)');
  7595. }
  7596. else if (value !== null) {
  7597. components.push(value);
  7598. }
  7599. else {
  7600. const field = orderBy.field.canonicalString();
  7601. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` +
  7602. `document for which the field '${field}' (used as the ` +
  7603. `orderBy) does not exist.`);
  7604. }
  7605. }
  7606. }
  7607. return new Bound(components, inclusive);
  7608. }
  7609. /**
  7610. * Converts a list of field values to a `Bound` for the given query.
  7611. */
  7612. function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) {
  7613. // Use explicit order by's because it has to match the query the user made
  7614. const orderBy = query.explicitOrderBy;
  7615. if (values.length > orderBy.length) {
  7616. throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` +
  7617. `The number of arguments must be less than or equal to the ` +
  7618. `number of orderBy() clauses`);
  7619. }
  7620. const components = [];
  7621. for (let i = 0; i < values.length; i++) {
  7622. const rawValue = values[i];
  7623. const orderByComponent = orderBy[i];
  7624. if (orderByComponent.field.isKeyField()) {
  7625. if (typeof rawValue !== 'string') {
  7626. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` +
  7627. `${methodName}(), but got a ${typeof rawValue}`);
  7628. }
  7629. if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {
  7630. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` +
  7631. `the value passed to ${methodName}() must be a plain document ID, but ` +
  7632. `'${rawValue}' contains a slash.`);
  7633. }
  7634. const path = query.path.child(ResourcePath.fromString(rawValue));
  7635. if (!DocumentKey.isDocumentKey(path)) {
  7636. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` +
  7637. `documentId(), the value passed to ${methodName}() must result in a ` +
  7638. `valid document path, but '${path}' is not because it contains an odd number ` +
  7639. `of segments.`);
  7640. }
  7641. const key = new DocumentKey(path);
  7642. components.push(refValue(databaseId, key));
  7643. }
  7644. else {
  7645. const wrapped = parseQueryValue(dataReader, methodName, rawValue);
  7646. components.push(wrapped);
  7647. }
  7648. }
  7649. return new Bound(components, inclusive);
  7650. }
  7651. /**
  7652. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  7653. * appropriate errors if the value is anything other than a `DocumentReference`
  7654. * or `string`, or if the string is malformed.
  7655. */
  7656. function parseDocumentIdValue(databaseId, query, documentIdValue) {
  7657. documentIdValue = getModularInstance(documentIdValue);
  7658. if (typeof documentIdValue === 'string') {
  7659. if (documentIdValue === '') {
  7660. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' +
  7661. 'must provide a valid document ID, but it was an empty string.');
  7662. }
  7663. if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {
  7664. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` +
  7665. `documentId(), you must provide a plain document ID, but ` +
  7666. `'${documentIdValue}' contains a '/' character.`);
  7667. }
  7668. const path = query.path.child(ResourcePath.fromString(documentIdValue));
  7669. if (!DocumentKey.isDocumentKey(path)) {
  7670. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` +
  7671. `documentId(), the value provided must result in a valid document path, ` +
  7672. `but '${path}' is not because it has an odd number of segments (${path.length}).`);
  7673. }
  7674. return refValue(databaseId, new DocumentKey(path));
  7675. }
  7676. else if (documentIdValue instanceof DocumentReference) {
  7677. return refValue(databaseId, documentIdValue._key);
  7678. }
  7679. else {
  7680. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` +
  7681. `string or a DocumentReference, but it was: ` +
  7682. `${valueDescription(documentIdValue)}.`);
  7683. }
  7684. }
  7685. /**
  7686. * Validates that the value passed into a disjunctive filter satisfies all
  7687. * array requirements.
  7688. */
  7689. function validateDisjunctiveFilterElements(value, operator) {
  7690. if (!Array.isArray(value) || value.length === 0) {
  7691. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' +
  7692. `'${operator.toString()}' filters.`);
  7693. }
  7694. }
  7695. /**
  7696. * Given an operator, returns the set of operators that cannot be used with it.
  7697. *
  7698. * This is not a comprehensive check, and this function should be removed in the
  7699. * long term. Validations should occur in the Firestore backend.
  7700. *
  7701. * Operators in a query must adhere to the following set of rules:
  7702. * 1. Only one inequality per query.
  7703. * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  7704. */
  7705. function conflictingOps(op) {
  7706. switch (op) {
  7707. case "!=" /* Operator.NOT_EQUAL */:
  7708. return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */];
  7709. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */:
  7710. case "in" /* Operator.IN */:
  7711. return ["not-in" /* Operator.NOT_IN */];
  7712. case "not-in" /* Operator.NOT_IN */:
  7713. return [
  7714. "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */,
  7715. "in" /* Operator.IN */,
  7716. "not-in" /* Operator.NOT_IN */,
  7717. "!=" /* Operator.NOT_EQUAL */
  7718. ];
  7719. default:
  7720. return [];
  7721. }
  7722. }
  7723. function validateNewFieldFilter(query, fieldFilter) {
  7724. if (fieldFilter.isInequality()) {
  7725. const existingInequality = getInequalityFilterField(query);
  7726. const newInequality = fieldFilter.field;
  7727. if (existingInequality !== null &&
  7728. !existingInequality.isEqual(newInequality)) {
  7729. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +
  7730. ' (<, <=, !=, not-in, >, or >=) must be on the same field. But you have' +
  7731. ` inequality filters on '${existingInequality.toString()}'` +
  7732. ` and '${newInequality.toString()}'`);
  7733. }
  7734. const firstOrderByField = getFirstOrderByField(query);
  7735. if (firstOrderByField !== null) {
  7736. validateOrderByAndInequalityMatch(query, newInequality, firstOrderByField);
  7737. }
  7738. }
  7739. const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op));
  7740. if (conflictingOp !== null) {
  7741. // Special case when it's a duplicate op to give a slightly clearer error message.
  7742. if (conflictingOp === fieldFilter.op) {
  7743. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' +
  7744. `'${fieldFilter.op.toString()}' filter.`);
  7745. }
  7746. else {
  7747. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +
  7748. `with '${conflictingOp.toString()}' filters.`);
  7749. }
  7750. }
  7751. }
  7752. function validateNewFilter(query, filter) {
  7753. let testQuery = query;
  7754. const subFilters = filter.getFlattenedFilters();
  7755. for (const subFilter of subFilters) {
  7756. validateNewFieldFilter(testQuery, subFilter);
  7757. testQuery = queryWithAddedFilter(testQuery, subFilter);
  7758. }
  7759. }
  7760. // Checks if any of the provided filter operators are included in the given list of filters and
  7761. // returns the first one that is, or null if none are.
  7762. function findOpInsideFilters(filters, operators) {
  7763. for (const filter of filters) {
  7764. for (const fieldFilter of filter.getFlattenedFilters()) {
  7765. if (operators.indexOf(fieldFilter.op) >= 0) {
  7766. return fieldFilter.op;
  7767. }
  7768. }
  7769. }
  7770. return null;
  7771. }
  7772. function validateNewOrderBy(query, orderBy) {
  7773. if (getFirstOrderByField(query) === null) {
  7774. // This is the first order by. It must match any inequality.
  7775. const inequalityField = getInequalityFilterField(query);
  7776. if (inequalityField !== null) {
  7777. validateOrderByAndInequalityMatch(query, inequalityField, orderBy.field);
  7778. }
  7779. }
  7780. }
  7781. function validateOrderByAndInequalityMatch(baseQuery, inequality, orderBy) {
  7782. if (!orderBy.isEqual(inequality)) {
  7783. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality ` +
  7784. `(<, <=, !=, not-in, >, or >=) on field '${inequality.toString()}' ` +
  7785. `and so you must also use '${inequality.toString()}' ` +
  7786. `as your first argument to orderBy(), but your first orderBy() ` +
  7787. `is on field '${orderBy.toString()}' instead.`);
  7788. }
  7789. }
  7790. function validateQueryFilterConstraint(functionName, queryConstraint) {
  7791. if (!(queryConstraint instanceof QueryFieldFilterConstraint) &&
  7792. !(queryConstraint instanceof QueryCompositeFilterConstraint)) {
  7793. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  7794. }
  7795. }
  7796. function validateQueryConstraintArray(queryConstraint) {
  7797. const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length;
  7798. const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length;
  7799. if (compositeFilterCount > 1 ||
  7800. (compositeFilterCount > 0 && fieldFilterCount > 0)) {
  7801. throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' +
  7802. 'more than one filter at the top level. Consider nesting the multiple ' +
  7803. 'filters within an `and(...)` statement. For example: ' +
  7804. 'change `query(query, where(...), or(...))` to ' +
  7805. '`query(query, and(where(...), or(...)))`.');
  7806. }
  7807. }
  7808. /**
  7809. * @license
  7810. * Copyright 2020 Google LLC
  7811. *
  7812. * Licensed under the Apache License, Version 2.0 (the "License");
  7813. * you may not use this file except in compliance with the License.
  7814. * You may obtain a copy of the License at
  7815. *
  7816. * http://www.apache.org/licenses/LICENSE-2.0
  7817. *
  7818. * Unless required by applicable law or agreed to in writing, software
  7819. * distributed under the License is distributed on an "AS IS" BASIS,
  7820. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7821. * See the License for the specific language governing permissions and
  7822. * limitations under the License.
  7823. */
  7824. /**
  7825. * Converts Firestore's internal types to the JavaScript types that we expose
  7826. * to the user.
  7827. *
  7828. * @internal
  7829. */
  7830. class AbstractUserDataWriter {
  7831. convertValue(value, serverTimestampBehavior = 'none') {
  7832. switch (typeOrder(value)) {
  7833. case 0 /* TypeOrder.NullValue */:
  7834. return null;
  7835. case 1 /* TypeOrder.BooleanValue */:
  7836. return value.booleanValue;
  7837. case 2 /* TypeOrder.NumberValue */:
  7838. return normalizeNumber(value.integerValue || value.doubleValue);
  7839. case 3 /* TypeOrder.TimestampValue */:
  7840. return this.convertTimestamp(value.timestampValue);
  7841. case 4 /* TypeOrder.ServerTimestampValue */:
  7842. return this.convertServerTimestamp(value, serverTimestampBehavior);
  7843. case 5 /* TypeOrder.StringValue */:
  7844. return value.stringValue;
  7845. case 6 /* TypeOrder.BlobValue */:
  7846. return this.convertBytes(normalizeByteString(value.bytesValue));
  7847. case 7 /* TypeOrder.RefValue */:
  7848. return this.convertReference(value.referenceValue);
  7849. case 8 /* TypeOrder.GeoPointValue */:
  7850. return this.convertGeoPoint(value.geoPointValue);
  7851. case 9 /* TypeOrder.ArrayValue */:
  7852. return this.convertArray(value.arrayValue, serverTimestampBehavior);
  7853. case 10 /* TypeOrder.ObjectValue */:
  7854. return this.convertObject(value.mapValue, serverTimestampBehavior);
  7855. default:
  7856. throw fail();
  7857. }
  7858. }
  7859. convertObject(mapValue, serverTimestampBehavior) {
  7860. return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);
  7861. }
  7862. /**
  7863. * @internal
  7864. */
  7865. convertObjectMap(fields, serverTimestampBehavior = 'none') {
  7866. const result = {};
  7867. forEach(fields, (key, value) => {
  7868. result[key] = this.convertValue(value, serverTimestampBehavior);
  7869. });
  7870. return result;
  7871. }
  7872. convertGeoPoint(value) {
  7873. return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude));
  7874. }
  7875. convertArray(arrayValue, serverTimestampBehavior) {
  7876. return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior));
  7877. }
  7878. convertServerTimestamp(value, serverTimestampBehavior) {
  7879. switch (serverTimestampBehavior) {
  7880. case 'previous':
  7881. const previousValue = getPreviousValue(value);
  7882. if (previousValue == null) {
  7883. return null;
  7884. }
  7885. return this.convertValue(previousValue, serverTimestampBehavior);
  7886. case 'estimate':
  7887. return this.convertTimestamp(getLocalWriteTime(value));
  7888. default:
  7889. return null;
  7890. }
  7891. }
  7892. convertTimestamp(value) {
  7893. const normalizedValue = normalizeTimestamp(value);
  7894. return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);
  7895. }
  7896. convertDocumentKey(name, expectedDatabaseId) {
  7897. const resourcePath = ResourcePath.fromString(name);
  7898. hardAssert(isValidResourceName(resourcePath));
  7899. const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));
  7900. const key = new DocumentKey(resourcePath.popFirst(5));
  7901. if (!databaseId.isEqual(expectedDatabaseId)) {
  7902. // TODO(b/64130202): Somehow support foreign references.
  7903. logError(`Document ${key} contains a document ` +
  7904. `reference within a different database (` +
  7905. `${databaseId.projectId}/${databaseId.database}) which is not ` +
  7906. `supported. It will be treated as a reference in the current ` +
  7907. `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +
  7908. `instead.`);
  7909. }
  7910. return key;
  7911. }
  7912. }
  7913. /**
  7914. * @license
  7915. * Copyright 2020 Google LLC
  7916. *
  7917. * Licensed under the Apache License, Version 2.0 (the "License");
  7918. * you may not use this file except in compliance with the License.
  7919. * You may obtain a copy of the License at
  7920. *
  7921. * http://www.apache.org/licenses/LICENSE-2.0
  7922. *
  7923. * Unless required by applicable law or agreed to in writing, software
  7924. * distributed under the License is distributed on an "AS IS" BASIS,
  7925. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7926. * See the License for the specific language governing permissions and
  7927. * limitations under the License.
  7928. */
  7929. /**
  7930. * Converts custom model object of type T into `DocumentData` by applying the
  7931. * converter if it exists.
  7932. *
  7933. * This function is used when converting user objects to `DocumentData`
  7934. * because we want to provide the user with a more specific error message if
  7935. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  7936. * call.
  7937. */
  7938. function applyFirestoreDataConverter(converter, value, options) {
  7939. let convertedValue;
  7940. if (converter) {
  7941. if (options && (options.merge || options.mergeFields)) {
  7942. // Cast to `any` in order to satisfy the union type constraint on
  7943. // toFirestore().
  7944. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7945. convertedValue = converter.toFirestore(value, options);
  7946. }
  7947. else {
  7948. convertedValue = converter.toFirestore(value);
  7949. }
  7950. }
  7951. else {
  7952. convertedValue = value;
  7953. }
  7954. return convertedValue;
  7955. }
  7956. class LiteUserDataWriter extends AbstractUserDataWriter {
  7957. constructor(firestore) {
  7958. super();
  7959. this.firestore = firestore;
  7960. }
  7961. convertBytes(bytes) {
  7962. return new Bytes(bytes);
  7963. }
  7964. convertReference(name) {
  7965. const key = this.convertDocumentKey(name, this.firestore._databaseId);
  7966. return new DocumentReference(this.firestore, /* converter= */ null, key);
  7967. }
  7968. }
  7969. /**
  7970. * Reads the document referred to by the specified document reference.
  7971. *
  7972. * All documents are directly fetched from the server, even if the document was
  7973. * previously read or modified. Recent modifications are only reflected in the
  7974. * retrieved `DocumentSnapshot` if they have already been applied by the
  7975. * backend. If the client is offline, the read fails. If you like to use
  7976. * caching or see local modifications, please use the full Firestore SDK.
  7977. *
  7978. * @param reference - The reference of the document to fetch.
  7979. * @returns A Promise resolved with a `DocumentSnapshot` containing the current
  7980. * document contents.
  7981. */
  7982. function getDoc(reference) {
  7983. reference = cast(reference, DocumentReference);
  7984. const datastore = getDatastore(reference.firestore);
  7985. const userDataWriter = new LiteUserDataWriter(reference.firestore);
  7986. return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(result => {
  7987. hardAssert(result.length === 1);
  7988. const document = result[0];
  7989. return new DocumentSnapshot(reference.firestore, userDataWriter, reference._key, document.isFoundDocument() ? document : null, reference.converter);
  7990. });
  7991. }
  7992. /**
  7993. * Executes the query and returns the results as a {@link QuerySnapshot}.
  7994. *
  7995. * All queries are executed directly by the server, even if the the query was
  7996. * previously executed. Recent modifications are only reflected in the retrieved
  7997. * results if they have already been applied by the backend. If the client is
  7998. * offline, the operation fails. To see previously cached result and local
  7999. * modifications, use the full Firestore SDK.
  8000. *
  8001. * @param query - The `Query` to execute.
  8002. * @returns A Promise that will be resolved with the results of the query.
  8003. */
  8004. function getDocs(query) {
  8005. query = cast(query, Query);
  8006. validateHasExplicitOrderByForLimitToLast(query._query);
  8007. const datastore = getDatastore(query.firestore);
  8008. const userDataWriter = new LiteUserDataWriter(query.firestore);
  8009. return invokeRunQueryRpc(datastore, query._query).then(result => {
  8010. const docs = result.map(doc => new QueryDocumentSnapshot(query.firestore, userDataWriter, doc.key, doc, query.converter));
  8011. if (query._query.limitType === "L" /* LimitType.Last */) {
  8012. // Limit to last queries reverse the orderBy constraint that was
  8013. // specified by the user. As such, we need to reverse the order of the
  8014. // results to return the documents in the expected order.
  8015. docs.reverse();
  8016. }
  8017. return new QuerySnapshot(query, docs);
  8018. });
  8019. }
  8020. function setDoc(reference, data, options) {
  8021. reference = cast(reference, DocumentReference);
  8022. const convertedValue = applyFirestoreDataConverter(reference.converter, data, options);
  8023. const dataReader = newUserDataReader(reference.firestore);
  8024. const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options);
  8025. const datastore = getDatastore(reference.firestore);
  8026. return invokeCommitRpc(datastore, [
  8027. parsed.toMutation(reference._key, Precondition.none())
  8028. ]);
  8029. }
  8030. function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) {
  8031. reference = cast(reference, DocumentReference);
  8032. const dataReader = newUserDataReader(reference.firestore);
  8033. // For Compat types, we have to "extract" the underlying types before
  8034. // performing validation.
  8035. fieldOrUpdateData = getModularInstance(fieldOrUpdateData);
  8036. let parsed;
  8037. if (typeof fieldOrUpdateData === 'string' ||
  8038. fieldOrUpdateData instanceof FieldPath) {
  8039. parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues);
  8040. }
  8041. else {
  8042. parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData);
  8043. }
  8044. const datastore = getDatastore(reference.firestore);
  8045. return invokeCommitRpc(datastore, [
  8046. parsed.toMutation(reference._key, Precondition.exists(true))
  8047. ]);
  8048. }
  8049. /**
  8050. * Deletes the document referred to by the specified `DocumentReference`.
  8051. *
  8052. * The deletion will only be reflected in document reads that occur after the
  8053. * returned promise resolves. If the client is offline, the
  8054. * delete fails. If you would like to see local modifications or buffer writes
  8055. * until the client is online, use the full Firestore SDK.
  8056. *
  8057. * @param reference - A reference to the document to delete.
  8058. * @returns A `Promise` resolved once the document has been successfully
  8059. * deleted from the backend.
  8060. */
  8061. function deleteDoc(reference) {
  8062. reference = cast(reference, DocumentReference);
  8063. const datastore = getDatastore(reference.firestore);
  8064. return invokeCommitRpc(datastore, [
  8065. new DeleteMutation(reference._key, Precondition.none())
  8066. ]);
  8067. }
  8068. /**
  8069. * Add a new document to specified `CollectionReference` with the given data,
  8070. * assigning it a document ID automatically.
  8071. *
  8072. * The result of this write will only be reflected in document reads that occur
  8073. * after the returned promise resolves. If the client is offline, the
  8074. * write fails. If you would like to see local modifications or buffer writes
  8075. * until the client is online, use the full Firestore SDK.
  8076. *
  8077. * @param reference - A reference to the collection to add this document to.
  8078. * @param data - An Object containing the data for the new document.
  8079. * @throws Error - If the provided input is not a valid Firestore document.
  8080. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  8081. * newly created document after it has been written to the backend.
  8082. */
  8083. function addDoc(reference, data) {
  8084. reference = cast(reference, CollectionReference);
  8085. const docRef = doc(reference);
  8086. const convertedValue = applyFirestoreDataConverter(reference.converter, data);
  8087. const dataReader = newUserDataReader(reference.firestore);
  8088. const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, docRef.converter !== null, {});
  8089. const datastore = getDatastore(reference.firestore);
  8090. return invokeCommitRpc(datastore, [
  8091. parsed.toMutation(docRef._key, Precondition.exists(false))
  8092. ]).then(() => docRef);
  8093. }
  8094. /**
  8095. * @license
  8096. * Copyright 2022 Google LLC
  8097. *
  8098. * Licensed under the Apache License, Version 2.0 (the "License");
  8099. * you may not use this file except in compliance with the License.
  8100. * You may obtain a copy of the License at
  8101. *
  8102. * http://www.apache.org/licenses/LICENSE-2.0
  8103. *
  8104. * Unless required by applicable law or agreed to in writing, software
  8105. * distributed under the License is distributed on an "AS IS" BASIS,
  8106. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8107. * See the License for the specific language governing permissions and
  8108. * limitations under the License.
  8109. */
  8110. /**
  8111. * Calculates the number of documents in the result set of the given query,
  8112. * without actually downloading the documents.
  8113. *
  8114. * Using this function to count the documents is efficient because only the
  8115. * final count, not the documents' data, is downloaded. This function can even
  8116. * count the documents if the result set would be prohibitively large to
  8117. * download entirely (e.g. thousands of documents).
  8118. *
  8119. * @param query - The query whose result set size to calculate.
  8120. * @returns A Promise that will be resolved with the count; the count can be
  8121. * retrieved from `snapshot.data().count`, where `snapshot` is the
  8122. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  8123. */
  8124. function getCount(query) {
  8125. const countQuerySpec = {
  8126. count: count()
  8127. };
  8128. return getAggregate(query, countQuerySpec);
  8129. }
  8130. /**
  8131. * Calculates the specified aggregations over the documents in the result
  8132. * set of the given query, without actually downloading the documents.
  8133. *
  8134. * Using this function to perform aggregations is efficient because only the
  8135. * final aggregation values, not the documents' data, is downloaded. This
  8136. * function can even perform aggregations of the documents if the result set
  8137. * would be prohibitively large to download entirely (e.g. thousands of documents).
  8138. *
  8139. * @param query The query whose result set to aggregate over.
  8140. * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates
  8141. * to perform over the result set. The AggregateSpec specifies aliases for each
  8142. * aggregate, which can be used to retrieve the aggregate result.
  8143. * @example
  8144. * ```typescript
  8145. * const aggregateSnapshot = await getAggregate(query, {
  8146. * countOfDocs: count(),
  8147. * totalHours: sum('hours'),
  8148. * averageScore: average('score')
  8149. * });
  8150. *
  8151. * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
  8152. * const totalHours: number = aggregateSnapshot.data().totalHours;
  8153. * const averageScore: number | null = aggregateSnapshot.data().averageScore;
  8154. * ```
  8155. * @internal TODO (sum/avg) remove when public
  8156. */
  8157. function getAggregate(query, aggregateSpec) {
  8158. const firestore = cast(query.firestore, Firestore);
  8159. const datastore = getDatastore(firestore);
  8160. const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {
  8161. return new AggregateImpl(alias, aggregate._aggregateType, aggregate._internalFieldPath);
  8162. });
  8163. // Run the aggregation and convert the results
  8164. return invokeRunAggregationQueryRpc(datastore, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult));
  8165. }
  8166. function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) {
  8167. const userDataWriter = new LiteUserDataWriter(firestore);
  8168. const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult);
  8169. return querySnapshot;
  8170. }
  8171. /**
  8172. * Create an AggregateField object that can be used to compute the sum of
  8173. * a specified field over a range of documents in the result set of a query.
  8174. * @param field Specifies the field to sum across the result set.
  8175. * @internal TODO (sum/avg) remove when public
  8176. */
  8177. function sum(field) {
  8178. return new AggregateField('sum', fieldPathFromArgument$1('sum', field));
  8179. }
  8180. /**
  8181. * Create an AggregateField object that can be used to compute the average of
  8182. * a specified field over a range of documents in the result set of a query.
  8183. * @param field Specifies the field to average across the result set.
  8184. * @internal TODO (sum/avg) remove when public
  8185. */
  8186. function average(field) {
  8187. return new AggregateField('avg', fieldPathFromArgument$1('average', field));
  8188. }
  8189. /**
  8190. * Create an AggregateField object that can be used to compute the count of
  8191. * documents in the result set of a query.
  8192. * @internal TODO (sum/avg) remove when public
  8193. */
  8194. function count() {
  8195. return new AggregateField('count');
  8196. }
  8197. /**
  8198. * Compares two 'AggregateField` instances for equality.
  8199. *
  8200. * @param left Compare this AggregateField to the `right`.
  8201. * @param right Compare this AggregateField to the `left`.
  8202. * @internal TODO (sum/avg) remove when public
  8203. */
  8204. function aggregateFieldEqual(left, right) {
  8205. var _a, _b;
  8206. return (left instanceof AggregateField &&
  8207. right instanceof AggregateField &&
  8208. left._aggregateType === right._aggregateType &&
  8209. ((_a = left._internalFieldPath) === null || _a === void 0 ? void 0 : _a.canonicalString()) ===
  8210. ((_b = right._internalFieldPath) === null || _b === void 0 ? void 0 : _b.canonicalString()));
  8211. }
  8212. /**
  8213. * Compares two `AggregateQuerySnapshot` instances for equality.
  8214. *
  8215. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  8216. * underlying queries that compare equal, and the same data.
  8217. *
  8218. * @param left - The first `AggregateQuerySnapshot` to compare.
  8219. * @param right - The second `AggregateQuerySnapshot` to compare.
  8220. *
  8221. * @returns `true` if the objects are "equal", as defined above, or `false`
  8222. * otherwise.
  8223. */
  8224. function aggregateQuerySnapshotEqual(left, right) {
  8225. return (queryEqual(left.query, right.query) && deepEqual(left.data(), right.data()));
  8226. }
  8227. /**
  8228. * @license
  8229. * Copyright 2020 Google LLC
  8230. *
  8231. * Licensed under the Apache License, Version 2.0 (the "License");
  8232. * you may not use this file except in compliance with the License.
  8233. * You may obtain a copy of the License at
  8234. *
  8235. * http://www.apache.org/licenses/LICENSE-2.0
  8236. *
  8237. * Unless required by applicable law or agreed to in writing, software
  8238. * distributed under the License is distributed on an "AS IS" BASIS,
  8239. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8240. * See the License for the specific language governing permissions and
  8241. * limitations under the License.
  8242. */
  8243. /**
  8244. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  8245. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  8246. */
  8247. function deleteField() {
  8248. return new DeleteFieldValueImpl('deleteField');
  8249. }
  8250. /**
  8251. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  8252. * include a server-generated timestamp in the written data.
  8253. */
  8254. function serverTimestamp() {
  8255. return new ServerTimestampFieldValueImpl('serverTimestamp');
  8256. }
  8257. /**
  8258. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  8259. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  8260. * value that already exists on the server. Each specified element that doesn't
  8261. * already exist in the array will be added to the end. If the field being
  8262. * modified is not already an array it will be overwritten with an array
  8263. * containing exactly the specified elements.
  8264. *
  8265. * @param elements - The elements to union into the array.
  8266. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  8267. * `updateDoc()`.
  8268. */
  8269. function arrayUnion(...elements) {
  8270. // NOTE: We don't actually parse the data until it's used in set() or
  8271. // update() since we'd need the Firestore instance to do this.
  8272. return new ArrayUnionFieldValueImpl('arrayUnion', elements);
  8273. }
  8274. /**
  8275. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  8276. * updateDoc:1} that tells the server to remove the given elements from any
  8277. * array value that already exists on the server. All instances of each element
  8278. * specified will be removed from the array. If the field being modified is not
  8279. * already an array it will be overwritten with an empty array.
  8280. *
  8281. * @param elements - The elements to remove from the array.
  8282. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  8283. * `updateDoc()`
  8284. */
  8285. function arrayRemove(...elements) {
  8286. // NOTE: We don't actually parse the data until it's used in set() or
  8287. // update() since we'd need the Firestore instance to do this.
  8288. return new ArrayRemoveFieldValueImpl('arrayRemove', elements);
  8289. }
  8290. /**
  8291. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  8292. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  8293. * the given value.
  8294. *
  8295. * If either the operand or the current field value uses floating point
  8296. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  8297. * integers, values outside of JavaScript's safe number range
  8298. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  8299. * precision loss. Furthermore, once processed by the Firestore backend, all
  8300. * integer operations are capped between -2^63 and 2^63-1.
  8301. *
  8302. * If the current field value is not of type `number`, or if the field does not
  8303. * yet exist, the transformation sets the field to the given value.
  8304. *
  8305. * @param n - The value to increment by.
  8306. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  8307. * `updateDoc()`
  8308. */
  8309. function increment(n) {
  8310. return new NumericIncrementFieldValueImpl('increment', n);
  8311. }
  8312. /**
  8313. * @license
  8314. * Copyright 2020 Google LLC
  8315. *
  8316. * Licensed under the Apache License, Version 2.0 (the "License");
  8317. * you may not use this file except in compliance with the License.
  8318. * You may obtain a copy of the License at
  8319. *
  8320. * http://www.apache.org/licenses/LICENSE-2.0
  8321. *
  8322. * Unless required by applicable law or agreed to in writing, software
  8323. * distributed under the License is distributed on an "AS IS" BASIS,
  8324. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8325. * See the License for the specific language governing permissions and
  8326. * limitations under the License.
  8327. */
  8328. /**
  8329. * A write batch, used to perform multiple writes as a single atomic unit.
  8330. *
  8331. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  8332. * provides methods for adding writes to the write batch. None of the writes
  8333. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  8334. * called.
  8335. */
  8336. class WriteBatch {
  8337. /** @hideconstructor */
  8338. constructor(_firestore, _commitHandler) {
  8339. this._firestore = _firestore;
  8340. this._commitHandler = _commitHandler;
  8341. this._mutations = [];
  8342. this._committed = false;
  8343. this._dataReader = newUserDataReader(_firestore);
  8344. }
  8345. set(documentRef, data, options) {
  8346. this._verifyNotCommitted();
  8347. const ref = validateReference(documentRef, this._firestore);
  8348. const convertedValue = applyFirestoreDataConverter(ref.converter, data, options);
  8349. const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options);
  8350. this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));
  8351. return this;
  8352. }
  8353. update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
  8354. this._verifyNotCommitted();
  8355. const ref = validateReference(documentRef, this._firestore);
  8356. // For Compat types, we have to "extract" the underlying types before
  8357. // performing validation.
  8358. fieldOrUpdateData = getModularInstance(fieldOrUpdateData);
  8359. let parsed;
  8360. if (typeof fieldOrUpdateData === 'string' ||
  8361. fieldOrUpdateData instanceof FieldPath) {
  8362. parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
  8363. }
  8364. else {
  8365. parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData);
  8366. }
  8367. this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true)));
  8368. return this;
  8369. }
  8370. /**
  8371. * Deletes the document referred to by the provided {@link DocumentReference}.
  8372. *
  8373. * @param documentRef - A reference to the document to be deleted.
  8374. * @returns This `WriteBatch` instance. Used for chaining method calls.
  8375. */
  8376. delete(documentRef) {
  8377. this._verifyNotCommitted();
  8378. const ref = validateReference(documentRef, this._firestore);
  8379. this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none()));
  8380. return this;
  8381. }
  8382. /**
  8383. * Commits all of the writes in this write batch as a single atomic unit.
  8384. *
  8385. * The result of these writes will only be reflected in document reads that
  8386. * occur after the returned promise resolves. If the client is offline, the
  8387. * write fails. If you would like to see local modifications or buffer writes
  8388. * until the client is online, use the full Firestore SDK.
  8389. *
  8390. * @returns A `Promise` resolved once all of the writes in the batch have been
  8391. * successfully written to the backend as an atomic unit (note that it won't
  8392. * resolve while you're offline).
  8393. */
  8394. commit() {
  8395. this._verifyNotCommitted();
  8396. this._committed = true;
  8397. if (this._mutations.length > 0) {
  8398. return this._commitHandler(this._mutations);
  8399. }
  8400. return Promise.resolve();
  8401. }
  8402. _verifyNotCommitted() {
  8403. if (this._committed) {
  8404. throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +
  8405. 'has been called.');
  8406. }
  8407. }
  8408. }
  8409. function validateReference(documentRef, firestore) {
  8410. documentRef = getModularInstance(documentRef);
  8411. if (documentRef.firestore !== firestore) {
  8412. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');
  8413. }
  8414. else {
  8415. return documentRef;
  8416. }
  8417. }
  8418. /**
  8419. * Creates a write batch, used for performing multiple writes as a single
  8420. * atomic operation. The maximum number of writes allowed in a single WriteBatch
  8421. * is 500.
  8422. *
  8423. * The result of these writes will only be reflected in document reads that
  8424. * occur after the returned promise resolves. If the client is offline, the
  8425. * write fails. If you would like to see local modifications or buffer writes
  8426. * until the client is online, use the full Firestore SDK.
  8427. *
  8428. * @returns A `WriteBatch` that can be used to atomically execute multiple
  8429. * writes.
  8430. */
  8431. function writeBatch(firestore) {
  8432. firestore = cast(firestore, Firestore);
  8433. const datastore = getDatastore(firestore);
  8434. return new WriteBatch(firestore, writes => invokeCommitRpc(datastore, writes));
  8435. }
  8436. /**
  8437. * @license
  8438. * Copyright 2022 Google LLC
  8439. *
  8440. * Licensed under the Apache License, Version 2.0 (the "License");
  8441. * you may not use this file except in compliance with the License.
  8442. * You may obtain a copy of the License at
  8443. *
  8444. * http://www.apache.org/licenses/LICENSE-2.0
  8445. *
  8446. * Unless required by applicable law or agreed to in writing, software
  8447. * distributed under the License is distributed on an "AS IS" BASIS,
  8448. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8449. * See the License for the specific language governing permissions and
  8450. * limitations under the License.
  8451. */
  8452. const DEFAULT_TRANSACTION_OPTIONS = {
  8453. maxAttempts: 5
  8454. };
  8455. function validateTransactionOptions(options) {
  8456. if (options.maxAttempts < 1) {
  8457. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1');
  8458. }
  8459. }
  8460. /**
  8461. * @license
  8462. * Copyright 2017 Google LLC
  8463. *
  8464. * Licensed under the Apache License, Version 2.0 (the "License");
  8465. * you may not use this file except in compliance with the License.
  8466. * You may obtain a copy of the License at
  8467. *
  8468. * http://www.apache.org/licenses/LICENSE-2.0
  8469. *
  8470. * Unless required by applicable law or agreed to in writing, software
  8471. * distributed under the License is distributed on an "AS IS" BASIS,
  8472. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8473. * See the License for the specific language governing permissions and
  8474. * limitations under the License.
  8475. */
  8476. /**
  8477. * Internal transaction object responsible for accumulating the mutations to
  8478. * perform and the base versions for any documents read.
  8479. */
  8480. class Transaction$1 {
  8481. constructor(datastore) {
  8482. this.datastore = datastore;
  8483. // The version of each document that was read during this transaction.
  8484. this.readVersions = new Map();
  8485. this.mutations = [];
  8486. this.committed = false;
  8487. /**
  8488. * A deferred usage error that occurred previously in this transaction that
  8489. * will cause the transaction to fail once it actually commits.
  8490. */
  8491. this.lastWriteError = null;
  8492. /**
  8493. * Set of documents that have been written in the transaction.
  8494. *
  8495. * When there's more than one write to the same key in a transaction, any
  8496. * writes after the first are handled differently.
  8497. */
  8498. this.writtenDocs = new Set();
  8499. }
  8500. async lookup(keys) {
  8501. this.ensureCommitNotCalled();
  8502. if (this.mutations.length > 0) {
  8503. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.');
  8504. }
  8505. const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);
  8506. docs.forEach(doc => this.recordVersion(doc));
  8507. return docs;
  8508. }
  8509. set(key, data) {
  8510. this.write(data.toMutation(key, this.precondition(key)));
  8511. this.writtenDocs.add(key.toString());
  8512. }
  8513. update(key, data) {
  8514. try {
  8515. this.write(data.toMutation(key, this.preconditionForUpdate(key)));
  8516. }
  8517. catch (e) {
  8518. this.lastWriteError = e;
  8519. }
  8520. this.writtenDocs.add(key.toString());
  8521. }
  8522. delete(key) {
  8523. this.write(new DeleteMutation(key, this.precondition(key)));
  8524. this.writtenDocs.add(key.toString());
  8525. }
  8526. async commit() {
  8527. this.ensureCommitNotCalled();
  8528. if (this.lastWriteError) {
  8529. throw this.lastWriteError;
  8530. }
  8531. const unwritten = this.readVersions;
  8532. // For each mutation, note that the doc was written.
  8533. this.mutations.forEach(mutation => {
  8534. unwritten.delete(mutation.key.toString());
  8535. });
  8536. // For each document that was read but not written to, we want to perform
  8537. // a `verify` operation.
  8538. unwritten.forEach((_, path) => {
  8539. const key = DocumentKey.fromPath(path);
  8540. this.mutations.push(new VerifyMutation(key, this.precondition(key)));
  8541. });
  8542. await invokeCommitRpc(this.datastore, this.mutations);
  8543. this.committed = true;
  8544. }
  8545. recordVersion(doc) {
  8546. let docVersion;
  8547. if (doc.isFoundDocument()) {
  8548. docVersion = doc.version;
  8549. }
  8550. else if (doc.isNoDocument()) {
  8551. // Represent a deleted doc using SnapshotVersion.min().
  8552. docVersion = SnapshotVersion.min();
  8553. }
  8554. else {
  8555. throw fail();
  8556. }
  8557. const existingVersion = this.readVersions.get(doc.key.toString());
  8558. if (existingVersion) {
  8559. if (!docVersion.isEqual(existingVersion)) {
  8560. // This transaction will fail no matter what.
  8561. throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');
  8562. }
  8563. }
  8564. else {
  8565. this.readVersions.set(doc.key.toString(), docVersion);
  8566. }
  8567. }
  8568. /**
  8569. * Returns the version of this document when it was read in this transaction,
  8570. * as a precondition, or no precondition if it was not read.
  8571. */
  8572. precondition(key) {
  8573. const version = this.readVersions.get(key.toString());
  8574. if (!this.writtenDocs.has(key.toString()) && version) {
  8575. if (version.isEqual(SnapshotVersion.min())) {
  8576. return Precondition.exists(false);
  8577. }
  8578. else {
  8579. return Precondition.updateTime(version);
  8580. }
  8581. }
  8582. else {
  8583. return Precondition.none();
  8584. }
  8585. }
  8586. /**
  8587. * Returns the precondition for a document if the operation is an update.
  8588. */
  8589. preconditionForUpdate(key) {
  8590. const version = this.readVersions.get(key.toString());
  8591. // The first time a document is written, we want to take into account the
  8592. // read time and existence
  8593. if (!this.writtenDocs.has(key.toString()) && version) {
  8594. if (version.isEqual(SnapshotVersion.min())) {
  8595. // The document doesn't exist, so fail the transaction.
  8596. // This has to be validated locally because you can't send a
  8597. // precondition that a document does not exist without changing the
  8598. // semantics of the backend write to be an insert. This is the reverse
  8599. // of what we want, since we want to assert that the document doesn't
  8600. // exist but then send the update and have it fail. Since we can't
  8601. // express that to the backend, we have to validate locally.
  8602. // Note: this can change once we can send separate verify writes in the
  8603. // transaction.
  8604. throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  8605. }
  8606. // Document exists, base precondition on document update time.
  8607. return Precondition.updateTime(version);
  8608. }
  8609. else {
  8610. // Document was not read, so we just use the preconditions for a blind
  8611. // update.
  8612. return Precondition.exists(true);
  8613. }
  8614. }
  8615. write(mutation) {
  8616. this.ensureCommitNotCalled();
  8617. this.mutations.push(mutation);
  8618. }
  8619. ensureCommitNotCalled() {
  8620. }
  8621. }
  8622. /**
  8623. * @license
  8624. * Copyright 2019 Google LLC
  8625. *
  8626. * Licensed under the Apache License, Version 2.0 (the "License");
  8627. * you may not use this file except in compliance with the License.
  8628. * You may obtain a copy of the License at
  8629. *
  8630. * http://www.apache.org/licenses/LICENSE-2.0
  8631. *
  8632. * Unless required by applicable law or agreed to in writing, software
  8633. * distributed under the License is distributed on an "AS IS" BASIS,
  8634. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8635. * See the License for the specific language governing permissions and
  8636. * limitations under the License.
  8637. */
  8638. /**
  8639. * TransactionRunner encapsulates the logic needed to run and retry transactions
  8640. * with backoff.
  8641. */
  8642. class TransactionRunner {
  8643. constructor(asyncQueue, datastore, options, updateFunction, deferred) {
  8644. this.asyncQueue = asyncQueue;
  8645. this.datastore = datastore;
  8646. this.options = options;
  8647. this.updateFunction = updateFunction;
  8648. this.deferred = deferred;
  8649. this.attemptsRemaining = options.maxAttempts;
  8650. this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  8651. }
  8652. /** Runs the transaction and sets the result on deferred. */
  8653. run() {
  8654. this.attemptsRemaining -= 1;
  8655. this.runWithBackOff();
  8656. }
  8657. runWithBackOff() {
  8658. this.backoff.backoffAndRun(async () => {
  8659. const transaction = new Transaction$1(this.datastore);
  8660. const userPromise = this.tryRunUpdateFunction(transaction);
  8661. if (userPromise) {
  8662. userPromise
  8663. .then(result => {
  8664. this.asyncQueue.enqueueAndForget(() => {
  8665. return transaction
  8666. .commit()
  8667. .then(() => {
  8668. this.deferred.resolve(result);
  8669. })
  8670. .catch(commitError => {
  8671. this.handleTransactionError(commitError);
  8672. });
  8673. });
  8674. })
  8675. .catch(userPromiseError => {
  8676. this.handleTransactionError(userPromiseError);
  8677. });
  8678. }
  8679. });
  8680. }
  8681. tryRunUpdateFunction(transaction) {
  8682. try {
  8683. const userPromise = this.updateFunction(transaction);
  8684. if (isNullOrUndefined(userPromise) ||
  8685. !userPromise.catch ||
  8686. !userPromise.then) {
  8687. this.deferred.reject(Error('Transaction callback must return a Promise'));
  8688. return null;
  8689. }
  8690. return userPromise;
  8691. }
  8692. catch (error) {
  8693. // Do not retry errors thrown by user provided updateFunction.
  8694. this.deferred.reject(error);
  8695. return null;
  8696. }
  8697. }
  8698. handleTransactionError(error) {
  8699. if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {
  8700. this.attemptsRemaining -= 1;
  8701. this.asyncQueue.enqueueAndForget(() => {
  8702. this.runWithBackOff();
  8703. return Promise.resolve();
  8704. });
  8705. }
  8706. else {
  8707. this.deferred.reject(error);
  8708. }
  8709. }
  8710. isRetryableTransactionError(error) {
  8711. if (error.name === 'FirebaseError') {
  8712. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  8713. // non-matching document versions with ABORTED. These errors should be retried.
  8714. const code = error.code;
  8715. return (code === 'aborted' ||
  8716. code === 'failed-precondition' ||
  8717. code === 'already-exists' ||
  8718. !isPermanentError(code));
  8719. }
  8720. return false;
  8721. }
  8722. }
  8723. /**
  8724. * @license
  8725. * Copyright 2017 Google LLC
  8726. *
  8727. * Licensed under the Apache License, Version 2.0 (the "License");
  8728. * you may not use this file except in compliance with the License.
  8729. * You may obtain a copy of the License at
  8730. *
  8731. * http://www.apache.org/licenses/LICENSE-2.0
  8732. *
  8733. * Unless required by applicable law or agreed to in writing, software
  8734. * distributed under the License is distributed on an "AS IS" BASIS,
  8735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8736. * See the License for the specific language governing permissions and
  8737. * limitations under the License.
  8738. */
  8739. /**
  8740. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  8741. *
  8742. * It is created via DelayedOperation.createAndSchedule().
  8743. *
  8744. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  8745. *
  8746. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  8747. * in newer versions of TypeScript defines `finally`, which is not available in
  8748. * IE.
  8749. */
  8750. class DelayedOperation {
  8751. constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) {
  8752. this.asyncQueue = asyncQueue;
  8753. this.timerId = timerId;
  8754. this.targetTimeMs = targetTimeMs;
  8755. this.op = op;
  8756. this.removalCallback = removalCallback;
  8757. this.deferred = new Deferred();
  8758. this.then = this.deferred.promise.then.bind(this.deferred.promise);
  8759. // It's normal for the deferred promise to be canceled (due to cancellation)
  8760. // and so we attach a dummy catch callback to avoid
  8761. // 'UnhandledPromiseRejectionWarning' log spam.
  8762. this.deferred.promise.catch(err => { });
  8763. }
  8764. /**
  8765. * Creates and returns a DelayedOperation that has been scheduled to be
  8766. * executed on the provided asyncQueue after the provided delayMs.
  8767. *
  8768. * @param asyncQueue - The queue to schedule the operation on.
  8769. * @param id - A Timer ID identifying the type of operation this is.
  8770. * @param delayMs - The delay (ms) before the operation should be scheduled.
  8771. * @param op - The operation to run.
  8772. * @param removalCallback - A callback to be called synchronously once the
  8773. * operation is executed or canceled, notifying the AsyncQueue to remove it
  8774. * from its delayedOperations list.
  8775. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  8776. * the DelayedOperation class public.
  8777. */
  8778. static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) {
  8779. const targetTime = Date.now() + delayMs;
  8780. const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback);
  8781. delayedOp.start(delayMs);
  8782. return delayedOp;
  8783. }
  8784. /**
  8785. * Starts the timer. This is called immediately after construction by
  8786. * createAndSchedule().
  8787. */
  8788. start(delayMs) {
  8789. this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);
  8790. }
  8791. /**
  8792. * Queues the operation to run immediately (if it hasn't already been run or
  8793. * canceled).
  8794. */
  8795. skipDelay() {
  8796. return this.handleDelayElapsed();
  8797. }
  8798. /**
  8799. * Cancels the operation if it hasn't already been executed or canceled. The
  8800. * promise will be rejected.
  8801. *
  8802. * As long as the operation has not yet been run, calling cancel() provides a
  8803. * guarantee that the operation will not be run.
  8804. */
  8805. cancel(reason) {
  8806. if (this.timerHandle !== null) {
  8807. this.clearTimeout();
  8808. this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : '')));
  8809. }
  8810. }
  8811. handleDelayElapsed() {
  8812. this.asyncQueue.enqueueAndForget(() => {
  8813. if (this.timerHandle !== null) {
  8814. this.clearTimeout();
  8815. return this.op().then(result => {
  8816. return this.deferred.resolve(result);
  8817. });
  8818. }
  8819. else {
  8820. return Promise.resolve();
  8821. }
  8822. });
  8823. }
  8824. clearTimeout() {
  8825. if (this.timerHandle !== null) {
  8826. this.removalCallback(this);
  8827. clearTimeout(this.timerHandle);
  8828. this.timerHandle = null;
  8829. }
  8830. }
  8831. }
  8832. /**
  8833. * @license
  8834. * Copyright 2020 Google LLC
  8835. *
  8836. * Licensed under the Apache License, Version 2.0 (the "License");
  8837. * you may not use this file except in compliance with the License.
  8838. * You may obtain a copy of the License at
  8839. *
  8840. * http://www.apache.org/licenses/LICENSE-2.0
  8841. *
  8842. * Unless required by applicable law or agreed to in writing, software
  8843. * distributed under the License is distributed on an "AS IS" BASIS,
  8844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8845. * See the License for the specific language governing permissions and
  8846. * limitations under the License.
  8847. */
  8848. const LOG_TAG = 'AsyncQueue';
  8849. class AsyncQueueImpl {
  8850. constructor() {
  8851. // The last promise in the queue.
  8852. this.tail = Promise.resolve();
  8853. // A list of retryable operations. Retryable operations are run in order and
  8854. // retried with backoff.
  8855. this.retryableOps = [];
  8856. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  8857. // be changed again.
  8858. this._isShuttingDown = false;
  8859. // Operations scheduled to be queued in the future. Operations are
  8860. // automatically removed after they are run or canceled.
  8861. this.delayedOperations = [];
  8862. // visible for testing
  8863. this.failure = null;
  8864. // Flag set while there's an outstanding AsyncQueue operation, used for
  8865. // assertion sanity-checks.
  8866. this.operationInProgress = false;
  8867. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  8868. this.skipNonRestrictedTasks = false;
  8869. // List of TimerIds to fast-forward delays for.
  8870. this.timerIdsToSkip = [];
  8871. // Backoff timer used to schedule retries for retryable operations
  8872. this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */);
  8873. // Visibility handler that triggers an immediate retry of all retryable
  8874. // operations. Meant to speed up recovery when we regain file system access
  8875. // after page comes into foreground.
  8876. this.visibilityHandler = () => {
  8877. this.backoff.skipBackoff();
  8878. };
  8879. }
  8880. get isShuttingDown() {
  8881. return this._isShuttingDown;
  8882. }
  8883. /**
  8884. * Adds a new operation to the queue without waiting for it to complete (i.e.
  8885. * we ignore the Promise result).
  8886. */
  8887. enqueueAndForget(op) {
  8888. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  8889. this.enqueue(op);
  8890. }
  8891. enqueueAndForgetEvenWhileRestricted(op) {
  8892. this.verifyNotFailed();
  8893. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  8894. this.enqueueInternal(op);
  8895. }
  8896. enterRestrictedMode(purgeExistingTasks) {
  8897. if (!this._isShuttingDown) {
  8898. this._isShuttingDown = true;
  8899. this.skipNonRestrictedTasks = purgeExistingTasks || false;
  8900. }
  8901. }
  8902. enqueue(op) {
  8903. this.verifyNotFailed();
  8904. if (this._isShuttingDown) {
  8905. // Return a Promise which never resolves.
  8906. return new Promise(() => { });
  8907. }
  8908. // Create a deferred Promise that we can return to the callee. This
  8909. // allows us to return a "hanging Promise" only to the callee and still
  8910. // advance the queue even when the operation is not run.
  8911. const task = new Deferred();
  8912. return this.enqueueInternal(() => {
  8913. if (this._isShuttingDown && this.skipNonRestrictedTasks) {
  8914. // We do not resolve 'task'
  8915. return Promise.resolve();
  8916. }
  8917. op().then(task.resolve, task.reject);
  8918. return task.promise;
  8919. }).then(() => task.promise);
  8920. }
  8921. enqueueRetryable(op) {
  8922. this.enqueueAndForget(() => {
  8923. this.retryableOps.push(op);
  8924. return this.retryNextOp();
  8925. });
  8926. }
  8927. /**
  8928. * Runs the next operation from the retryable queue. If the operation fails,
  8929. * reschedules with backoff.
  8930. */
  8931. async retryNextOp() {
  8932. if (this.retryableOps.length === 0) {
  8933. return;
  8934. }
  8935. try {
  8936. await this.retryableOps[0]();
  8937. this.retryableOps.shift();
  8938. this.backoff.reset();
  8939. }
  8940. catch (e) {
  8941. if (isIndexedDbTransactionError(e)) {
  8942. logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);
  8943. }
  8944. else {
  8945. throw e; // Failure will be handled by AsyncQueue
  8946. }
  8947. }
  8948. if (this.retryableOps.length > 0) {
  8949. // If there are additional operations, we re-schedule `retryNextOp()`.
  8950. // This is necessary to run retryable operations that failed during
  8951. // their initial attempt since we don't know whether they are already
  8952. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  8953. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  8954. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  8955. // call scheduled here.
  8956. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  8957. // new backoff on every call, there is only ever a single additional
  8958. // operation in the queue.
  8959. this.backoff.backoffAndRun(() => this.retryNextOp());
  8960. }
  8961. }
  8962. enqueueInternal(op) {
  8963. const newTail = this.tail.then(() => {
  8964. this.operationInProgress = true;
  8965. return op()
  8966. .catch((error) => {
  8967. this.failure = error;
  8968. this.operationInProgress = false;
  8969. const message = getMessageOrStack(error);
  8970. logError('INTERNAL UNHANDLED ERROR: ', message);
  8971. // Re-throw the error so that this.tail becomes a rejected Promise and
  8972. // all further attempts to chain (via .then) will just short-circuit
  8973. // and return the rejected Promise.
  8974. throw error;
  8975. })
  8976. .then(result => {
  8977. this.operationInProgress = false;
  8978. return result;
  8979. });
  8980. });
  8981. this.tail = newTail;
  8982. return newTail;
  8983. }
  8984. enqueueAfterDelay(timerId, delayMs, op) {
  8985. this.verifyNotFailed();
  8986. // Fast-forward delays for timerIds that have been overriden.
  8987. if (this.timerIdsToSkip.indexOf(timerId) > -1) {
  8988. delayMs = 0;
  8989. }
  8990. const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp));
  8991. this.delayedOperations.push(delayedOp);
  8992. return delayedOp;
  8993. }
  8994. verifyNotFailed() {
  8995. if (this.failure) {
  8996. fail();
  8997. }
  8998. }
  8999. verifyOperationInProgress() {
  9000. }
  9001. /**
  9002. * Waits until all currently queued tasks are finished executing. Delayed
  9003. * operations are not run.
  9004. */
  9005. async drain() {
  9006. // Operations in the queue prior to draining may have enqueued additional
  9007. // operations. Keep draining the queue until the tail is no longer advanced,
  9008. // which indicates that no more new operations were enqueued and that all
  9009. // operations were executed.
  9010. let currentTail;
  9011. do {
  9012. currentTail = this.tail;
  9013. await currentTail;
  9014. } while (currentTail !== this.tail);
  9015. }
  9016. /**
  9017. * For Tests: Determine if a delayed operation with a particular TimerId
  9018. * exists.
  9019. */
  9020. containsDelayedOperation(timerId) {
  9021. for (const op of this.delayedOperations) {
  9022. if (op.timerId === timerId) {
  9023. return true;
  9024. }
  9025. }
  9026. return false;
  9027. }
  9028. /**
  9029. * For Tests: Runs some or all delayed operations early.
  9030. *
  9031. * @param lastTimerId - Delayed operations up to and including this TimerId
  9032. * will be drained. Pass TimerId.All to run all delayed operations.
  9033. * @returns a Promise that resolves once all operations have been run.
  9034. */
  9035. runAllDelayedOperationsUntil(lastTimerId) {
  9036. // Note that draining may generate more delayed ops, so we do that first.
  9037. return this.drain().then(() => {
  9038. // Run ops in the same order they'd run if they ran naturally.
  9039. this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);
  9040. for (const op of this.delayedOperations) {
  9041. op.skipDelay();
  9042. if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) {
  9043. break;
  9044. }
  9045. }
  9046. return this.drain();
  9047. });
  9048. }
  9049. /**
  9050. * For Tests: Skip all subsequent delays for a timer id.
  9051. */
  9052. skipDelaysForTimerId(timerId) {
  9053. this.timerIdsToSkip.push(timerId);
  9054. }
  9055. /** Called once a DelayedOperation is run or canceled. */
  9056. removeDelayedOperation(op) {
  9057. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  9058. const index = this.delayedOperations.indexOf(op);
  9059. this.delayedOperations.splice(index, 1);
  9060. }
  9061. }
  9062. function newAsyncQueue() {
  9063. return new AsyncQueueImpl();
  9064. }
  9065. /**
  9066. * Chrome includes Error.message in Error.stack. Other browsers do not.
  9067. * This returns expected output of message + stack when available.
  9068. * @param error - Error or FirestoreError
  9069. */
  9070. function getMessageOrStack(error) {
  9071. let message = error.message || '';
  9072. if (error.stack) {
  9073. if (error.stack.includes(error.message)) {
  9074. message = error.stack;
  9075. }
  9076. else {
  9077. message = error.message + '\n' + error.stack;
  9078. }
  9079. }
  9080. return message;
  9081. }
  9082. /**
  9083. * @license
  9084. * Copyright 2020 Google LLC
  9085. *
  9086. * Licensed under the Apache License, Version 2.0 (the "License");
  9087. * you may not use this file except in compliance with the License.
  9088. * You may obtain a copy of the License at
  9089. *
  9090. * http://www.apache.org/licenses/LICENSE-2.0
  9091. *
  9092. * Unless required by applicable law or agreed to in writing, software
  9093. * distributed under the License is distributed on an "AS IS" BASIS,
  9094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9095. * See the License for the specific language governing permissions and
  9096. * limitations under the License.
  9097. */
  9098. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  9099. // legacy SDK.
  9100. /**
  9101. * A reference to a transaction.
  9102. *
  9103. * The `Transaction` object passed to a transaction's `updateFunction` provides
  9104. * the methods to read and write data within the transaction context. See
  9105. * {@link runTransaction}.
  9106. */
  9107. class Transaction {
  9108. /** @hideconstructor */
  9109. constructor(_firestore, _transaction) {
  9110. this._firestore = _firestore;
  9111. this._transaction = _transaction;
  9112. this._dataReader = newUserDataReader(_firestore);
  9113. }
  9114. /**
  9115. * Reads the document referenced by the provided {@link DocumentReference}.
  9116. *
  9117. * @param documentRef - A reference to the document to be read.
  9118. * @returns A `DocumentSnapshot` with the read data.
  9119. */
  9120. get(documentRef) {
  9121. const ref = validateReference(documentRef, this._firestore);
  9122. const userDataWriter = new LiteUserDataWriter(this._firestore);
  9123. return this._transaction.lookup([ref._key]).then(docs => {
  9124. if (!docs || docs.length !== 1) {
  9125. return fail();
  9126. }
  9127. const doc = docs[0];
  9128. if (doc.isFoundDocument()) {
  9129. return new DocumentSnapshot(this._firestore, userDataWriter, doc.key, doc, ref.converter);
  9130. }
  9131. else if (doc.isNoDocument()) {
  9132. return new DocumentSnapshot(this._firestore, userDataWriter, ref._key, null, ref.converter);
  9133. }
  9134. else {
  9135. throw fail();
  9136. }
  9137. });
  9138. }
  9139. set(documentRef, value, options) {
  9140. const ref = validateReference(documentRef, this._firestore);
  9141. const convertedValue = applyFirestoreDataConverter(ref.converter, value, options);
  9142. const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options);
  9143. this._transaction.set(ref._key, parsed);
  9144. return this;
  9145. }
  9146. update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
  9147. const ref = validateReference(documentRef, this._firestore);
  9148. // For Compat types, we have to "extract" the underlying types before
  9149. // performing validation.
  9150. fieldOrUpdateData = getModularInstance(fieldOrUpdateData);
  9151. let parsed;
  9152. if (typeof fieldOrUpdateData === 'string' ||
  9153. fieldOrUpdateData instanceof FieldPath) {
  9154. parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
  9155. }
  9156. else {
  9157. parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData);
  9158. }
  9159. this._transaction.update(ref._key, parsed);
  9160. return this;
  9161. }
  9162. /**
  9163. * Deletes the document referred to by the provided {@link DocumentReference}.
  9164. *
  9165. * @param documentRef - A reference to the document to be deleted.
  9166. * @returns This `Transaction` instance. Used for chaining method calls.
  9167. */
  9168. delete(documentRef) {
  9169. const ref = validateReference(documentRef, this._firestore);
  9170. this._transaction.delete(ref._key);
  9171. return this;
  9172. }
  9173. }
  9174. /**
  9175. * Executes the given `updateFunction` and then attempts to commit the changes
  9176. * applied within the transaction. If any document read within the transaction
  9177. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  9178. * commit after 5 attempts, the transaction fails.
  9179. *
  9180. * The maximum number of writes allowed in a single transaction is 500.
  9181. *
  9182. * @param firestore - A reference to the Firestore database to run this
  9183. * transaction against.
  9184. * @param updateFunction - The function to execute within the transaction
  9185. * context.
  9186. * @param options - An options object to configure maximum number of attempts to
  9187. * commit.
  9188. * @returns If the transaction completed successfully or was explicitly aborted
  9189. * (the `updateFunction` returned a failed promise), the promise returned by the
  9190. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  9191. * rejected promise with the corresponding failure error is returned.
  9192. */
  9193. function runTransaction(firestore, updateFunction, options) {
  9194. firestore = cast(firestore, Firestore);
  9195. const datastore = getDatastore(firestore);
  9196. const optionsWithDefaults = Object.assign(Object.assign({}, DEFAULT_TRANSACTION_OPTIONS), options);
  9197. validateTransactionOptions(optionsWithDefaults);
  9198. const deferred = new Deferred();
  9199. new TransactionRunner(newAsyncQueue(), datastore, optionsWithDefaults, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), deferred).run();
  9200. return deferred.promise;
  9201. }
  9202. /**
  9203. * Firestore Lite
  9204. *
  9205. * @remarks Firestore Lite is a small online-only SDK that allows read
  9206. * and write access to your Firestore database. All operations connect
  9207. * directly to the backend, and `onSnapshot()` APIs are not supported.
  9208. * @packageDocumentation
  9209. */
  9210. registerFirestore();
  9211. export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, where, writeBatch };
  9212. //# sourceMappingURL=index.node.mjs.map