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

index.node.mjs 332KB

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