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.rn.js 795KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565
  1. import { _getProvider, getApp as t, _removeServiceInstance as e, _registerComponent as n, registerVersion as s, SDK_VERSION as i } from "@firebase/app";
  2. import { Component as r } from "@firebase/component";
  3. import { Logger as o, LogLevel as u } from "@firebase/logger";
  4. import { FirebaseError as c, getUA as a, isIndexedDBAvailable as h, base64 as l, isSafari as f, createMockUserToken as d, getModularInstance as _, deepEqual as w, getDefaultEmulatorHostnameAndPort as m } from "@firebase/util";
  5. import { XhrIo as g, EventType as y, ErrorCode as p, createWebChannelTransport as I, getStatEventTarget as T, FetchXmlHttpFactory as E, WebChannel as A, Event as R, Stat as b } from "@firebase/webchannel-wrapper";
  6. const P = "@firebase/firestore";
  7. /**
  8. * @license
  9. * Copyright 2017 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /**
  24. * Simple wrapper around a nullable UID. Mostly exists to make code more
  25. * readable.
  26. */
  27. class v {
  28. constructor(t) {
  29. this.uid = t;
  30. }
  31. isAuthenticated() {
  32. return null != this.uid;
  33. }
  34. /**
  35. * Returns a key representing this user, suitable for inclusion in a
  36. * dictionary.
  37. */ toKey() {
  38. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  39. }
  40. isEqual(t) {
  41. return t.uid === this.uid;
  42. }
  43. }
  44. /** A user with a null UID. */ v.UNAUTHENTICATED = new v(null),
  45. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  46. // non-FirebaseAuth providers.
  47. v.GOOGLE_CREDENTIALS = new v("google-credentials-uid"), v.FIRST_PARTY = new v("first-party-uid"),
  48. v.MOCK_USER = new v("mock-user");
  49. /**
  50. * @license
  51. * Copyright 2017 Google LLC
  52. *
  53. * Licensed under the Apache License, Version 2.0 (the "License");
  54. * you may not use this file except in compliance with the License.
  55. * You may obtain a copy of the License at
  56. *
  57. * http://www.apache.org/licenses/LICENSE-2.0
  58. *
  59. * Unless required by applicable law or agreed to in writing, software
  60. * distributed under the License is distributed on an "AS IS" BASIS,
  61. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62. * See the License for the specific language governing permissions and
  63. * limitations under the License.
  64. */
  65. let V = "9.16.0";
  66. /**
  67. * @license
  68. * Copyright 2017 Google LLC
  69. *
  70. * Licensed under the Apache License, Version 2.0 (the "License");
  71. * you may not use this file except in compliance with the License.
  72. * You may obtain a copy of the License at
  73. *
  74. * http://www.apache.org/licenses/LICENSE-2.0
  75. *
  76. * Unless required by applicable law or agreed to in writing, software
  77. * distributed under the License is distributed on an "AS IS" BASIS,
  78. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  79. * See the License for the specific language governing permissions and
  80. * limitations under the License.
  81. */
  82. const S = new o("@firebase/firestore");
  83. // Helper methods are needed because variables can't be exported as read/write
  84. function D() {
  85. return S.logLevel;
  86. }
  87. /**
  88. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  89. *
  90. * @param logLevel - The verbosity you set for activity and error logging. Can
  91. * be any of the following values:
  92. *
  93. * <ul>
  94. * <li>`debug` for the most verbose logging level, primarily for
  95. * debugging.</li>
  96. * <li>`error` to log errors only.</li>
  97. * <li><code>`silent` to turn off logging.</li>
  98. * </ul>
  99. */ function C(t) {
  100. S.setLogLevel(t);
  101. }
  102. function x(t, ...e) {
  103. if (S.logLevel <= u.DEBUG) {
  104. const n = e.map(O);
  105. S.debug(`Firestore (${V}): ${t}`, ...n);
  106. }
  107. }
  108. function N(t, ...e) {
  109. if (S.logLevel <= u.ERROR) {
  110. const n = e.map(O);
  111. S.error(`Firestore (${V}): ${t}`, ...n);
  112. }
  113. }
  114. /**
  115. * @internal
  116. */ function k(t, ...e) {
  117. if (S.logLevel <= u.WARN) {
  118. const n = e.map(O);
  119. S.warn(`Firestore (${V}): ${t}`, ...n);
  120. }
  121. }
  122. /**
  123. * Converts an additional log parameter to a string representation.
  124. */ function O(t) {
  125. if ("string" == typeof t) return t;
  126. try {
  127. return e = t, JSON.stringify(e);
  128. } catch (e) {
  129. // Converting to JSON failed, just log the object directly
  130. return t;
  131. }
  132. /**
  133. * @license
  134. * Copyright 2020 Google LLC
  135. *
  136. * Licensed under the Apache License, Version 2.0 (the "License");
  137. * you may not use this file except in compliance with the License.
  138. * You may obtain a copy of the License at
  139. *
  140. * http://www.apache.org/licenses/LICENSE-2.0
  141. *
  142. * Unless required by applicable law or agreed to in writing, software
  143. * distributed under the License is distributed on an "AS IS" BASIS,
  144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  145. * See the License for the specific language governing permissions and
  146. * limitations under the License.
  147. */
  148. /** Formats an object as a JSON string, suitable for logging. */
  149. var e;
  150. }
  151. /**
  152. * @license
  153. * Copyright 2017 Google LLC
  154. *
  155. * Licensed under the Apache License, Version 2.0 (the "License");
  156. * you may not use this file except in compliance with the License.
  157. * You may obtain a copy of the License at
  158. *
  159. * http://www.apache.org/licenses/LICENSE-2.0
  160. *
  161. * Unless required by applicable law or agreed to in writing, software
  162. * distributed under the License is distributed on an "AS IS" BASIS,
  163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  164. * See the License for the specific language governing permissions and
  165. * limitations under the License.
  166. */
  167. /**
  168. * Unconditionally fails, throwing an Error with the given message.
  169. * Messages are stripped in production builds.
  170. *
  171. * Returns `never` and can be used in expressions:
  172. * @example
  173. * let futureVar = fail('not implemented yet');
  174. */ function M(t = "Unexpected state") {
  175. // Log the failure in addition to throw an exception, just in case the
  176. // exception is swallowed.
  177. const e = `FIRESTORE (${V}) INTERNAL ASSERTION FAILED: ` + t;
  178. // NOTE: We don't use FirestoreError here because these are internal failures
  179. // that cannot be handled by the user. (Also it would create a circular
  180. // dependency between the error and assert modules which doesn't work.)
  181. throw N(e), new Error(e);
  182. }
  183. /**
  184. * Fails if the given assertion condition is false, throwing an Error with the
  185. * given message if it did.
  186. *
  187. * Messages are stripped in production builds.
  188. */ function F(t, e) {
  189. t || M();
  190. }
  191. /**
  192. * Fails if the given assertion condition is false, throwing an Error with the
  193. * given message if it did.
  194. *
  195. * The code of callsites invoking this function are stripped out in production
  196. * builds. Any side-effects of code within the debugAssert() invocation will not
  197. * happen in this case.
  198. *
  199. * @internal
  200. */ function $(t, e) {
  201. t || M();
  202. }
  203. /**
  204. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  205. * instance of `T` before casting.
  206. */ function B(t,
  207. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  208. e) {
  209. return t;
  210. }
  211. /**
  212. * @license
  213. * Copyright 2017 Google LLC
  214. *
  215. * Licensed under the Apache License, Version 2.0 (the "License");
  216. * you may not use this file except in compliance with the License.
  217. * You may obtain a copy of the License at
  218. *
  219. * http://www.apache.org/licenses/LICENSE-2.0
  220. *
  221. * Unless required by applicable law or agreed to in writing, software
  222. * distributed under the License is distributed on an "AS IS" BASIS,
  223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  224. * See the License for the specific language governing permissions and
  225. * limitations under the License.
  226. */ const L = {
  227. // Causes are copied from:
  228. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  229. /** Not an error; returned on success. */
  230. OK: "ok",
  231. /** The operation was cancelled (typically by the caller). */
  232. CANCELLED: "cancelled",
  233. /** Unknown error or an error from a different error domain. */
  234. UNKNOWN: "unknown",
  235. /**
  236. * Client specified an invalid argument. Note that this differs from
  237. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  238. * problematic regardless of the state of the system (e.g., a malformed file
  239. * name).
  240. */
  241. INVALID_ARGUMENT: "invalid-argument",
  242. /**
  243. * Deadline expired before operation could complete. For operations that
  244. * change the state of the system, this error may be returned even if the
  245. * operation has completed successfully. For example, a successful response
  246. * from a server could have been delayed long enough for the deadline to
  247. * expire.
  248. */
  249. DEADLINE_EXCEEDED: "deadline-exceeded",
  250. /** Some requested entity (e.g., file or directory) was not found. */
  251. NOT_FOUND: "not-found",
  252. /**
  253. * Some entity that we attempted to create (e.g., file or directory) already
  254. * exists.
  255. */
  256. ALREADY_EXISTS: "already-exists",
  257. /**
  258. * The caller does not have permission to execute the specified operation.
  259. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  260. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  261. * PERMISSION_DENIED must not be used if the caller can not be identified
  262. * (use UNAUTHENTICATED instead for those errors).
  263. */
  264. PERMISSION_DENIED: "permission-denied",
  265. /**
  266. * The request does not have valid authentication credentials for the
  267. * operation.
  268. */
  269. UNAUTHENTICATED: "unauthenticated",
  270. /**
  271. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  272. * entire file system is out of space.
  273. */
  274. RESOURCE_EXHAUSTED: "resource-exhausted",
  275. /**
  276. * Operation was rejected because the system is not in a state required for
  277. * the operation's execution. For example, directory to be deleted may be
  278. * non-empty, an rmdir operation is applied to a non-directory, etc.
  279. *
  280. * A litmus test that may help a service implementor in deciding
  281. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  282. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  283. * (b) Use ABORTED if the client should retry at a higher-level
  284. * (e.g., restarting a read-modify-write sequence).
  285. * (c) Use FAILED_PRECONDITION if the client should not retry until
  286. * the system state has been explicitly fixed. E.g., if an "rmdir"
  287. * fails because the directory is non-empty, FAILED_PRECONDITION
  288. * should be returned since the client should not retry unless
  289. * they have first fixed up the directory by deleting files from it.
  290. * (d) Use FAILED_PRECONDITION if the client performs conditional
  291. * REST Get/Update/Delete on a resource and the resource on the
  292. * server does not match the condition. E.g., conflicting
  293. * read-modify-write on the same resource.
  294. */
  295. FAILED_PRECONDITION: "failed-precondition",
  296. /**
  297. * The operation was aborted, typically due to a concurrency issue like
  298. * sequencer check failures, transaction aborts, etc.
  299. *
  300. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  301. * and UNAVAILABLE.
  302. */
  303. ABORTED: "aborted",
  304. /**
  305. * Operation was attempted past the valid range. E.g., seeking or reading
  306. * past end of file.
  307. *
  308. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  309. * if the system state changes. For example, a 32-bit file system will
  310. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  311. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  312. * an offset past the current file size.
  313. *
  314. * There is a fair bit of overlap between FAILED_PRECONDITION and
  315. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  316. * when it applies so that callers who are iterating through a space can
  317. * easily look for an OUT_OF_RANGE error to detect when they are done.
  318. */
  319. OUT_OF_RANGE: "out-of-range",
  320. /** Operation is not implemented or not supported/enabled in this service. */
  321. UNIMPLEMENTED: "unimplemented",
  322. /**
  323. * Internal errors. Means some invariants expected by underlying System has
  324. * been broken. If you see one of these errors, Something is very broken.
  325. */
  326. INTERNAL: "internal",
  327. /**
  328. * The service is currently unavailable. This is a most likely a transient
  329. * condition and may be corrected by retrying with a backoff.
  330. *
  331. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  332. * and UNAVAILABLE.
  333. */
  334. UNAVAILABLE: "unavailable",
  335. /** Unrecoverable data loss or corruption. */
  336. DATA_LOSS: "data-loss"
  337. };
  338. /** An error returned by a Firestore operation. */ class q extends c {
  339. /** @hideconstructor */
  340. constructor(
  341. /**
  342. * The backend error code associated with this error.
  343. */
  344. t,
  345. /**
  346. * A custom error description.
  347. */
  348. e) {
  349. super(t, e), this.code = t, this.message = e,
  350. // HACK: We write a toString property directly because Error is not a real
  351. // class and so inheritance does not work correctly. We could alternatively
  352. // do the same "back-door inheritance" trick that FirebaseError does.
  353. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  354. }
  355. }
  356. /**
  357. * @license
  358. * Copyright 2017 Google LLC
  359. *
  360. * Licensed under the Apache License, Version 2.0 (the "License");
  361. * you may not use this file except in compliance with the License.
  362. * You may obtain a copy of the License at
  363. *
  364. * http://www.apache.org/licenses/LICENSE-2.0
  365. *
  366. * Unless required by applicable law or agreed to in writing, software
  367. * distributed under the License is distributed on an "AS IS" BASIS,
  368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  369. * See the License for the specific language governing permissions and
  370. * limitations under the License.
  371. */ class U {
  372. constructor() {
  373. this.promise = new Promise(((t, e) => {
  374. this.resolve = t, this.reject = e;
  375. }));
  376. }
  377. }
  378. /**
  379. * @license
  380. * Copyright 2017 Google LLC
  381. *
  382. * Licensed under the Apache License, Version 2.0 (the "License");
  383. * you may not use this file except in compliance with the License.
  384. * You may obtain a copy of the License at
  385. *
  386. * http://www.apache.org/licenses/LICENSE-2.0
  387. *
  388. * Unless required by applicable law or agreed to in writing, software
  389. * distributed under the License is distributed on an "AS IS" BASIS,
  390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  391. * See the License for the specific language governing permissions and
  392. * limitations under the License.
  393. */ class K {
  394. constructor(t, e) {
  395. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`);
  396. }
  397. }
  398. /**
  399. * A CredentialsProvider that always yields an empty token.
  400. * @internal
  401. */ class G {
  402. getToken() {
  403. return Promise.resolve(null);
  404. }
  405. invalidateToken() {}
  406. start(t, e) {
  407. // Fire with initial user.
  408. t.enqueueRetryable((() => e(v.UNAUTHENTICATED)));
  409. }
  410. shutdown() {}
  411. }
  412. /**
  413. * A CredentialsProvider that always returns a constant token. Used for
  414. * emulator token mocking.
  415. */ class Q {
  416. constructor(t) {
  417. this.token = t,
  418. /**
  419. * Stores the listener registered with setChangeListener()
  420. * This isn't actually necessary since the UID never changes, but we use this
  421. * to verify the listen contract is adhered to in tests.
  422. */
  423. this.changeListener = null;
  424. }
  425. getToken() {
  426. return Promise.resolve(this.token);
  427. }
  428. invalidateToken() {}
  429. start(t, e) {
  430. this.changeListener = e,
  431. // Fire with initial user.
  432. t.enqueueRetryable((() => e(this.token.user)));
  433. }
  434. shutdown() {
  435. this.changeListener = null;
  436. }
  437. }
  438. class j {
  439. constructor(t) {
  440. this.t = t,
  441. /** Tracks the current User. */
  442. this.currentUser = v.UNAUTHENTICATED,
  443. /**
  444. * Counter used to detect if the token changed while a getToken request was
  445. * outstanding.
  446. */
  447. this.i = 0, this.forceRefresh = !1, this.auth = null;
  448. }
  449. start(t, e) {
  450. let n = this.i;
  451. // A change listener that prevents double-firing for the same token change.
  452. const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();
  453. // A promise that can be waited on to block on the next token change.
  454. // This promise is re-created after each change.
  455. let i = new U;
  456. this.o = () => {
  457. this.i++, this.currentUser = this.u(), i.resolve(), i = new U, t.enqueueRetryable((() => s(this.currentUser)));
  458. };
  459. const r = () => {
  460. const e = i;
  461. t.enqueueRetryable((async () => {
  462. await e.promise, await s(this.currentUser);
  463. }));
  464. }, o = t => {
  465. x("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = t, this.auth.addAuthTokenListener(this.o),
  466. r();
  467. };
  468. this.t.onInit((t => o(t))),
  469. // Our users can initialize Auth right after Firestore, so we give it
  470. // a chance to register itself with the component framework before we
  471. // determine whether to start up in unauthenticated mode.
  472. setTimeout((() => {
  473. if (!this.auth) {
  474. const t = this.t.getImmediate({
  475. optional: !0
  476. });
  477. t ? o(t) : (
  478. // If auth is still not available, proceed with `null` user
  479. x("FirebaseAuthCredentialsProvider", "Auth not yet detected"), i.resolve(), i = new U);
  480. }
  481. }), 0), r();
  482. }
  483. getToken() {
  484. // Take note of the current value of the tokenCounter so that this method
  485. // can fail (with an ABORTED error) if there is a token change while the
  486. // request is outstanding.
  487. const t = this.i, e = this.forceRefresh;
  488. return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e =>
  489. // Cancel the request since the token changed while the request was
  490. // outstanding so the response is potentially for a previous user (which
  491. // user, we can't be sure).
  492. this.i !== t ? (x("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."),
  493. this.getToken()) : e ? (F("string" == typeof e.accessToken), new K(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);
  494. }
  495. invalidateToken() {
  496. this.forceRefresh = !0;
  497. }
  498. shutdown() {
  499. this.auth && this.auth.removeAuthTokenListener(this.o);
  500. }
  501. // Auth.getUid() can return null even with a user logged in. It is because
  502. // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  503. // This method should only be called in the AuthTokenListener callback
  504. // to guarantee to get the actual user.
  505. u() {
  506. const t = this.auth && this.auth.getUid();
  507. return F(null === t || "string" == typeof t), new v(t);
  508. }
  509. }
  510. /*
  511. * FirstPartyToken provides a fresh token each time its value
  512. * is requested, because if the token is too old, requests will be rejected.
  513. * Technically this may no longer be necessary since the SDK should gracefully
  514. * recover from unauthenticated errors (see b/33147818 for context), but it's
  515. * safer to keep the implementation as-is.
  516. */ class W {
  517. constructor(t, e, n, s) {
  518. this.h = t, this.l = e, this.m = n, this.g = s, this.type = "FirstParty", this.user = v.FIRST_PARTY,
  519. this.p = new Map;
  520. }
  521. /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */ I() {
  522. return this.g ? this.g() : (
  523. // Make sure this really is a Gapi client.
  524. F(!("object" != typeof this.h || null === this.h || !this.h.auth || !this.h.auth.getAuthHeaderValueForFirstParty)),
  525. this.h.auth.getAuthHeaderValueForFirstParty([]));
  526. }
  527. get headers() {
  528. this.p.set("X-Goog-AuthUser", this.l);
  529. // Use array notation to prevent minification
  530. const t = this.I();
  531. return t && this.p.set("Authorization", t), this.m && this.p.set("X-Goog-Iam-Authorization-Token", this.m),
  532. this.p;
  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. */ class z {
  540. constructor(t, e, n, s) {
  541. this.h = t, this.l = e, this.m = n, this.g = s;
  542. }
  543. getToken() {
  544. return Promise.resolve(new W(this.h, this.l, this.m, this.g));
  545. }
  546. start(t, e) {
  547. // Fire with initial uid.
  548. t.enqueueRetryable((() => e(v.FIRST_PARTY)));
  549. }
  550. shutdown() {}
  551. invalidateToken() {}
  552. }
  553. class H {
  554. constructor(t) {
  555. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  556. }
  557. }
  558. class J {
  559. constructor(t) {
  560. this.T = t, this.forceRefresh = !1, this.appCheck = null, this.A = null;
  561. }
  562. start(t, e) {
  563. const n = t => {
  564. null != t.error && x("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);
  565. const n = t.token !== this.A;
  566. return this.A = t.token, x("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`),
  567. n ? e(t.token) : Promise.resolve();
  568. };
  569. this.o = e => {
  570. t.enqueueRetryable((() => n(e)));
  571. };
  572. const s = t => {
  573. x("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = t, this.appCheck.addTokenListener(this.o);
  574. };
  575. this.T.onInit((t => s(t))),
  576. // Our users can initialize AppCheck after Firestore, so we give it
  577. // a chance to register itself with the component framework.
  578. setTimeout((() => {
  579. if (!this.appCheck) {
  580. const t = this.T.getImmediate({
  581. optional: !0
  582. });
  583. t ? s(t) :
  584. // If AppCheck is still not available, proceed without it.
  585. x("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
  586. }
  587. }), 0);
  588. }
  589. getToken() {
  590. const t = this.forceRefresh;
  591. return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (F("string" == typeof t.token),
  592. this.A = t.token, new H(t.token)) : null)) : Promise.resolve(null);
  593. }
  594. invalidateToken() {
  595. this.forceRefresh = !0;
  596. }
  597. shutdown() {
  598. this.appCheck && this.appCheck.removeTokenListener(this.o);
  599. }
  600. }
  601. /**
  602. * An AppCheck token provider that always yields an empty token.
  603. * @internal
  604. */ class Y {
  605. getToken() {
  606. return Promise.resolve(new H(""));
  607. }
  608. invalidateToken() {}
  609. start(t, e) {}
  610. shutdown() {}
  611. }
  612. /**
  613. * Builds a CredentialsProvider depending on the type of
  614. * the credentials passed in.
  615. */
  616. /**
  617. * @license
  618. * Copyright 2020 Google LLC
  619. *
  620. * Licensed under the Apache License, Version 2.0 (the "License");
  621. * you may not use this file except in compliance with the License.
  622. * You may obtain a copy of the License at
  623. *
  624. * http://www.apache.org/licenses/LICENSE-2.0
  625. *
  626. * Unless required by applicable law or agreed to in writing, software
  627. * distributed under the License is distributed on an "AS IS" BASIS,
  628. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  629. * See the License for the specific language governing permissions and
  630. * limitations under the License.
  631. */
  632. /**
  633. * Generates `nBytes` of random bytes.
  634. *
  635. * If `nBytes < 0` , an error will be thrown.
  636. */
  637. function X(t) {
  638. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  639. const e =
  640. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  641. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  642. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  643. // Falls back to Math.random
  644. for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
  645. return n;
  646. }
  647. /**
  648. * @license
  649. * Copyright 2017 Google LLC
  650. *
  651. * Licensed under the Apache License, Version 2.0 (the "License");
  652. * you may not use this file except in compliance with the License.
  653. * You may obtain a copy of the License at
  654. *
  655. * http://www.apache.org/licenses/LICENSE-2.0
  656. *
  657. * Unless required by applicable law or agreed to in writing, software
  658. * distributed under the License is distributed on an "AS IS" BASIS,
  659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  660. * See the License for the specific language governing permissions and
  661. * limitations under the License.
  662. */ class Z {
  663. static R() {
  664. // Alphanumeric characters
  665. const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
  666. // The largest byte value that is a multiple of `char.length`.
  667. let n = "";
  668. for (;n.length < 20; ) {
  669. const s = X(40);
  670. for (let i = 0; i < s.length; ++i)
  671. // Only accept values that are [0, maxMultiple), this ensures they can
  672. // be evenly mapped to indices of `chars` via a modulo operation.
  673. n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));
  674. }
  675. return n;
  676. }
  677. }
  678. function tt(t, e) {
  679. return t < e ? -1 : t > e ? 1 : 0;
  680. }
  681. /** Helper to compare arrays using isEqual(). */ function et(t, e, n) {
  682. return t.length === e.length && t.every(((t, s) => n(t, e[s])));
  683. }
  684. /**
  685. * Returns the immediate lexicographically-following string. This is useful to
  686. * construct an inclusive range for indexeddb iterators.
  687. */ function nt(t) {
  688. // Return the input string, with an additional NUL byte appended.
  689. return t + "\0";
  690. }
  691. /**
  692. * @license
  693. * Copyright 2017 Google LLC
  694. *
  695. * Licensed under the Apache License, Version 2.0 (the "License");
  696. * you may not use this file except in compliance with the License.
  697. * You may obtain a copy of the License at
  698. *
  699. * http://www.apache.org/licenses/LICENSE-2.0
  700. *
  701. * Unless required by applicable law or agreed to in writing, software
  702. * distributed under the License is distributed on an "AS IS" BASIS,
  703. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  704. * See the License for the specific language governing permissions and
  705. * limitations under the License.
  706. */
  707. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  708. /**
  709. * A `Timestamp` represents a point in time independent of any time zone or
  710. * calendar, represented as seconds and fractions of seconds at nanosecond
  711. * resolution in UTC Epoch time.
  712. *
  713. * It is encoded using the Proleptic Gregorian Calendar which extends the
  714. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  715. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  716. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  717. * 9999-12-31T23:59:59.999999999Z.
  718. *
  719. * For examples and further specifications, refer to the
  720. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  721. */
  722. class st {
  723. /**
  724. * Creates a new timestamp.
  725. *
  726. * @param seconds - The number of seconds of UTC time since Unix epoch
  727. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  728. * 9999-12-31T23:59:59Z inclusive.
  729. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  730. * resolution. Negative second values with fractions must still have
  731. * non-negative nanoseconds values that count forward in time. Must be
  732. * from 0 to 999,999,999 inclusive.
  733. */
  734. constructor(
  735. /**
  736. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  737. */
  738. t,
  739. /**
  740. * The fractions of a second at nanosecond resolution.*
  741. */
  742. e) {
  743. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new q(L.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  744. if (e >= 1e9) throw new q(L.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  745. if (t < -62135596800) throw new q(L.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  746. // This will break in the year 10,000.
  747. if (t >= 253402300800) throw new q(L.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  748. }
  749. /**
  750. * Creates a new timestamp with the current date, with millisecond precision.
  751. *
  752. * @returns a new timestamp representing the current date.
  753. */ static now() {
  754. return st.fromMillis(Date.now());
  755. }
  756. /**
  757. * Creates a new timestamp from the given date.
  758. *
  759. * @param date - The date to initialize the `Timestamp` from.
  760. * @returns A new `Timestamp` representing the same point in time as the given
  761. * date.
  762. */ static fromDate(t) {
  763. return st.fromMillis(t.getTime());
  764. }
  765. /**
  766. * Creates a new timestamp from the given number of milliseconds.
  767. *
  768. * @param milliseconds - Number of milliseconds since Unix epoch
  769. * 1970-01-01T00:00:00Z.
  770. * @returns A new `Timestamp` representing the same point in time as the given
  771. * number of milliseconds.
  772. */ static fromMillis(t) {
  773. const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
  774. return new st(e, n);
  775. }
  776. /**
  777. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  778. * causes a loss of precision since `Date` objects only support millisecond
  779. * precision.
  780. *
  781. * @returns JavaScript `Date` object representing the same point in time as
  782. * this `Timestamp`, with millisecond precision.
  783. */ toDate() {
  784. return new Date(this.toMillis());
  785. }
  786. /**
  787. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  788. * epoch). This operation causes a loss of precision.
  789. *
  790. * @returns The point in time corresponding to this timestamp, represented as
  791. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  792. */ toMillis() {
  793. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  794. }
  795. _compareTo(t) {
  796. return this.seconds === t.seconds ? tt(this.nanoseconds, t.nanoseconds) : tt(this.seconds, t.seconds);
  797. }
  798. /**
  799. * Returns true if this `Timestamp` is equal to the provided one.
  800. *
  801. * @param other - The `Timestamp` to compare against.
  802. * @returns true if this `Timestamp` is equal to the provided one.
  803. */ isEqual(t) {
  804. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  805. }
  806. /** Returns a textual representation of this `Timestamp`. */ toString() {
  807. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  808. }
  809. /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
  810. return {
  811. seconds: this.seconds,
  812. nanoseconds: this.nanoseconds
  813. };
  814. }
  815. /**
  816. * Converts this object to a primitive string, which allows `Timestamp` objects
  817. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  818. */ valueOf() {
  819. // This method returns a string of the form <seconds>.<nanoseconds> where
  820. // <seconds> is translated to have a non-negative value and both <seconds>
  821. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  822. // Strings with this format then have a lexiographical ordering that matches
  823. // the expected ordering. The <seconds> translation is done to avoid having
  824. // a leading negative sign (i.e. a leading '-' character) in its string
  825. // representation, which would affect its lexiographical ordering.
  826. const t = this.seconds - -62135596800;
  827. // Note: Up to 12 decimal digits are required to represent all valid
  828. // 'seconds' values.
  829. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  830. }
  831. }
  832. /**
  833. * @license
  834. * Copyright 2017 Google LLC
  835. *
  836. * Licensed under the Apache License, Version 2.0 (the "License");
  837. * you may not use this file except in compliance with the License.
  838. * You may obtain a copy of the License at
  839. *
  840. * http://www.apache.org/licenses/LICENSE-2.0
  841. *
  842. * Unless required by applicable law or agreed to in writing, software
  843. * distributed under the License is distributed on an "AS IS" BASIS,
  844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  845. * See the License for the specific language governing permissions and
  846. * limitations under the License.
  847. */
  848. /**
  849. * A version of a document in Firestore. This corresponds to the version
  850. * timestamp, such as update_time or read_time.
  851. */ class it {
  852. constructor(t) {
  853. this.timestamp = t;
  854. }
  855. static fromTimestamp(t) {
  856. return new it(t);
  857. }
  858. static min() {
  859. return new it(new st(0, 0));
  860. }
  861. static max() {
  862. return new it(new st(253402300799, 999999999));
  863. }
  864. compareTo(t) {
  865. return this.timestamp._compareTo(t.timestamp);
  866. }
  867. isEqual(t) {
  868. return this.timestamp.isEqual(t.timestamp);
  869. }
  870. /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
  871. // Convert to microseconds.
  872. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  873. }
  874. toString() {
  875. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  876. }
  877. toTimestamp() {
  878. return this.timestamp;
  879. }
  880. }
  881. /**
  882. * @license
  883. * Copyright 2017 Google LLC
  884. *
  885. * Licensed under the Apache License, Version 2.0 (the "License");
  886. * you may not use this file except in compliance with the License.
  887. * You may obtain a copy of the License at
  888. *
  889. * http://www.apache.org/licenses/LICENSE-2.0
  890. *
  891. * Unless required by applicable law or agreed to in writing, software
  892. * distributed under the License is distributed on an "AS IS" BASIS,
  893. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  894. * See the License for the specific language governing permissions and
  895. * limitations under the License.
  896. */
  897. /**
  898. * Path represents an ordered sequence of string segments.
  899. */
  900. class rt {
  901. constructor(t, e, n) {
  902. void 0 === e ? e = 0 : e > t.length && M(), void 0 === n ? n = t.length - e : n > t.length - e && M(),
  903. this.segments = t, this.offset = e, this.len = n;
  904. }
  905. get length() {
  906. return this.len;
  907. }
  908. isEqual(t) {
  909. return 0 === rt.comparator(this, t);
  910. }
  911. child(t) {
  912. const e = this.segments.slice(this.offset, this.limit());
  913. return t instanceof rt ? t.forEach((t => {
  914. e.push(t);
  915. })) : e.push(t), this.construct(e);
  916. }
  917. /** The index of one past the last segment of the path. */ limit() {
  918. return this.offset + this.length;
  919. }
  920. popFirst(t) {
  921. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  922. }
  923. popLast() {
  924. return this.construct(this.segments, this.offset, this.length - 1);
  925. }
  926. firstSegment() {
  927. return this.segments[this.offset];
  928. }
  929. lastSegment() {
  930. return this.get(this.length - 1);
  931. }
  932. get(t) {
  933. return this.segments[this.offset + t];
  934. }
  935. isEmpty() {
  936. return 0 === this.length;
  937. }
  938. isPrefixOf(t) {
  939. if (t.length < this.length) return !1;
  940. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  941. return !0;
  942. }
  943. isImmediateParentOf(t) {
  944. if (this.length + 1 !== t.length) return !1;
  945. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  946. return !0;
  947. }
  948. forEach(t) {
  949. for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  950. }
  951. toArray() {
  952. return this.segments.slice(this.offset, this.limit());
  953. }
  954. static comparator(t, e) {
  955. const n = Math.min(t.length, e.length);
  956. for (let s = 0; s < n; s++) {
  957. const n = t.get(s), i = e.get(s);
  958. if (n < i) return -1;
  959. if (n > i) return 1;
  960. }
  961. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  962. }
  963. }
  964. /**
  965. * A slash-separated path for navigating resources (documents and collections)
  966. * within Firestore.
  967. *
  968. * @internal
  969. */ class ot extends rt {
  970. construct(t, e, n) {
  971. return new ot(t, e, n);
  972. }
  973. canonicalString() {
  974. // NOTE: The client is ignorant of any path segments containing escape
  975. // sequences (e.g. __id123__) and just passes them through raw (they exist
  976. // for legacy reasons and should not be used frequently).
  977. return this.toArray().join("/");
  978. }
  979. toString() {
  980. return this.canonicalString();
  981. }
  982. /**
  983. * Creates a resource path from the given slash-delimited string. If multiple
  984. * arguments are provided, all components are combined. Leading and trailing
  985. * slashes from all components are ignored.
  986. */ static fromString(...t) {
  987. // NOTE: The client is ignorant of any path segments containing escape
  988. // sequences (e.g. __id123__) and just passes them through raw (they exist
  989. // for legacy reasons and should not be used frequently).
  990. const e = [];
  991. for (const n of t) {
  992. if (n.indexOf("//") >= 0) throw new q(L.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
  993. // Strip leading and traling slashed.
  994. e.push(...n.split("/").filter((t => t.length > 0)));
  995. }
  996. return new ot(e);
  997. }
  998. static emptyPath() {
  999. return new ot([]);
  1000. }
  1001. }
  1002. const ut = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  1003. /**
  1004. * A dot-separated path for navigating sub-objects within a document.
  1005. * @internal
  1006. */ class ct extends rt {
  1007. construct(t, e, n) {
  1008. return new ct(t, e, n);
  1009. }
  1010. /**
  1011. * Returns true if the string could be used as a segment in a field path
  1012. * without escaping.
  1013. */ static isValidIdentifier(t) {
  1014. return ut.test(t);
  1015. }
  1016. canonicalString() {
  1017. return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"),
  1018. ct.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join(".");
  1019. }
  1020. toString() {
  1021. return this.canonicalString();
  1022. }
  1023. /**
  1024. * Returns true if this field references the key of a document.
  1025. */ isKeyField() {
  1026. return 1 === this.length && "__name__" === this.get(0);
  1027. }
  1028. /**
  1029. * The field designating the key of a document.
  1030. */ static keyField() {
  1031. return new ct([ "__name__" ]);
  1032. }
  1033. /**
  1034. * Parses a field string from the given server-formatted string.
  1035. *
  1036. * - Splitting the empty string is not allowed (for now at least).
  1037. * - Empty segments within the string (e.g. if there are two consecutive
  1038. * separators) are not allowed.
  1039. *
  1040. * TODO(b/37244157): we should make this more strict. Right now, it allows
  1041. * non-identifier path components, even if they aren't escaped.
  1042. */ static fromServerFormat(t) {
  1043. const e = [];
  1044. let n = "", s = 0;
  1045. const i = () => {
  1046. if (0 === n.length) throw new q(L.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
  1047. e.push(n), n = "";
  1048. };
  1049. let r = !1;
  1050. for (;s < t.length; ) {
  1051. const e = t[s];
  1052. if ("\\" === e) {
  1053. if (s + 1 === t.length) throw new q(L.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
  1054. const e = t[s + 1];
  1055. if ("\\" !== e && "." !== e && "`" !== e) throw new q(L.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
  1056. n += e, s += 2;
  1057. } else "`" === e ? (r = !r, s++) : "." !== e || r ? (n += e, s++) : (i(), s++);
  1058. }
  1059. if (i(), r) throw new q(L.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
  1060. return new ct(e);
  1061. }
  1062. static emptyPath() {
  1063. return new ct([]);
  1064. }
  1065. }
  1066. /**
  1067. * @license
  1068. * Copyright 2017 Google LLC
  1069. *
  1070. * Licensed under the Apache License, Version 2.0 (the "License");
  1071. * you may not use this file except in compliance with the License.
  1072. * You may obtain a copy of the License at
  1073. *
  1074. * http://www.apache.org/licenses/LICENSE-2.0
  1075. *
  1076. * Unless required by applicable law or agreed to in writing, software
  1077. * distributed under the License is distributed on an "AS IS" BASIS,
  1078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1079. * See the License for the specific language governing permissions and
  1080. * limitations under the License.
  1081. */
  1082. /**
  1083. * @internal
  1084. */ class at {
  1085. constructor(t) {
  1086. this.path = t;
  1087. }
  1088. static fromPath(t) {
  1089. return new at(ot.fromString(t));
  1090. }
  1091. static fromName(t) {
  1092. return new at(ot.fromString(t).popFirst(5));
  1093. }
  1094. static empty() {
  1095. return new at(ot.emptyPath());
  1096. }
  1097. get collectionGroup() {
  1098. return this.path.popLast().lastSegment();
  1099. }
  1100. /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
  1101. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  1102. }
  1103. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {
  1104. return this.path.get(this.path.length - 2);
  1105. }
  1106. /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {
  1107. return this.path.popLast();
  1108. }
  1109. isEqual(t) {
  1110. return null !== t && 0 === ot.comparator(this.path, t.path);
  1111. }
  1112. toString() {
  1113. return this.path.toString();
  1114. }
  1115. static comparator(t, e) {
  1116. return ot.comparator(t.path, e.path);
  1117. }
  1118. static isDocumentKey(t) {
  1119. return t.length % 2 == 0;
  1120. }
  1121. /**
  1122. * Creates and returns a new document key with the given segments.
  1123. *
  1124. * @param segments - The segments of the path to the document
  1125. * @returns A new instance of DocumentKey
  1126. */ static fromSegments(t) {
  1127. return new at(new ot(t.slice()));
  1128. }
  1129. }
  1130. /**
  1131. * @license
  1132. * Copyright 2021 Google LLC
  1133. *
  1134. * Licensed under the Apache License, Version 2.0 (the "License");
  1135. * you may not use this file except in compliance with the License.
  1136. * You may obtain a copy of the License at
  1137. *
  1138. * http://www.apache.org/licenses/LICENSE-2.0
  1139. *
  1140. * Unless required by applicable law or agreed to in writing, software
  1141. * distributed under the License is distributed on an "AS IS" BASIS,
  1142. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1143. * See the License for the specific language governing permissions and
  1144. * limitations under the License.
  1145. */
  1146. /**
  1147. * The initial mutation batch id for each index. Gets updated during index
  1148. * backfill.
  1149. */
  1150. /**
  1151. * An index definition for field indexes in Firestore.
  1152. *
  1153. * Every index is associated with a collection. The definition contains a list
  1154. * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
  1155. * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
  1156. *
  1157. * Unlike the backend, the SDK does not differentiate between collection or
  1158. * collection group-scoped indices. Every index can be used for both single
  1159. * collection and collection group queries.
  1160. */
  1161. class ht {
  1162. constructor(
  1163. /**
  1164. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1165. * has not yet been persisted).
  1166. */
  1167. t,
  1168. /** The collection ID this index applies to. */
  1169. e,
  1170. /** The field segments for this index. */
  1171. n,
  1172. /** Shows how up-to-date the index is for the current user. */
  1173. s) {
  1174. this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;
  1175. }
  1176. }
  1177. /** An ID for an index that has not yet been added to persistence. */
  1178. /** Returns the ArrayContains/ArrayContainsAny segment for this index. */
  1179. function lt(t) {
  1180. return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));
  1181. }
  1182. /** Returns all directional (ascending/descending) segments for this index. */ function ft(t) {
  1183. return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));
  1184. }
  1185. /**
  1186. * Returns the order of the document key component for the given index.
  1187. *
  1188. * PORTING NOTE: This is only used in the Web IndexedDb implementation.
  1189. */
  1190. /**
  1191. * Compares indexes by collection group and segments. Ignores update time and
  1192. * index ID.
  1193. */
  1194. function dt(t, e) {
  1195. let n = tt(t.collectionGroup, e.collectionGroup);
  1196. if (0 !== n) return n;
  1197. for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = wt(t.fields[s], e.fields[s]),
  1198. 0 !== n) return n;
  1199. return tt(t.fields.length, e.fields.length);
  1200. }
  1201. /** Returns a debug representation of the field index */ ht.UNKNOWN_ID = -1;
  1202. /** An index component consisting of field path and index type. */
  1203. class _t {
  1204. constructor(
  1205. /** The field path of the component. */
  1206. t,
  1207. /** The fields sorting order. */
  1208. e) {
  1209. this.fieldPath = t, this.kind = e;
  1210. }
  1211. }
  1212. function wt(t, e) {
  1213. const n = ct.comparator(t.fieldPath, e.fieldPath);
  1214. return 0 !== n ? n : tt(t.kind, e.kind);
  1215. }
  1216. /**
  1217. * Stores the "high water mark" that indicates how updated the Index is for the
  1218. * current user.
  1219. */ class mt {
  1220. constructor(
  1221. /**
  1222. * Indicates when the index was last updated (relative to other indexes).
  1223. */
  1224. t,
  1225. /** The the latest indexed read time, document and batch id. */
  1226. e) {
  1227. this.sequenceNumber = t, this.offset = e;
  1228. }
  1229. /** The state of an index that has not yet been backfilled. */ static empty() {
  1230. return new mt(0, pt.min());
  1231. }
  1232. }
  1233. /**
  1234. * Creates an offset that matches all documents with a read time higher than
  1235. * `readTime`.
  1236. */ function gt(t, e) {
  1237. // We want to create an offset that matches all documents with a read time
  1238. // greater than the provided read time. To do so, we technically need to
  1239. // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
  1240. // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
  1241. // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
  1242. // all valid document IDs.
  1243. const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = it.fromTimestamp(1e9 === s ? new st(n + 1, 0) : new st(n, s));
  1244. return new pt(i, at.empty(), e);
  1245. }
  1246. /** Creates a new offset based on the provided document. */ function yt(t) {
  1247. return new pt(t.readTime, t.key, -1);
  1248. }
  1249. /**
  1250. * Stores the latest read time, document and batch ID that were processed for an
  1251. * index.
  1252. */ class pt {
  1253. constructor(
  1254. /**
  1255. * The latest read time version that has been indexed by Firestore for this
  1256. * field index.
  1257. */
  1258. t,
  1259. /**
  1260. * The key of the last document that was indexed for this query. Use
  1261. * `DocumentKey.empty()` if no document has been indexed.
  1262. */
  1263. e,
  1264. /*
  1265. * The largest mutation batch id that's been processed by Firestore.
  1266. */
  1267. n) {
  1268. this.readTime = t, this.documentKey = e, this.largestBatchId = n;
  1269. }
  1270. /** Returns an offset that sorts before all regular offsets. */ static min() {
  1271. return new pt(it.min(), at.empty(), -1);
  1272. }
  1273. /** Returns an offset that sorts after all regular offsets. */ static max() {
  1274. return new pt(it.max(), at.empty(), -1);
  1275. }
  1276. }
  1277. function It(t, e) {
  1278. let n = t.readTime.compareTo(e.readTime);
  1279. return 0 !== n ? n : (n = at.comparator(t.documentKey, e.documentKey), 0 !== n ? n : tt(t.largestBatchId, e.largestBatchId));
  1280. }
  1281. /**
  1282. * @license
  1283. * Copyright 2020 Google LLC
  1284. *
  1285. * Licensed under the Apache License, Version 2.0 (the "License");
  1286. * you may not use this file except in compliance with the License.
  1287. * You may obtain a copy of the License at
  1288. *
  1289. * http://www.apache.org/licenses/LICENSE-2.0
  1290. *
  1291. * Unless required by applicable law or agreed to in writing, software
  1292. * distributed under the License is distributed on an "AS IS" BASIS,
  1293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1294. * See the License for the specific language governing permissions and
  1295. * limitations under the License.
  1296. */ const Tt = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";
  1297. /**
  1298. * A base class representing a persistence transaction, encapsulating both the
  1299. * transaction's sequence numbers as well as a list of onCommitted listeners.
  1300. *
  1301. * When you call Persistence.runTransaction(), it will create a transaction and
  1302. * pass it to your callback. You then pass it to any method that operates
  1303. * on persistence.
  1304. */ class Et {
  1305. constructor() {
  1306. this.onCommittedListeners = [];
  1307. }
  1308. addOnCommittedListener(t) {
  1309. this.onCommittedListeners.push(t);
  1310. }
  1311. raiseOnCommittedEvent() {
  1312. this.onCommittedListeners.forEach((t => t()));
  1313. }
  1314. }
  1315. /**
  1316. * @license
  1317. * Copyright 2017 Google LLC
  1318. *
  1319. * Licensed under the Apache License, Version 2.0 (the "License");
  1320. * you may not use this file except in compliance with the License.
  1321. * You may obtain a copy of the License at
  1322. *
  1323. * http://www.apache.org/licenses/LICENSE-2.0
  1324. *
  1325. * Unless required by applicable law or agreed to in writing, software
  1326. * distributed under the License is distributed on an "AS IS" BASIS,
  1327. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1328. * See the License for the specific language governing permissions and
  1329. * limitations under the License.
  1330. */
  1331. /**
  1332. * Verifies the error thrown by a LocalStore operation. If a LocalStore
  1333. * operation fails because the primary lease has been taken by another client,
  1334. * we ignore the error (the persistence layer will immediately call
  1335. * `applyPrimaryLease` to propagate the primary state change). All other errors
  1336. * are re-thrown.
  1337. *
  1338. * @param err - An error returned by a LocalStore operation.
  1339. * @returns A Promise that resolves after we recovered, or the original error.
  1340. */ async function At(t) {
  1341. if (t.code !== L.FAILED_PRECONDITION || t.message !== Tt) throw t;
  1342. x("LocalStore", "Unexpectedly lost primary lease");
  1343. }
  1344. /**
  1345. * @license
  1346. * Copyright 2017 Google LLC
  1347. *
  1348. * Licensed under the Apache License, Version 2.0 (the "License");
  1349. * you may not use this file except in compliance with the License.
  1350. * You may obtain a copy of the License at
  1351. *
  1352. * http://www.apache.org/licenses/LICENSE-2.0
  1353. *
  1354. * Unless required by applicable law or agreed to in writing, software
  1355. * distributed under the License is distributed on an "AS IS" BASIS,
  1356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1357. * See the License for the specific language governing permissions and
  1358. * limitations under the License.
  1359. */
  1360. /**
  1361. * PersistencePromise is essentially a re-implementation of Promise except
  1362. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  1363. * are executed synchronously when a PersistencePromise resolves rather than
  1364. * asynchronously (Promise implementations use setImmediate() or similar).
  1365. *
  1366. * This is necessary to interoperate with IndexedDB which will automatically
  1367. * commit transactions if control is returned to the event loop without
  1368. * synchronously initiating another operation on the transaction.
  1369. *
  1370. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  1371. * Promises.
  1372. */ class Rt {
  1373. constructor(t) {
  1374. // NOTE: next/catchCallback will always point to our own wrapper functions,
  1375. // not the user's raw next() or catch() callbacks.
  1376. this.nextCallback = null, this.catchCallback = null,
  1377. // When the operation resolves, we'll set result or error and mark isDone.
  1378. this.result = void 0, this.error = void 0, this.isDone = !1,
  1379. // Set to true when .then() or .catch() are called and prevents additional
  1380. // chaining.
  1381. this.callbackAttached = !1, t((t => {
  1382. this.isDone = !0, this.result = t, this.nextCallback &&
  1383. // value should be defined unless T is Void, but we can't express
  1384. // that in the type system.
  1385. this.nextCallback(t);
  1386. }), (t => {
  1387. this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);
  1388. }));
  1389. }
  1390. catch(t) {
  1391. return this.next(void 0, t);
  1392. }
  1393. next(t, e) {
  1394. return this.callbackAttached && M(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new Rt(((n, s) => {
  1395. this.nextCallback = e => {
  1396. this.wrapSuccess(t, e).next(n, s);
  1397. }, this.catchCallback = t => {
  1398. this.wrapFailure(e, t).next(n, s);
  1399. };
  1400. }));
  1401. }
  1402. toPromise() {
  1403. return new Promise(((t, e) => {
  1404. this.next(t, e);
  1405. }));
  1406. }
  1407. wrapUserFunction(t) {
  1408. try {
  1409. const e = t();
  1410. return e instanceof Rt ? e : Rt.resolve(e);
  1411. } catch (t) {
  1412. return Rt.reject(t);
  1413. }
  1414. }
  1415. wrapSuccess(t, e) {
  1416. return t ? this.wrapUserFunction((() => t(e))) : Rt.resolve(e);
  1417. }
  1418. wrapFailure(t, e) {
  1419. return t ? this.wrapUserFunction((() => t(e))) : Rt.reject(e);
  1420. }
  1421. static resolve(t) {
  1422. return new Rt(((e, n) => {
  1423. e(t);
  1424. }));
  1425. }
  1426. static reject(t) {
  1427. return new Rt(((e, n) => {
  1428. n(t);
  1429. }));
  1430. }
  1431. static waitFor(
  1432. // Accept all Promise types in waitFor().
  1433. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1434. t) {
  1435. return new Rt(((e, n) => {
  1436. let s = 0, i = 0, r = !1;
  1437. t.forEach((t => {
  1438. ++s, t.next((() => {
  1439. ++i, r && i === s && e();
  1440. }), (t => n(t)));
  1441. })), r = !0, i === s && e();
  1442. }));
  1443. }
  1444. /**
  1445. * Given an array of predicate functions that asynchronously evaluate to a
  1446. * boolean, implements a short-circuiting `or` between the results. Predicates
  1447. * will be evaluated until one of them returns `true`, then stop. The final
  1448. * result will be whether any of them returned `true`.
  1449. */ static or(t) {
  1450. let e = Rt.resolve(!1);
  1451. for (const n of t) e = e.next((t => t ? Rt.resolve(t) : n()));
  1452. return e;
  1453. }
  1454. static forEach(t, e) {
  1455. const n = [];
  1456. return t.forEach(((t, s) => {
  1457. n.push(e.call(this, t, s));
  1458. })), this.waitFor(n);
  1459. }
  1460. /**
  1461. * Concurrently map all array elements through asynchronous function.
  1462. */ static mapArray(t, e) {
  1463. return new Rt(((n, s) => {
  1464. const i = t.length, r = new Array(i);
  1465. let o = 0;
  1466. for (let u = 0; u < i; u++) {
  1467. const c = u;
  1468. e(t[c]).next((t => {
  1469. r[c] = t, ++o, o === i && n(r);
  1470. }), (t => s(t)));
  1471. }
  1472. }));
  1473. }
  1474. /**
  1475. * An alternative to recursive PersistencePromise calls, that avoids
  1476. * potential memory problems from unbounded chains of promises.
  1477. *
  1478. * The `action` will be called repeatedly while `condition` is true.
  1479. */ static doWhile(t, e) {
  1480. return new Rt(((n, s) => {
  1481. const i = () => {
  1482. !0 === t() ? e().next((() => {
  1483. i();
  1484. }), s) : n();
  1485. };
  1486. i();
  1487. }));
  1488. }
  1489. }
  1490. /**
  1491. * @license
  1492. * Copyright 2017 Google LLC
  1493. *
  1494. * Licensed under the Apache License, Version 2.0 (the "License");
  1495. * you may not use this file except in compliance with the License.
  1496. * You may obtain a copy of the License at
  1497. *
  1498. * http://www.apache.org/licenses/LICENSE-2.0
  1499. *
  1500. * Unless required by applicable law or agreed to in writing, software
  1501. * distributed under the License is distributed on an "AS IS" BASIS,
  1502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1503. * See the License for the specific language governing permissions and
  1504. * limitations under the License.
  1505. */
  1506. // References to `window` are guarded by SimpleDb.isAvailable()
  1507. /* eslint-disable no-restricted-globals */
  1508. /**
  1509. * Wraps an IDBTransaction and exposes a store() method to get a handle to a
  1510. * specific object store.
  1511. */
  1512. class bt {
  1513. constructor(t, e) {
  1514. this.action = t, this.transaction = e, this.aborted = !1,
  1515. /**
  1516. * A `Promise` that resolves with the result of the IndexedDb transaction.
  1517. */
  1518. this.P = new U, this.transaction.oncomplete = () => {
  1519. this.P.resolve();
  1520. }, this.transaction.onabort = () => {
  1521. e.error ? this.P.reject(new Vt(t, e.error)) : this.P.resolve();
  1522. }, this.transaction.onerror = e => {
  1523. const n = Nt(e.target.error);
  1524. this.P.reject(new Vt(t, n));
  1525. };
  1526. }
  1527. static open(t, e, n, s) {
  1528. try {
  1529. return new bt(e, t.transaction(s, n));
  1530. } catch (t) {
  1531. throw new Vt(e, t);
  1532. }
  1533. }
  1534. get v() {
  1535. return this.P.promise;
  1536. }
  1537. abort(t) {
  1538. t && this.P.reject(t), this.aborted || (x("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"),
  1539. this.aborted = !0, this.transaction.abort());
  1540. }
  1541. V() {
  1542. // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
  1543. // speed up index DB processing if the event loop remains blocks.
  1544. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1545. const t = this.transaction;
  1546. this.aborted || "function" != typeof t.commit || t.commit();
  1547. }
  1548. /**
  1549. * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
  1550. * operations performed on the SimpleDbStore happen within the context of this
  1551. * transaction and it cannot be used anymore once the transaction is
  1552. * completed.
  1553. *
  1554. * Note that we can't actually enforce that the KeyType and ValueType are
  1555. * correct, but they allow type safety through the rest of the consuming code.
  1556. */ store(t) {
  1557. const e = this.transaction.objectStore(t);
  1558. return new Dt(e);
  1559. }
  1560. }
  1561. /**
  1562. * Provides a wrapper around IndexedDb with a simplified interface that uses
  1563. * Promise-like return values to chain operations. Real promises cannot be used
  1564. * since .then() continuations are executed asynchronously (e.g. via
  1565. * .setImmediate), which would cause IndexedDB to end the transaction.
  1566. * See PersistencePromise for more details.
  1567. */ class Pt {
  1568. /*
  1569. * Creates a new SimpleDb wrapper for IndexedDb database `name`.
  1570. *
  1571. * Note that `version` must not be a downgrade. IndexedDB does not support
  1572. * downgrading the schema version. We currently do not support any way to do
  1573. * versioning outside of IndexedDB's versioning mechanism, as only
  1574. * version-upgrade transactions are allowed to do things like create
  1575. * objectstores.
  1576. */
  1577. constructor(t, e, n) {
  1578. this.name = t, this.version = e, this.S = n;
  1579. // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
  1580. // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
  1581. // whatever reason it's much harder to hit after 12.2 so we only proactively
  1582. // log on 12.2.
  1583. 12.2 === Pt.D(a()) && N("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");
  1584. }
  1585. /** Deletes the specified database. */ static delete(t) {
  1586. return x("SimpleDb", "Removing database:", t), Ct(window.indexedDB.deleteDatabase(t)).toPromise();
  1587. }
  1588. /** Returns true if IndexedDB is available in the current environment. */ static C() {
  1589. if (!h()) return !1;
  1590. if (Pt.N()) return !0;
  1591. // We extensively use indexed array values and compound keys,
  1592. // which IE and Edge do not support. However, they still have indexedDB
  1593. // defined on the window, so we need to check for them here and make sure
  1594. // to return that persistence is not enabled for those browsers.
  1595. // For tracking support of this feature, see here:
  1596. // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
  1597. // Check the UA string to find out the browser.
  1598. const t = a(), e = Pt.D(t), n = 0 < e && e < 10, s = Pt.k(t), i = 0 < s && s < 4.5;
  1599. // IE 10
  1600. // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
  1601. // IE 11
  1602. // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
  1603. // Edge
  1604. // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
  1605. // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
  1606. // iOS Safari: Disable for users running iOS version < 10.
  1607. return !(t.indexOf("MSIE ") > 0 || t.indexOf("Trident/") > 0 || t.indexOf("Edge/") > 0 || n || i);
  1608. }
  1609. /**
  1610. * Returns true if the backing IndexedDB store is the Node IndexedDBShim
  1611. * (see https://github.com/axemclion/IndexedDBShim).
  1612. */ static N() {
  1613. var t;
  1614. return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.O);
  1615. }
  1616. /** Helper to get a typed SimpleDbStore from a transaction. */ static M(t, e) {
  1617. return t.store(e);
  1618. }
  1619. // visible for testing
  1620. /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  1621. static D(t) {
  1622. const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
  1623. return Number(n);
  1624. }
  1625. // visible for testing
  1626. /** Parse User Agent to determine Android version. Returns -1 if not found. */
  1627. static k(t) {
  1628. const e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
  1629. return Number(n);
  1630. }
  1631. /**
  1632. * Opens the specified database, creating or upgrading it if necessary.
  1633. */ async F(t) {
  1634. return this.db || (x("SimpleDb", "Opening database:", this.name), this.db = await new Promise(((e, n) => {
  1635. // TODO(mikelehen): Investigate browser compatibility.
  1636. // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  1637. // suggests IE9 and older WebKit browsers handle upgrade
  1638. // differently. They expect setVersion, as described here:
  1639. // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
  1640. const s = indexedDB.open(this.name, this.version);
  1641. s.onsuccess = t => {
  1642. const n = t.target.result;
  1643. e(n);
  1644. }, s.onblocked = () => {
  1645. n(new Vt(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
  1646. }, s.onerror = e => {
  1647. const s = e.target.error;
  1648. "VersionError" === s.name ? n(new q(L.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === s.name ? n(new q(L.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + s)) : n(new Vt(t, s));
  1649. }, s.onupgradeneeded = t => {
  1650. x("SimpleDb", 'Database "' + this.name + '" requires upgrade from version:', t.oldVersion);
  1651. const e = t.target.result;
  1652. this.S.$(e, s.transaction, t.oldVersion, this.version).next((() => {
  1653. x("SimpleDb", "Database upgrade to version " + this.version + " complete");
  1654. }));
  1655. };
  1656. }))), this.B && (this.db.onversionchange = t => this.B(t)), this.db;
  1657. }
  1658. L(t) {
  1659. this.B = t, this.db && (this.db.onversionchange = e => t(e));
  1660. }
  1661. async runTransaction(t, e, n, s) {
  1662. const i = "readonly" === e;
  1663. let r = 0;
  1664. for (;;) {
  1665. ++r;
  1666. try {
  1667. this.db = await this.F(t);
  1668. const e = bt.open(this.db, t, i ? "readonly" : "readwrite", n), r = s(e).next((t => (e.V(),
  1669. t))).catch((t => (
  1670. // Abort the transaction if there was an error.
  1671. e.abort(t), Rt.reject(t)))).toPromise();
  1672. // As noted above, errors are propagated by aborting the transaction. So
  1673. // we swallow any error here to avoid the browser logging it as unhandled.
  1674. return r.catch((() => {})),
  1675. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1676. // fire), but still return the original transactionFnResult back to the
  1677. // caller.
  1678. await e.v, r;
  1679. } catch (t) {
  1680. const e = t, n = "FirebaseError" !== e.name && r < 3;
  1681. // TODO(schmidt-sebastian): We could probably be smarter about this and
  1682. // not retry exceptions that are likely unrecoverable (such as quota
  1683. // exceeded errors).
  1684. // Note: We cannot use an instanceof check for FirestoreException, since the
  1685. // exception is wrapped in a generic error by our async/await handling.
  1686. if (x("SimpleDb", "Transaction failed with error:", e.message, "Retrying:", n),
  1687. this.close(), !n) return Promise.reject(e);
  1688. }
  1689. }
  1690. }
  1691. close() {
  1692. this.db && this.db.close(), this.db = void 0;
  1693. }
  1694. }
  1695. /**
  1696. * A controller for iterating over a key range or index. It allows an iterate
  1697. * callback to delete the currently-referenced object, or jump to a new key
  1698. * within the key range or index.
  1699. */ class vt {
  1700. constructor(t) {
  1701. this.q = t, this.U = !1, this.K = null;
  1702. }
  1703. get isDone() {
  1704. return this.U;
  1705. }
  1706. get G() {
  1707. return this.K;
  1708. }
  1709. set cursor(t) {
  1710. this.q = t;
  1711. }
  1712. /**
  1713. * This function can be called to stop iteration at any point.
  1714. */ done() {
  1715. this.U = !0;
  1716. }
  1717. /**
  1718. * This function can be called to skip to that next key, which could be
  1719. * an index or a primary key.
  1720. */ j(t) {
  1721. this.K = t;
  1722. }
  1723. /**
  1724. * Delete the current cursor value from the object store.
  1725. *
  1726. * NOTE: You CANNOT do this with a keysOnly query.
  1727. */ delete() {
  1728. return Ct(this.q.delete());
  1729. }
  1730. }
  1731. /** An error that wraps exceptions that thrown during IndexedDB execution. */ class Vt extends q {
  1732. constructor(t, e) {
  1733. super(L.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = "IndexedDbTransactionError";
  1734. }
  1735. }
  1736. /** Verifies whether `e` is an IndexedDbTransactionError. */ function St(t) {
  1737. // Use name equality, as instanceof checks on errors don't work with errors
  1738. // that wrap other errors.
  1739. return "IndexedDbTransactionError" === t.name;
  1740. }
  1741. /**
  1742. * A wrapper around an IDBObjectStore providing an API that:
  1743. *
  1744. * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
  1745. * methods for acting against the object store.
  1746. * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
  1747. * method return a PersistencePromise instead.
  1748. * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
  1749. * intermediate IndexedDB types (IDBCursorWithValue, etc.)
  1750. */ class Dt {
  1751. constructor(t) {
  1752. this.store = t;
  1753. }
  1754. put(t, e) {
  1755. let n;
  1756. return void 0 !== e ? (x("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : (x("SimpleDb", "PUT", this.store.name, "<auto-key>", t),
  1757. n = this.store.put(t)), Ct(n);
  1758. }
  1759. /**
  1760. * Adds a new value into an Object Store and returns the new key. Similar to
  1761. * IndexedDb's `add()`, this method will fail on primary key collisions.
  1762. *
  1763. * @param value - The object to write.
  1764. * @returns The key of the value to add.
  1765. */ add(t) {
  1766. x("SimpleDb", "ADD", this.store.name, t, t);
  1767. return Ct(this.store.add(t));
  1768. }
  1769. /**
  1770. * Gets the object with the specified key from the specified store, or null
  1771. * if no object exists with the specified key.
  1772. *
  1773. * @key The key of the object to get.
  1774. * @returns The object with the specified key or null if no object exists.
  1775. */ get(t) {
  1776. // We're doing an unsafe cast to ValueType.
  1777. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1778. return Ct(this.store.get(t)).next((e => (
  1779. // Normalize nonexistence to null.
  1780. void 0 === e && (e = null), x("SimpleDb", "GET", this.store.name, t, e), e)));
  1781. }
  1782. delete(t) {
  1783. x("SimpleDb", "DELETE", this.store.name, t);
  1784. return Ct(this.store.delete(t));
  1785. }
  1786. /**
  1787. * If we ever need more of the count variants, we can add overloads. For now,
  1788. * all we need is to count everything in a store.
  1789. *
  1790. * Returns the number of rows in the store.
  1791. */ count() {
  1792. x("SimpleDb", "COUNT", this.store.name);
  1793. return Ct(this.store.count());
  1794. }
  1795. W(t, e) {
  1796. const n = this.options(t, e);
  1797. // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
  1798. // 20% faster. Unfortunately, getAll() does not support custom indices.
  1799. if (n.index || "function" != typeof this.store.getAll) {
  1800. const t = this.cursor(n), e = [];
  1801. return this.H(t, ((t, n) => {
  1802. e.push(n);
  1803. })).next((() => e));
  1804. }
  1805. {
  1806. const t = this.store.getAll(n.range);
  1807. return new Rt(((e, n) => {
  1808. t.onerror = t => {
  1809. n(t.target.error);
  1810. }, t.onsuccess = t => {
  1811. e(t.target.result);
  1812. };
  1813. }));
  1814. }
  1815. }
  1816. /**
  1817. * Loads the first `count` elements from the provided index range. Loads all
  1818. * elements if no limit is provided.
  1819. */ J(t, e) {
  1820. const n = this.store.getAll(t, null === e ? void 0 : e);
  1821. return new Rt(((t, e) => {
  1822. n.onerror = t => {
  1823. e(t.target.error);
  1824. }, n.onsuccess = e => {
  1825. t(e.target.result);
  1826. };
  1827. }));
  1828. }
  1829. Y(t, e) {
  1830. x("SimpleDb", "DELETE ALL", this.store.name);
  1831. const n = this.options(t, e);
  1832. n.X = !1;
  1833. const s = this.cursor(n);
  1834. return this.H(s, ((t, e, n) => n.delete()));
  1835. }
  1836. Z(t, e) {
  1837. let n;
  1838. e ? n = t : (n = {}, e = t);
  1839. const s = this.cursor(n);
  1840. return this.H(s, e);
  1841. }
  1842. /**
  1843. * Iterates over a store, but waits for the given callback to complete for
  1844. * each entry before iterating the next entry. This allows the callback to do
  1845. * asynchronous work to determine if this iteration should continue.
  1846. *
  1847. * The provided callback should return `true` to continue iteration, and
  1848. * `false` otherwise.
  1849. */ tt(t) {
  1850. const e = this.cursor({});
  1851. return new Rt(((n, s) => {
  1852. e.onerror = t => {
  1853. const e = Nt(t.target.error);
  1854. s(e);
  1855. }, e.onsuccess = e => {
  1856. const s = e.target.result;
  1857. s ? t(s.primaryKey, s.value).next((t => {
  1858. t ? s.continue() : n();
  1859. })) : n();
  1860. };
  1861. }));
  1862. }
  1863. H(t, e) {
  1864. const n = [];
  1865. return new Rt(((s, i) => {
  1866. t.onerror = t => {
  1867. i(t.target.error);
  1868. }, t.onsuccess = t => {
  1869. const i = t.target.result;
  1870. if (!i) return void s();
  1871. const r = new vt(i), o = e(i.primaryKey, i.value, r);
  1872. if (o instanceof Rt) {
  1873. const t = o.catch((t => (r.done(), Rt.reject(t))));
  1874. n.push(t);
  1875. }
  1876. r.isDone ? s() : null === r.G ? i.continue() : i.continue(r.G);
  1877. };
  1878. })).next((() => Rt.waitFor(n)));
  1879. }
  1880. options(t, e) {
  1881. let n;
  1882. return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
  1883. index: n,
  1884. range: e
  1885. };
  1886. }
  1887. cursor(t) {
  1888. let e = "next";
  1889. if (t.reverse && (e = "prev"), t.index) {
  1890. const n = this.store.index(t.index);
  1891. return t.X ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
  1892. }
  1893. return this.store.openCursor(t.range, e);
  1894. }
  1895. }
  1896. /**
  1897. * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
  1898. * handlers to resolve / reject the PersistencePromise as appropriate.
  1899. */ function Ct(t) {
  1900. return new Rt(((e, n) => {
  1901. t.onsuccess = t => {
  1902. const n = t.target.result;
  1903. e(n);
  1904. }, t.onerror = t => {
  1905. const e = Nt(t.target.error);
  1906. n(e);
  1907. };
  1908. }));
  1909. }
  1910. // Guard so we only report the error once.
  1911. let xt = !1;
  1912. function Nt(t) {
  1913. const e = Pt.D(a());
  1914. if (e >= 12.2 && e < 13) {
  1915. const e = "An internal error was encountered in the Indexed Database server";
  1916. if (t.message.indexOf(e) >= 0) {
  1917. // Wrap error in a more descriptive one.
  1918. const t = new q("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
  1919. return xt || (xt = !0,
  1920. // Throw a global exception outside of this promise chain, for the user to
  1921. // potentially catch.
  1922. setTimeout((() => {
  1923. throw t;
  1924. }), 0)), t;
  1925. }
  1926. }
  1927. return t;
  1928. }
  1929. /** This class is responsible for the scheduling of Index Backfiller. */
  1930. class kt {
  1931. constructor(t, e) {
  1932. this.asyncQueue = t, this.et = e, this.task = null;
  1933. }
  1934. start() {
  1935. this.nt(15e3);
  1936. }
  1937. stop() {
  1938. this.task && (this.task.cancel(), this.task = null);
  1939. }
  1940. get started() {
  1941. return null !== this.task;
  1942. }
  1943. nt(t) {
  1944. x("IndexBackiller", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , t, (async () => {
  1945. this.task = null;
  1946. try {
  1947. x("IndexBackiller", `Documents written: ${await this.et.st()}`);
  1948. } catch (t) {
  1949. St(t) ? x("IndexBackiller", "Ignoring IndexedDB error during index backfill: ", t) : await At(t);
  1950. }
  1951. await this.nt(6e4);
  1952. }));
  1953. }
  1954. }
  1955. /** Implements the steps for backfilling indexes. */ class Ot {
  1956. constructor(
  1957. /**
  1958. * LocalStore provides access to IndexManager and LocalDocumentView.
  1959. * These properties will update when the user changes. Consequently,
  1960. * making a local copy of IndexManager and LocalDocumentView will require
  1961. * updates over time. The simpler solution is to rely on LocalStore to have
  1962. * an up-to-date references to IndexManager and LocalDocumentStore.
  1963. */
  1964. t, e) {
  1965. this.localStore = t, this.persistence = e;
  1966. }
  1967. async st(t = 50) {
  1968. return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (e => this.it(e, t)));
  1969. }
  1970. /** Writes index entries until the cap is reached. Returns the number of documents processed. */ it(t, e) {
  1971. const n = new Set;
  1972. let s = e, i = !0;
  1973. return Rt.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {
  1974. if (null !== e && !n.has(e)) return x("IndexBackiller", `Processing collection: ${e}`),
  1975. this.rt(t, e, s).next((t => {
  1976. s -= t, n.add(e);
  1977. }));
  1978. i = !1;
  1979. })))).next((() => e - s));
  1980. }
  1981. /**
  1982. * Writes entries for the provided collection group. Returns the number of documents processed.
  1983. */ rt(t, e, n) {
  1984. // Use the earliest offset of all field indexes to query the local cache.
  1985. return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {
  1986. const i = n.changes;
  1987. return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.ot(s, n))).next((n => (x("IndexBackiller", `Updating offset: ${n}`),
  1988. this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));
  1989. }))));
  1990. }
  1991. /** Returns the next offset based on the provided documents. */ ot(t, e) {
  1992. let n = t;
  1993. return e.changes.forEach(((t, e) => {
  1994. const s = yt(e);
  1995. It(s, n) > 0 && (n = s);
  1996. })), new pt(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));
  1997. }
  1998. }
  1999. /**
  2000. * @license
  2001. * Copyright 2018 Google LLC
  2002. *
  2003. * Licensed under the Apache License, Version 2.0 (the "License");
  2004. * you may not use this file except in compliance with the License.
  2005. * You may obtain a copy of the License at
  2006. *
  2007. * http://www.apache.org/licenses/LICENSE-2.0
  2008. *
  2009. * Unless required by applicable law or agreed to in writing, software
  2010. * distributed under the License is distributed on an "AS IS" BASIS,
  2011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2012. * See the License for the specific language governing permissions and
  2013. * limitations under the License.
  2014. */
  2015. /**
  2016. * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
  2017. * exceed. All subsequent calls to next will return increasing values. If provided with a
  2018. * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
  2019. * well as write out sequence numbers that it produces via `next()`.
  2020. */ class Mt {
  2021. constructor(t, e) {
  2022. this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ut(t), this.ct = t => e.writeSequenceNumber(t));
  2023. }
  2024. ut(t) {
  2025. return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
  2026. }
  2027. next() {
  2028. const t = ++this.previousValue;
  2029. return this.ct && this.ct(t), t;
  2030. }
  2031. }
  2032. Mt.at = -1;
  2033. /**
  2034. * @license
  2035. * Copyright 2017 Google LLC
  2036. *
  2037. * Licensed under the Apache License, Version 2.0 (the "License");
  2038. * you may not use this file except in compliance with the License.
  2039. * You may obtain a copy of the License at
  2040. *
  2041. * http://www.apache.org/licenses/LICENSE-2.0
  2042. *
  2043. * Unless required by applicable law or agreed to in writing, software
  2044. * distributed under the License is distributed on an "AS IS" BASIS,
  2045. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2046. * See the License for the specific language governing permissions and
  2047. * limitations under the License.
  2048. */
  2049. class Ft {
  2050. /**
  2051. * Constructs a DatabaseInfo using the provided host, databaseId and
  2052. * persistenceKey.
  2053. *
  2054. * @param databaseId - The database to use.
  2055. * @param appId - The Firebase App Id.
  2056. * @param persistenceKey - A unique identifier for this Firestore's local
  2057. * storage (used in conjunction with the databaseId).
  2058. * @param host - The Firestore backend host to connect to.
  2059. * @param ssl - Whether to use SSL when connecting.
  2060. * @param forceLongPolling - Whether to use the forceLongPolling option
  2061. * when using WebChannel as the network transport.
  2062. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  2063. * option when using WebChannel as the network transport.
  2064. * @param useFetchStreams Whether to use the Fetch API instead of
  2065. * XMLHTTPRequest
  2066. */
  2067. constructor(t, e, n, s, i, r, o, u) {
  2068. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i,
  2069. this.forceLongPolling = r, this.autoDetectLongPolling = o, this.useFetchStreams = u;
  2070. }
  2071. }
  2072. /** The default database name for a project. */
  2073. /**
  2074. * Represents the database ID a Firestore client is associated with.
  2075. * @internal
  2076. */
  2077. class $t {
  2078. constructor(t, e) {
  2079. this.projectId = t, this.database = e || "(default)";
  2080. }
  2081. static empty() {
  2082. return new $t("", "");
  2083. }
  2084. get isDefaultDatabase() {
  2085. return "(default)" === this.database;
  2086. }
  2087. isEqual(t) {
  2088. return t instanceof $t && t.projectId === this.projectId && t.database === this.database;
  2089. }
  2090. }
  2091. /**
  2092. * @license
  2093. * Copyright 2017 Google LLC
  2094. *
  2095. * Licensed under the Apache License, Version 2.0 (the "License");
  2096. * you may not use this file except in compliance with the License.
  2097. * You may obtain a copy of the License at
  2098. *
  2099. * http://www.apache.org/licenses/LICENSE-2.0
  2100. *
  2101. * Unless required by applicable law or agreed to in writing, software
  2102. * distributed under the License is distributed on an "AS IS" BASIS,
  2103. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2104. * See the License for the specific language governing permissions and
  2105. * limitations under the License.
  2106. */
  2107. function Bt(t) {
  2108. let e = 0;
  2109. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  2110. return e;
  2111. }
  2112. function Lt(t, e) {
  2113. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  2114. }
  2115. function qt(t) {
  2116. for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  2117. return !0;
  2118. }
  2119. /**
  2120. * @license
  2121. * Copyright 2017 Google LLC
  2122. *
  2123. * Licensed under the Apache License, Version 2.0 (the "License");
  2124. * you may not use this file except in compliance with the License.
  2125. * You may obtain a copy of the License at
  2126. *
  2127. * http://www.apache.org/licenses/LICENSE-2.0
  2128. *
  2129. * Unless required by applicable law or agreed to in writing, software
  2130. * distributed under the License is distributed on an "AS IS" BASIS,
  2131. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2132. * See the License for the specific language governing permissions and
  2133. * limitations under the License.
  2134. */
  2135. /** Sentinel value that sorts before any Mutation Batch ID. */
  2136. /**
  2137. * Returns whether a variable is either undefined or null.
  2138. */
  2139. function Ut(t) {
  2140. return null == t;
  2141. }
  2142. /** Returns whether the value represents -0. */ function Kt(t) {
  2143. // Detect if the value is -0.0. Based on polyfill from
  2144. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2145. return 0 === t && 1 / t == -1 / 0;
  2146. }
  2147. /**
  2148. * Returns whether a value is an integer and in the safe integer range
  2149. * @param value - The value to test for being an integer and in the safe range
  2150. */ function Gt(t) {
  2151. return "number" == typeof t && Number.isInteger(t) && !Kt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2152. }
  2153. /**
  2154. * @license
  2155. * Copyright 2020 Google LLC
  2156. *
  2157. * Licensed under the Apache License, Version 2.0 (the "License");
  2158. * you may not use this file except in compliance with the License.
  2159. * You may obtain a copy of the License at
  2160. *
  2161. * http://www.apache.org/licenses/LICENSE-2.0
  2162. *
  2163. * Unless required by applicable law or agreed to in writing, software
  2164. * distributed under the License is distributed on an "AS IS" BASIS,
  2165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2166. * See the License for the specific language governing permissions and
  2167. * limitations under the License.
  2168. */
  2169. // WebSafe uses a different URL-encoding safe alphabet that doesn't match
  2170. // the encoding used on the backend.
  2171. /** Converts a Base64 encoded string to a binary string. */
  2172. function Qt(t) {
  2173. return String.fromCharCode.apply(null,
  2174. // We use `decodeStringToByteArray()` instead of `decodeString()` since
  2175. // `decodeString()` returns Unicode strings, which doesn't match the values
  2176. // returned by `atob()`'s Latin1 representation.
  2177. l.decodeStringToByteArray(t, false));
  2178. }
  2179. /** Converts a binary string to a Base64 encoded string. */
  2180. /** True if and only if the Base64 conversion functions are available. */
  2181. function jt() {
  2182. return !0;
  2183. }
  2184. /**
  2185. * @license
  2186. * Copyright 2020 Google LLC
  2187. *
  2188. * Licensed under the Apache License, Version 2.0 (the "License");
  2189. * you may not use this file except in compliance with the License.
  2190. * You may obtain a copy of the License at
  2191. *
  2192. * http://www.apache.org/licenses/LICENSE-2.0
  2193. *
  2194. * Unless required by applicable law or agreed to in writing, software
  2195. * distributed under the License is distributed on an "AS IS" BASIS,
  2196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2197. * See the License for the specific language governing permissions and
  2198. * limitations under the License.
  2199. */
  2200. /**
  2201. * Immutable class that represents a "proto" byte string.
  2202. *
  2203. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  2204. * sent on the wire. This class abstracts away this differentiation by holding
  2205. * the proto byte string in a common class that must be converted into a string
  2206. * before being sent as a proto.
  2207. * @internal
  2208. */ class Wt {
  2209. constructor(t) {
  2210. this.binaryString = t;
  2211. }
  2212. static fromBase64String(t) {
  2213. const e = Qt(t);
  2214. return new Wt(e);
  2215. }
  2216. static fromUint8Array(t) {
  2217. // TODO(indexing); Remove the copy of the byte string here as this method
  2218. // is frequently called during indexing.
  2219. const e =
  2220. /**
  2221. * Helper function to convert an Uint8array to a binary string.
  2222. */
  2223. function(t) {
  2224. let e = "";
  2225. for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  2226. return e;
  2227. }
  2228. /**
  2229. * Helper function to convert a binary string to an Uint8Array.
  2230. */ (t);
  2231. return new Wt(e);
  2232. }
  2233. [Symbol.iterator]() {
  2234. let t = 0;
  2235. return {
  2236. next: () => t < this.binaryString.length ? {
  2237. value: this.binaryString.charCodeAt(t++),
  2238. done: !1
  2239. } : {
  2240. value: void 0,
  2241. done: !0
  2242. }
  2243. };
  2244. }
  2245. toBase64() {
  2246. return function(t) {
  2247. const e = [];
  2248. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2249. return l.encodeByteArray(e, !1);
  2250. }(this.binaryString);
  2251. }
  2252. toUint8Array() {
  2253. return function(t) {
  2254. const e = new Uint8Array(t.length);
  2255. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2256. return e;
  2257. }
  2258. /**
  2259. * @license
  2260. * Copyright 2020 Google LLC
  2261. *
  2262. * Licensed under the Apache License, Version 2.0 (the "License");
  2263. * you may not use this file except in compliance with the License.
  2264. * You may obtain a copy of the License at
  2265. *
  2266. * http://www.apache.org/licenses/LICENSE-2.0
  2267. *
  2268. * Unless required by applicable law or agreed to in writing, software
  2269. * distributed under the License is distributed on an "AS IS" BASIS,
  2270. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2271. * See the License for the specific language governing permissions and
  2272. * limitations under the License.
  2273. */
  2274. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  2275. (this.binaryString);
  2276. }
  2277. approximateByteSize() {
  2278. return 2 * this.binaryString.length;
  2279. }
  2280. compareTo(t) {
  2281. return tt(this.binaryString, t.binaryString);
  2282. }
  2283. isEqual(t) {
  2284. return this.binaryString === t.binaryString;
  2285. }
  2286. }
  2287. Wt.EMPTY_BYTE_STRING = new Wt("");
  2288. const zt = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  2289. /**
  2290. * Converts the possible Proto values for a timestamp value into a "seconds and
  2291. * nanos" representation.
  2292. */ function Ht(t) {
  2293. // The json interface (for the browser) will return an iso timestamp string,
  2294. // while the proto js library (for node) will return a
  2295. // google.protobuf.Timestamp instance.
  2296. if (F(!!t), "string" == typeof t) {
  2297. // The date string can have higher precision (nanos) than the Date class
  2298. // (millis), so we do some custom parsing here.
  2299. // Parse the nanos right out of the string.
  2300. let e = 0;
  2301. const n = zt.exec(t);
  2302. if (F(!!n), n[1]) {
  2303. // Pad the fraction out to 9 digits (nanos).
  2304. let t = n[1];
  2305. t = (t + "000000000").substr(0, 9), e = Number(t);
  2306. }
  2307. // Parse the date to get the seconds.
  2308. const s = new Date(t);
  2309. return {
  2310. seconds: Math.floor(s.getTime() / 1e3),
  2311. nanos: e
  2312. };
  2313. }
  2314. return {
  2315. seconds: Jt(t.seconds),
  2316. nanos: Jt(t.nanos)
  2317. };
  2318. }
  2319. /**
  2320. * Converts the possible Proto types for numbers into a JavaScript number.
  2321. * Returns 0 if the value is not numeric.
  2322. */ function Jt(t) {
  2323. // TODO(bjornick): Handle int64 greater than 53 bits.
  2324. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  2325. }
  2326. /** Converts the possible Proto types for Blobs into a ByteString. */ function Yt(t) {
  2327. return "string" == typeof t ? Wt.fromBase64String(t) : Wt.fromUint8Array(t);
  2328. }
  2329. /**
  2330. * @license
  2331. * Copyright 2020 Google LLC
  2332. *
  2333. * Licensed under the Apache License, Version 2.0 (the "License");
  2334. * you may not use this file except in compliance with the License.
  2335. * You may obtain a copy of the License at
  2336. *
  2337. * http://www.apache.org/licenses/LICENSE-2.0
  2338. *
  2339. * Unless required by applicable law or agreed to in writing, software
  2340. * distributed under the License is distributed on an "AS IS" BASIS,
  2341. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2342. * See the License for the specific language governing permissions and
  2343. * limitations under the License.
  2344. */
  2345. /**
  2346. * Represents a locally-applied ServerTimestamp.
  2347. *
  2348. * Server Timestamps are backed by MapValues that contain an internal field
  2349. * `__type__` with a value of `server_timestamp`. The previous value and local
  2350. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2351. * fields respectively.
  2352. *
  2353. * Notes:
  2354. * - ServerTimestampValue instances are created as the result of applying a
  2355. * transform. They can only exist in the local view of a document. Therefore
  2356. * they do not need to be parsed or serialized.
  2357. * - When evaluated locally (e.g. for snapshot.data()), they by default
  2358. * evaluate to `null`. This behavior can be configured by passing custom
  2359. * FieldValueOptions to value().
  2360. * - With respect to other ServerTimestampValues, they sort by their
  2361. * localWriteTime.
  2362. */ function Xt(t) {
  2363. var e, n;
  2364. return "server_timestamp" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);
  2365. }
  2366. /**
  2367. * Creates a new ServerTimestamp proto value (using the internal format).
  2368. */
  2369. /**
  2370. * Returns the value of the field before this ServerTimestamp was set.
  2371. *
  2372. * Preserving the previous values allows the user to display the last resoled
  2373. * value until the backend responds with the timestamp.
  2374. */
  2375. function Zt(t) {
  2376. const e = t.mapValue.fields.__previous_value__;
  2377. return Xt(e) ? Zt(e) : e;
  2378. }
  2379. /**
  2380. * Returns the local time at which this timestamp was first set.
  2381. */ function te(t) {
  2382. const e = Ht(t.mapValue.fields.__local_write_time__.timestampValue);
  2383. return new st(e.seconds, e.nanos);
  2384. }
  2385. /**
  2386. * @license
  2387. * Copyright 2020 Google LLC
  2388. *
  2389. * Licensed under the Apache License, Version 2.0 (the "License");
  2390. * you may not use this file except in compliance with the License.
  2391. * You may obtain a copy of the License at
  2392. *
  2393. * http://www.apache.org/licenses/LICENSE-2.0
  2394. *
  2395. * Unless required by applicable law or agreed to in writing, software
  2396. * distributed under the License is distributed on an "AS IS" BASIS,
  2397. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2398. * See the License for the specific language governing permissions and
  2399. * limitations under the License.
  2400. */ const ee = {
  2401. mapValue: {
  2402. fields: {
  2403. __type__: {
  2404. stringValue: "__max__"
  2405. }
  2406. }
  2407. }
  2408. }, ne = {
  2409. nullValue: "NULL_VALUE"
  2410. };
  2411. /** Extracts the backend's type order for the provided value. */
  2412. function se(t) {
  2413. return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? Xt(t) ? 4 /* TypeOrder.ServerTimestampValue */ : ge(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : M();
  2414. }
  2415. /** Tests `left` and `right` for equality based on the backend semantics. */ function ie(t, e) {
  2416. if (t === e) return !0;
  2417. const n = se(t);
  2418. if (n !== se(e)) return !1;
  2419. switch (n) {
  2420. case 0 /* TypeOrder.NullValue */ :
  2421. case 9007199254740991 /* TypeOrder.MaxValue */ :
  2422. return !0;
  2423. case 1 /* TypeOrder.BooleanValue */ :
  2424. return t.booleanValue === e.booleanValue;
  2425. case 4 /* TypeOrder.ServerTimestampValue */ :
  2426. return te(t).isEqual(te(e));
  2427. case 3 /* TypeOrder.TimestampValue */ :
  2428. return function(t, e) {
  2429. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  2430. // Use string equality for ISO 8601 timestamps
  2431. return t.timestampValue === e.timestampValue;
  2432. const n = Ht(t.timestampValue), s = Ht(e.timestampValue);
  2433. return n.seconds === s.seconds && n.nanos === s.nanos;
  2434. }(t, e);
  2435. case 5 /* TypeOrder.StringValue */ :
  2436. return t.stringValue === e.stringValue;
  2437. case 6 /* TypeOrder.BlobValue */ :
  2438. return function(t, e) {
  2439. return Yt(t.bytesValue).isEqual(Yt(e.bytesValue));
  2440. }(t, e);
  2441. case 7 /* TypeOrder.RefValue */ :
  2442. return t.referenceValue === e.referenceValue;
  2443. case 8 /* TypeOrder.GeoPointValue */ :
  2444. return function(t, e) {
  2445. return Jt(t.geoPointValue.latitude) === Jt(e.geoPointValue.latitude) && Jt(t.geoPointValue.longitude) === Jt(e.geoPointValue.longitude);
  2446. }(t, e);
  2447. case 2 /* TypeOrder.NumberValue */ :
  2448. return function(t, e) {
  2449. if ("integerValue" in t && "integerValue" in e) return Jt(t.integerValue) === Jt(e.integerValue);
  2450. if ("doubleValue" in t && "doubleValue" in e) {
  2451. const n = Jt(t.doubleValue), s = Jt(e.doubleValue);
  2452. return n === s ? Kt(n) === Kt(s) : isNaN(n) && isNaN(s);
  2453. }
  2454. return !1;
  2455. }(t, e);
  2456. case 9 /* TypeOrder.ArrayValue */ :
  2457. return et(t.arrayValue.values || [], e.arrayValue.values || [], ie);
  2458. case 10 /* TypeOrder.ObjectValue */ :
  2459. return function(t, e) {
  2460. const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};
  2461. if (Bt(n) !== Bt(s)) return !1;
  2462. for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !ie(n[t], s[t]))) return !1;
  2463. return !0;
  2464. }
  2465. /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  2466. default:
  2467. return M();
  2468. }
  2469. }
  2470. function re(t, e) {
  2471. return void 0 !== (t.values || []).find((t => ie(t, e)));
  2472. }
  2473. function oe(t, e) {
  2474. if (t === e) return 0;
  2475. const n = se(t), s = se(e);
  2476. if (n !== s) return tt(n, s);
  2477. switch (n) {
  2478. case 0 /* TypeOrder.NullValue */ :
  2479. case 9007199254740991 /* TypeOrder.MaxValue */ :
  2480. return 0;
  2481. case 1 /* TypeOrder.BooleanValue */ :
  2482. return tt(t.booleanValue, e.booleanValue);
  2483. case 2 /* TypeOrder.NumberValue */ :
  2484. return function(t, e) {
  2485. const n = Jt(t.integerValue || t.doubleValue), s = Jt(e.integerValue || e.doubleValue);
  2486. return n < s ? -1 : n > s ? 1 : n === s ? 0 :
  2487. // one or both are NaN.
  2488. isNaN(n) ? isNaN(s) ? 0 : -1 : 1;
  2489. }(t, e);
  2490. case 3 /* TypeOrder.TimestampValue */ :
  2491. return ue(t.timestampValue, e.timestampValue);
  2492. case 4 /* TypeOrder.ServerTimestampValue */ :
  2493. return ue(te(t), te(e));
  2494. case 5 /* TypeOrder.StringValue */ :
  2495. return tt(t.stringValue, e.stringValue);
  2496. case 6 /* TypeOrder.BlobValue */ :
  2497. return function(t, e) {
  2498. const n = Yt(t), s = Yt(e);
  2499. return n.compareTo(s);
  2500. }(t.bytesValue, e.bytesValue);
  2501. case 7 /* TypeOrder.RefValue */ :
  2502. return function(t, e) {
  2503. const n = t.split("/"), s = e.split("/");
  2504. for (let t = 0; t < n.length && t < s.length; t++) {
  2505. const e = tt(n[t], s[t]);
  2506. if (0 !== e) return e;
  2507. }
  2508. return tt(n.length, s.length);
  2509. }(t.referenceValue, e.referenceValue);
  2510. case 8 /* TypeOrder.GeoPointValue */ :
  2511. return function(t, e) {
  2512. const n = tt(Jt(t.latitude), Jt(e.latitude));
  2513. if (0 !== n) return n;
  2514. return tt(Jt(t.longitude), Jt(e.longitude));
  2515. }(t.geoPointValue, e.geoPointValue);
  2516. case 9 /* TypeOrder.ArrayValue */ :
  2517. return function(t, e) {
  2518. const n = t.values || [], s = e.values || [];
  2519. for (let t = 0; t < n.length && t < s.length; ++t) {
  2520. const e = oe(n[t], s[t]);
  2521. if (e) return e;
  2522. }
  2523. return tt(n.length, s.length);
  2524. }(t.arrayValue, e.arrayValue);
  2525. case 10 /* TypeOrder.ObjectValue */ :
  2526. return function(t, e) {
  2527. if (t === ee.mapValue && e === ee.mapValue) return 0;
  2528. if (t === ee.mapValue) return 1;
  2529. if (e === ee.mapValue) return -1;
  2530. const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);
  2531. // Even though MapValues are likely sorted correctly based on their insertion
  2532. // order (e.g. when received from the backend), local modifications can bring
  2533. // elements out of order. We need to re-sort the elements to ensure that
  2534. // canonical IDs are independent of insertion order.
  2535. s.sort(), r.sort();
  2536. for (let t = 0; t < s.length && t < r.length; ++t) {
  2537. const e = tt(s[t], r[t]);
  2538. if (0 !== e) return e;
  2539. const o = oe(n[s[t]], i[r[t]]);
  2540. if (0 !== o) return o;
  2541. }
  2542. return tt(s.length, r.length);
  2543. }
  2544. /**
  2545. * Generates the canonical ID for the provided field value (as used in Target
  2546. * serialization).
  2547. */ (t.mapValue, e.mapValue);
  2548. default:
  2549. throw M();
  2550. }
  2551. }
  2552. function ue(t, e) {
  2553. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return tt(t, e);
  2554. const n = Ht(t), s = Ht(e), i = tt(n.seconds, s.seconds);
  2555. return 0 !== i ? i : tt(n.nanos, s.nanos);
  2556. }
  2557. function ce(t) {
  2558. return ae(t);
  2559. }
  2560. function ae(t) {
  2561. return "nullValue" in t ? "null" : "booleanValue" in t ? "" + t.booleanValue : "integerValue" in t ? "" + t.integerValue : "doubleValue" in t ? "" + t.doubleValue : "timestampValue" in t ? function(t) {
  2562. const e = Ht(t);
  2563. return `time(${e.seconds},${e.nanos})`;
  2564. }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? Yt(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue,
  2565. at.fromName(n).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
  2566. let e = "[", n = !0;
  2567. for (const s of t.values || []) n ? n = !1 : e += ",", e += ae(s);
  2568. return e + "]";
  2569. }
  2570. /** Returns a reference value for the provided database and key. */ (t.arrayValue) : "mapValue" in t ? function(t) {
  2571. // Iteration order in JavaScript is not guaranteed. To ensure that we generate
  2572. // matching canonical IDs for identical maps, we need to sort the keys.
  2573. const e = Object.keys(t.fields || {}).sort();
  2574. let n = "{", s = !0;
  2575. for (const i of e) s ? s = !1 : n += ",", n += `${i}:${ae(t.fields[i])}`;
  2576. return n + "}";
  2577. }(t.mapValue) : M();
  2578. var e, n;
  2579. }
  2580. function he(t, e) {
  2581. return {
  2582. referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`
  2583. };
  2584. }
  2585. /** Returns true if `value` is an IntegerValue . */ function le(t) {
  2586. return !!t && "integerValue" in t;
  2587. }
  2588. /** Returns true if `value` is a DoubleValue. */
  2589. /** Returns true if `value` is an ArrayValue. */
  2590. function fe(t) {
  2591. return !!t && "arrayValue" in t;
  2592. }
  2593. /** Returns true if `value` is a NullValue. */ function de(t) {
  2594. return !!t && "nullValue" in t;
  2595. }
  2596. /** Returns true if `value` is NaN. */ function _e(t) {
  2597. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  2598. }
  2599. /** Returns true if `value` is a MapValue. */ function we(t) {
  2600. return !!t && "mapValue" in t;
  2601. }
  2602. /** Creates a deep copy of `source`. */ function me(t) {
  2603. if (t.geoPointValue) return {
  2604. geoPointValue: Object.assign({}, t.geoPointValue)
  2605. };
  2606. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  2607. timestampValue: Object.assign({}, t.timestampValue)
  2608. };
  2609. if (t.mapValue) {
  2610. const e = {
  2611. mapValue: {
  2612. fields: {}
  2613. }
  2614. };
  2615. return Lt(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = me(n))), e;
  2616. }
  2617. if (t.arrayValue) {
  2618. const e = {
  2619. arrayValue: {
  2620. values: []
  2621. }
  2622. };
  2623. for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = me(t.arrayValue.values[n]);
  2624. return e;
  2625. }
  2626. return Object.assign({}, t);
  2627. }
  2628. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function ge(t) {
  2629. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  2630. }
  2631. /** Returns the lowest value for the given value type (inclusive). */ function ye(t) {
  2632. return "nullValue" in t ? ne : "booleanValue" in t ? {
  2633. booleanValue: !1
  2634. } : "integerValue" in t || "doubleValue" in t ? {
  2635. doubleValue: NaN
  2636. } : "timestampValue" in t ? {
  2637. timestampValue: {
  2638. seconds: Number.MIN_SAFE_INTEGER
  2639. }
  2640. } : "stringValue" in t ? {
  2641. stringValue: ""
  2642. } : "bytesValue" in t ? {
  2643. bytesValue: ""
  2644. } : "referenceValue" in t ? he($t.empty(), at.empty()) : "geoPointValue" in t ? {
  2645. geoPointValue: {
  2646. latitude: -90,
  2647. longitude: -180
  2648. }
  2649. } : "arrayValue" in t ? {
  2650. arrayValue: {}
  2651. } : "mapValue" in t ? {
  2652. mapValue: {}
  2653. } : M();
  2654. }
  2655. /** Returns the largest value for the given value type (exclusive). */ function pe(t) {
  2656. return "nullValue" in t ? {
  2657. booleanValue: !1
  2658. } : "booleanValue" in t ? {
  2659. doubleValue: NaN
  2660. } : "integerValue" in t || "doubleValue" in t ? {
  2661. timestampValue: {
  2662. seconds: Number.MIN_SAFE_INTEGER
  2663. }
  2664. } : "timestampValue" in t ? {
  2665. stringValue: ""
  2666. } : "stringValue" in t ? {
  2667. bytesValue: ""
  2668. } : "bytesValue" in t ? he($t.empty(), at.empty()) : "referenceValue" in t ? {
  2669. geoPointValue: {
  2670. latitude: -90,
  2671. longitude: -180
  2672. }
  2673. } : "geoPointValue" in t ? {
  2674. arrayValue: {}
  2675. } : "arrayValue" in t ? {
  2676. mapValue: {}
  2677. } : "mapValue" in t ? ee : M();
  2678. }
  2679. function Ie(t, e) {
  2680. const n = oe(t.value, e.value);
  2681. return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;
  2682. }
  2683. function Te(t, e) {
  2684. const n = oe(t.value, e.value);
  2685. return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;
  2686. }
  2687. /**
  2688. * @license
  2689. * Copyright 2022 Google LLC
  2690. *
  2691. * Licensed under the Apache License, Version 2.0 (the "License");
  2692. * you may not use this file except in compliance with the License.
  2693. * You may obtain a copy of the License at
  2694. *
  2695. * http://www.apache.org/licenses/LICENSE-2.0
  2696. *
  2697. * Unless required by applicable law or agreed to in writing, software
  2698. * distributed under the License is distributed on an "AS IS" BASIS,
  2699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2700. * See the License for the specific language governing permissions and
  2701. * limitations under the License.
  2702. */
  2703. /**
  2704. * Represents a bound of a query.
  2705. *
  2706. * The bound is specified with the given components representing a position and
  2707. * whether it's just before or just after the position (relative to whatever the
  2708. * query order is).
  2709. *
  2710. * The position represents a logical index position for a query. It's a prefix
  2711. * of values for the (potentially implicit) order by clauses of a query.
  2712. *
  2713. * Bound provides a function to determine whether a document comes before or
  2714. * after a bound. This is influenced by whether the position is just before or
  2715. * just after the provided values.
  2716. */ class Ee {
  2717. constructor(t, e) {
  2718. this.position = t, this.inclusive = e;
  2719. }
  2720. }
  2721. function Ae(t, e, n) {
  2722. let s = 0;
  2723. for (let i = 0; i < t.position.length; i++) {
  2724. const r = e[i], o = t.position[i];
  2725. if (r.field.isKeyField()) s = at.comparator(at.fromName(o.referenceValue), n.key); else {
  2726. s = oe(o, n.data.field(r.field));
  2727. }
  2728. if ("desc" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;
  2729. }
  2730. return s;
  2731. }
  2732. /**
  2733. * Returns true if a document sorts after a bound using the provided sort
  2734. * order.
  2735. */ function Re(t, e) {
  2736. if (null === t) return null === e;
  2737. if (null === e) return !1;
  2738. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  2739. for (let n = 0; n < t.position.length; n++) {
  2740. if (!ie(t.position[n], e.position[n])) return !1;
  2741. }
  2742. return !0;
  2743. }
  2744. /**
  2745. * @license
  2746. * Copyright 2022 Google LLC
  2747. *
  2748. * Licensed under the Apache License, Version 2.0 (the "License");
  2749. * you may not use this file except in compliance with the License.
  2750. * You may obtain a copy of the License at
  2751. *
  2752. * http://www.apache.org/licenses/LICENSE-2.0
  2753. *
  2754. * Unless required by applicable law or agreed to in writing, software
  2755. * distributed under the License is distributed on an "AS IS" BASIS,
  2756. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2757. * See the License for the specific language governing permissions and
  2758. * limitations under the License.
  2759. */ class be {}
  2760. class Pe extends be {
  2761. constructor(t, e, n) {
  2762. super(), this.field = t, this.op = e, this.value = n;
  2763. }
  2764. /**
  2765. * Creates a filter based on the provided arguments.
  2766. */ static create(t, e, n) {
  2767. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new Me(t, e, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new Le(t, n) : "in" /* Operator.IN */ === e ? new qe(t, n) : "not-in" /* Operator.NOT_IN */ === e ? new Ue(t, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new Ke(t, n) : new Pe(t, e, n);
  2768. }
  2769. static createKeyFieldInFilter(t, e, n) {
  2770. return "in" /* Operator.IN */ === e ? new Fe(t, n) : new $e(t, n);
  2771. }
  2772. matches(t) {
  2773. const e = t.data.field(this.field);
  2774. // Types do not have to match in NOT_EQUAL filters.
  2775. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(oe(e, this.value)) : null !== e && se(this.value) === se(e) && this.matchesComparison(oe(e, this.value));
  2776. // Only compare types with matching backend order (such as double and int).
  2777. }
  2778. matchesComparison(t) {
  2779. switch (this.op) {
  2780. case "<" /* Operator.LESS_THAN */ :
  2781. return t < 0;
  2782. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  2783. return t <= 0;
  2784. case "==" /* Operator.EQUAL */ :
  2785. return 0 === t;
  2786. case "!=" /* Operator.NOT_EQUAL */ :
  2787. return 0 !== t;
  2788. case ">" /* Operator.GREATER_THAN */ :
  2789. return t > 0;
  2790. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  2791. return t >= 0;
  2792. default:
  2793. return M();
  2794. }
  2795. }
  2796. isInequality() {
  2797. return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;
  2798. }
  2799. getFlattenedFilters() {
  2800. return [ this ];
  2801. }
  2802. getFilters() {
  2803. return [ this ];
  2804. }
  2805. getFirstInequalityField() {
  2806. return this.isInequality() ? this.field : null;
  2807. }
  2808. }
  2809. class ve extends be {
  2810. constructor(t, e) {
  2811. super(), this.filters = t, this.op = e, this.ht = null;
  2812. }
  2813. /**
  2814. * Creates a filter based on the provided arguments.
  2815. */ static create(t, e) {
  2816. return new ve(t, e);
  2817. }
  2818. matches(t) {
  2819. return Ve(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));
  2820. }
  2821. getFlattenedFilters() {
  2822. return null !== this.ht || (this.ht = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])),
  2823. this.ht;
  2824. }
  2825. // Returns a mutable copy of `this.filters`
  2826. getFilters() {
  2827. return Object.assign([], this.filters);
  2828. }
  2829. getFirstInequalityField() {
  2830. const t = this.lt((t => t.isInequality()));
  2831. return null !== t ? t.field : null;
  2832. }
  2833. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  2834. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  2835. // predicate.
  2836. lt(t) {
  2837. for (const e of this.getFlattenedFilters()) if (t(e)) return e;
  2838. return null;
  2839. }
  2840. }
  2841. function Ve(t) {
  2842. return "and" /* CompositeOperator.AND */ === t.op;
  2843. }
  2844. function Se(t) {
  2845. return "or" /* CompositeOperator.OR */ === t.op;
  2846. }
  2847. /**
  2848. * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
  2849. */ function De(t) {
  2850. return Ce(t) && Ve(t);
  2851. }
  2852. /**
  2853. * Returns true if this filter does not contain any composite filters. Returns false otherwise.
  2854. */ function Ce(t) {
  2855. for (const e of t.filters) if (e instanceof ve) return !1;
  2856. return !0;
  2857. }
  2858. function xe(t) {
  2859. if (t instanceof Pe)
  2860. // TODO(b/29183165): Technically, this won't be unique if two values have
  2861. // the same description, such as the int 3 and the string "3". So we should
  2862. // add the types in here somehow, too.
  2863. return t.field.canonicalString() + t.op.toString() + ce(t.value);
  2864. if (De(t))
  2865. // Older SDK versions use an implicit AND operation between their filters.
  2866. // In the new SDK versions, the developer may use an explicit AND filter.
  2867. // To stay consistent with the old usages, we add a special case to ensure
  2868. // the canonical ID for these two are the same. For example:
  2869. // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
  2870. // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
  2871. return t.filters.map((t => xe(t))).join(",");
  2872. {
  2873. // filter instanceof CompositeFilter
  2874. const e = t.filters.map((t => xe(t))).join(",");
  2875. return `${t.op}(${e})`;
  2876. }
  2877. }
  2878. function Ne(t, e) {
  2879. return t instanceof Pe ? function(t, e) {
  2880. return e instanceof Pe && t.op === e.op && t.field.isEqual(e.field) && ie(t.value, e.value);
  2881. }(t, e) : t instanceof ve ? function(t, e) {
  2882. if (e instanceof ve && t.op === e.op && t.filters.length === e.filters.length) {
  2883. return t.filters.reduce(((t, n, s) => t && Ne(n, e.filters[s])), !0);
  2884. }
  2885. return !1;
  2886. }
  2887. /**
  2888. * Returns a new composite filter that contains all filter from
  2889. * `compositeFilter` plus all the given filters in `otherFilters`.
  2890. */ (t, e) : void M();
  2891. }
  2892. function ke(t, e) {
  2893. const n = t.filters.concat(e);
  2894. return ve.create(n, t.op);
  2895. }
  2896. /** Returns a debug description for `filter`. */ function Oe(t) {
  2897. return t instanceof Pe ? function(t) {
  2898. return `${t.field.canonicalString()} ${t.op} ${ce(t.value)}`;
  2899. }
  2900. /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof ve ? function(t) {
  2901. return t.op.toString() + " {" + t.getFilters().map(Oe).join(" ,") + "}";
  2902. }(t) : "Filter";
  2903. }
  2904. class Me extends Pe {
  2905. constructor(t, e, n) {
  2906. super(t, e, n), this.key = at.fromName(n.referenceValue);
  2907. }
  2908. matches(t) {
  2909. const e = at.comparator(t.key, this.key);
  2910. return this.matchesComparison(e);
  2911. }
  2912. }
  2913. /** Filter that matches on key fields within an array. */ class Fe extends Pe {
  2914. constructor(t, e) {
  2915. super(t, "in" /* Operator.IN */ , e), this.keys = Be("in" /* Operator.IN */ , e);
  2916. }
  2917. matches(t) {
  2918. return this.keys.some((e => e.isEqual(t.key)));
  2919. }
  2920. }
  2921. /** Filter that matches on key fields not present within an array. */ class $e extends Pe {
  2922. constructor(t, e) {
  2923. super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = Be("not-in" /* Operator.NOT_IN */ , e);
  2924. }
  2925. matches(t) {
  2926. return !this.keys.some((e => e.isEqual(t.key)));
  2927. }
  2928. }
  2929. function Be(t, e) {
  2930. var n;
  2931. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => at.fromName(t.referenceValue)));
  2932. }
  2933. /** A Filter that implements the array-contains operator. */ class Le extends Pe {
  2934. constructor(t, e) {
  2935. super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e);
  2936. }
  2937. matches(t) {
  2938. const e = t.data.field(this.field);
  2939. return fe(e) && re(e.arrayValue, this.value);
  2940. }
  2941. }
  2942. /** A Filter that implements the IN operator. */ class qe extends Pe {
  2943. constructor(t, e) {
  2944. super(t, "in" /* Operator.IN */ , e);
  2945. }
  2946. matches(t) {
  2947. const e = t.data.field(this.field);
  2948. return null !== e && re(this.value.arrayValue, e);
  2949. }
  2950. }
  2951. /** A Filter that implements the not-in operator. */ class Ue extends Pe {
  2952. constructor(t, e) {
  2953. super(t, "not-in" /* Operator.NOT_IN */ , e);
  2954. }
  2955. matches(t) {
  2956. if (re(this.value.arrayValue, {
  2957. nullValue: "NULL_VALUE"
  2958. })) return !1;
  2959. const e = t.data.field(this.field);
  2960. return null !== e && !re(this.value.arrayValue, e);
  2961. }
  2962. }
  2963. /** A Filter that implements the array-contains-any operator. */ class Ke extends Pe {
  2964. constructor(t, e) {
  2965. super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e);
  2966. }
  2967. matches(t) {
  2968. const e = t.data.field(this.field);
  2969. return !(!fe(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => re(this.value.arrayValue, t)));
  2970. }
  2971. }
  2972. /**
  2973. * @license
  2974. * Copyright 2022 Google LLC
  2975. *
  2976. * Licensed under the Apache License, Version 2.0 (the "License");
  2977. * you may not use this file except in compliance with the License.
  2978. * You may obtain a copy of the License at
  2979. *
  2980. * http://www.apache.org/licenses/LICENSE-2.0
  2981. *
  2982. * Unless required by applicable law or agreed to in writing, software
  2983. * distributed under the License is distributed on an "AS IS" BASIS,
  2984. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2985. * See the License for the specific language governing permissions and
  2986. * limitations under the License.
  2987. */
  2988. /**
  2989. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  2990. */ class Ge {
  2991. constructor(t, e = "asc" /* Direction.ASCENDING */) {
  2992. this.field = t, this.dir = e;
  2993. }
  2994. }
  2995. function Qe(t, e) {
  2996. return t.dir === e.dir && t.field.isEqual(e.field);
  2997. }
  2998. /**
  2999. * @license
  3000. * Copyright 2017 Google LLC
  3001. *
  3002. * Licensed under the Apache License, Version 2.0 (the "License");
  3003. * you may not use this file except in compliance with the License.
  3004. * You may obtain a copy of the License at
  3005. *
  3006. * http://www.apache.org/licenses/LICENSE-2.0
  3007. *
  3008. * Unless required by applicable law or agreed to in writing, software
  3009. * distributed under the License is distributed on an "AS IS" BASIS,
  3010. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3011. * See the License for the specific language governing permissions and
  3012. * limitations under the License.
  3013. */
  3014. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  3015. // tree.
  3016. class je {
  3017. constructor(t, e) {
  3018. this.comparator = t, this.root = e || ze.EMPTY;
  3019. }
  3020. // Returns a copy of the map, with the specified key/value added or replaced.
  3021. insert(t, e) {
  3022. return new je(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, ze.BLACK, null, null));
  3023. }
  3024. // Returns a copy of the map, with the specified key removed.
  3025. remove(t) {
  3026. return new je(this.comparator, this.root.remove(t, this.comparator).copy(null, null, ze.BLACK, null, null));
  3027. }
  3028. // Returns the value of the node with the given key, or null.
  3029. get(t) {
  3030. let e = this.root;
  3031. for (;!e.isEmpty(); ) {
  3032. const n = this.comparator(t, e.key);
  3033. if (0 === n) return e.value;
  3034. n < 0 ? e = e.left : n > 0 && (e = e.right);
  3035. }
  3036. return null;
  3037. }
  3038. // Returns the index of the element in this sorted map, or -1 if it doesn't
  3039. // exist.
  3040. indexOf(t) {
  3041. // Number of nodes that were pruned when descending right
  3042. let e = 0, n = this.root;
  3043. for (;!n.isEmpty(); ) {
  3044. const s = this.comparator(t, n.key);
  3045. if (0 === s) return e + n.left.size;
  3046. s < 0 ? n = n.left : (
  3047. // Count all nodes left of the node plus the node itself
  3048. e += n.left.size + 1, n = n.right);
  3049. }
  3050. // Node not found
  3051. return -1;
  3052. }
  3053. isEmpty() {
  3054. return this.root.isEmpty();
  3055. }
  3056. // Returns the total number of nodes in the map.
  3057. get size() {
  3058. return this.root.size;
  3059. }
  3060. // Returns the minimum key in the map.
  3061. minKey() {
  3062. return this.root.minKey();
  3063. }
  3064. // Returns the maximum key in the map.
  3065. maxKey() {
  3066. return this.root.maxKey();
  3067. }
  3068. // Traverses the map in key order and calls the specified action function
  3069. // for each key/value pair. If action returns true, traversal is aborted.
  3070. // Returns the first truthy value returned by action, or the last falsey
  3071. // value returned by action.
  3072. inorderTraversal(t) {
  3073. return this.root.inorderTraversal(t);
  3074. }
  3075. forEach(t) {
  3076. this.inorderTraversal(((e, n) => (t(e, n), !1)));
  3077. }
  3078. toString() {
  3079. const t = [];
  3080. return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
  3081. }
  3082. // Traverses the map in reverse key order and calls the specified action
  3083. // function for each key/value pair. If action returns true, traversal is
  3084. // aborted.
  3085. // Returns the first truthy value returned by action, or the last falsey
  3086. // value returned by action.
  3087. reverseTraversal(t) {
  3088. return this.root.reverseTraversal(t);
  3089. }
  3090. // Returns an iterator over the SortedMap.
  3091. getIterator() {
  3092. return new We(this.root, null, this.comparator, !1);
  3093. }
  3094. getIteratorFrom(t) {
  3095. return new We(this.root, t, this.comparator, !1);
  3096. }
  3097. getReverseIterator() {
  3098. return new We(this.root, null, this.comparator, !0);
  3099. }
  3100. getReverseIteratorFrom(t) {
  3101. return new We(this.root, t, this.comparator, !0);
  3102. }
  3103. }
  3104. // end SortedMap
  3105. // An iterator over an LLRBNode.
  3106. class We {
  3107. constructor(t, e, n, s) {
  3108. this.isReverse = s, this.nodeStack = [];
  3109. let i = 1;
  3110. for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1,
  3111. // flip the comparison if we're going in reverse
  3112. e && s && (i *= -1), i < 0)
  3113. // This node is less than our start key. ignore it
  3114. t = this.isReverse ? t.left : t.right; else {
  3115. if (0 === i) {
  3116. // This node is exactly equal to our start key. Push it on the stack,
  3117. // but stop iterating;
  3118. this.nodeStack.push(t);
  3119. break;
  3120. }
  3121. // This node is greater than our start key, add it to the stack and move
  3122. // to the next one
  3123. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  3124. }
  3125. }
  3126. getNext() {
  3127. let t = this.nodeStack.pop();
  3128. const e = {
  3129. key: t.key,
  3130. value: t.value
  3131. };
  3132. if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t),
  3133. t = t.left;
  3134. return e;
  3135. }
  3136. hasNext() {
  3137. return this.nodeStack.length > 0;
  3138. }
  3139. peek() {
  3140. if (0 === this.nodeStack.length) return null;
  3141. const t = this.nodeStack[this.nodeStack.length - 1];
  3142. return {
  3143. key: t.key,
  3144. value: t.value
  3145. };
  3146. }
  3147. }
  3148. // end SortedMapIterator
  3149. // Represents a node in a Left-leaning Red-Black tree.
  3150. class ze {
  3151. constructor(t, e, n, s, i) {
  3152. this.key = t, this.value = e, this.color = null != n ? n : ze.RED, this.left = null != s ? s : ze.EMPTY,
  3153. this.right = null != i ? i : ze.EMPTY, this.size = this.left.size + 1 + this.right.size;
  3154. }
  3155. // Returns a copy of the current node, optionally replacing pieces of it.
  3156. copy(t, e, n, s, i) {
  3157. return new ze(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);
  3158. }
  3159. isEmpty() {
  3160. return !1;
  3161. }
  3162. // Traverses the tree in key order and calls the specified action function
  3163. // for each node. If action returns true, traversal is aborted.
  3164. // Returns the first truthy value returned by action, or the last falsey
  3165. // value returned by action.
  3166. inorderTraversal(t) {
  3167. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  3168. }
  3169. // Traverses the tree in reverse key order and calls the specified action
  3170. // function for each node. If action returns true, traversal is aborted.
  3171. // Returns the first truthy value returned by action, or the last falsey
  3172. // value returned by action.
  3173. reverseTraversal(t) {
  3174. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  3175. }
  3176. // Returns the minimum node in the tree.
  3177. min() {
  3178. return this.left.isEmpty() ? this : this.left.min();
  3179. }
  3180. // Returns the maximum key in the tree.
  3181. minKey() {
  3182. return this.min().key;
  3183. }
  3184. // Returns the maximum key in the tree.
  3185. maxKey() {
  3186. return this.right.isEmpty() ? this.key : this.right.maxKey();
  3187. }
  3188. // Returns new tree, with the key/value added.
  3189. insert(t, e, n) {
  3190. let s = this;
  3191. const i = n(t, s.key);
  3192. return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)),
  3193. s.fixUp();
  3194. }
  3195. removeMin() {
  3196. if (this.left.isEmpty()) return ze.EMPTY;
  3197. let t = this;
  3198. return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null),
  3199. t.fixUp();
  3200. }
  3201. // Returns new tree, with the specified item removed.
  3202. remove(t, e) {
  3203. let n, s = this;
  3204. if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()),
  3205. s = s.copy(null, null, null, s.left.remove(t, e), null); else {
  3206. if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()),
  3207. 0 === e(t, s.key)) {
  3208. if (s.right.isEmpty()) return ze.EMPTY;
  3209. n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());
  3210. }
  3211. s = s.copy(null, null, null, null, s.right.remove(t, e));
  3212. }
  3213. return s.fixUp();
  3214. }
  3215. isRed() {
  3216. return this.color;
  3217. }
  3218. // Returns new tree after performing any needed rotations.
  3219. fixUp() {
  3220. let t = this;
  3221. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  3222. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  3223. }
  3224. moveRedLeft() {
  3225. let t = this.colorFlip();
  3226. return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()),
  3227. t = t.rotateLeft(), t = t.colorFlip()), t;
  3228. }
  3229. moveRedRight() {
  3230. let t = this.colorFlip();
  3231. return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;
  3232. }
  3233. rotateLeft() {
  3234. const t = this.copy(null, null, ze.RED, null, this.right.left);
  3235. return this.right.copy(null, null, this.color, t, null);
  3236. }
  3237. rotateRight() {
  3238. const t = this.copy(null, null, ze.RED, this.left.right, null);
  3239. return this.left.copy(null, null, this.color, null, t);
  3240. }
  3241. colorFlip() {
  3242. const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  3243. return this.copy(null, null, !this.color, t, e);
  3244. }
  3245. // For testing.
  3246. checkMaxDepth() {
  3247. const t = this.check();
  3248. return Math.pow(2, t) <= this.size + 1;
  3249. }
  3250. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  3251. // leaves is equal on both sides. This function verifies that or asserts.
  3252. check() {
  3253. if (this.isRed() && this.left.isRed()) throw M();
  3254. if (this.right.isRed()) throw M();
  3255. const t = this.left.check();
  3256. if (t !== this.right.check()) throw M();
  3257. return t + (this.isRed() ? 0 : 1);
  3258. }
  3259. }
  3260. // end LLRBNode
  3261. // Empty node is shared between all LLRB trees.
  3262. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3263. ze.EMPTY = null, ze.RED = !0, ze.BLACK = !1;
  3264. // end LLRBEmptyNode
  3265. ze.EMPTY = new
  3266. // Represents an empty node (a leaf node in the Red-Black Tree).
  3267. class {
  3268. constructor() {
  3269. this.size = 0;
  3270. }
  3271. get key() {
  3272. throw M();
  3273. }
  3274. get value() {
  3275. throw M();
  3276. }
  3277. get color() {
  3278. throw M();
  3279. }
  3280. get left() {
  3281. throw M();
  3282. }
  3283. get right() {
  3284. throw M();
  3285. }
  3286. // Returns a copy of the current node.
  3287. copy(t, e, n, s, i) {
  3288. return this;
  3289. }
  3290. // Returns a copy of the tree, with the specified key/value added.
  3291. insert(t, e, n) {
  3292. return new ze(t, e);
  3293. }
  3294. // Returns a copy of the tree, with the specified key removed.
  3295. remove(t, e) {
  3296. return this;
  3297. }
  3298. isEmpty() {
  3299. return !0;
  3300. }
  3301. inorderTraversal(t) {
  3302. return !1;
  3303. }
  3304. reverseTraversal(t) {
  3305. return !1;
  3306. }
  3307. minKey() {
  3308. return null;
  3309. }
  3310. maxKey() {
  3311. return null;
  3312. }
  3313. isRed() {
  3314. return !1;
  3315. }
  3316. // For testing.
  3317. checkMaxDepth() {
  3318. return !0;
  3319. }
  3320. check() {
  3321. return 0;
  3322. }
  3323. };
  3324. /**
  3325. * @license
  3326. * Copyright 2017 Google LLC
  3327. *
  3328. * Licensed under the Apache License, Version 2.0 (the "License");
  3329. * you may not use this file except in compliance with the License.
  3330. * You may obtain a copy of the License at
  3331. *
  3332. * http://www.apache.org/licenses/LICENSE-2.0
  3333. *
  3334. * Unless required by applicable law or agreed to in writing, software
  3335. * distributed under the License is distributed on an "AS IS" BASIS,
  3336. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3337. * See the License for the specific language governing permissions and
  3338. * limitations under the License.
  3339. */
  3340. /**
  3341. * SortedSet is an immutable (copy-on-write) collection that holds elements
  3342. * in order specified by the provided comparator.
  3343. *
  3344. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  3345. * be equal!
  3346. */
  3347. class He {
  3348. constructor(t) {
  3349. this.comparator = t, this.data = new je(this.comparator);
  3350. }
  3351. has(t) {
  3352. return null !== this.data.get(t);
  3353. }
  3354. first() {
  3355. return this.data.minKey();
  3356. }
  3357. last() {
  3358. return this.data.maxKey();
  3359. }
  3360. get size() {
  3361. return this.data.size;
  3362. }
  3363. indexOf(t) {
  3364. return this.data.indexOf(t);
  3365. }
  3366. /** Iterates elements in order defined by "comparator" */ forEach(t) {
  3367. this.data.inorderTraversal(((e, n) => (t(e), !1)));
  3368. }
  3369. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {
  3370. const n = this.data.getIteratorFrom(t[0]);
  3371. for (;n.hasNext(); ) {
  3372. const s = n.getNext();
  3373. if (this.comparator(s.key, t[1]) >= 0) return;
  3374. e(s.key);
  3375. }
  3376. }
  3377. /**
  3378. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  3379. */ forEachWhile(t, e) {
  3380. let n;
  3381. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {
  3382. if (!t(n.getNext().key)) return;
  3383. }
  3384. }
  3385. /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
  3386. const e = this.data.getIteratorFrom(t);
  3387. return e.hasNext() ? e.getNext().key : null;
  3388. }
  3389. getIterator() {
  3390. return new Je(this.data.getIterator());
  3391. }
  3392. getIteratorFrom(t) {
  3393. return new Je(this.data.getIteratorFrom(t));
  3394. }
  3395. /** Inserts or updates an element */ add(t) {
  3396. return this.copy(this.data.remove(t).insert(t, !0));
  3397. }
  3398. /** Deletes an element */ delete(t) {
  3399. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  3400. }
  3401. isEmpty() {
  3402. return this.data.isEmpty();
  3403. }
  3404. unionWith(t) {
  3405. let e = this;
  3406. // Make sure `result` always refers to the larger one of the two sets.
  3407. return e.size < t.size && (e = t, t = this), t.forEach((t => {
  3408. e = e.add(t);
  3409. })), e;
  3410. }
  3411. isEqual(t) {
  3412. if (!(t instanceof He)) return !1;
  3413. if (this.size !== t.size) return !1;
  3414. const e = this.data.getIterator(), n = t.data.getIterator();
  3415. for (;e.hasNext(); ) {
  3416. const t = e.getNext().key, s = n.getNext().key;
  3417. if (0 !== this.comparator(t, s)) return !1;
  3418. }
  3419. return !0;
  3420. }
  3421. toArray() {
  3422. const t = [];
  3423. return this.forEach((e => {
  3424. t.push(e);
  3425. })), t;
  3426. }
  3427. toString() {
  3428. const t = [];
  3429. return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
  3430. }
  3431. copy(t) {
  3432. const e = new He(this.comparator);
  3433. return e.data = t, e;
  3434. }
  3435. }
  3436. class Je {
  3437. constructor(t) {
  3438. this.iter = t;
  3439. }
  3440. getNext() {
  3441. return this.iter.getNext().key;
  3442. }
  3443. hasNext() {
  3444. return this.iter.hasNext();
  3445. }
  3446. }
  3447. /**
  3448. * Compares two sorted sets for equality using their natural ordering. The
  3449. * method computes the intersection and invokes `onAdd` for every element that
  3450. * is in `after` but not `before`. `onRemove` is invoked for every element in
  3451. * `before` but missing from `after`.
  3452. *
  3453. * The method creates a copy of both `before` and `after` and runs in O(n log
  3454. * n), where n is the size of the two lists.
  3455. *
  3456. * @param before - The elements that exist in the original set.
  3457. * @param after - The elements to diff against the original set.
  3458. * @param comparator - The comparator for the elements in before and after.
  3459. * @param onAdd - A function to invoke for every element that is part of `
  3460. * after` but not `before`.
  3461. * @param onRemove - A function to invoke for every element that is part of
  3462. * `before` but not `after`.
  3463. */
  3464. /**
  3465. * Returns the next element from the iterator or `undefined` if none available.
  3466. */
  3467. function Ye(t) {
  3468. return t.hasNext() ? t.getNext() : void 0;
  3469. }
  3470. /**
  3471. * @license
  3472. * Copyright 2020 Google LLC
  3473. *
  3474. * Licensed under the Apache License, Version 2.0 (the "License");
  3475. * you may not use this file except in compliance with the License.
  3476. * You may obtain a copy of the License at
  3477. *
  3478. * http://www.apache.org/licenses/LICENSE-2.0
  3479. *
  3480. * Unless required by applicable law or agreed to in writing, software
  3481. * distributed under the License is distributed on an "AS IS" BASIS,
  3482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3483. * See the License for the specific language governing permissions and
  3484. * limitations under the License.
  3485. */
  3486. /**
  3487. * Provides a set of fields that can be used to partially patch a document.
  3488. * FieldMask is used in conjunction with ObjectValue.
  3489. * Examples:
  3490. * foo - Overwrites foo entirely with the provided value. If foo is not
  3491. * present in the companion ObjectValue, the field is deleted.
  3492. * foo.bar - Overwrites only the field bar of the object foo.
  3493. * If foo is not an object, foo is replaced with an object
  3494. * containing foo
  3495. */ class Xe {
  3496. constructor(t) {
  3497. this.fields = t,
  3498. // TODO(dimond): validation of FieldMask
  3499. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  3500. t.sort(ct.comparator);
  3501. }
  3502. static empty() {
  3503. return new Xe([]);
  3504. }
  3505. /**
  3506. * Returns a new FieldMask object that is the result of adding all the given
  3507. * fields paths to this field mask.
  3508. */ unionWith(t) {
  3509. let e = new He(ct.comparator);
  3510. for (const t of this.fields) e = e.add(t);
  3511. for (const n of t) e = e.add(n);
  3512. return new Xe(e.toArray());
  3513. }
  3514. /**
  3515. * Verifies that `fieldPath` is included by at least one field in this field
  3516. * mask.
  3517. *
  3518. * This is an O(n) operation, where `n` is the size of the field mask.
  3519. */ covers(t) {
  3520. for (const e of this.fields) if (e.isPrefixOf(t)) return !0;
  3521. return !1;
  3522. }
  3523. isEqual(t) {
  3524. return et(this.fields, t.fields, ((t, e) => t.isEqual(e)));
  3525. }
  3526. }
  3527. /**
  3528. * @license
  3529. * Copyright 2017 Google LLC
  3530. *
  3531. * Licensed under the Apache License, Version 2.0 (the "License");
  3532. * you may not use this file except in compliance with the License.
  3533. * You may obtain a copy of the License at
  3534. *
  3535. * http://www.apache.org/licenses/LICENSE-2.0
  3536. *
  3537. * Unless required by applicable law or agreed to in writing, software
  3538. * distributed under the License is distributed on an "AS IS" BASIS,
  3539. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3540. * See the License for the specific language governing permissions and
  3541. * limitations under the License.
  3542. */
  3543. /**
  3544. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3545. * ability to add and remove fields (via the ObjectValueBuilder).
  3546. */ class Ze {
  3547. constructor(t) {
  3548. this.value = t;
  3549. }
  3550. static empty() {
  3551. return new Ze({
  3552. mapValue: {}
  3553. });
  3554. }
  3555. /**
  3556. * Returns the value at the given path or null.
  3557. *
  3558. * @param path - the path to search
  3559. * @returns The value at the path or null if the path is not set.
  3560. */ field(t) {
  3561. if (t.isEmpty()) return this.value;
  3562. {
  3563. let e = this.value;
  3564. for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)],
  3565. !we(e)) return null;
  3566. return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;
  3567. }
  3568. }
  3569. /**
  3570. * Sets the field to the provided value.
  3571. *
  3572. * @param path - The field path to set.
  3573. * @param value - The value to set.
  3574. */ set(t, e) {
  3575. this.getFieldsMap(t.popLast())[t.lastSegment()] = me(e);
  3576. }
  3577. /**
  3578. * Sets the provided fields to the provided values.
  3579. *
  3580. * @param data - A map of fields to values (or null for deletes).
  3581. */ setAll(t) {
  3582. let e = ct.emptyPath(), n = {}, s = [];
  3583. t.forEach(((t, i) => {
  3584. if (!e.isImmediateParentOf(i)) {
  3585. // Insert the accumulated changes at this parent location
  3586. const t = this.getFieldsMap(e);
  3587. this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();
  3588. }
  3589. t ? n[i.lastSegment()] = me(t) : s.push(i.lastSegment());
  3590. }));
  3591. const i = this.getFieldsMap(e);
  3592. this.applyChanges(i, n, s);
  3593. }
  3594. /**
  3595. * Removes the field at the specified path. If there is no field at the
  3596. * specified path, nothing is changed.
  3597. *
  3598. * @param path - The field path to remove.
  3599. */ delete(t) {
  3600. const e = this.field(t.popLast());
  3601. we(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  3602. }
  3603. isEqual(t) {
  3604. return ie(this.value, t.value);
  3605. }
  3606. /**
  3607. * Returns the map that contains the leaf element of `path`. If the parent
  3608. * entry does not yet exist, or if it is not a map, a new map will be created.
  3609. */ getFieldsMap(t) {
  3610. let e = this.value;
  3611. e.mapValue.fields || (e.mapValue = {
  3612. fields: {}
  3613. });
  3614. for (let n = 0; n < t.length; ++n) {
  3615. let s = e.mapValue.fields[t.get(n)];
  3616. we(s) && s.mapValue.fields || (s = {
  3617. mapValue: {
  3618. fields: {}
  3619. }
  3620. }, e.mapValue.fields[t.get(n)] = s), e = s;
  3621. }
  3622. return e.mapValue.fields;
  3623. }
  3624. /**
  3625. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3626. * entries.
  3627. */ applyChanges(t, e, n) {
  3628. Lt(e, ((e, n) => t[e] = n));
  3629. for (const e of n) delete t[e];
  3630. }
  3631. clone() {
  3632. return new Ze(me(this.value));
  3633. }
  3634. }
  3635. /**
  3636. * Returns a FieldMask built from all fields in a MapValue.
  3637. */ function tn(t) {
  3638. const e = [];
  3639. return Lt(t.fields, ((t, n) => {
  3640. const s = new ct([ t ]);
  3641. if (we(n)) {
  3642. const t = tn(n.mapValue).fields;
  3643. if (0 === t.length)
  3644. // Preserve the empty map by adding it to the FieldMask.
  3645. e.push(s); else
  3646. // For nested and non-empty ObjectValues, add the FieldPath of the
  3647. // leaf nodes.
  3648. for (const n of t) e.push(s.child(n));
  3649. } else
  3650. // For nested and non-empty ObjectValues, add the FieldPath of the leaf
  3651. // nodes.
  3652. e.push(s);
  3653. })), new Xe(e);
  3654. }
  3655. /**
  3656. * @license
  3657. * Copyright 2017 Google LLC
  3658. *
  3659. * Licensed under the Apache License, Version 2.0 (the "License");
  3660. * you may not use this file except in compliance with the License.
  3661. * You may obtain a copy of the License at
  3662. *
  3663. * http://www.apache.org/licenses/LICENSE-2.0
  3664. *
  3665. * Unless required by applicable law or agreed to in writing, software
  3666. * distributed under the License is distributed on an "AS IS" BASIS,
  3667. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3668. * See the License for the specific language governing permissions and
  3669. * limitations under the License.
  3670. */
  3671. /**
  3672. * Represents a document in Firestore with a key, version, data and whether it
  3673. * has local mutations applied to it.
  3674. *
  3675. * Documents can transition between states via `convertToFoundDocument()`,
  3676. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3677. * not transition to one of these states even after all mutations have been
  3678. * applied, `isValidDocument()` returns false and the document should be removed
  3679. * from all views.
  3680. */ class en {
  3681. constructor(t, e, n, s, i, r, o) {
  3682. this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i,
  3683. this.data = r, this.documentState = o;
  3684. }
  3685. /**
  3686. * Creates a document with no known version or data, but which can serve as
  3687. * base document for mutations.
  3688. */ static newInvalidDocument(t) {
  3689. return new en(t, 0 /* DocumentType.INVALID */ ,
  3690. /* version */ it.min(),
  3691. /* readTime */ it.min(),
  3692. /* createTime */ it.min(), Ze.empty(), 0 /* DocumentState.SYNCED */);
  3693. }
  3694. /**
  3695. * Creates a new document that is known to exist with the given data at the
  3696. * given version.
  3697. */ static newFoundDocument(t, e, n, s) {
  3698. return new en(t, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  3699. /* version */ e,
  3700. /* readTime */ it.min(),
  3701. /* createTime */ n, s, 0 /* DocumentState.SYNCED */);
  3702. }
  3703. /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
  3704. return new en(t, 2 /* DocumentType.NO_DOCUMENT */ ,
  3705. /* version */ e,
  3706. /* readTime */ it.min(),
  3707. /* createTime */ it.min(), Ze.empty(), 0 /* DocumentState.SYNCED */);
  3708. }
  3709. /**
  3710. * Creates a new document that is known to exist at the given version but
  3711. * whose data is not known (e.g. a document that was updated without a known
  3712. * base document).
  3713. */ static newUnknownDocument(t, e) {
  3714. return new en(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3715. /* version */ e,
  3716. /* readTime */ it.min(),
  3717. /* createTime */ it.min(), Ze.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3718. }
  3719. /**
  3720. * Changes the document type to indicate that it exists and that its version
  3721. * and data are known.
  3722. */ convertToFoundDocument(t, e) {
  3723. // If a document is switching state from being an invalid or deleted
  3724. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3725. // update from Watch or due to applying a local set mutation on top
  3726. // of a deleted document, our best guess about its createTime would be the
  3727. // version at which the document transitioned to a FOUND_DOCUMENT.
  3728. return !this.createTime.isEqual(it.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  3729. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  3730. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3731. }
  3732. /**
  3733. * Changes the document type to indicate that it doesn't exist at the given
  3734. * version.
  3735. */ convertToNoDocument(t) {
  3736. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  3737. this.data = Ze.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3738. }
  3739. /**
  3740. * Changes the document type to indicate that it exists at a given version but
  3741. * that its data is not known (e.g. a document that was updated without a known
  3742. * base document).
  3743. */ convertToUnknownDocument(t) {
  3744. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3745. this.data = Ze.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  3746. this;
  3747. }
  3748. setHasCommittedMutations() {
  3749. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  3750. }
  3751. setHasLocalMutations() {
  3752. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = it.min(),
  3753. this;
  3754. }
  3755. setReadTime(t) {
  3756. return this.readTime = t, this;
  3757. }
  3758. get hasLocalMutations() {
  3759. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  3760. }
  3761. get hasCommittedMutations() {
  3762. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  3763. }
  3764. get hasPendingWrites() {
  3765. return this.hasLocalMutations || this.hasCommittedMutations;
  3766. }
  3767. isValidDocument() {
  3768. return 0 /* DocumentType.INVALID */ !== this.documentType;
  3769. }
  3770. isFoundDocument() {
  3771. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  3772. }
  3773. isNoDocument() {
  3774. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  3775. }
  3776. isUnknownDocument() {
  3777. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  3778. }
  3779. isEqual(t) {
  3780. return t instanceof en && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
  3781. }
  3782. mutableCopy() {
  3783. return new en(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3784. }
  3785. toString() {
  3786. return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  3787. }
  3788. }
  3789. /**
  3790. * Compares the value for field `field` in the provided documents. Throws if
  3791. * the field does not exist in both documents.
  3792. */
  3793. /**
  3794. * @license
  3795. * Copyright 2019 Google LLC
  3796. *
  3797. * Licensed under the Apache License, Version 2.0 (the "License");
  3798. * you may not use this file except in compliance with the License.
  3799. * You may obtain a copy of the License at
  3800. *
  3801. * http://www.apache.org/licenses/LICENSE-2.0
  3802. *
  3803. * Unless required by applicable law or agreed to in writing, software
  3804. * distributed under the License is distributed on an "AS IS" BASIS,
  3805. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3806. * See the License for the specific language governing permissions and
  3807. * limitations under the License.
  3808. */
  3809. // Visible for testing
  3810. class nn {
  3811. constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  3812. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i,
  3813. this.startAt = r, this.endAt = o, this.ft = null;
  3814. }
  3815. }
  3816. /**
  3817. * Initializes a Target with a path and optional additional query constraints.
  3818. * Path must currently be empty if this is a collection group query.
  3819. *
  3820. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  3821. * using this factory method, because `Query` provides an implicit `orderBy`
  3822. * property.
  3823. */ function sn(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  3824. return new nn(t, e, n, s, i, r, o);
  3825. }
  3826. function rn(t) {
  3827. const e = B(t);
  3828. if (null === e.ft) {
  3829. let t = e.path.canonicalString();
  3830. null !== e.collectionGroup && (t += "|cg:" + e.collectionGroup), t += "|f:", t += e.filters.map((t => xe(t))).join(","),
  3831. t += "|ob:", t += e.orderBy.map((t => function(t) {
  3832. // TODO(b/29183165): Make this collision robust.
  3833. return t.field.canonicalString() + t.dir;
  3834. }(t))).join(","), Ut(e.limit) || (t += "|l:", t += e.limit), e.startAt && (t += "|lb:",
  3835. t += e.startAt.inclusive ? "b:" : "a:", t += e.startAt.position.map((t => ce(t))).join(",")),
  3836. e.endAt && (t += "|ub:", t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((t => ce(t))).join(",")),
  3837. e.ft = t;
  3838. }
  3839. return e.ft;
  3840. }
  3841. function on(t, e) {
  3842. if (t.limit !== e.limit) return !1;
  3843. if (t.orderBy.length !== e.orderBy.length) return !1;
  3844. for (let n = 0; n < t.orderBy.length; n++) if (!Qe(t.orderBy[n], e.orderBy[n])) return !1;
  3845. if (t.filters.length !== e.filters.length) return !1;
  3846. for (let n = 0; n < t.filters.length; n++) if (!Ne(t.filters[n], e.filters[n])) return !1;
  3847. return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!Re(t.startAt, e.startAt) && Re(t.endAt, e.endAt)));
  3848. }
  3849. function un(t) {
  3850. return at.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  3851. }
  3852. /** Returns the field filters that target the given field path. */ function cn(t, e) {
  3853. return t.filters.filter((t => t instanceof Pe && t.field.isEqual(e)));
  3854. }
  3855. /**
  3856. * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
  3857. * filters. Returns `null` if there are no such filters.
  3858. */
  3859. /**
  3860. * Returns the value to use as the lower bound for ascending index segment at
  3861. * the provided `fieldPath` (or the upper bound for an descending segment).
  3862. */
  3863. function an(t, e, n) {
  3864. let s = ne, i = !0;
  3865. // Process all filters to find a value for the current field segment
  3866. for (const n of cn(t, e)) {
  3867. let t = ne, e = !0;
  3868. switch (n.op) {
  3869. case "<" /* Operator.LESS_THAN */ :
  3870. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3871. t = ye(n.value);
  3872. break;
  3873. case "==" /* Operator.EQUAL */ :
  3874. case "in" /* Operator.IN */ :
  3875. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3876. t = n.value;
  3877. break;
  3878. case ">" /* Operator.GREATER_THAN */ :
  3879. t = n.value, e = !1;
  3880. break;
  3881. case "!=" /* Operator.NOT_EQUAL */ :
  3882. case "not-in" /* Operator.NOT_IN */ :
  3883. t = ne;
  3884. // Remaining filters cannot be used as lower bounds.
  3885. }
  3886. Ie({
  3887. value: s,
  3888. inclusive: i
  3889. }, {
  3890. value: t,
  3891. inclusive: e
  3892. }) < 0 && (s = t, i = e);
  3893. }
  3894. // If there is an additional bound, compare the values against the existing
  3895. // range to see if we can narrow the scope.
  3896. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  3897. if (t.orderBy[r].field.isEqual(e)) {
  3898. const t = n.position[r];
  3899. Ie({
  3900. value: s,
  3901. inclusive: i
  3902. }, {
  3903. value: t,
  3904. inclusive: n.inclusive
  3905. }) < 0 && (s = t, i = n.inclusive);
  3906. break;
  3907. }
  3908. }
  3909. return {
  3910. value: s,
  3911. inclusive: i
  3912. };
  3913. }
  3914. /**
  3915. * Returns the value to use as the upper bound for ascending index segment at
  3916. * the provided `fieldPath` (or the lower bound for a descending segment).
  3917. */ function hn(t, e, n) {
  3918. let s = ee, i = !0;
  3919. // Process all filters to find a value for the current field segment
  3920. for (const n of cn(t, e)) {
  3921. let t = ee, e = !0;
  3922. switch (n.op) {
  3923. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3924. case ">" /* Operator.GREATER_THAN */ :
  3925. t = pe(n.value), e = !1;
  3926. break;
  3927. case "==" /* Operator.EQUAL */ :
  3928. case "in" /* Operator.IN */ :
  3929. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3930. t = n.value;
  3931. break;
  3932. case "<" /* Operator.LESS_THAN */ :
  3933. t = n.value, e = !1;
  3934. break;
  3935. case "!=" /* Operator.NOT_EQUAL */ :
  3936. case "not-in" /* Operator.NOT_IN */ :
  3937. t = ee;
  3938. // Remaining filters cannot be used as upper bounds.
  3939. }
  3940. Te({
  3941. value: s,
  3942. inclusive: i
  3943. }, {
  3944. value: t,
  3945. inclusive: e
  3946. }) > 0 && (s = t, i = e);
  3947. }
  3948. // If there is an additional bound, compare the values against the existing
  3949. // range to see if we can narrow the scope.
  3950. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  3951. if (t.orderBy[r].field.isEqual(e)) {
  3952. const t = n.position[r];
  3953. Te({
  3954. value: s,
  3955. inclusive: i
  3956. }, {
  3957. value: t,
  3958. inclusive: n.inclusive
  3959. }) > 0 && (s = t, i = n.inclusive);
  3960. break;
  3961. }
  3962. }
  3963. return {
  3964. value: s,
  3965. inclusive: i
  3966. };
  3967. }
  3968. /** Returns the number of segments of a perfect index for this target. */
  3969. /**
  3970. * @license
  3971. * Copyright 2017 Google LLC
  3972. *
  3973. * Licensed under the Apache License, Version 2.0 (the "License");
  3974. * you may not use this file except in compliance with the License.
  3975. * You may obtain a copy of the License at
  3976. *
  3977. * http://www.apache.org/licenses/LICENSE-2.0
  3978. *
  3979. * Unless required by applicable law or agreed to in writing, software
  3980. * distributed under the License is distributed on an "AS IS" BASIS,
  3981. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3982. * See the License for the specific language governing permissions and
  3983. * limitations under the License.
  3984. */
  3985. /**
  3986. * Query encapsulates all the query attributes we support in the SDK. It can
  3987. * be run against the LocalStore, as well as be converted to a `Target` to
  3988. * query the RemoteStore results.
  3989. *
  3990. * Visible for testing.
  3991. */
  3992. class ln {
  3993. /**
  3994. * Initializes a Query with a path and optional additional query constraints.
  3995. * Path must currently be empty if this is a collection group query.
  3996. */
  3997. constructor(t, e = null, n = [], s = [], i = null, r = "F" /* LimitType.First */ , o = null, u = null) {
  3998. this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s,
  3999. this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.dt = null,
  4000. // The corresponding `Target` of this `Query` instance.
  4001. this._t = null, this.startAt, this.endAt;
  4002. }
  4003. }
  4004. /** Creates a new Query instance with the options provided. */ function fn(t, e, n, s, i, r, o, u) {
  4005. return new ln(t, e, n, s, i, r, o, u);
  4006. }
  4007. /** Creates a new Query for a query that matches all documents at `path` */ function dn(t) {
  4008. return new ln(t);
  4009. }
  4010. /**
  4011. * Helper to convert a collection group query into a collection query at a
  4012. * specific path. This is used when executing collection group queries, since
  4013. * we have to split the query into a set of collection queries at multiple
  4014. * paths.
  4015. */
  4016. /**
  4017. * Returns true if this query does not specify any query constraints that
  4018. * could remove results.
  4019. */
  4020. function _n(t) {
  4021. return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());
  4022. }
  4023. function wn(t) {
  4024. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  4025. }
  4026. function mn(t) {
  4027. for (const e of t.filters) {
  4028. const t = e.getFirstInequalityField();
  4029. if (null !== t) return t;
  4030. }
  4031. return null;
  4032. }
  4033. /**
  4034. * Creates a new Query for a collection group query that matches all documents
  4035. * within the provided collection group.
  4036. */
  4037. /**
  4038. * Returns whether the query matches a collection group rather than a specific
  4039. * collection.
  4040. */
  4041. function gn(t) {
  4042. return null !== t.collectionGroup;
  4043. }
  4044. /**
  4045. * Returns the implicit order by constraint that is used to execute the Query,
  4046. * which can be different from the order by constraints the user provided (e.g.
  4047. * the SDK and backend always orders by `__name__`).
  4048. */ function yn(t) {
  4049. const e = B(t);
  4050. if (null === e.dt) {
  4051. e.dt = [];
  4052. const t = mn(e), n = wn(e);
  4053. if (null !== t && null === n)
  4054. // In order to implicitly add key ordering, we must also add the
  4055. // inequality filter field for it to be a valid query.
  4056. // Note that the default inequality field and key ordering is ascending.
  4057. t.isKeyField() || e.dt.push(new Ge(t)), e.dt.push(new Ge(ct.keyField(), "asc" /* Direction.ASCENDING */)); else {
  4058. let t = !1;
  4059. for (const n of e.explicitOrderBy) e.dt.push(n), n.field.isKeyField() && (t = !0);
  4060. if (!t) {
  4061. // The order of the implicit key ordering always matches the last
  4062. // explicit order by
  4063. const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  4064. e.dt.push(new Ge(ct.keyField(), t));
  4065. }
  4066. }
  4067. }
  4068. return e.dt;
  4069. }
  4070. /**
  4071. * Converts this `Query` instance to it's corresponding `Target` representation.
  4072. */ function pn(t) {
  4073. const e = B(t);
  4074. if (!e._t) if ("F" /* LimitType.First */ === e.limitType) e._t = sn(e.path, e.collectionGroup, yn(e), e.filters, e.limit, e.startAt, e.endAt); else {
  4075. // Flip the orderBy directions since we want the last results
  4076. const t = [];
  4077. for (const n of yn(e)) {
  4078. const e = "desc" /* Direction.DESCENDING */ === n.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  4079. t.push(new Ge(n.field, e));
  4080. }
  4081. // We need to swap the cursors to match the now-flipped query ordering.
  4082. const n = e.endAt ? new Ee(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new Ee(e.startAt.position, e.startAt.inclusive) : null;
  4083. // Now return as a LimitType.First query.
  4084. e._t = sn(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);
  4085. }
  4086. return e._t;
  4087. }
  4088. function In(t, e) {
  4089. e.getFirstInequalityField(), mn(t);
  4090. const n = t.filters.concat([ e ]);
  4091. return new ln(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  4092. }
  4093. function Tn(t, e, n) {
  4094. return new ln(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  4095. }
  4096. function En(t, e) {
  4097. return on(pn(t), pn(e)) && t.limitType === e.limitType;
  4098. }
  4099. // TODO(b/29183165): This is used to get a unique string from a query to, for
  4100. // example, use as a dictionary key, but the implementation is subject to
  4101. // collisions. Make it collision-free.
  4102. function An(t) {
  4103. return `${rn(pn(t))}|lt:${t.limitType}`;
  4104. }
  4105. function Rn(t) {
  4106. return `Query(target=${function(t) {
  4107. let e = t.path.canonicalString();
  4108. return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup),
  4109. t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Oe(t))).join(", ")}]`),
  4110. Ut(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {
  4111. return `${t.field.canonicalString()} (${t.dir})`;
  4112. }(t))).join(", ")}]`), t.startAt && (e += ", startAt: ", e += t.startAt.inclusive ? "b:" : "a:",
  4113. e += t.startAt.position.map((t => ce(t))).join(",")), t.endAt && (e += ", endAt: ",
  4114. e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((t => ce(t))).join(",")),
  4115. `Target(${e})`;
  4116. }(pn(t))}; limitType=${t.limitType})`;
  4117. }
  4118. /** Returns whether `doc` matches the constraints of `query`. */ function bn(t, e) {
  4119. return e.isFoundDocument() && function(t, e) {
  4120. const n = e.key.path;
  4121. return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : at.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
  4122. }
  4123. /**
  4124. * A document must have a value for every ordering clause in order to show up
  4125. * in the results.
  4126. */ (t, e) && function(t, e) {
  4127. // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
  4128. // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
  4129. // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
  4130. // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
  4131. // A document with content of {b:1} matches the filters, but does not match the orderBy because
  4132. // it's missing the field 'a'.
  4133. for (const n of yn(t))
  4134. // order by key always matches
  4135. if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;
  4136. return !0;
  4137. }(t, e) && function(t, e) {
  4138. for (const n of t.filters) if (!n.matches(e)) return !1;
  4139. return !0;
  4140. }
  4141. /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {
  4142. if (t.startAt && !
  4143. /**
  4144. * Returns true if a document sorts before a bound using the provided sort
  4145. * order.
  4146. */
  4147. function(t, e, n) {
  4148. const s = Ae(t, e, n);
  4149. return t.inclusive ? s <= 0 : s < 0;
  4150. }(t.startAt, yn(t), e)) return !1;
  4151. if (t.endAt && !function(t, e, n) {
  4152. const s = Ae(t, e, n);
  4153. return t.inclusive ? s >= 0 : s > 0;
  4154. }(t.endAt, yn(t), e)) return !1;
  4155. return !0;
  4156. }
  4157. /**
  4158. * Returns the collection group that this query targets.
  4159. *
  4160. * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
  4161. * synchronization for query results.
  4162. */ (t, e);
  4163. }
  4164. function Pn(t) {
  4165. return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));
  4166. }
  4167. /**
  4168. * Returns a new comparator function that can be used to compare two documents
  4169. * based on the Query's ordering constraint.
  4170. */ function vn(t) {
  4171. return (e, n) => {
  4172. let s = !1;
  4173. for (const i of yn(t)) {
  4174. const t = Vn(i, e, n);
  4175. if (0 !== t) return t;
  4176. s = s || i.field.isKeyField();
  4177. }
  4178. return 0;
  4179. };
  4180. }
  4181. function Vn(t, e, n) {
  4182. const s = t.field.isKeyField() ? at.comparator(e.key, n.key) : function(t, e, n) {
  4183. const s = e.data.field(t), i = n.data.field(t);
  4184. return null !== s && null !== i ? oe(s, i) : M();
  4185. }(t.field, e, n);
  4186. switch (t.dir) {
  4187. case "asc" /* Direction.ASCENDING */ :
  4188. return s;
  4189. case "desc" /* Direction.DESCENDING */ :
  4190. return -1 * s;
  4191. default:
  4192. return M();
  4193. }
  4194. }
  4195. /**
  4196. * @license
  4197. * Copyright 2020 Google LLC
  4198. *
  4199. * Licensed under the Apache License, Version 2.0 (the "License");
  4200. * you may not use this file except in compliance with the License.
  4201. * You may obtain a copy of the License at
  4202. *
  4203. * http://www.apache.org/licenses/LICENSE-2.0
  4204. *
  4205. * Unless required by applicable law or agreed to in writing, software
  4206. * distributed under the License is distributed on an "AS IS" BASIS,
  4207. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4208. * See the License for the specific language governing permissions and
  4209. * limitations under the License.
  4210. */
  4211. /**
  4212. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4213. * `useProto3Json` setting.
  4214. */ function Sn(t, e) {
  4215. if (t.wt) {
  4216. if (isNaN(e)) return {
  4217. doubleValue: "NaN"
  4218. };
  4219. if (e === 1 / 0) return {
  4220. doubleValue: "Infinity"
  4221. };
  4222. if (e === -1 / 0) return {
  4223. doubleValue: "-Infinity"
  4224. };
  4225. }
  4226. return {
  4227. doubleValue: Kt(e) ? "-0" : e
  4228. };
  4229. }
  4230. /**
  4231. * Returns an IntegerValue for `value`.
  4232. */ function Dn(t) {
  4233. return {
  4234. integerValue: "" + t
  4235. };
  4236. }
  4237. /**
  4238. * Returns a value for a number that's appropriate to put into a proto.
  4239. * The return value is an IntegerValue if it can safely represent the value,
  4240. * otherwise a DoubleValue is returned.
  4241. */ function Cn(t, e) {
  4242. return Gt(e) ? Dn(e) : Sn(t, e);
  4243. }
  4244. /**
  4245. * @license
  4246. * Copyright 2018 Google LLC
  4247. *
  4248. * Licensed under the Apache License, Version 2.0 (the "License");
  4249. * you may not use this file except in compliance with the License.
  4250. * You may obtain a copy of the License at
  4251. *
  4252. * http://www.apache.org/licenses/LICENSE-2.0
  4253. *
  4254. * Unless required by applicable law or agreed to in writing, software
  4255. * distributed under the License is distributed on an "AS IS" BASIS,
  4256. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4257. * See the License for the specific language governing permissions and
  4258. * limitations under the License.
  4259. */
  4260. /** Used to represent a field transform on a mutation. */ class xn {
  4261. constructor() {
  4262. // Make sure that the structural type of `TransformOperation` is unique.
  4263. // See https://github.com/microsoft/TypeScript/issues/5451
  4264. this._ = void 0;
  4265. }
  4266. }
  4267. /**
  4268. * Computes the local transform result against the provided `previousValue`,
  4269. * optionally using the provided localWriteTime.
  4270. */ function Nn(t, e, n) {
  4271. return t instanceof Mn ? function(t, e) {
  4272. const n = {
  4273. fields: {
  4274. __type__: {
  4275. stringValue: "server_timestamp"
  4276. },
  4277. __local_write_time__: {
  4278. timestampValue: {
  4279. seconds: t.seconds,
  4280. nanos: t.nanoseconds
  4281. }
  4282. }
  4283. }
  4284. };
  4285. return e && (n.fields.__previous_value__ = e), {
  4286. mapValue: n
  4287. };
  4288. }(n, e) : t instanceof Fn ? $n(t, e) : t instanceof Bn ? Ln(t, e) : function(t, e) {
  4289. // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
  4290. // precision and resolves overflows by reducing precision, we do not
  4291. // manually cap overflows at 2^63.
  4292. const n = On(t, e), s = Un(n) + Un(t.gt);
  4293. return le(n) && le(t.gt) ? Dn(s) : Sn(t.yt, s);
  4294. }(t, e);
  4295. }
  4296. /**
  4297. * Computes a final transform result after the transform has been acknowledged
  4298. * by the server, potentially using the server-provided transformResult.
  4299. */ function kn(t, e, n) {
  4300. // The server just sends null as the transform result for array operations,
  4301. // so we have to calculate a result the same as we do for local
  4302. // applications.
  4303. return t instanceof Fn ? $n(t, e) : t instanceof Bn ? Ln(t, e) : n;
  4304. }
  4305. /**
  4306. * If this transform operation is not idempotent, returns the base value to
  4307. * persist for this transform. If a base value is returned, the transform
  4308. * operation is always applied to this base value, even if document has
  4309. * already been updated.
  4310. *
  4311. * Base values provide consistent behavior for non-idempotent transforms and
  4312. * allow us to return the same latency-compensated value even if the backend
  4313. * has already applied the transform operation. The base value is null for
  4314. * idempotent transforms, as they can be re-played even if the backend has
  4315. * already applied them.
  4316. *
  4317. * @returns a base value to store along with the mutation, or null for
  4318. * idempotent transforms.
  4319. */ function On(t, e) {
  4320. return t instanceof qn ? le(n = e) || function(t) {
  4321. return !!t && "doubleValue" in t;
  4322. }
  4323. /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {
  4324. integerValue: 0
  4325. } : null;
  4326. var n;
  4327. }
  4328. /** Transforms a value into a server-generated timestamp. */
  4329. class Mn extends xn {}
  4330. /** Transforms an array value via a union operation. */ class Fn extends xn {
  4331. constructor(t) {
  4332. super(), this.elements = t;
  4333. }
  4334. }
  4335. function $n(t, e) {
  4336. const n = Kn(e);
  4337. for (const e of t.elements) n.some((t => ie(t, e))) || n.push(e);
  4338. return {
  4339. arrayValue: {
  4340. values: n
  4341. }
  4342. };
  4343. }
  4344. /** Transforms an array value via a remove operation. */ class Bn extends xn {
  4345. constructor(t) {
  4346. super(), this.elements = t;
  4347. }
  4348. }
  4349. function Ln(t, e) {
  4350. let n = Kn(e);
  4351. for (const e of t.elements) n = n.filter((t => !ie(t, e)));
  4352. return {
  4353. arrayValue: {
  4354. values: n
  4355. }
  4356. };
  4357. }
  4358. /**
  4359. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4360. * transforms. Converts all field values to integers or doubles, but unlike the
  4361. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4362. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4363. */ class qn extends xn {
  4364. constructor(t, e) {
  4365. super(), this.yt = t, this.gt = e;
  4366. }
  4367. }
  4368. function Un(t) {
  4369. return Jt(t.integerValue || t.doubleValue);
  4370. }
  4371. function Kn(t) {
  4372. return fe(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
  4373. }
  4374. /**
  4375. * @license
  4376. * Copyright 2017 Google LLC
  4377. *
  4378. * Licensed under the Apache License, Version 2.0 (the "License");
  4379. * you may not use this file except in compliance with the License.
  4380. * You may obtain a copy of the License at
  4381. *
  4382. * http://www.apache.org/licenses/LICENSE-2.0
  4383. *
  4384. * Unless required by applicable law or agreed to in writing, software
  4385. * distributed under the License is distributed on an "AS IS" BASIS,
  4386. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4387. * See the License for the specific language governing permissions and
  4388. * limitations under the License.
  4389. */
  4390. /** A field path and the TransformOperation to perform upon it. */ class Gn {
  4391. constructor(t, e) {
  4392. this.field = t, this.transform = e;
  4393. }
  4394. }
  4395. function Qn(t, e) {
  4396. return t.field.isEqual(e.field) && function(t, e) {
  4397. return t instanceof Fn && e instanceof Fn || t instanceof Bn && e instanceof Bn ? et(t.elements, e.elements, ie) : t instanceof qn && e instanceof qn ? ie(t.gt, e.gt) : t instanceof Mn && e instanceof Mn;
  4398. }(t.transform, e.transform);
  4399. }
  4400. /** The result of successfully applying a mutation to the backend. */
  4401. class jn {
  4402. constructor(
  4403. /**
  4404. * The version at which the mutation was committed:
  4405. *
  4406. * - For most operations, this is the updateTime in the WriteResult.
  4407. * - For deletes, the commitTime of the WriteResponse (because deletes are
  4408. * not stored and have no updateTime).
  4409. *
  4410. * Note that these versions can be different: No-op writes will not change
  4411. * the updateTime even though the commitTime advances.
  4412. */
  4413. t,
  4414. /**
  4415. * The resulting fields returned from the backend after a mutation
  4416. * containing field transforms has been committed. Contains one FieldValue
  4417. * for each FieldTransform that was in the mutation.
  4418. *
  4419. * Will be empty if the mutation did not contain any field transforms.
  4420. */
  4421. e) {
  4422. this.version = t, this.transformResults = e;
  4423. }
  4424. }
  4425. /**
  4426. * Encodes a precondition for a mutation. This follows the model that the
  4427. * backend accepts with the special case of an explicit "empty" precondition
  4428. * (meaning no precondition).
  4429. */ class Wn {
  4430. constructor(t, e) {
  4431. this.updateTime = t, this.exists = e;
  4432. }
  4433. /** Creates a new empty Precondition. */ static none() {
  4434. return new Wn;
  4435. }
  4436. /** Creates a new Precondition with an exists flag. */ static exists(t) {
  4437. return new Wn(void 0, t);
  4438. }
  4439. /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {
  4440. return new Wn(t);
  4441. }
  4442. /** Returns whether this Precondition is empty. */ get isNone() {
  4443. return void 0 === this.updateTime && void 0 === this.exists;
  4444. }
  4445. isEqual(t) {
  4446. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  4447. }
  4448. }
  4449. /** Returns true if the preconditions is valid for the given document. */ function zn(t, e) {
  4450. return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
  4451. }
  4452. /**
  4453. * A mutation describes a self-contained change to a document. Mutations can
  4454. * create, replace, delete, and update subsets of documents.
  4455. *
  4456. * Mutations not only act on the value of the document but also its version.
  4457. *
  4458. * For local mutations (mutations that haven't been committed yet), we preserve
  4459. * the existing version for Set and Patch mutations. For Delete mutations, we
  4460. * reset the version to 0.
  4461. *
  4462. * Here's the expected transition table.
  4463. *
  4464. * MUTATION APPLIED TO RESULTS IN
  4465. *
  4466. * SetMutation Document(v3) Document(v3)
  4467. * SetMutation NoDocument(v3) Document(v0)
  4468. * SetMutation InvalidDocument(v0) Document(v0)
  4469. * PatchMutation Document(v3) Document(v3)
  4470. * PatchMutation NoDocument(v3) NoDocument(v3)
  4471. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4472. * DeleteMutation Document(v3) NoDocument(v0)
  4473. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4474. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4475. *
  4476. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4477. * the resulting version for Set and Patch mutations. As deletes have no
  4478. * explicit update time, we use the commitTime of the WriteResponse for
  4479. * Delete mutations.
  4480. *
  4481. * If a mutation is acknowledged by the backend but fails the precondition check
  4482. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4483. * the updated version.
  4484. *
  4485. * Field transforms are used only with Patch and Set Mutations. We use the
  4486. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4487. * messages.
  4488. *
  4489. * ## Subclassing Notes
  4490. *
  4491. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4492. * applyToLocalView() to implement the actual behavior of applying the mutation
  4493. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4494. * example).
  4495. */ class Hn {}
  4496. /**
  4497. * A utility method to calculate a `Mutation` representing the overlay from the
  4498. * final state of the document, and a `FieldMask` representing the fields that
  4499. * are mutated by the local mutations.
  4500. */ function Jn(t, e) {
  4501. if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;
  4502. // mask is null when sets or deletes are applied to the current document.
  4503. if (null === e) return t.isNoDocument() ? new os(t.key, Wn.none()) : new es(t.key, t.data, Wn.none());
  4504. {
  4505. const n = t.data, s = Ze.empty();
  4506. let i = new He(ct.comparator);
  4507. for (let t of e.fields) if (!i.has(t)) {
  4508. let e = n.field(t);
  4509. // If we are deleting a nested field, we take the immediate parent as
  4510. // the mask used to construct the resulting mutation.
  4511. // Justification: Nested fields can create parent fields implicitly. If
  4512. // only a leaf entry is deleted in later mutations, the parent field
  4513. // should still remain, but we may have lost this information.
  4514. // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
  4515. // This leaves the final result (foo, {}). Despite the fact that `doc`
  4516. // has the correct result, `foo` is not in `mask`, and the resulting
  4517. // mutation would miss `foo`.
  4518. null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e),
  4519. i = i.add(t);
  4520. }
  4521. return new ns(t.key, s, new Xe(i.toArray()), Wn.none());
  4522. }
  4523. }
  4524. /**
  4525. * Applies this mutation to the given document for the purposes of computing a
  4526. * new remote document. If the input document doesn't match the expected state
  4527. * (e.g. it is invalid or outdated), the document type may transition to
  4528. * unknown.
  4529. *
  4530. * @param mutation - The mutation to apply.
  4531. * @param document - The document to mutate. The input document can be an
  4532. * invalid document if the client has no knowledge of the pre-mutation state
  4533. * of the document.
  4534. * @param mutationResult - The result of applying the mutation from the backend.
  4535. */ function Yn(t, e, n) {
  4536. t instanceof es ? function(t, e, n) {
  4537. // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
  4538. // remote document the server has accepted the mutation so the precondition
  4539. // must have held.
  4540. const s = t.value.clone(), i = is(t.fieldTransforms, e, n.transformResults);
  4541. s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();
  4542. }(t, e, n) : t instanceof ns ? function(t, e, n) {
  4543. if (!zn(t.precondition, e))
  4544. // Since the mutation was not rejected, we know that the precondition
  4545. // matched on the backend. We therefore must not have the expected version
  4546. // of the document in our cache and convert to an UnknownDocument with a
  4547. // known updateTime.
  4548. return void e.convertToUnknownDocument(n.version);
  4549. const s = is(t.fieldTransforms, e, n.transformResults), i = e.data;
  4550. i.setAll(ss(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
  4551. }(t, e, n) : function(t, e, n) {
  4552. // Unlike applyToLocalView, if we're applying a mutation to a remote
  4553. // document the server has accepted the mutation so the precondition must
  4554. // have held.
  4555. e.convertToNoDocument(n.version).setHasCommittedMutations();
  4556. }(0, e, n);
  4557. }
  4558. /**
  4559. * Applies this mutation to the given document for the purposes of computing
  4560. * the new local view of a document. If the input document doesn't match the
  4561. * expected state, the document is not modified.
  4562. *
  4563. * @param mutation - The mutation to apply.
  4564. * @param document - The document to mutate. The input document can be an
  4565. * invalid document if the client has no knowledge of the pre-mutation state
  4566. * of the document.
  4567. * @param previousMask - The fields that have been updated before applying this mutation.
  4568. * @param localWriteTime - A timestamp indicating the local write time of the
  4569. * batch this mutation is a part of.
  4570. * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
  4571. */ function Xn(t, e, n, s) {
  4572. return t instanceof es ? function(t, e, n, s) {
  4573. if (!zn(t.precondition, e))
  4574. // The mutation failed to apply (e.g. a document ID created with add()
  4575. // caused a name collision).
  4576. return n;
  4577. const i = t.value.clone(), r = rs(t.fieldTransforms, s, e);
  4578. return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(),
  4579. null;
  4580. // SetMutation overwrites all fields.
  4581. }
  4582. /**
  4583. * A mutation that modifies fields of the document at the given key with the
  4584. * given values. The values are applied through a field mask:
  4585. *
  4586. * * When a field is in both the mask and the values, the corresponding field
  4587. * is updated.
  4588. * * When a field is in neither the mask nor the values, the corresponding
  4589. * field is unmodified.
  4590. * * When a field is in the mask but not in the values, the corresponding field
  4591. * is deleted.
  4592. * * When a field is not in the mask but is in the values, the values map is
  4593. * ignored.
  4594. */ (t, e, n, s) : t instanceof ns ? function(t, e, n, s) {
  4595. if (!zn(t.precondition, e)) return n;
  4596. const i = rs(t.fieldTransforms, s, e), r = e.data;
  4597. if (r.setAll(ss(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(),
  4598. null === n) return null;
  4599. return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));
  4600. }
  4601. /**
  4602. * Returns a FieldPath/Value map with the content of the PatchMutation.
  4603. */ (t, e, n, s) : function(t, e, n) {
  4604. if (zn(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(),
  4605. null;
  4606. return n;
  4607. }
  4608. /**
  4609. * A mutation that verifies the existence of the document at the given key with
  4610. * the provided precondition.
  4611. *
  4612. * The `verify` operation is only used in Transactions, and this class serves
  4613. * primarily to facilitate serialization into protos.
  4614. */ (t, e, n);
  4615. }
  4616. /**
  4617. * If this mutation is not idempotent, returns the base value to persist with
  4618. * this mutation. If a base value is returned, the mutation is always applied
  4619. * to this base value, even if document has already been updated.
  4620. *
  4621. * The base value is a sparse object that consists of only the document
  4622. * fields for which this mutation contains a non-idempotent transformation
  4623. * (e.g. a numeric increment). The provided value guarantees consistent
  4624. * behavior for non-idempotent transforms and allow us to return the same
  4625. * latency-compensated value even if the backend has already applied the
  4626. * mutation. The base value is null for idempotent mutations, as they can be
  4627. * re-played even if the backend has already applied them.
  4628. *
  4629. * @returns a base value to store along with the mutation, or null for
  4630. * idempotent mutations.
  4631. */ function Zn(t, e) {
  4632. let n = null;
  4633. for (const s of t.fieldTransforms) {
  4634. const t = e.data.field(s.field), i = On(s.transform, t || null);
  4635. null != i && (null === n && (n = Ze.empty()), n.set(s.field, i));
  4636. }
  4637. return n || null;
  4638. }
  4639. function ts(t, e) {
  4640. return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {
  4641. return void 0 === t && void 0 === e || !(!t || !e) && et(t, e, ((t, e) => Qn(t, e)));
  4642. }(t.fieldTransforms, e.fieldTransforms) && (0 /* MutationType.Set */ === t.type ? t.value.isEqual(e.value) : 1 /* MutationType.Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask)))));
  4643. }
  4644. /**
  4645. * A mutation that creates or replaces the document at the given key with the
  4646. * object value contents.
  4647. */ class es extends Hn {
  4648. constructor(t, e, n, s = []) {
  4649. super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s,
  4650. this.type = 0 /* MutationType.Set */;
  4651. }
  4652. getFieldMask() {
  4653. return null;
  4654. }
  4655. }
  4656. class ns extends Hn {
  4657. constructor(t, e, n, s, i = []) {
  4658. super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s,
  4659. this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;
  4660. }
  4661. getFieldMask() {
  4662. return this.fieldMask;
  4663. }
  4664. }
  4665. function ss(t) {
  4666. const e = new Map;
  4667. return t.fieldMask.fields.forEach((n => {
  4668. if (!n.isEmpty()) {
  4669. const s = t.data.field(n);
  4670. e.set(n, s);
  4671. }
  4672. })), e;
  4673. }
  4674. /**
  4675. * Creates a list of "transform results" (a transform result is a field value
  4676. * representing the result of applying a transform) for use after a mutation
  4677. * containing transforms has been acknowledged by the server.
  4678. *
  4679. * @param fieldTransforms - The field transforms to apply the result to.
  4680. * @param mutableDocument - The current state of the document after applying all
  4681. * previous mutations.
  4682. * @param serverTransformResults - The transform results received by the server.
  4683. * @returns The transform results list.
  4684. */ function is(t, e, n) {
  4685. const s = new Map;
  4686. F(t.length === n.length);
  4687. for (let i = 0; i < n.length; i++) {
  4688. const r = t[i], o = r.transform, u = e.data.field(r.field);
  4689. s.set(r.field, kn(o, u, n[i]));
  4690. }
  4691. return s;
  4692. }
  4693. /**
  4694. * Creates a list of "transform results" (a transform result is a field value
  4695. * representing the result of applying a transform) for use when applying a
  4696. * transform locally.
  4697. *
  4698. * @param fieldTransforms - The field transforms to apply the result to.
  4699. * @param localWriteTime - The local time of the mutation (used to
  4700. * generate ServerTimestampValues).
  4701. * @param mutableDocument - The document to apply transforms on.
  4702. * @returns The transform results list.
  4703. */ function rs(t, e, n) {
  4704. const s = new Map;
  4705. for (const i of t) {
  4706. const t = i.transform, r = n.data.field(i.field);
  4707. s.set(i.field, Nn(t, r, e));
  4708. }
  4709. return s;
  4710. }
  4711. /** A mutation that deletes the document at the given key. */ class os extends Hn {
  4712. constructor(t, e) {
  4713. super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ ,
  4714. this.fieldTransforms = [];
  4715. }
  4716. getFieldMask() {
  4717. return null;
  4718. }
  4719. }
  4720. class us extends Hn {
  4721. constructor(t, e) {
  4722. super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ ,
  4723. this.fieldTransforms = [];
  4724. }
  4725. getFieldMask() {
  4726. return null;
  4727. }
  4728. }
  4729. /**
  4730. * @license
  4731. * Copyright 2017 Google LLC
  4732. *
  4733. * Licensed under the Apache License, Version 2.0 (the "License");
  4734. * you may not use this file except in compliance with the License.
  4735. * You may obtain a copy of the License at
  4736. *
  4737. * http://www.apache.org/licenses/LICENSE-2.0
  4738. *
  4739. * Unless required by applicable law or agreed to in writing, software
  4740. * distributed under the License is distributed on an "AS IS" BASIS,
  4741. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4742. * See the License for the specific language governing permissions and
  4743. * limitations under the License.
  4744. */ class cs {
  4745. // TODO(b/33078163): just use simplest form of existence filter for now
  4746. constructor(t) {
  4747. this.count = t;
  4748. }
  4749. }
  4750. /**
  4751. * @license
  4752. * Copyright 2017 Google LLC
  4753. *
  4754. * Licensed under the Apache License, Version 2.0 (the "License");
  4755. * you may not use this file except in compliance with the License.
  4756. * You may obtain a copy of the License at
  4757. *
  4758. * http://www.apache.org/licenses/LICENSE-2.0
  4759. *
  4760. * Unless required by applicable law or agreed to in writing, software
  4761. * distributed under the License is distributed on an "AS IS" BASIS,
  4762. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4763. * See the License for the specific language governing permissions and
  4764. * limitations under the License.
  4765. */
  4766. /**
  4767. * Error Codes describing the different ways GRPC can fail. These are copied
  4768. * directly from GRPC's sources here:
  4769. *
  4770. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  4771. *
  4772. * Important! The names of these identifiers matter because the string forms
  4773. * are used for reverse lookups from the webchannel stream. Do NOT change the
  4774. * names of these identifiers or change this into a const enum.
  4775. */ var as, hs;
  4776. /**
  4777. * Determines whether an error code represents a permanent error when received
  4778. * in response to a non-write operation.
  4779. *
  4780. * See isPermanentWriteError for classifying write errors.
  4781. */
  4782. function ls(t) {
  4783. switch (t) {
  4784. default:
  4785. return M();
  4786. case L.CANCELLED:
  4787. case L.UNKNOWN:
  4788. case L.DEADLINE_EXCEEDED:
  4789. case L.RESOURCE_EXHAUSTED:
  4790. case L.INTERNAL:
  4791. case L.UNAVAILABLE:
  4792. // Unauthenticated means something went wrong with our token and we need
  4793. // to retry with new credentials which will happen automatically.
  4794. case L.UNAUTHENTICATED:
  4795. return !1;
  4796. case L.INVALID_ARGUMENT:
  4797. case L.NOT_FOUND:
  4798. case L.ALREADY_EXISTS:
  4799. case L.PERMISSION_DENIED:
  4800. case L.FAILED_PRECONDITION:
  4801. // Aborted might be retried in some scenarios, but that is dependant on
  4802. // the context and should handled individually by the calling code.
  4803. // See https://cloud.google.com/apis/design/errors.
  4804. case L.ABORTED:
  4805. case L.OUT_OF_RANGE:
  4806. case L.UNIMPLEMENTED:
  4807. case L.DATA_LOSS:
  4808. return !0;
  4809. }
  4810. }
  4811. /**
  4812. * Determines whether an error code represents a permanent error when received
  4813. * in response to a write operation.
  4814. *
  4815. * Write operations must be handled specially because as of b/119437764, ABORTED
  4816. * errors on the write stream should be retried too (even though ABORTED errors
  4817. * are not generally retryable).
  4818. *
  4819. * Note that during the initial handshake on the write stream an ABORTED error
  4820. * signals that we should discard our stream token (i.e. it is permanent). This
  4821. * means a handshake error should be classified with isPermanentError, above.
  4822. */
  4823. /**
  4824. * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
  4825. * are not the same as HTTP status codes.
  4826. *
  4827. * @returns The Code equivalent to the given GRPC status code. Fails if there
  4828. * is no match.
  4829. */
  4830. function fs(t) {
  4831. if (void 0 === t)
  4832. // This shouldn't normally happen, but in certain error cases (like trying
  4833. // to send invalid proto messages) we may get an error with no GRPC code.
  4834. return N("GRPC error has no .code"), L.UNKNOWN;
  4835. switch (t) {
  4836. case as.OK:
  4837. return L.OK;
  4838. case as.CANCELLED:
  4839. return L.CANCELLED;
  4840. case as.UNKNOWN:
  4841. return L.UNKNOWN;
  4842. case as.DEADLINE_EXCEEDED:
  4843. return L.DEADLINE_EXCEEDED;
  4844. case as.RESOURCE_EXHAUSTED:
  4845. return L.RESOURCE_EXHAUSTED;
  4846. case as.INTERNAL:
  4847. return L.INTERNAL;
  4848. case as.UNAVAILABLE:
  4849. return L.UNAVAILABLE;
  4850. case as.UNAUTHENTICATED:
  4851. return L.UNAUTHENTICATED;
  4852. case as.INVALID_ARGUMENT:
  4853. return L.INVALID_ARGUMENT;
  4854. case as.NOT_FOUND:
  4855. return L.NOT_FOUND;
  4856. case as.ALREADY_EXISTS:
  4857. return L.ALREADY_EXISTS;
  4858. case as.PERMISSION_DENIED:
  4859. return L.PERMISSION_DENIED;
  4860. case as.FAILED_PRECONDITION:
  4861. return L.FAILED_PRECONDITION;
  4862. case as.ABORTED:
  4863. return L.ABORTED;
  4864. case as.OUT_OF_RANGE:
  4865. return L.OUT_OF_RANGE;
  4866. case as.UNIMPLEMENTED:
  4867. return L.UNIMPLEMENTED;
  4868. case as.DATA_LOSS:
  4869. return L.DATA_LOSS;
  4870. default:
  4871. return M();
  4872. }
  4873. }
  4874. /**
  4875. * Converts an HTTP response's error status to the equivalent error code.
  4876. *
  4877. * @param status - An HTTP error response status ("FAILED_PRECONDITION",
  4878. * "UNKNOWN", etc.)
  4879. * @returns The equivalent Code. Non-matching responses are mapped to
  4880. * Code.UNKNOWN.
  4881. */ (hs = as || (as = {}))[hs.OK = 0] = "OK", hs[hs.CANCELLED = 1] = "CANCELLED",
  4882. hs[hs.UNKNOWN = 2] = "UNKNOWN", hs[hs.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  4883. hs[hs.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", hs[hs.NOT_FOUND = 5] = "NOT_FOUND",
  4884. hs[hs.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", hs[hs.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  4885. hs[hs.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", hs[hs.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  4886. hs[hs.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", hs[hs.ABORTED = 10] = "ABORTED",
  4887. hs[hs.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", hs[hs.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  4888. hs[hs.INTERNAL = 13] = "INTERNAL", hs[hs.UNAVAILABLE = 14] = "UNAVAILABLE", hs[hs.DATA_LOSS = 15] = "DATA_LOSS";
  4889. /**
  4890. * @license
  4891. * Copyright 2017 Google LLC
  4892. *
  4893. * Licensed under the Apache License, Version 2.0 (the "License");
  4894. * you may not use this file except in compliance with the License.
  4895. * You may obtain a copy of the License at
  4896. *
  4897. * http://www.apache.org/licenses/LICENSE-2.0
  4898. *
  4899. * Unless required by applicable law or agreed to in writing, software
  4900. * distributed under the License is distributed on an "AS IS" BASIS,
  4901. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4902. * See the License for the specific language governing permissions and
  4903. * limitations under the License.
  4904. */
  4905. /**
  4906. * A map implementation that uses objects as keys. Objects must have an
  4907. * associated equals function and must be immutable. Entries in the map are
  4908. * stored together with the key being produced from the mapKeyFn. This map
  4909. * automatically handles collisions of keys.
  4910. */
  4911. class ds {
  4912. constructor(t, e) {
  4913. this.mapKeyFn = t, this.equalsFn = e,
  4914. /**
  4915. * The inner map for a key/value pair. Due to the possibility of collisions we
  4916. * keep a list of entries that we do a linear search through to find an actual
  4917. * match. Note that collisions should be rare, so we still expect near
  4918. * constant time lookups in practice.
  4919. */
  4920. this.inner = {},
  4921. /** The number of entries stored in the map */
  4922. this.innerSize = 0;
  4923. }
  4924. /** Get a value for this key, or undefined if it does not exist. */ get(t) {
  4925. const e = this.mapKeyFn(t), n = this.inner[e];
  4926. if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;
  4927. }
  4928. has(t) {
  4929. return void 0 !== this.get(t);
  4930. }
  4931. /** Put this key and value in the map. */ set(t, e) {
  4932. const n = this.mapKeyFn(t), s = this.inner[n];
  4933. if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;
  4934. for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t))
  4935. // This is updating an existing entry and does not increase `innerSize`.
  4936. return void (s[n] = [ t, e ]);
  4937. s.push([ t, e ]), this.innerSize++;
  4938. }
  4939. /**
  4940. * Remove this key from the map. Returns a boolean if anything was deleted.
  4941. */ delete(t) {
  4942. const e = this.mapKeyFn(t), n = this.inner[e];
  4943. if (void 0 === n) return !1;
  4944. for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1),
  4945. this.innerSize--, !0;
  4946. return !1;
  4947. }
  4948. forEach(t) {
  4949. Lt(this.inner, ((e, n) => {
  4950. for (const [e, s] of n) t(e, s);
  4951. }));
  4952. }
  4953. isEmpty() {
  4954. return qt(this.inner);
  4955. }
  4956. size() {
  4957. return this.innerSize;
  4958. }
  4959. }
  4960. /**
  4961. * @license
  4962. * Copyright 2017 Google LLC
  4963. *
  4964. * Licensed under the Apache License, Version 2.0 (the "License");
  4965. * you may not use this file except in compliance with the License.
  4966. * You may obtain a copy of the License at
  4967. *
  4968. * http://www.apache.org/licenses/LICENSE-2.0
  4969. *
  4970. * Unless required by applicable law or agreed to in writing, software
  4971. * distributed under the License is distributed on an "AS IS" BASIS,
  4972. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4973. * See the License for the specific language governing permissions and
  4974. * limitations under the License.
  4975. */ const _s = new je(at.comparator);
  4976. function ws() {
  4977. return _s;
  4978. }
  4979. const ms = new je(at.comparator);
  4980. function gs(...t) {
  4981. let e = ms;
  4982. for (const n of t) e = e.insert(n.key, n);
  4983. return e;
  4984. }
  4985. function ys(t) {
  4986. let e = ms;
  4987. return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;
  4988. }
  4989. function ps() {
  4990. return Ts();
  4991. }
  4992. function Is() {
  4993. return Ts();
  4994. }
  4995. function Ts() {
  4996. return new ds((t => t.toString()), ((t, e) => t.isEqual(e)));
  4997. }
  4998. const Es = new je(at.comparator);
  4999. const As = new He(at.comparator);
  5000. function Rs(...t) {
  5001. let e = As;
  5002. for (const n of t) e = e.add(n);
  5003. return e;
  5004. }
  5005. const bs = new He(tt);
  5006. function Ps() {
  5007. return bs;
  5008. }
  5009. /**
  5010. * @license
  5011. * Copyright 2017 Google LLC
  5012. *
  5013. * Licensed under the Apache License, Version 2.0 (the "License");
  5014. * you may not use this file except in compliance with the License.
  5015. * You may obtain a copy of the License at
  5016. *
  5017. * http://www.apache.org/licenses/LICENSE-2.0
  5018. *
  5019. * Unless required by applicable law or agreed to in writing, software
  5020. * distributed under the License is distributed on an "AS IS" BASIS,
  5021. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5022. * See the License for the specific language governing permissions and
  5023. * limitations under the License.
  5024. */
  5025. /**
  5026. * An event from the RemoteStore. It is split into targetChanges (changes to the
  5027. * state or the set of documents in our watched targets) and documentUpdates
  5028. * (changes to the actual documents).
  5029. */ class vs {
  5030. constructor(
  5031. /**
  5032. * The snapshot version this event brings us up to, or MIN if not set.
  5033. */
  5034. t,
  5035. /**
  5036. * A map from target to changes to the target. See TargetChange.
  5037. */
  5038. e,
  5039. /**
  5040. * A set of targets that is known to be inconsistent. Listens for these
  5041. * targets should be re-established without resume tokens.
  5042. */
  5043. n,
  5044. /**
  5045. * A set of which documents have changed or been deleted, along with the
  5046. * doc's new values (if not deleted).
  5047. */
  5048. s,
  5049. /**
  5050. * A set of which document updates are due only to limbo resolution targets.
  5051. */
  5052. i) {
  5053. this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s,
  5054. this.resolvedLimboDocuments = i;
  5055. }
  5056. /**
  5057. * HACK: Views require RemoteEvents in order to determine whether the view is
  5058. * CURRENT, but secondary tabs don't receive remote events. So this method is
  5059. * used to create a synthesized RemoteEvent that can be used to apply a
  5060. * CURRENT status change to a View, for queries executed in a different tab.
  5061. */
  5062. // PORTING NOTE: Multi-tab only
  5063. static createSynthesizedRemoteEventForCurrentChange(t, e, n) {
  5064. const s = new Map;
  5065. return s.set(t, Vs.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new vs(it.min(), s, Ps(), ws(), Rs());
  5066. }
  5067. }
  5068. /**
  5069. * A TargetChange specifies the set of changes for a specific target as part of
  5070. * a RemoteEvent. These changes track which documents are added, modified or
  5071. * removed, as well as the target's resume token and whether the target is
  5072. * marked CURRENT.
  5073. * The actual changes *to* documents are not part of the TargetChange since
  5074. * documents may be part of multiple targets.
  5075. */ class Vs {
  5076. constructor(
  5077. /**
  5078. * An opaque, server-assigned token that allows watching a query to be resumed
  5079. * after disconnecting without retransmitting all the data that matches the
  5080. * query. The resume token essentially identifies a point in time from which
  5081. * the server should resume sending results.
  5082. */
  5083. t,
  5084. /**
  5085. * The "current" (synced) status of this target. Note that "current"
  5086. * has special meaning in the RPC protocol that implies that a target is
  5087. * both up-to-date and consistent with the rest of the watch stream.
  5088. */
  5089. e,
  5090. /**
  5091. * The set of documents that were newly assigned to this target as part of
  5092. * this remote event.
  5093. */
  5094. n,
  5095. /**
  5096. * The set of documents that were already assigned to this target but received
  5097. * an update during this remote event.
  5098. */
  5099. s,
  5100. /**
  5101. * The set of documents that were removed from this target as part of this
  5102. * remote event.
  5103. */
  5104. i) {
  5105. this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s,
  5106. this.removedDocuments = i;
  5107. }
  5108. /**
  5109. * This method is used to create a synthesized TargetChanges that can be used to
  5110. * apply a CURRENT status change to a View (for queries executed in a different
  5111. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5112. */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {
  5113. return new Vs(n, e, Rs(), Rs(), Rs());
  5114. }
  5115. }
  5116. /**
  5117. * @license
  5118. * Copyright 2017 Google LLC
  5119. *
  5120. * Licensed under the Apache License, Version 2.0 (the "License");
  5121. * you may not use this file except in compliance with the License.
  5122. * You may obtain a copy of the License at
  5123. *
  5124. * http://www.apache.org/licenses/LICENSE-2.0
  5125. *
  5126. * Unless required by applicable law or agreed to in writing, software
  5127. * distributed under the License is distributed on an "AS IS" BASIS,
  5128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5129. * See the License for the specific language governing permissions and
  5130. * limitations under the License.
  5131. */
  5132. /**
  5133. * Represents a changed document and a list of target ids to which this change
  5134. * applies.
  5135. *
  5136. * If document has been deleted NoDocument will be provided.
  5137. */ class Ss {
  5138. constructor(
  5139. /** The new document applies to all of these targets. */
  5140. t,
  5141. /** The new document is removed from all of these targets. */
  5142. e,
  5143. /** The key of the document for this change. */
  5144. n,
  5145. /**
  5146. * The new document or NoDocument if it was deleted. Is null if the
  5147. * document went out of view without the server sending a new document.
  5148. */
  5149. s) {
  5150. this.It = t, this.removedTargetIds = e, this.key = n, this.Tt = s;
  5151. }
  5152. }
  5153. class Ds {
  5154. constructor(t, e) {
  5155. this.targetId = t, this.Et = e;
  5156. }
  5157. }
  5158. class Cs {
  5159. constructor(
  5160. /** What kind of change occurred to the watch target. */
  5161. t,
  5162. /** The target IDs that were added/removed/set. */
  5163. e,
  5164. /**
  5165. * An opaque, server-assigned token that allows watching a target to be
  5166. * resumed after disconnecting without retransmitting all the data that
  5167. * matches the target. The resume token essentially identifies a point in
  5168. * time from which the server should resume sending results.
  5169. */
  5170. n = Wt.EMPTY_BYTE_STRING
  5171. /** An RPC error indicating why the watch failed. */ , s = null) {
  5172. this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;
  5173. }
  5174. }
  5175. /** Tracks the internal state of a Watch target. */ class xs {
  5176. constructor() {
  5177. /**
  5178. * The number of pending responses (adds or removes) that we are waiting on.
  5179. * We only consider targets active that have no pending responses.
  5180. */
  5181. this.At = 0,
  5182. /**
  5183. * Keeps track of the document changes since the last raised snapshot.
  5184. *
  5185. * These changes are continuously updated as we receive document updates and
  5186. * always reflect the current set of changes against the last issued snapshot.
  5187. */
  5188. this.Rt = Os(),
  5189. /** See public getters for explanations of these fields. */
  5190. this.bt = Wt.EMPTY_BYTE_STRING, this.Pt = !1,
  5191. /**
  5192. * Whether this target state should be included in the next snapshot. We
  5193. * initialize to true so that newly-added targets are included in the next
  5194. * RemoteEvent.
  5195. */
  5196. this.vt = !0;
  5197. }
  5198. /**
  5199. * Whether this target has been marked 'current'.
  5200. *
  5201. * 'Current' has special meaning in the RPC protocol: It implies that the
  5202. * Watch backend has sent us all changes up to the point at which the target
  5203. * was added and that the target is consistent with the rest of the watch
  5204. * stream.
  5205. */ get current() {
  5206. return this.Pt;
  5207. }
  5208. /** The last resume token sent to us for this target. */ get resumeToken() {
  5209. return this.bt;
  5210. }
  5211. /** Whether this target has pending target adds or target removes. */ get Vt() {
  5212. return 0 !== this.At;
  5213. }
  5214. /** Whether we have modified any state that should trigger a snapshot. */ get St() {
  5215. return this.vt;
  5216. }
  5217. /**
  5218. * Applies the resume token to the TargetChange, but only when it has a new
  5219. * value. Empty resumeTokens are discarded.
  5220. */ Dt(t) {
  5221. t.approximateByteSize() > 0 && (this.vt = !0, this.bt = t);
  5222. }
  5223. /**
  5224. * Creates a target change from the current set of changes.
  5225. *
  5226. * To reset the document changes after raising this snapshot, call
  5227. * `clearPendingChanges()`.
  5228. */ Ct() {
  5229. let t = Rs(), e = Rs(), n = Rs();
  5230. return this.Rt.forEach(((s, i) => {
  5231. switch (i) {
  5232. case 0 /* ChangeType.Added */ :
  5233. t = t.add(s);
  5234. break;
  5235. case 2 /* ChangeType.Modified */ :
  5236. e = e.add(s);
  5237. break;
  5238. case 1 /* ChangeType.Removed */ :
  5239. n = n.add(s);
  5240. break;
  5241. default:
  5242. M();
  5243. }
  5244. })), new Vs(this.bt, this.Pt, t, e, n);
  5245. }
  5246. /**
  5247. * Resets the document changes and sets `hasPendingChanges` to false.
  5248. */ xt() {
  5249. this.vt = !1, this.Rt = Os();
  5250. }
  5251. Nt(t, e) {
  5252. this.vt = !0, this.Rt = this.Rt.insert(t, e);
  5253. }
  5254. kt(t) {
  5255. this.vt = !0, this.Rt = this.Rt.remove(t);
  5256. }
  5257. Ot() {
  5258. this.At += 1;
  5259. }
  5260. Mt() {
  5261. this.At -= 1;
  5262. }
  5263. Ft() {
  5264. this.vt = !0, this.Pt = !0;
  5265. }
  5266. }
  5267. /**
  5268. * A helper class to accumulate watch changes into a RemoteEvent.
  5269. */
  5270. class Ns {
  5271. constructor(t) {
  5272. this.$t = t,
  5273. /** The internal state of all tracked targets. */
  5274. this.Bt = new Map,
  5275. /** Keeps track of the documents to update since the last raised snapshot. */
  5276. this.Lt = ws(),
  5277. /** A mapping of document keys to their set of target IDs. */
  5278. this.qt = ks(),
  5279. /**
  5280. * A list of targets with existence filter mismatches. These targets are
  5281. * known to be inconsistent and their listens needs to be re-established by
  5282. * RemoteStore.
  5283. */
  5284. this.Ut = new He(tt);
  5285. }
  5286. /**
  5287. * Processes and adds the DocumentWatchChange to the current set of changes.
  5288. */ Kt(t) {
  5289. for (const e of t.It) t.Tt && t.Tt.isFoundDocument() ? this.Gt(e, t.Tt) : this.Qt(e, t.key, t.Tt);
  5290. for (const e of t.removedTargetIds) this.Qt(e, t.key, t.Tt);
  5291. }
  5292. /** Processes and adds the WatchTargetChange to the current set of changes. */ jt(t) {
  5293. this.forEachTarget(t, (e => {
  5294. const n = this.Wt(e);
  5295. switch (t.state) {
  5296. case 0 /* WatchTargetChangeState.NoChange */ :
  5297. this.zt(e) && n.Dt(t.resumeToken);
  5298. break;
  5299. case 1 /* WatchTargetChangeState.Added */ :
  5300. // We need to decrement the number of pending acks needed from watch
  5301. // for this targetId.
  5302. n.Mt(), n.Vt ||
  5303. // We have a freshly added target, so we need to reset any state
  5304. // that we had previously. This can happen e.g. when remove and add
  5305. // back a target for existence filter mismatches.
  5306. n.xt(), n.Dt(t.resumeToken);
  5307. break;
  5308. case 2 /* WatchTargetChangeState.Removed */ :
  5309. // We need to keep track of removed targets to we can post-filter and
  5310. // remove any target changes.
  5311. // We need to decrement the number of pending acks needed from watch
  5312. // for this targetId.
  5313. n.Mt(), n.Vt || this.removeTarget(e);
  5314. break;
  5315. case 3 /* WatchTargetChangeState.Current */ :
  5316. this.zt(e) && (n.Ft(), n.Dt(t.resumeToken));
  5317. break;
  5318. case 4 /* WatchTargetChangeState.Reset */ :
  5319. this.zt(e) && (
  5320. // Reset the target and synthesizes removes for all existing
  5321. // documents. The backend will re-add any documents that still
  5322. // match the target before it sends the next global snapshot.
  5323. this.Ht(e), n.Dt(t.resumeToken));
  5324. break;
  5325. default:
  5326. M();
  5327. }
  5328. }));
  5329. }
  5330. /**
  5331. * Iterates over all targetIds that the watch change applies to: either the
  5332. * targetIds explicitly listed in the change or the targetIds of all currently
  5333. * active targets.
  5334. */ forEachTarget(t, e) {
  5335. t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Bt.forEach(((t, n) => {
  5336. this.zt(n) && e(n);
  5337. }));
  5338. }
  5339. /**
  5340. * Handles existence filters and synthesizes deletes for filter mismatches.
  5341. * Targets that are invalidated by filter mismatches are added to
  5342. * `pendingTargetResets`.
  5343. */ Jt(t) {
  5344. const e = t.targetId, n = t.Et.count, s = this.Yt(e);
  5345. if (s) {
  5346. const t = s.target;
  5347. if (un(t)) if (0 === n) {
  5348. // The existence filter told us the document does not exist. We deduce
  5349. // that this document does not exist and apply a deleted document to
  5350. // our updates. Without applying this deleted document there might be
  5351. // another query that will raise this document as part of a snapshot
  5352. // until it is resolved, essentially exposing inconsistency between
  5353. // queries.
  5354. const n = new at(t.path);
  5355. this.Qt(e, n, en.newNoDocument(n, it.min()));
  5356. } else F(1 === n); else {
  5357. this.Xt(e) !== n && (
  5358. // Existence filter mismatch: We reset the mapping and raise a new
  5359. // snapshot with `isFromCache:true`.
  5360. this.Ht(e), this.Ut = this.Ut.add(e));
  5361. }
  5362. }
  5363. }
  5364. /**
  5365. * Converts the currently accumulated state into a remote event at the
  5366. * provided snapshot version. Resets the accumulated changes before returning.
  5367. */ Zt(t) {
  5368. const e = new Map;
  5369. this.Bt.forEach(((n, s) => {
  5370. const i = this.Yt(s);
  5371. if (i) {
  5372. if (n.current && un(i.target)) {
  5373. // Document queries for document that don't exist can produce an empty
  5374. // result set. To update our local cache, we synthesize a document
  5375. // delete if we have not previously received the document. This
  5376. // resolves the limbo state of the document, removing it from
  5377. // limboDocumentRefs.
  5378. // TODO(dimond): Ideally we would have an explicit lookup target
  5379. // instead resulting in an explicit delete message and we could
  5380. // remove this special logic.
  5381. const e = new at(i.target.path);
  5382. null !== this.Lt.get(e) || this.te(s, e) || this.Qt(s, e, en.newNoDocument(e, t));
  5383. }
  5384. n.St && (e.set(s, n.Ct()), n.xt());
  5385. }
  5386. }));
  5387. let n = Rs();
  5388. // We extract the set of limbo-only document updates as the GC logic
  5389. // special-cases documents that do not appear in the target cache.
  5390. // TODO(gsoltis): Expand on this comment once GC is available in the JS
  5391. // client.
  5392. this.qt.forEach(((t, e) => {
  5393. let s = !0;
  5394. e.forEachWhile((t => {
  5395. const e = this.Yt(t);
  5396. return !e || 2 /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1, !1);
  5397. })), s && (n = n.add(t));
  5398. })), this.Lt.forEach(((e, n) => n.setReadTime(t)));
  5399. const s = new vs(t, e, this.Ut, this.Lt, n);
  5400. return this.Lt = ws(), this.qt = ks(), this.Ut = new He(tt), s;
  5401. }
  5402. /**
  5403. * Adds the provided document to the internal list of document updates and
  5404. * its document key to the given target's mapping.
  5405. */
  5406. // Visible for testing.
  5407. Gt(t, e) {
  5408. if (!this.zt(t)) return;
  5409. const n = this.te(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
  5410. this.Wt(t).Nt(e.key, n), this.Lt = this.Lt.insert(e.key, e), this.qt = this.qt.insert(e.key, this.ee(e.key).add(t));
  5411. }
  5412. /**
  5413. * Removes the provided document from the target mapping. If the
  5414. * document no longer matches the target, but the document's state is still
  5415. * known (e.g. we know that the document was deleted or we received the change
  5416. * that caused the filter mismatch), the new document can be provided
  5417. * to update the remote document cache.
  5418. */
  5419. // Visible for testing.
  5420. Qt(t, e, n) {
  5421. if (!this.zt(t)) return;
  5422. const s = this.Wt(t);
  5423. this.te(t, e) ? s.Nt(e, 1 /* ChangeType.Removed */) :
  5424. // The document may have entered and left the target before we raised a
  5425. // snapshot, so we can just ignore the change.
  5426. s.kt(e), this.qt = this.qt.insert(e, this.ee(e).delete(t)), n && (this.Lt = this.Lt.insert(e, n));
  5427. }
  5428. removeTarget(t) {
  5429. this.Bt.delete(t);
  5430. }
  5431. /**
  5432. * Returns the current count of documents in the target. This includes both
  5433. * the number of documents that the LocalStore considers to be part of the
  5434. * target as well as any accumulated changes.
  5435. */ Xt(t) {
  5436. const e = this.Wt(t).Ct();
  5437. return this.$t.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
  5438. }
  5439. /**
  5440. * Increment the number of acks needed from watch before we can consider the
  5441. * server to be 'in-sync' with the client's active targets.
  5442. */ Ot(t) {
  5443. this.Wt(t).Ot();
  5444. }
  5445. Wt(t) {
  5446. let e = this.Bt.get(t);
  5447. return e || (e = new xs, this.Bt.set(t, e)), e;
  5448. }
  5449. ee(t) {
  5450. let e = this.qt.get(t);
  5451. return e || (e = new He(tt), this.qt = this.qt.insert(t, e)), e;
  5452. }
  5453. /**
  5454. * Verifies that the user is still interested in this target (by calling
  5455. * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
  5456. * from watch.
  5457. */ zt(t) {
  5458. const e = null !== this.Yt(t);
  5459. return e || x("WatchChangeAggregator", "Detected inactive target", t), e;
  5460. }
  5461. /**
  5462. * Returns the TargetData for an active target (i.e. a target that the user
  5463. * is still interested in that has no outstanding target change requests).
  5464. */ Yt(t) {
  5465. const e = this.Bt.get(t);
  5466. return e && e.Vt ? null : this.$t.ne(t);
  5467. }
  5468. /**
  5469. * Resets the state of a Watch target to its initial state (e.g. sets
  5470. * 'current' to false, clears the resume token and removes its target mapping
  5471. * from all documents).
  5472. */ Ht(t) {
  5473. this.Bt.set(t, new xs);
  5474. this.$t.getRemoteKeysForTarget(t).forEach((e => {
  5475. this.Qt(t, e, /*updatedDocument=*/ null);
  5476. }));
  5477. }
  5478. /**
  5479. * Returns whether the LocalStore considers the document to be part of the
  5480. * specified target.
  5481. */ te(t, e) {
  5482. return this.$t.getRemoteKeysForTarget(t).has(e);
  5483. }
  5484. }
  5485. function ks() {
  5486. return new je(at.comparator);
  5487. }
  5488. function Os() {
  5489. return new je(at.comparator);
  5490. }
  5491. /**
  5492. * @license
  5493. * Copyright 2017 Google LLC
  5494. *
  5495. * Licensed under the Apache License, Version 2.0 (the "License");
  5496. * you may not use this file except in compliance with the License.
  5497. * You may obtain a copy of the License at
  5498. *
  5499. * http://www.apache.org/licenses/LICENSE-2.0
  5500. *
  5501. * Unless required by applicable law or agreed to in writing, software
  5502. * distributed under the License is distributed on an "AS IS" BASIS,
  5503. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5504. * See the License for the specific language governing permissions and
  5505. * limitations under the License.
  5506. */ const Ms = (() => {
  5507. const t = {
  5508. asc: "ASCENDING",
  5509. desc: "DESCENDING"
  5510. };
  5511. return t;
  5512. })(), Fs = (() => {
  5513. const t = {
  5514. "<": "LESS_THAN",
  5515. "<=": "LESS_THAN_OR_EQUAL",
  5516. ">": "GREATER_THAN",
  5517. ">=": "GREATER_THAN_OR_EQUAL",
  5518. "==": "EQUAL",
  5519. "!=": "NOT_EQUAL",
  5520. "array-contains": "ARRAY_CONTAINS",
  5521. in: "IN",
  5522. "not-in": "NOT_IN",
  5523. "array-contains-any": "ARRAY_CONTAINS_ANY"
  5524. };
  5525. return t;
  5526. })(), $s = (() => {
  5527. const t = {
  5528. and: "AND",
  5529. or: "OR"
  5530. };
  5531. return t;
  5532. })();
  5533. /**
  5534. * This class generates JsonObject values for the Datastore API suitable for
  5535. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  5536. *
  5537. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  5538. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  5539. * format.
  5540. *
  5541. * For a description of the Proto3 JSON format check
  5542. * https://developers.google.com/protocol-buffers/docs/proto3#json
  5543. *
  5544. * TODO(klimt): We can remove the databaseId argument if we keep the full
  5545. * resource name in documents.
  5546. */
  5547. class Bs {
  5548. constructor(t, e) {
  5549. this.databaseId = t, this.wt = e;
  5550. }
  5551. }
  5552. /**
  5553. * Returns a value for a Date that's appropriate to put into a proto.
  5554. */
  5555. function Ls(t, e) {
  5556. if (t.wt) {
  5557. return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
  5558. }
  5559. return {
  5560. seconds: "" + e.seconds,
  5561. nanos: e.nanoseconds
  5562. };
  5563. }
  5564. /**
  5565. * Returns a value for bytes that's appropriate to put in a proto.
  5566. *
  5567. * Visible for testing.
  5568. */
  5569. function qs(t, e) {
  5570. return t.wt ? e.toBase64() : e.toUint8Array();
  5571. }
  5572. /**
  5573. * Returns a ByteString based on the proto string value.
  5574. */ function Us(t, e) {
  5575. return Ls(t, e.toTimestamp());
  5576. }
  5577. function Ks(t) {
  5578. return F(!!t), it.fromTimestamp(function(t) {
  5579. const e = Ht(t);
  5580. return new st(e.seconds, e.nanos);
  5581. }(t));
  5582. }
  5583. function Gs(t, e) {
  5584. return function(t) {
  5585. return new ot([ "projects", t.projectId, "databases", t.database ]);
  5586. }(t).child("documents").child(e).canonicalString();
  5587. }
  5588. function Qs(t) {
  5589. const e = ot.fromString(t);
  5590. return F(gi(e)), e;
  5591. }
  5592. function js(t, e) {
  5593. return Gs(t.databaseId, e.path);
  5594. }
  5595. function Ws(t, e) {
  5596. const n = Qs(e);
  5597. if (n.get(1) !== t.databaseId.projectId) throw new q(L.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  5598. if (n.get(3) !== t.databaseId.database) throw new q(L.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  5599. return new at(Ys(n));
  5600. }
  5601. function zs(t, e) {
  5602. return Gs(t.databaseId, e);
  5603. }
  5604. function Hs(t) {
  5605. const e = Qs(t);
  5606. // In v1beta1 queries for collections at the root did not have a trailing
  5607. // "/documents". In v1 all resource paths contain "/documents". Preserve the
  5608. // ability to read the v1beta1 form for compatibility with queries persisted
  5609. // in the local target cache.
  5610. return 4 === e.length ? ot.emptyPath() : Ys(e);
  5611. }
  5612. function Js(t) {
  5613. return new ot([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  5614. }
  5615. function Ys(t) {
  5616. return F(t.length > 4 && "documents" === t.get(4)), t.popFirst(5);
  5617. }
  5618. /** Creates a Document proto from key and fields (but no create/update time) */ function Xs(t, e, n) {
  5619. return {
  5620. name: js(t, e),
  5621. fields: n.value.mapValue.fields
  5622. };
  5623. }
  5624. function Zs(t, e, n) {
  5625. const s = Ws(t, e.name), i = Ks(e.updateTime), r = e.createTime ? Ks(e.createTime) : it.min(), o = new Ze({
  5626. mapValue: {
  5627. fields: e.fields
  5628. }
  5629. }), u = en.newFoundDocument(s, i, r, o);
  5630. return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;
  5631. }
  5632. function ti(t, e) {
  5633. return "found" in e ? function(t, e) {
  5634. F(!!e.found), e.found.name, e.found.updateTime;
  5635. const n = Ws(t, e.found.name), s = Ks(e.found.updateTime), i = e.found.createTime ? Ks(e.found.createTime) : it.min(), r = new Ze({
  5636. mapValue: {
  5637. fields: e.found.fields
  5638. }
  5639. });
  5640. return en.newFoundDocument(n, s, i, r);
  5641. }(t, e) : "missing" in e ? function(t, e) {
  5642. F(!!e.missing), F(!!e.readTime);
  5643. const n = Ws(t, e.missing), s = Ks(e.readTime);
  5644. return en.newNoDocument(n, s);
  5645. }(t, e) : M();
  5646. }
  5647. function ei(t, e) {
  5648. let n;
  5649. if ("targetChange" in e) {
  5650. e.targetChange;
  5651. // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
  5652. // if unset
  5653. const s = function(t) {
  5654. return "NO_CHANGE" === t ? 0 /* WatchTargetChangeState.NoChange */ : "ADD" === t ? 1 /* WatchTargetChangeState.Added */ : "REMOVE" === t ? 2 /* WatchTargetChangeState.Removed */ : "CURRENT" === t ? 3 /* WatchTargetChangeState.Current */ : "RESET" === t ? 4 /* WatchTargetChangeState.Reset */ : M();
  5655. }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], r = function(t, e) {
  5656. return t.wt ? (F(void 0 === e || "string" == typeof e), Wt.fromBase64String(e || "")) : (F(void 0 === e || e instanceof Uint8Array),
  5657. Wt.fromUint8Array(e || new Uint8Array));
  5658. }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {
  5659. const e = void 0 === t.code ? L.UNKNOWN : fs(t.code);
  5660. return new q(e, t.message || "");
  5661. }
  5662. /**
  5663. * Returns a value for a number (or null) that's appropriate to put into
  5664. * a google.protobuf.Int32Value proto.
  5665. * DO NOT USE THIS FOR ANYTHING ELSE.
  5666. * This method cheats. It's typed as returning "number" because that's what
  5667. * our generated proto interfaces say Int32Value must be. But GRPC actually
  5668. * expects a { value: <number> } struct.
  5669. */ (o);
  5670. n = new Cs(s, i, r, u || null);
  5671. } else if ("documentChange" in e) {
  5672. e.documentChange;
  5673. const s = e.documentChange;
  5674. s.document, s.document.name, s.document.updateTime;
  5675. const i = Ws(t, s.document.name), r = Ks(s.document.updateTime), o = s.document.createTime ? Ks(s.document.createTime) : it.min(), u = new Ze({
  5676. mapValue: {
  5677. fields: s.document.fields
  5678. }
  5679. }), c = en.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];
  5680. n = new Ss(a, h, c.key, c);
  5681. } else if ("documentDelete" in e) {
  5682. e.documentDelete;
  5683. const s = e.documentDelete;
  5684. s.document;
  5685. const i = Ws(t, s.document), r = s.readTime ? Ks(s.readTime) : it.min(), o = en.newNoDocument(i, r), u = s.removedTargetIds || [];
  5686. n = new Ss([], u, o.key, o);
  5687. } else if ("documentRemove" in e) {
  5688. e.documentRemove;
  5689. const s = e.documentRemove;
  5690. s.document;
  5691. const i = Ws(t, s.document), r = s.removedTargetIds || [];
  5692. n = new Ss([], r, i, null);
  5693. } else {
  5694. if (!("filter" in e)) return M();
  5695. {
  5696. e.filter;
  5697. const t = e.filter;
  5698. t.targetId;
  5699. const s = t.count || 0, i = new cs(s), r = t.targetId;
  5700. n = new Ds(r, i);
  5701. }
  5702. }
  5703. return n;
  5704. }
  5705. function ni(t, e) {
  5706. let n;
  5707. if (e instanceof es) n = {
  5708. update: Xs(t, e.key, e.value)
  5709. }; else if (e instanceof os) n = {
  5710. delete: js(t, e.key)
  5711. }; else if (e instanceof ns) n = {
  5712. update: Xs(t, e.key, e.data),
  5713. updateMask: mi(e.fieldMask)
  5714. }; else {
  5715. if (!(e instanceof us)) return M();
  5716. n = {
  5717. verify: js(t, e.key)
  5718. };
  5719. }
  5720. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
  5721. const n = e.transform;
  5722. if (n instanceof Mn) return {
  5723. fieldPath: e.field.canonicalString(),
  5724. setToServerValue: "REQUEST_TIME"
  5725. };
  5726. if (n instanceof Fn) return {
  5727. fieldPath: e.field.canonicalString(),
  5728. appendMissingElements: {
  5729. values: n.elements
  5730. }
  5731. };
  5732. if (n instanceof Bn) return {
  5733. fieldPath: e.field.canonicalString(),
  5734. removeAllFromArray: {
  5735. values: n.elements
  5736. }
  5737. };
  5738. if (n instanceof qn) return {
  5739. fieldPath: e.field.canonicalString(),
  5740. increment: n.gt
  5741. };
  5742. throw M();
  5743. }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  5744. return void 0 !== e.updateTime ? {
  5745. updateTime: Us(t, e.updateTime)
  5746. } : void 0 !== e.exists ? {
  5747. exists: e.exists
  5748. } : M();
  5749. }(t, e.precondition)), n;
  5750. }
  5751. function si(t, e) {
  5752. const n = e.currentDocument ? function(t) {
  5753. return void 0 !== t.updateTime ? Wn.updateTime(Ks(t.updateTime)) : void 0 !== t.exists ? Wn.exists(t.exists) : Wn.none();
  5754. }(e.currentDocument) : Wn.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {
  5755. let n = null;
  5756. if ("setToServerValue" in e) F("REQUEST_TIME" === e.setToServerValue), n = new Mn; else if ("appendMissingElements" in e) {
  5757. const t = e.appendMissingElements.values || [];
  5758. n = new Fn(t);
  5759. } else if ("removeAllFromArray" in e) {
  5760. const t = e.removeAllFromArray.values || [];
  5761. n = new Bn(t);
  5762. } else "increment" in e ? n = new qn(t, e.increment) : M();
  5763. const s = ct.fromServerFormat(e.fieldPath);
  5764. return new Gn(s, n);
  5765. }(t, e))) : [];
  5766. if (e.update) {
  5767. e.update.name;
  5768. const i = Ws(t, e.update.name), r = new Ze({
  5769. mapValue: {
  5770. fields: e.update.fields
  5771. }
  5772. });
  5773. if (e.updateMask) {
  5774. const t = function(t) {
  5775. const e = t.fieldPaths || [];
  5776. return new Xe(e.map((t => ct.fromServerFormat(t))));
  5777. }(e.updateMask);
  5778. return new ns(i, r, t, n, s);
  5779. }
  5780. return new es(i, r, n, s);
  5781. }
  5782. if (e.delete) {
  5783. const s = Ws(t, e.delete);
  5784. return new os(s, n);
  5785. }
  5786. if (e.verify) {
  5787. const s = Ws(t, e.verify);
  5788. return new us(s, n);
  5789. }
  5790. return M();
  5791. }
  5792. function ii(t, e) {
  5793. return t && t.length > 0 ? (F(void 0 !== e), t.map((t => function(t, e) {
  5794. // NOTE: Deletes don't have an updateTime.
  5795. let n = t.updateTime ? Ks(t.updateTime) : Ks(e);
  5796. return n.isEqual(it.min()) && (
  5797. // The Firestore Emulator currently returns an update time of 0 for
  5798. // deletes of non-existing documents (rather than null). This breaks the
  5799. // test "get deleted doc while offline with source=cache" as NoDocuments
  5800. // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
  5801. // TODO(#2149): Remove this when Emulator is fixed
  5802. n = Ks(e)), new jn(n, t.transformResults || []);
  5803. }(t, e)))) : [];
  5804. }
  5805. function ri(t, e) {
  5806. return {
  5807. documents: [ zs(t, e.path) ]
  5808. };
  5809. }
  5810. function oi(t, e) {
  5811. // Dissect the path into parent, collectionId, and optional key filter.
  5812. const n = {
  5813. structuredQuery: {}
  5814. }, s = e.path;
  5815. null !== e.collectionGroup ? (n.parent = zs(t, s), n.structuredQuery.from = [ {
  5816. collectionId: e.collectionGroup,
  5817. allDescendants: !0
  5818. } ]) : (n.parent = zs(t, s.popLast()), n.structuredQuery.from = [ {
  5819. collectionId: s.lastSegment()
  5820. } ]);
  5821. const i = function(t) {
  5822. if (0 === t.length) return;
  5823. return wi(ve.create(t, "and" /* CompositeOperator.AND */));
  5824. }(e.filters);
  5825. i && (n.structuredQuery.where = i);
  5826. const r = function(t) {
  5827. if (0 === t.length) return;
  5828. return t.map((t =>
  5829. // visible for testing
  5830. function(t) {
  5831. return {
  5832. field: di(t.field),
  5833. direction: hi(t.dir)
  5834. };
  5835. }(t)));
  5836. }(e.orderBy);
  5837. r && (n.structuredQuery.orderBy = r);
  5838. const o = function(t, e) {
  5839. return t.wt || Ut(e) ? e : {
  5840. value: e
  5841. };
  5842. }
  5843. /**
  5844. * Returns a number (or null) from a google.protobuf.Int32Value proto.
  5845. */ (t, e.limit);
  5846. var u;
  5847. return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {
  5848. before: (u = e.startAt).inclusive,
  5849. values: u.position
  5850. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  5851. return {
  5852. before: !t.inclusive,
  5853. values: t.position
  5854. };
  5855. }(e.endAt)), n;
  5856. }
  5857. function ui(t) {
  5858. let e = Hs(t.parent);
  5859. const n = t.structuredQuery, s = n.from ? n.from.length : 0;
  5860. let i = null;
  5861. if (s > 0) {
  5862. F(1 === s);
  5863. const t = n.from[0];
  5864. t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);
  5865. }
  5866. let r = [];
  5867. n.where && (r = function(t) {
  5868. const e = ai(t);
  5869. if (e instanceof ve && De(e)) return e.getFilters();
  5870. return [ e ];
  5871. }(n.where));
  5872. let o = [];
  5873. n.orderBy && (o = n.orderBy.map((t => function(t) {
  5874. return new Ge(_i(t.field),
  5875. // visible for testing
  5876. function(t) {
  5877. switch (t) {
  5878. case "ASCENDING":
  5879. return "asc" /* Direction.ASCENDING */;
  5880. case "DESCENDING":
  5881. return "desc" /* Direction.DESCENDING */;
  5882. default:
  5883. return;
  5884. }
  5885. }
  5886. // visible for testing
  5887. (t.direction));
  5888. }
  5889. // visible for testing
  5890. (t))));
  5891. let u = null;
  5892. n.limit && (u = function(t) {
  5893. let e;
  5894. return e = "object" == typeof t ? t.value : t, Ut(e) ? null : e;
  5895. }(n.limit));
  5896. let c = null;
  5897. n.startAt && (c = function(t) {
  5898. const e = !!t.before, n = t.values || [];
  5899. return new Ee(n, e);
  5900. }(n.startAt));
  5901. let a = null;
  5902. return n.endAt && (a = function(t) {
  5903. const e = !t.before, n = t.values || [];
  5904. return new Ee(n, e);
  5905. }
  5906. // visible for testing
  5907. (n.endAt)), fn(e, i, o, r, u, "F" /* LimitType.First */ , c, a);
  5908. }
  5909. function ci(t, e) {
  5910. const n = function(t, e) {
  5911. switch (e) {
  5912. case 0 /* TargetPurpose.Listen */ :
  5913. return null;
  5914. case 1 /* TargetPurpose.ExistenceFilterMismatch */ :
  5915. return "existence-filter-mismatch";
  5916. case 2 /* TargetPurpose.LimboResolution */ :
  5917. return "limbo-document";
  5918. default:
  5919. return M();
  5920. }
  5921. }(0, e.purpose);
  5922. return null == n ? null : {
  5923. "goog-listen-tags": n
  5924. };
  5925. }
  5926. function ai(t) {
  5927. return void 0 !== t.unaryFilter ? function(t) {
  5928. switch (t.unaryFilter.op) {
  5929. case "IS_NAN":
  5930. const e = _i(t.unaryFilter.field);
  5931. return Pe.create(e, "==" /* Operator.EQUAL */ , {
  5932. doubleValue: NaN
  5933. });
  5934. case "IS_NULL":
  5935. const n = _i(t.unaryFilter.field);
  5936. return Pe.create(n, "==" /* Operator.EQUAL */ , {
  5937. nullValue: "NULL_VALUE"
  5938. });
  5939. case "IS_NOT_NAN":
  5940. const s = _i(t.unaryFilter.field);
  5941. return Pe.create(s, "!=" /* Operator.NOT_EQUAL */ , {
  5942. doubleValue: NaN
  5943. });
  5944. case "IS_NOT_NULL":
  5945. const i = _i(t.unaryFilter.field);
  5946. return Pe.create(i, "!=" /* Operator.NOT_EQUAL */ , {
  5947. nullValue: "NULL_VALUE"
  5948. });
  5949. default:
  5950. return M();
  5951. }
  5952. }(t) : void 0 !== t.fieldFilter ? function(t) {
  5953. return Pe.create(_i(t.fieldFilter.field), function(t) {
  5954. switch (t) {
  5955. case "EQUAL":
  5956. return "==" /* Operator.EQUAL */;
  5957. case "NOT_EQUAL":
  5958. return "!=" /* Operator.NOT_EQUAL */;
  5959. case "GREATER_THAN":
  5960. return ">" /* Operator.GREATER_THAN */;
  5961. case "GREATER_THAN_OR_EQUAL":
  5962. return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;
  5963. case "LESS_THAN":
  5964. return "<" /* Operator.LESS_THAN */;
  5965. case "LESS_THAN_OR_EQUAL":
  5966. return "<=" /* Operator.LESS_THAN_OR_EQUAL */;
  5967. case "ARRAY_CONTAINS":
  5968. return "array-contains" /* Operator.ARRAY_CONTAINS */;
  5969. case "IN":
  5970. return "in" /* Operator.IN */;
  5971. case "NOT_IN":
  5972. return "not-in" /* Operator.NOT_IN */;
  5973. case "ARRAY_CONTAINS_ANY":
  5974. return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;
  5975. default:
  5976. return M();
  5977. }
  5978. }(t.fieldFilter.op), t.fieldFilter.value);
  5979. }(t) : void 0 !== t.compositeFilter ? function(t) {
  5980. return ve.create(t.compositeFilter.filters.map((t => ai(t))), function(t) {
  5981. switch (t) {
  5982. case "AND":
  5983. return "and" /* CompositeOperator.AND */;
  5984. case "OR":
  5985. return "or" /* CompositeOperator.OR */;
  5986. default:
  5987. return M();
  5988. }
  5989. }(t.compositeFilter.op));
  5990. }(t) : M();
  5991. }
  5992. function hi(t) {
  5993. return Ms[t];
  5994. }
  5995. function li(t) {
  5996. return Fs[t];
  5997. }
  5998. function fi(t) {
  5999. return $s[t];
  6000. }
  6001. function di(t) {
  6002. return {
  6003. fieldPath: t.canonicalString()
  6004. };
  6005. }
  6006. function _i(t) {
  6007. return ct.fromServerFormat(t.fieldPath);
  6008. }
  6009. function wi(t) {
  6010. return t instanceof Pe ? function(t) {
  6011. if ("==" /* Operator.EQUAL */ === t.op) {
  6012. if (_e(t.value)) return {
  6013. unaryFilter: {
  6014. field: di(t.field),
  6015. op: "IS_NAN"
  6016. }
  6017. };
  6018. if (de(t.value)) return {
  6019. unaryFilter: {
  6020. field: di(t.field),
  6021. op: "IS_NULL"
  6022. }
  6023. };
  6024. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  6025. if (_e(t.value)) return {
  6026. unaryFilter: {
  6027. field: di(t.field),
  6028. op: "IS_NOT_NAN"
  6029. }
  6030. };
  6031. if (de(t.value)) return {
  6032. unaryFilter: {
  6033. field: di(t.field),
  6034. op: "IS_NOT_NULL"
  6035. }
  6036. };
  6037. }
  6038. return {
  6039. fieldFilter: {
  6040. field: di(t.field),
  6041. op: li(t.op),
  6042. value: t.value
  6043. }
  6044. };
  6045. }(t) : t instanceof ve ? function(t) {
  6046. const e = t.getFilters().map((t => wi(t)));
  6047. if (1 === e.length) return e[0];
  6048. return {
  6049. compositeFilter: {
  6050. op: fi(t.op),
  6051. filters: e
  6052. }
  6053. };
  6054. }(t) : M();
  6055. }
  6056. function mi(t) {
  6057. const e = [];
  6058. return t.fields.forEach((t => e.push(t.canonicalString()))), {
  6059. fieldPaths: e
  6060. };
  6061. }
  6062. function gi(t) {
  6063. // Resource names have at least 4 components (project ID, database ID)
  6064. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  6065. }
  6066. /**
  6067. * @license
  6068. * Copyright 2017 Google LLC
  6069. *
  6070. * Licensed under the Apache License, Version 2.0 (the "License");
  6071. * you may not use this file except in compliance with the License.
  6072. * You may obtain a copy of the License at
  6073. *
  6074. * http://www.apache.org/licenses/LICENSE-2.0
  6075. *
  6076. * Unless required by applicable law or agreed to in writing, software
  6077. * distributed under the License is distributed on an "AS IS" BASIS,
  6078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6079. * See the License for the specific language governing permissions and
  6080. * limitations under the License.
  6081. */
  6082. /**
  6083. * Encodes a resource path into a IndexedDb-compatible string form.
  6084. */
  6085. function yi(t) {
  6086. let e = "";
  6087. for (let n = 0; n < t.length; n++) e.length > 0 && (e = Ii(e)), e = pi(t.get(n), e);
  6088. return Ii(e);
  6089. }
  6090. /** Encodes a single segment of a resource path into the given result */ function pi(t, e) {
  6091. let n = e;
  6092. const s = t.length;
  6093. for (let e = 0; e < s; e++) {
  6094. const s = t.charAt(e);
  6095. switch (s) {
  6096. case "\0":
  6097. n += "";
  6098. break;
  6099. case "":
  6100. n += "";
  6101. break;
  6102. default:
  6103. n += s;
  6104. }
  6105. }
  6106. return n;
  6107. }
  6108. /** Encodes a path separator into the given result */ function Ii(t) {
  6109. return t + "";
  6110. }
  6111. /**
  6112. * Decodes the given IndexedDb-compatible string form of a resource path into
  6113. * a ResourcePath instance. Note that this method is not suitable for use with
  6114. * decoding resource names from the server; those are One Platform format
  6115. * strings.
  6116. */ function Ti(t) {
  6117. // Event the empty path must encode as a path of at least length 2. A path
  6118. // with exactly 2 must be the empty path.
  6119. const e = t.length;
  6120. if (F(e >= 2), 2 === e) return F("" === t.charAt(0) && "" === t.charAt(1)), ot.emptyPath();
  6121. // Escape characters cannot exist past the second-to-last position in the
  6122. // source value.
  6123. const n = e - 2, s = [];
  6124. let i = "";
  6125. for (let r = 0; r < e; ) {
  6126. // The last two characters of a valid encoded path must be a separator, so
  6127. // there must be an end to this segment.
  6128. const e = t.indexOf("", r);
  6129. (e < 0 || e > n) && M();
  6130. switch (t.charAt(e + 1)) {
  6131. case "":
  6132. const n = t.substring(r, e);
  6133. let o;
  6134. 0 === i.length ?
  6135. // Avoid copying for the common case of a segment that excludes \0
  6136. // and \001
  6137. o = n : (i += n, o = i, i = ""), s.push(o);
  6138. break;
  6139. case "":
  6140. i += t.substring(r, e), i += "\0";
  6141. break;
  6142. case "":
  6143. // The escape character can be used in the output to encode itself.
  6144. i += t.substring(r, e + 1);
  6145. break;
  6146. default:
  6147. M();
  6148. }
  6149. r = e + 2;
  6150. }
  6151. return new ot(s);
  6152. }
  6153. /**
  6154. * @license
  6155. * Copyright 2022 Google LLC
  6156. *
  6157. * Licensed under the Apache License, Version 2.0 (the "License");
  6158. * you may not use this file except in compliance with the License.
  6159. * You may obtain a copy of the License at
  6160. *
  6161. * http://www.apache.org/licenses/LICENSE-2.0
  6162. *
  6163. * Unless required by applicable law or agreed to in writing, software
  6164. * distributed under the License is distributed on an "AS IS" BASIS,
  6165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6166. * See the License for the specific language governing permissions and
  6167. * limitations under the License.
  6168. */ const Ei = [ "userId", "batchId" ];
  6169. /**
  6170. * @license
  6171. * Copyright 2022 Google LLC
  6172. *
  6173. * Licensed under the Apache License, Version 2.0 (the "License");
  6174. * you may not use this file except in compliance with the License.
  6175. * You may obtain a copy of the License at
  6176. *
  6177. * http://www.apache.org/licenses/LICENSE-2.0
  6178. *
  6179. * Unless required by applicable law or agreed to in writing, software
  6180. * distributed under the License is distributed on an "AS IS" BASIS,
  6181. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6182. * See the License for the specific language governing permissions and
  6183. * limitations under the License.
  6184. */
  6185. /**
  6186. * Name of the IndexedDb object store.
  6187. *
  6188. * Note that the name 'owner' is chosen to ensure backwards compatibility with
  6189. * older clients that only supported single locked access to the persistence
  6190. * layer.
  6191. */
  6192. /**
  6193. * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
  6194. * index to iterate over all at document mutations for a given path or lower.
  6195. */
  6196. function Ai(t, e) {
  6197. return [ t, yi(e) ];
  6198. }
  6199. /**
  6200. * Creates a full index key of [userId, encodedPath, batchId] for inserting
  6201. * and deleting into the DbDocumentMutations index.
  6202. */ function Ri(t, e, n) {
  6203. return [ t, yi(e), n ];
  6204. }
  6205. /**
  6206. * Because we store all the useful information for this store in the key,
  6207. * there is no useful information to store as the value. The raw (unencoded)
  6208. * path cannot be stored because IndexedDb doesn't store prototype
  6209. * information.
  6210. */ const bi = {}, Pi = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], vi = [ "prefixPath", "collectionGroup", "documentId" ], Vi = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], Si = [ "canonicalId", "targetId" ], Di = [ "targetId", "path" ], Ci = [ "path", "targetId" ], xi = [ "collectionId", "parent" ], Ni = [ "indexId", "uid" ], ki = [ "uid", "sequenceNumber" ], Oi = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], Mi = [ "indexId", "uid", "orderedDocumentKey" ], Fi = [ "userId", "collectionPath", "documentId" ], $i = [ "userId", "collectionPath", "largestBatchId" ], Bi = [ "userId", "collectionGroup", "largestBatchId" ], Li = [ ...[ ...[ ...[ ...[ "mutationQueues", "mutations", "documentMutations", "remoteDocuments", "targets", "owner", "targetGlobal", "targetDocuments" ], "clientMetadata" ], "remoteDocumentGlobal" ], "collectionParents" ], "bundles", "namedQueries" ], qi = [ ...Li, "documentOverlays" ], Ui = [ "mutationQueues", "mutations", "documentMutations", "remoteDocumentsV14", "targets", "owner", "targetGlobal", "targetDocuments", "clientMetadata", "remoteDocumentGlobal", "collectionParents", "bundles", "namedQueries", "documentOverlays" ], Ki = Ui, Gi = [ ...Ki, "indexConfiguration", "indexState", "indexEntries" ];
  6211. /**
  6212. * @license
  6213. * Copyright 2020 Google LLC
  6214. *
  6215. * Licensed under the Apache License, Version 2.0 (the "License");
  6216. * you may not use this file except in compliance with the License.
  6217. * You may obtain a copy of the License at
  6218. *
  6219. * http://www.apache.org/licenses/LICENSE-2.0
  6220. *
  6221. * Unless required by applicable law or agreed to in writing, software
  6222. * distributed under the License is distributed on an "AS IS" BASIS,
  6223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6224. * See the License for the specific language governing permissions and
  6225. * limitations under the License.
  6226. */
  6227. class Qi extends Et {
  6228. constructor(t, e) {
  6229. super(), this.se = t, this.currentSequenceNumber = e;
  6230. }
  6231. }
  6232. function ji(t, e) {
  6233. const n = B(t);
  6234. return Pt.M(n.se, e);
  6235. }
  6236. /**
  6237. * @license
  6238. * Copyright 2017 Google LLC
  6239. *
  6240. * Licensed under the Apache License, Version 2.0 (the "License");
  6241. * you may not use this file except in compliance with the License.
  6242. * You may obtain a copy of the License at
  6243. *
  6244. * http://www.apache.org/licenses/LICENSE-2.0
  6245. *
  6246. * Unless required by applicable law or agreed to in writing, software
  6247. * distributed under the License is distributed on an "AS IS" BASIS,
  6248. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6249. * See the License for the specific language governing permissions and
  6250. * limitations under the License.
  6251. */
  6252. /**
  6253. * A batch of mutations that will be sent as one unit to the backend.
  6254. */ class Wi {
  6255. /**
  6256. * @param batchId - The unique ID of this mutation batch.
  6257. * @param localWriteTime - The original write time of this mutation.
  6258. * @param baseMutations - Mutations that are used to populate the base
  6259. * values when this mutation is applied locally. This can be used to locally
  6260. * overwrite values that are persisted in the remote document cache. Base
  6261. * mutations are never sent to the backend.
  6262. * @param mutations - The user-provided mutations in this mutation batch.
  6263. * User-provided mutations are applied both locally and remotely on the
  6264. * backend.
  6265. */
  6266. constructor(t, e, n, s) {
  6267. this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;
  6268. }
  6269. /**
  6270. * Applies all the mutations in this MutationBatch to the specified document
  6271. * to compute the state of the remote document
  6272. *
  6273. * @param document - The document to apply mutations to.
  6274. * @param batchResult - The result of applying the MutationBatch to the
  6275. * backend.
  6276. */ applyToRemoteDocument(t, e) {
  6277. const n = e.mutationResults;
  6278. for (let e = 0; e < this.mutations.length; e++) {
  6279. const s = this.mutations[e];
  6280. if (s.key.isEqual(t.key)) {
  6281. Yn(s, t, n[e]);
  6282. }
  6283. }
  6284. }
  6285. /**
  6286. * Computes the local view of a document given all the mutations in this
  6287. * batch.
  6288. *
  6289. * @param document - The document to apply mutations to.
  6290. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  6291. * @returns A `FieldMask` representing all the fields that are mutated.
  6292. */ applyToLocalView(t, e) {
  6293. // First, apply the base state. This allows us to apply non-idempotent
  6294. // transform against a consistent set of values.
  6295. for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = Xn(n, t, e, this.localWriteTime));
  6296. // Second, apply all user-provided mutations.
  6297. for (const n of this.mutations) n.key.isEqual(t.key) && (e = Xn(n, t, e, this.localWriteTime));
  6298. return e;
  6299. }
  6300. /**
  6301. * Computes the local view for all provided documents given the mutations in
  6302. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  6303. * replace all the mutation applications.
  6304. */ applyToLocalDocumentSet(t, e) {
  6305. // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
  6306. // directly (as done in `applyToLocalView()`), we can reduce the complexity
  6307. // to O(n).
  6308. const n = Is();
  6309. return this.mutations.forEach((s => {
  6310. const i = t.get(s.key), r = i.overlayedDocument;
  6311. // TODO(mutabledocuments): This method should take a MutableDocumentMap
  6312. // and we should remove this cast.
  6313. let o = this.applyToLocalView(r, i.mutatedFields);
  6314. // Set mutatedFields to null if the document is only from local mutations.
  6315. // This creates a Set or Delete mutation, instead of trying to create a
  6316. // patch mutation as the overlay.
  6317. o = e.has(s.key) ? null : o;
  6318. const u = Jn(r, o);
  6319. null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(it.min());
  6320. })), n;
  6321. }
  6322. keys() {
  6323. return this.mutations.reduce(((t, e) => t.add(e.key)), Rs());
  6324. }
  6325. isEqual(t) {
  6326. return this.batchId === t.batchId && et(this.mutations, t.mutations, ((t, e) => ts(t, e))) && et(this.baseMutations, t.baseMutations, ((t, e) => ts(t, e)));
  6327. }
  6328. }
  6329. /** The result of applying a mutation batch to the backend. */ class zi {
  6330. constructor(t, e, n,
  6331. /**
  6332. * A pre-computed mapping from each mutated document to the resulting
  6333. * version.
  6334. */
  6335. s) {
  6336. this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;
  6337. }
  6338. /**
  6339. * Creates a new MutationBatchResult for the given batch and results. There
  6340. * must be one result for each mutation in the batch. This static factory
  6341. * caches a document=&gt;version mapping (docVersions).
  6342. */ static from(t, e, n) {
  6343. F(t.mutations.length === n.length);
  6344. let s = Es;
  6345. const i = t.mutations;
  6346. for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);
  6347. return new zi(t, e, n, s);
  6348. }
  6349. }
  6350. /**
  6351. * @license
  6352. * Copyright 2022 Google LLC
  6353. *
  6354. * Licensed under the Apache License, Version 2.0 (the "License");
  6355. * you may not use this file except in compliance with the License.
  6356. * You may obtain a copy of the License at
  6357. *
  6358. * http://www.apache.org/licenses/LICENSE-2.0
  6359. *
  6360. * Unless required by applicable law or agreed to in writing, software
  6361. * distributed under the License is distributed on an "AS IS" BASIS,
  6362. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6363. * See the License for the specific language governing permissions and
  6364. * limitations under the License.
  6365. */
  6366. /**
  6367. * Representation of an overlay computed by Firestore.
  6368. *
  6369. * Holds information about a mutation and the largest batch id in Firestore when
  6370. * the mutation was created.
  6371. */ class Hi {
  6372. constructor(t, e) {
  6373. this.largestBatchId = t, this.mutation = e;
  6374. }
  6375. getKey() {
  6376. return this.mutation.key;
  6377. }
  6378. isEqual(t) {
  6379. return null !== t && this.mutation === t.mutation;
  6380. }
  6381. toString() {
  6382. return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;
  6383. }
  6384. }
  6385. /**
  6386. * @license
  6387. * Copyright 2017 Google LLC
  6388. *
  6389. * Licensed under the Apache License, Version 2.0 (the "License");
  6390. * you may not use this file except in compliance with the License.
  6391. * You may obtain a copy of the License at
  6392. *
  6393. * http://www.apache.org/licenses/LICENSE-2.0
  6394. *
  6395. * Unless required by applicable law or agreed to in writing, software
  6396. * distributed under the License is distributed on an "AS IS" BASIS,
  6397. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6398. * See the License for the specific language governing permissions and
  6399. * limitations under the License.
  6400. */
  6401. /**
  6402. * An immutable set of metadata that the local store tracks for each target.
  6403. */ class Ji {
  6404. constructor(
  6405. /** The target being listened to. */
  6406. t,
  6407. /**
  6408. * The target ID to which the target corresponds; Assigned by the
  6409. * LocalStore for user listens and by the SyncEngine for limbo watches.
  6410. */
  6411. e,
  6412. /** The purpose of the target. */
  6413. n,
  6414. /**
  6415. * The sequence number of the last transaction during which this target data
  6416. * was modified.
  6417. */
  6418. s,
  6419. /** The latest snapshot version seen for this target. */
  6420. i = it.min()
  6421. /**
  6422. * The maximum snapshot version at which the associated view
  6423. * contained no limbo documents.
  6424. */ , r = it.min()
  6425. /**
  6426. * An opaque, server-assigned token that allows watching a target to be
  6427. * resumed after disconnecting without retransmitting all the data that
  6428. * matches the target. The resume token essentially identifies a point in
  6429. * time from which the server should resume sending results.
  6430. */ , o = Wt.EMPTY_BYTE_STRING) {
  6431. this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i,
  6432. this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o;
  6433. }
  6434. /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {
  6435. return new Ji(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);
  6436. }
  6437. /**
  6438. * Creates a new target data instance with an updated resume token and
  6439. * snapshot version.
  6440. */ withResumeToken(t, e) {
  6441. return new Ji(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);
  6442. }
  6443. /**
  6444. * Creates a new target data instance with an updated last limbo free
  6445. * snapshot version number.
  6446. */ withLastLimboFreeSnapshotVersion(t) {
  6447. return new Ji(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken);
  6448. }
  6449. }
  6450. /**
  6451. * @license
  6452. * Copyright 2017 Google LLC
  6453. *
  6454. * Licensed under the Apache License, Version 2.0 (the "License");
  6455. * you may not use this file except in compliance with the License.
  6456. * You may obtain a copy of the License at
  6457. *
  6458. * http://www.apache.org/licenses/LICENSE-2.0
  6459. *
  6460. * Unless required by applicable law or agreed to in writing, software
  6461. * distributed under the License is distributed on an "AS IS" BASIS,
  6462. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6463. * See the License for the specific language governing permissions and
  6464. * limitations under the License.
  6465. */
  6466. /** Serializer for values stored in the LocalStore. */ class Yi {
  6467. constructor(t) {
  6468. this.ie = t;
  6469. }
  6470. }
  6471. /** Decodes a remote document from storage locally to a Document. */ function Xi(t, e) {
  6472. let n;
  6473. if (e.document) n = Zs(t.ie, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {
  6474. const t = at.fromSegments(e.noDocument.path), s = nr(e.noDocument.readTime);
  6475. n = en.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();
  6476. } else {
  6477. if (!e.unknownDocument) return M();
  6478. {
  6479. const t = at.fromSegments(e.unknownDocument.path), s = nr(e.unknownDocument.version);
  6480. n = en.newUnknownDocument(t, s);
  6481. }
  6482. }
  6483. return e.readTime && n.setReadTime(function(t) {
  6484. const e = new st(t[0], t[1]);
  6485. return it.fromTimestamp(e);
  6486. }(e.readTime)), n;
  6487. }
  6488. /** Encodes a document for storage locally. */ function Zi(t, e) {
  6489. const n = e.key, s = {
  6490. prefixPath: n.getCollectionPath().popLast().toArray(),
  6491. collectionGroup: n.collectionGroup,
  6492. documentId: n.path.lastSegment(),
  6493. readTime: tr(e.readTime),
  6494. hasCommittedMutations: e.hasCommittedMutations
  6495. };
  6496. if (e.isFoundDocument()) s.document = function(t, e) {
  6497. return {
  6498. name: js(t, e.key),
  6499. fields: e.data.value.mapValue.fields,
  6500. updateTime: Ls(t, e.version.toTimestamp()),
  6501. createTime: Ls(t, e.createTime.toTimestamp())
  6502. };
  6503. }(t.ie, e); else if (e.isNoDocument()) s.noDocument = {
  6504. path: n.path.toArray(),
  6505. readTime: er(e.version)
  6506. }; else {
  6507. if (!e.isUnknownDocument()) return M();
  6508. s.unknownDocument = {
  6509. path: n.path.toArray(),
  6510. version: er(e.version)
  6511. };
  6512. }
  6513. return s;
  6514. }
  6515. function tr(t) {
  6516. const e = t.toTimestamp();
  6517. return [ e.seconds, e.nanoseconds ];
  6518. }
  6519. function er(t) {
  6520. const e = t.toTimestamp();
  6521. return {
  6522. seconds: e.seconds,
  6523. nanoseconds: e.nanoseconds
  6524. };
  6525. }
  6526. function nr(t) {
  6527. const e = new st(t.seconds, t.nanoseconds);
  6528. return it.fromTimestamp(e);
  6529. }
  6530. /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
  6531. /** Decodes a DbMutationBatch into a MutationBatch */
  6532. function sr(t, e) {
  6533. const n = (e.baseMutations || []).map((e => si(t.ie, e)));
  6534. // Squash old transform mutations into existing patch or set mutations.
  6535. // The replacement of representing `transforms` with `update_transforms`
  6536. // on the SDK means that old `transform` mutations stored in IndexedDB need
  6537. // to be updated to `update_transforms`.
  6538. // TODO(b/174608374): Remove this code once we perform a schema migration.
  6539. for (let t = 0; t < e.mutations.length - 1; ++t) {
  6540. const n = e.mutations[t];
  6541. if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {
  6542. const s = e.mutations[t + 1];
  6543. n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1),
  6544. ++t;
  6545. }
  6546. }
  6547. const s = e.mutations.map((e => si(t.ie, e))), i = st.fromMillis(e.localWriteTimeMs);
  6548. return new Wi(e.batchId, i, n, s);
  6549. }
  6550. /** Decodes a DbTarget into TargetData */ function ir(t) {
  6551. const e = nr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? nr(t.lastLimboFreeSnapshotVersion) : it.min();
  6552. let s;
  6553. var i;
  6554. return void 0 !== t.query.documents ? (F(1 === (i = t.query).documents.length),
  6555. s = pn(dn(Hs(i.documents[0])))) : s = function(t) {
  6556. return pn(ui(t));
  6557. }(t.query), new Ji(s, t.targetId, 0 /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Wt.fromBase64String(t.resumeToken));
  6558. }
  6559. /** Encodes TargetData into a DbTarget for storage locally. */ function rr(t, e) {
  6560. const n = er(e.snapshotVersion), s = er(e.lastLimboFreeSnapshotVersion);
  6561. let i;
  6562. i = un(e.target) ? ri(t.ie, e.target) : oi(t.ie, e.target);
  6563. // We can't store the resumeToken as a ByteString in IndexedDb, so we
  6564. // convert it to a base64 string for storage.
  6565. const r = e.resumeToken.toBase64();
  6566. // lastListenSequenceNumber is always 0 until we do real GC.
  6567. return {
  6568. targetId: e.targetId,
  6569. canonicalId: rn(e.target),
  6570. readTime: n,
  6571. resumeToken: r,
  6572. lastListenSequenceNumber: e.sequenceNumber,
  6573. lastLimboFreeSnapshotVersion: s,
  6574. query: i
  6575. };
  6576. }
  6577. /**
  6578. * A helper function for figuring out what kind of query has been stored.
  6579. */
  6580. /**
  6581. * Encodes a `BundledQuery` from bundle proto to a Query object.
  6582. *
  6583. * This reconstructs the original query used to build the bundle being loaded,
  6584. * including features exists only in SDKs (for example: limit-to-last).
  6585. */
  6586. function or(t) {
  6587. const e = ui({
  6588. parent: t.parent,
  6589. structuredQuery: t.structuredQuery
  6590. });
  6591. return "LAST" === t.limitType ? Tn(e, e.limit, "L" /* LimitType.Last */) : e;
  6592. }
  6593. /** Encodes a NamedQuery proto object to a NamedQuery model object. */
  6594. /** Encodes a DbDocumentOverlay object to an Overlay model object. */
  6595. function ur(t, e) {
  6596. return new Hi(e.largestBatchId, si(t.ie, e.overlayMutation));
  6597. }
  6598. /** Decodes an Overlay model object into a DbDocumentOverlay object. */
  6599. /**
  6600. * Returns the DbDocumentOverlayKey corresponding to the given user and
  6601. * document key.
  6602. */
  6603. function cr(t, e) {
  6604. const n = e.path.lastSegment();
  6605. return [ t, yi(e.path.popLast()), n ];
  6606. }
  6607. function ar(t, e, n, s) {
  6608. return {
  6609. indexId: t,
  6610. uid: e.uid || "",
  6611. sequenceNumber: n,
  6612. readTime: er(s.readTime),
  6613. documentKey: yi(s.documentKey.path),
  6614. largestBatchId: s.largestBatchId
  6615. };
  6616. }
  6617. /**
  6618. * @license
  6619. * Copyright 2020 Google LLC
  6620. *
  6621. * Licensed under the Apache License, Version 2.0 (the "License");
  6622. * you may not use this file except in compliance with the License.
  6623. * You may obtain a copy of the License at
  6624. *
  6625. * http://www.apache.org/licenses/LICENSE-2.0
  6626. *
  6627. * Unless required by applicable law or agreed to in writing, software
  6628. * distributed under the License is distributed on an "AS IS" BASIS,
  6629. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6630. * See the License for the specific language governing permissions and
  6631. * limitations under the License.
  6632. */ class hr {
  6633. getBundleMetadata(t, e) {
  6634. return lr(t).get(e).next((t => {
  6635. if (t) return {
  6636. id: (e = t).bundleId,
  6637. createTime: nr(e.createTime),
  6638. version: e.version
  6639. };
  6640. /** Encodes a DbBundle to a BundleMetadata object. */
  6641. var e;
  6642. /** Encodes a BundleMetadata to a DbBundle. */ }));
  6643. }
  6644. saveBundleMetadata(t, e) {
  6645. return lr(t).put({
  6646. bundleId: (n = e).id,
  6647. createTime: er(Ks(n.createTime)),
  6648. version: n.version
  6649. });
  6650. var n;
  6651. /** Encodes a DbNamedQuery to a NamedQuery. */ }
  6652. getNamedQuery(t, e) {
  6653. return fr(t).get(e).next((t => {
  6654. if (t) return {
  6655. name: (e = t).name,
  6656. query: or(e.bundledQuery),
  6657. readTime: nr(e.readTime)
  6658. };
  6659. var e;
  6660. /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));
  6661. }
  6662. saveNamedQuery(t, e) {
  6663. return fr(t).put(function(t) {
  6664. return {
  6665. name: t.name,
  6666. readTime: er(Ks(t.readTime)),
  6667. bundledQuery: t.bundledQuery
  6668. };
  6669. }(e));
  6670. }
  6671. }
  6672. /**
  6673. * Helper to get a typed SimpleDbStore for the bundles object store.
  6674. */ function lr(t) {
  6675. return ji(t, "bundles");
  6676. }
  6677. /**
  6678. * Helper to get a typed SimpleDbStore for the namedQueries object store.
  6679. */ function fr(t) {
  6680. return ji(t, "namedQueries");
  6681. }
  6682. /**
  6683. * @license
  6684. * Copyright 2022 Google LLC
  6685. *
  6686. * Licensed under the Apache License, Version 2.0 (the "License");
  6687. * you may not use this file except in compliance with the License.
  6688. * You may obtain a copy of the License at
  6689. *
  6690. * http://www.apache.org/licenses/LICENSE-2.0
  6691. *
  6692. * Unless required by applicable law or agreed to in writing, software
  6693. * distributed under the License is distributed on an "AS IS" BASIS,
  6694. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6695. * See the License for the specific language governing permissions and
  6696. * limitations under the License.
  6697. */
  6698. /**
  6699. * Implementation of DocumentOverlayCache using IndexedDb.
  6700. */ class dr {
  6701. /**
  6702. * @param serializer - The document serializer.
  6703. * @param userId - The userId for which we are accessing overlays.
  6704. */
  6705. constructor(t, e) {
  6706. this.yt = t, this.userId = e;
  6707. }
  6708. static re(t, e) {
  6709. const n = e.uid || "";
  6710. return new dr(t, n);
  6711. }
  6712. getOverlay(t, e) {
  6713. return _r(t).get(cr(this.userId, e)).next((t => t ? ur(this.yt, t) : null));
  6714. }
  6715. getOverlays(t, e) {
  6716. const n = ps();
  6717. return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  6718. null !== t && n.set(e, t);
  6719. })))).next((() => n));
  6720. }
  6721. saveOverlays(t, e, n) {
  6722. const s = [];
  6723. return n.forEach(((n, i) => {
  6724. const r = new Hi(e, i);
  6725. s.push(this.oe(t, r));
  6726. })), Rt.waitFor(s);
  6727. }
  6728. removeOverlaysForBatchId(t, e, n) {
  6729. const s = new Set;
  6730. // Get the set of unique collection paths.
  6731. e.forEach((t => s.add(yi(t.getCollectionPath()))));
  6732. const i = [];
  6733. return s.forEach((e => {
  6734. const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ],
  6735. /*lowerOpen=*/ !1,
  6736. /*upperOpen=*/ !0);
  6737. i.push(_r(t).Y("collectionPathOverlayIndex", s));
  6738. })), Rt.waitFor(i);
  6739. }
  6740. getOverlaysForCollection(t, e, n) {
  6741. const s = ps(), i = yi(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ],
  6742. /*lowerOpen=*/ !0);
  6743. return _r(t).W("collectionPathOverlayIndex", r).next((t => {
  6744. for (const e of t) {
  6745. const t = ur(this.yt, e);
  6746. s.set(t.getKey(), t);
  6747. }
  6748. return s;
  6749. }));
  6750. }
  6751. getOverlaysForCollectionGroup(t, e, n, s) {
  6752. const i = ps();
  6753. let r;
  6754. // We want batch IDs larger than `sinceBatchId`, and so the lower bound
  6755. // is not inclusive.
  6756. const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ],
  6757. /*lowerOpen=*/ !0);
  6758. return _r(t).Z({
  6759. index: "collectionGroupOverlayIndex",
  6760. range: o
  6761. }, ((t, e, n) => {
  6762. // We do not want to return partial batch overlays, even if the size
  6763. // of the result set exceeds the given `count` argument. Therefore, we
  6764. // continue to aggregate results even after the result size exceeds
  6765. // `count` if there are more overlays from the `currentBatchId`.
  6766. const o = ur(this.yt, e);
  6767. i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();
  6768. })).next((() => i));
  6769. }
  6770. oe(t, e) {
  6771. return _r(t).put(function(t, e, n) {
  6772. const [s, i, r] = cr(e, n.mutation.key);
  6773. return {
  6774. userId: e,
  6775. collectionPath: i,
  6776. documentId: r,
  6777. collectionGroup: n.mutation.key.getCollectionGroup(),
  6778. largestBatchId: n.largestBatchId,
  6779. overlayMutation: ni(t.ie, n.mutation)
  6780. };
  6781. }(this.yt, this.userId, e));
  6782. }
  6783. }
  6784. /**
  6785. * Helper to get a typed SimpleDbStore for the document overlay object store.
  6786. */ function _r(t) {
  6787. return ji(t, "documentOverlays");
  6788. }
  6789. /**
  6790. * @license
  6791. * Copyright 2021 Google LLC
  6792. *
  6793. * Licensed under the Apache License, Version 2.0 (the "License");
  6794. * you may not use this file except in compliance with the License.
  6795. * You may obtain a copy of the License at
  6796. *
  6797. * http://www.apache.org/licenses/LICENSE-2.0
  6798. *
  6799. * Unless required by applicable law or agreed to in writing, software
  6800. * distributed under the License is distributed on an "AS IS" BASIS,
  6801. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6802. * See the License for the specific language governing permissions and
  6803. * limitations under the License.
  6804. */
  6805. // Note: This code is copied from the backend. Code that is not used by
  6806. // Firestore was removed.
  6807. /** Firestore index value writer. */
  6808. class wr {
  6809. constructor() {}
  6810. // The write methods below short-circuit writing terminators for values
  6811. // containing a (terminating) truncated value.
  6812. // As an example, consider the resulting encoding for:
  6813. // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  6814. // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  6815. // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  6816. /** Writes an index value. */
  6817. ue(t, e) {
  6818. this.ce(t, e),
  6819. // Write separator to split index values
  6820. // (see go/firestore-storage-format#encodings).
  6821. e.ae();
  6822. }
  6823. ce(t, e) {
  6824. if ("nullValue" in t) this.he(e, 5); else if ("booleanValue" in t) this.he(e, 10),
  6825. e.le(t.booleanValue ? 1 : 0); else if ("integerValue" in t) this.he(e, 15), e.le(Jt(t.integerValue)); else if ("doubleValue" in t) {
  6826. const n = Jt(t.doubleValue);
  6827. isNaN(n) ? this.he(e, 13) : (this.he(e, 15), Kt(n) ?
  6828. // -0.0, 0 and 0.0 are all considered the same
  6829. e.le(0) : e.le(n));
  6830. } else if ("timestampValue" in t) {
  6831. const n = t.timestampValue;
  6832. this.he(e, 20), "string" == typeof n ? e.fe(n) : (e.fe(`${n.seconds || ""}`), e.le(n.nanos || 0));
  6833. } else if ("stringValue" in t) this.de(t.stringValue, e), this._e(e); else if ("bytesValue" in t) this.he(e, 30),
  6834. e.we(Yt(t.bytesValue)), this._e(e); else if ("referenceValue" in t) this.me(t.referenceValue, e); else if ("geoPointValue" in t) {
  6835. const n = t.geoPointValue;
  6836. this.he(e, 45), e.le(n.latitude || 0), e.le(n.longitude || 0);
  6837. } else "mapValue" in t ? ge(t) ? this.he(e, Number.MAX_SAFE_INTEGER) : (this.ge(t.mapValue, e),
  6838. this._e(e)) : "arrayValue" in t ? (this.ye(t.arrayValue, e), this._e(e)) : M();
  6839. }
  6840. de(t, e) {
  6841. this.he(e, 25), this.pe(t, e);
  6842. }
  6843. pe(t, e) {
  6844. e.fe(t);
  6845. }
  6846. ge(t, e) {
  6847. const n = t.fields || {};
  6848. this.he(e, 55);
  6849. for (const t of Object.keys(n)) this.de(t, e), this.ce(n[t], e);
  6850. }
  6851. ye(t, e) {
  6852. const n = t.values || [];
  6853. this.he(e, 50);
  6854. for (const t of n) this.ce(t, e);
  6855. }
  6856. me(t, e) {
  6857. this.he(e, 37);
  6858. at.fromName(t).path.forEach((t => {
  6859. this.he(e, 60), this.pe(t, e);
  6860. }));
  6861. }
  6862. he(t, e) {
  6863. t.le(e);
  6864. }
  6865. _e(t) {
  6866. // While the SDK does not implement truncation, the truncation marker is
  6867. // used to terminate all variable length values (which are strings, bytes,
  6868. // references, arrays and maps).
  6869. t.le(2);
  6870. }
  6871. }
  6872. wr.Ie = new wr;
  6873. /**
  6874. * Counts the number of zeros in a byte.
  6875. *
  6876. * Visible for testing.
  6877. */
  6878. function mr(t) {
  6879. if (0 === t) return 8;
  6880. let e = 0;
  6881. return t >> 4 == 0 && (
  6882. // Test if the first four bits are zero.
  6883. e += 4, t <<= 4), t >> 6 == 0 && (
  6884. // Test if the first two (or next two) bits are zero.
  6885. e += 2, t <<= 2), t >> 7 == 0 && (
  6886. // Test if the remaining bit is zero.
  6887. e += 1), e;
  6888. }
  6889. /** Counts the number of leading zeros in the given byte array. */
  6890. /**
  6891. * Returns the number of bytes required to store "value". Leading zero bytes
  6892. * are skipped.
  6893. */
  6894. function gr(t) {
  6895. // This is just the number of bytes for the unsigned representation of the number.
  6896. const e = 64 - function(t) {
  6897. let e = 0;
  6898. for (let n = 0; n < 8; ++n) {
  6899. const s = mr(255 & t[n]);
  6900. if (e += s, 8 !== s) break;
  6901. }
  6902. return e;
  6903. }(t);
  6904. return Math.ceil(e / 8);
  6905. }
  6906. /**
  6907. * OrderedCodeWriter is a minimal-allocation implementation of the writing
  6908. * behavior defined by the backend.
  6909. *
  6910. * The code is ported from its Java counterpart.
  6911. */ class yr {
  6912. constructor() {
  6913. this.buffer = new Uint8Array(1024), this.position = 0;
  6914. }
  6915. Te(t) {
  6916. const e = t[Symbol.iterator]();
  6917. let n = e.next();
  6918. for (;!n.done; ) this.Ee(n.value), n = e.next();
  6919. this.Ae();
  6920. }
  6921. Re(t) {
  6922. const e = t[Symbol.iterator]();
  6923. let n = e.next();
  6924. for (;!n.done; ) this.be(n.value), n = e.next();
  6925. this.Pe();
  6926. }
  6927. /** Writes utf8 bytes into this byte sequence, ascending. */ ve(t) {
  6928. for (const e of t) {
  6929. const t = e.charCodeAt(0);
  6930. if (t < 128) this.Ee(t); else if (t < 2048) this.Ee(960 | t >>> 6), this.Ee(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.Ee(480 | t >>> 12),
  6931. this.Ee(128 | 63 & t >>> 6), this.Ee(128 | 63 & t); else {
  6932. const t = e.codePointAt(0);
  6933. this.Ee(240 | t >>> 18), this.Ee(128 | 63 & t >>> 12), this.Ee(128 | 63 & t >>> 6),
  6934. this.Ee(128 | 63 & t);
  6935. }
  6936. }
  6937. this.Ae();
  6938. }
  6939. /** Writes utf8 bytes into this byte sequence, descending */ Ve(t) {
  6940. for (const e of t) {
  6941. const t = e.charCodeAt(0);
  6942. if (t < 128) this.be(t); else if (t < 2048) this.be(960 | t >>> 6), this.be(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.be(480 | t >>> 12),
  6943. this.be(128 | 63 & t >>> 6), this.be(128 | 63 & t); else {
  6944. const t = e.codePointAt(0);
  6945. this.be(240 | t >>> 18), this.be(128 | 63 & t >>> 12), this.be(128 | 63 & t >>> 6),
  6946. this.be(128 | 63 & t);
  6947. }
  6948. }
  6949. this.Pe();
  6950. }
  6951. Se(t) {
  6952. // Values are encoded with a single byte length prefix, followed by the
  6953. // actual value in big-endian format with leading 0 bytes dropped.
  6954. const e = this.De(t), n = gr(e);
  6955. this.Ce(1 + n), this.buffer[this.position++] = 255 & n;
  6956. // Write the length
  6957. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];
  6958. }
  6959. xe(t) {
  6960. // Values are encoded with a single byte length prefix, followed by the
  6961. // inverted value in big-endian format with leading 0 bytes dropped.
  6962. const e = this.De(t), n = gr(e);
  6963. this.Ce(1 + n), this.buffer[this.position++] = ~(255 & n);
  6964. // Write the length
  6965. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);
  6966. }
  6967. /**
  6968. * Writes the "infinity" byte sequence that sorts after all other byte
  6969. * sequences written in ascending order.
  6970. */ Ne() {
  6971. this.ke(255), this.ke(255);
  6972. }
  6973. /**
  6974. * Writes the "infinity" byte sequence that sorts before all other byte
  6975. * sequences written in descending order.
  6976. */ Oe() {
  6977. this.Me(255), this.Me(255);
  6978. }
  6979. /**
  6980. * Resets the buffer such that it is the same as when it was newly
  6981. * constructed.
  6982. */ reset() {
  6983. this.position = 0;
  6984. }
  6985. seed(t) {
  6986. this.Ce(t.length), this.buffer.set(t, this.position), this.position += t.length;
  6987. }
  6988. /** Makes a copy of the encoded bytes in this buffer. */ Fe() {
  6989. return this.buffer.slice(0, this.position);
  6990. }
  6991. /**
  6992. * Encodes `val` into an encoding so that the order matches the IEEE 754
  6993. * floating-point comparison results with the following exceptions:
  6994. * -0.0 < 0.0
  6995. * all non-NaN < NaN
  6996. * NaN = NaN
  6997. */ De(t) {
  6998. const e =
  6999. /** Converts a JavaScript number to a byte array (using big endian encoding). */
  7000. function(t) {
  7001. const e = new DataView(new ArrayBuffer(8));
  7002. return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);
  7003. }(t), n = 0 != (128 & e[0]);
  7004. // Check if the first bit is set. We use a bit mask since value[0] is
  7005. // encoded as a number from 0 to 255.
  7006. // Revert the two complement to get natural ordering
  7007. e[0] ^= n ? 255 : 128;
  7008. for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;
  7009. return e;
  7010. }
  7011. /** Writes a single byte ascending to the buffer. */ Ee(t) {
  7012. const e = 255 & t;
  7013. 0 === e ? (this.ke(0), this.ke(255)) : 255 === e ? (this.ke(255), this.ke(0)) : this.ke(e);
  7014. }
  7015. /** Writes a single byte descending to the buffer. */ be(t) {
  7016. const e = 255 & t;
  7017. 0 === e ? (this.Me(0), this.Me(255)) : 255 === e ? (this.Me(255), this.Me(0)) : this.Me(t);
  7018. }
  7019. Ae() {
  7020. this.ke(0), this.ke(1);
  7021. }
  7022. Pe() {
  7023. this.Me(0), this.Me(1);
  7024. }
  7025. ke(t) {
  7026. this.Ce(1), this.buffer[this.position++] = t;
  7027. }
  7028. Me(t) {
  7029. this.Ce(1), this.buffer[this.position++] = ~t;
  7030. }
  7031. Ce(t) {
  7032. const e = t + this.position;
  7033. if (e <= this.buffer.length) return;
  7034. // Try doubling.
  7035. let n = 2 * this.buffer.length;
  7036. // Still not big enough? Just allocate the right size.
  7037. n < e && (n = e);
  7038. // Create the new buffer.
  7039. const s = new Uint8Array(n);
  7040. s.set(this.buffer), // copy old data
  7041. this.buffer = s;
  7042. }
  7043. }
  7044. class pr {
  7045. constructor(t) {
  7046. this.$e = t;
  7047. }
  7048. we(t) {
  7049. this.$e.Te(t);
  7050. }
  7051. fe(t) {
  7052. this.$e.ve(t);
  7053. }
  7054. le(t) {
  7055. this.$e.Se(t);
  7056. }
  7057. ae() {
  7058. this.$e.Ne();
  7059. }
  7060. }
  7061. class Ir {
  7062. constructor(t) {
  7063. this.$e = t;
  7064. }
  7065. we(t) {
  7066. this.$e.Re(t);
  7067. }
  7068. fe(t) {
  7069. this.$e.Ve(t);
  7070. }
  7071. le(t) {
  7072. this.$e.xe(t);
  7073. }
  7074. ae() {
  7075. this.$e.Oe();
  7076. }
  7077. }
  7078. /**
  7079. * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the
  7080. * actual encoding.
  7081. */ class Tr {
  7082. constructor() {
  7083. this.$e = new yr, this.Be = new pr(this.$e), this.Le = new Ir(this.$e);
  7084. }
  7085. seed(t) {
  7086. this.$e.seed(t);
  7087. }
  7088. qe(t) {
  7089. return 0 /* IndexKind.ASCENDING */ === t ? this.Be : this.Le;
  7090. }
  7091. Fe() {
  7092. return this.$e.Fe();
  7093. }
  7094. reset() {
  7095. this.$e.reset();
  7096. }
  7097. }
  7098. /**
  7099. * @license
  7100. * Copyright 2022 Google LLC
  7101. *
  7102. * Licensed under the Apache License, Version 2.0 (the "License");
  7103. * you may not use this file except in compliance with the License.
  7104. * You may obtain a copy of the License at
  7105. *
  7106. * http://www.apache.org/licenses/LICENSE-2.0
  7107. *
  7108. * Unless required by applicable law or agreed to in writing, software
  7109. * distributed under the License is distributed on an "AS IS" BASIS,
  7110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7111. * See the License for the specific language governing permissions and
  7112. * limitations under the License.
  7113. */
  7114. /** Represents an index entry saved by the SDK in persisted storage. */ class Er {
  7115. constructor(t, e, n, s) {
  7116. this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;
  7117. }
  7118. /**
  7119. * Returns an IndexEntry entry that sorts immediately after the current
  7120. * directional value.
  7121. */ Ue() {
  7122. const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);
  7123. return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1],
  7124. new Er(this.indexId, this.documentKey, this.arrayValue, n);
  7125. }
  7126. }
  7127. function Ar(t, e) {
  7128. let n = t.indexId - e.indexId;
  7129. return 0 !== n ? n : (n = Rr(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = Rr(t.directionalValue, e.directionalValue),
  7130. 0 !== n ? n : at.comparator(t.documentKey, e.documentKey)));
  7131. }
  7132. function Rr(t, e) {
  7133. for (let n = 0; n < t.length && n < e.length; ++n) {
  7134. const s = t[n] - e[n];
  7135. if (0 !== s) return s;
  7136. }
  7137. return t.length - e.length;
  7138. }
  7139. /**
  7140. * @license
  7141. * Copyright 2022 Google LLC
  7142. *
  7143. * Licensed under the Apache License, Version 2.0 (the "License");
  7144. * you may not use this file except in compliance with the License.
  7145. * You may obtain a copy of the License at
  7146. *
  7147. * http://www.apache.org/licenses/LICENSE-2.0
  7148. *
  7149. * Unless required by applicable law or agreed to in writing, software
  7150. * distributed under the License is distributed on an "AS IS" BASIS,
  7151. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7152. * See the License for the specific language governing permissions and
  7153. * limitations under the License.
  7154. */
  7155. /**
  7156. * A light query planner for Firestore.
  7157. *
  7158. * This class matches a `FieldIndex` against a Firestore Query `Target`. It
  7159. * determines whether a given index can be used to serve the specified target.
  7160. *
  7161. * The following table showcases some possible index configurations:
  7162. *
  7163. * Query | Index
  7164. * -----------------------------------------------------------------------------
  7165. * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC
  7166. * where('a', '==', 'a').where('b', '==', 'b') | a ASC
  7167. * where('a', '==', 'a').where('b', '==', 'b') | b DESC
  7168. * where('a', '>=', 'a').orderBy('a') | a ASC
  7169. * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC
  7170. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC
  7171. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC
  7172. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING
  7173. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS
  7174. */ class br {
  7175. constructor(t) {
  7176. this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(),
  7177. this.Ke = t.orderBy, this.Ge = [];
  7178. for (const e of t.filters) {
  7179. const t = e;
  7180. t.isInequality() ? this.Qe = t : this.Ge.push(t);
  7181. }
  7182. }
  7183. /**
  7184. * Returns whether the index can be used to serve the TargetIndexMatcher's
  7185. * target.
  7186. *
  7187. * An index is considered capable of serving the target when:
  7188. * - The target uses all index segments for its filters and orderBy clauses.
  7189. * The target can have additional filter and orderBy clauses, but not
  7190. * fewer.
  7191. * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
  7192. * have a corresponding `CONTAINS` segment.
  7193. * - All directional index segments can be mapped to the target as a series of
  7194. * equality filters, a single inequality filter and a series of orderBy
  7195. * clauses.
  7196. * - The segments that represent the equality filters may appear out of order.
  7197. * - The optional segment for the inequality filter must appear after all
  7198. * equality segments.
  7199. * - The segments that represent that orderBy clause of the target must appear
  7200. * in order after all equality and inequality segments. Single orderBy
  7201. * clauses cannot be skipped, but a continuous orderBy suffix may be
  7202. * omitted.
  7203. */ je(t) {
  7204. F(t.collectionGroup === this.collectionId);
  7205. // If there is an array element, find a matching filter.
  7206. const e = lt(t);
  7207. if (void 0 !== e && !this.We(e)) return !1;
  7208. const n = ft(t);
  7209. let s = 0, i = 0;
  7210. // Process all equalities first. Equalities can appear out of order.
  7211. for (;s < n.length && this.We(n[s]); ++s) ;
  7212. // If we already have processed all segments, all segments are used to serve
  7213. // the equality filters and we do not need to map any segments to the
  7214. // target's inequality and orderBy clauses.
  7215. if (s === n.length) return !0;
  7216. // If there is an inequality filter, the next segment must match both the
  7217. // filter and the first orderBy clause.
  7218. if (void 0 !== this.Qe) {
  7219. const t = n[s];
  7220. if (!this.ze(this.Qe, t) || !this.He(this.Ke[i++], t)) return !1;
  7221. ++s;
  7222. }
  7223. // All remaining segments need to represent the prefix of the target's
  7224. // orderBy.
  7225. for (;s < n.length; ++s) {
  7226. const t = n[s];
  7227. if (i >= this.Ke.length || !this.He(this.Ke[i++], t)) return !1;
  7228. }
  7229. return !0;
  7230. }
  7231. We(t) {
  7232. for (const e of this.Ge) if (this.ze(e, t)) return !0;
  7233. return !1;
  7234. }
  7235. ze(t, e) {
  7236. if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;
  7237. const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;
  7238. return 2 /* IndexKind.CONTAINS */ === e.kind === n;
  7239. }
  7240. He(t, e) {
  7241. return !!t.field.isEqual(e.fieldPath) && (0 /* IndexKind.ASCENDING */ === e.kind && "asc" /* Direction.ASCENDING */ === t.dir || 1 /* IndexKind.DESCENDING */ === e.kind && "desc" /* Direction.DESCENDING */ === t.dir);
  7242. }
  7243. }
  7244. /**
  7245. * @license
  7246. * Copyright 2022 Google LLC
  7247. *
  7248. * Licensed under the Apache License, Version 2.0 (the "License");
  7249. * you may not use this file except in compliance with the License.
  7250. * You may obtain a copy of the License at
  7251. *
  7252. * http://www.apache.org/licenses/LICENSE-2.0
  7253. *
  7254. * Unless required by applicable law or agreed to in writing, software
  7255. * distributed under the License is distributed on an "AS IS" BASIS,
  7256. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7257. * See the License for the specific language governing permissions and
  7258. * limitations under the License.
  7259. */
  7260. /**
  7261. * Provides utility functions that help with boolean logic transformations needed for handling
  7262. * complex filters used in queries.
  7263. */
  7264. /**
  7265. * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
  7266. * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
  7267. * input into a disjunction of equality filters and returns the expanded filter.
  7268. */ function Pr(t) {
  7269. var e, n;
  7270. if (F(t instanceof Pe || t instanceof ve), t instanceof Pe) {
  7271. if (t instanceof qe) {
  7272. const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => Pe.create(t.field, "==" /* Operator.EQUAL */ , e)))) || [];
  7273. return ve.create(s, "or" /* CompositeOperator.OR */);
  7274. }
  7275. // We have reached other kinds of field filters.
  7276. return t;
  7277. }
  7278. // We have a composite filter.
  7279. const s = t.filters.map((t => Pr(t)));
  7280. return ve.create(s, t.op);
  7281. }
  7282. /**
  7283. * Given a composite filter, returns the list of terms in its disjunctive normal form.
  7284. *
  7285. * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
  7286. * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
  7287. * with two elements: a composite filter that performs (A && C), and a composite filter that
  7288. * performs (B && C).
  7289. *
  7290. * @param filter the composite filter to calculate DNF transform for.
  7291. * @return the terms in the DNF transform.
  7292. */ function vr(t) {
  7293. if (0 === t.getFilters().length) return [];
  7294. const e = Cr(Pr(t));
  7295. return F(Dr(e)), Vr(e) || Sr(e) ? [ e ] : e.getFilters();
  7296. }
  7297. /** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Vr(t) {
  7298. return t instanceof Pe;
  7299. }
  7300. /**
  7301. * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
  7302. * && b == 20)
  7303. */ function Sr(t) {
  7304. return t instanceof ve && De(t);
  7305. }
  7306. /**
  7307. * Returns whether or not the given filter is in disjunctive normal form (DNF).
  7308. *
  7309. * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
  7310. * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
  7311. *
  7312. * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
  7313. */ function Dr(t) {
  7314. return Vr(t) || Sr(t) ||
  7315. /**
  7316. * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  7317. * field filters. e.g. (a == 10) || (b==20 && c==30)
  7318. */
  7319. function(t) {
  7320. if (t instanceof ve && Se(t)) {
  7321. for (const e of t.getFilters()) if (!Vr(e) && !Sr(e)) return !1;
  7322. return !0;
  7323. }
  7324. return !1;
  7325. }(t);
  7326. }
  7327. function Cr(t) {
  7328. if (F(t instanceof Pe || t instanceof ve), t instanceof Pe) return t;
  7329. if (1 === t.filters.length) return Cr(t.filters[0]);
  7330. // Compute DNF for each of the subfilters first
  7331. const e = t.filters.map((t => Cr(t)));
  7332. let n = ve.create(e, t.op);
  7333. return n = kr(n), Dr(n) ? n : (F(n instanceof ve), F(Ve(n)), F(n.filters.length > 1),
  7334. n.filters.reduce(((t, e) => xr(t, e))));
  7335. }
  7336. function xr(t, e) {
  7337. let n;
  7338. return F(t instanceof Pe || t instanceof ve), F(e instanceof Pe || e instanceof ve),
  7339. // FieldFilter FieldFilter
  7340. n = t instanceof Pe ? e instanceof Pe ? function(t, e) {
  7341. // Conjunction distribution for two field filters is the conjunction of them.
  7342. return ve.create([ t, e ], "and" /* CompositeOperator.AND */);
  7343. }(t, e) : Nr(t, e) : e instanceof Pe ? Nr(e, t) : function(t, e) {
  7344. // There are four cases:
  7345. // (A & B) & (C & D) --> (A & B & C & D)
  7346. // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
  7347. // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
  7348. // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
  7349. // Case 1 is a merge.
  7350. if (F(t.filters.length > 0 && e.filters.length > 0), Ve(t) && Ve(e)) return ke(t, e.getFilters());
  7351. // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
  7352. // we should take each element of the disjunction and distribute it over the other side, and
  7353. // return the disjunction of the distribution results.
  7354. const n = Se(t) ? t : e, s = Se(t) ? e : t, i = n.filters.map((t => xr(t, s)));
  7355. return ve.create(i, "or" /* CompositeOperator.OR */);
  7356. }(t, e), kr(n);
  7357. }
  7358. function Nr(t, e) {
  7359. // There are two cases:
  7360. // A & (B & C) --> (A & B & C)
  7361. // A & (B | C) --> (A & B) | (A & C)
  7362. if (Ve(e))
  7363. // Case 1
  7364. return ke(e, t.getFilters());
  7365. {
  7366. // Case 2
  7367. const n = e.filters.map((e => xr(t, e)));
  7368. return ve.create(n, "or" /* CompositeOperator.OR */);
  7369. }
  7370. }
  7371. /**
  7372. * Applies the associativity property to the given filter and returns the resulting filter.
  7373. *
  7374. * <ul>
  7375. * <li>A | (B | C) == (A | B) | C == (A | B | C)
  7376. * <li>A & (B & C) == (A & B) & C == (A & B & C)
  7377. * </ul>
  7378. *
  7379. * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
  7380. */ function kr(t) {
  7381. if (F(t instanceof Pe || t instanceof ve), t instanceof Pe) return t;
  7382. const e = t.getFilters();
  7383. // If the composite filter only contains 1 filter, apply associativity to it.
  7384. if (1 === e.length) return kr(e[0]);
  7385. // Associativity applied to a flat composite filter results is itself.
  7386. if (Ce(t)) return t;
  7387. // First apply associativity to all subfilters. This will in turn recursively apply
  7388. // associativity to all nested composite filters and field filters.
  7389. const n = e.map((t => kr(t))), s = [];
  7390. // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
  7391. // take out their filters and add them to `compositeFilter`. For example:
  7392. // compositeFilter = (A | (B | C | D))
  7393. // compositeSubfilter = (B | C | D)
  7394. // Result: (A | B | C | D)
  7395. // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
  7396. // added to the top-level "compositeFilter".
  7397. return n.forEach((e => {
  7398. e instanceof Pe ? s.push(e) : e instanceof ve && (e.op === t.op ?
  7399. // compositeFilter: (A | (B | C))
  7400. // compositeSubfilter: (B | C)
  7401. // Result: (A | B | C)
  7402. s.push(...e.filters) :
  7403. // compositeFilter: (A | (B & C))
  7404. // compositeSubfilter: (B & C)
  7405. // Result: (A | (B & C))
  7406. s.push(e));
  7407. })), 1 === s.length ? s[0] : ve.create(s, t.op);
  7408. }
  7409. /**
  7410. * @license
  7411. * Copyright 2019 Google LLC
  7412. *
  7413. * Licensed under the Apache License, Version 2.0 (the "License");
  7414. * you may not use this file except in compliance with the License.
  7415. * You may obtain a copy of the License at
  7416. *
  7417. * http://www.apache.org/licenses/LICENSE-2.0
  7418. *
  7419. * Unless required by applicable law or agreed to in writing, software
  7420. * distributed under the License is distributed on an "AS IS" BASIS,
  7421. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7422. * See the License for the specific language governing permissions and
  7423. * limitations under the License.
  7424. */
  7425. /**
  7426. * An in-memory implementation of IndexManager.
  7427. */ class Or {
  7428. constructor() {
  7429. this.Je = new Mr;
  7430. }
  7431. addToCollectionParentIndex(t, e) {
  7432. return this.Je.add(e), Rt.resolve();
  7433. }
  7434. getCollectionParents(t, e) {
  7435. return Rt.resolve(this.Je.getEntries(e));
  7436. }
  7437. addFieldIndex(t, e) {
  7438. // Field indices are not supported with memory persistence.
  7439. return Rt.resolve();
  7440. }
  7441. deleteFieldIndex(t, e) {
  7442. // Field indices are not supported with memory persistence.
  7443. return Rt.resolve();
  7444. }
  7445. getDocumentsMatchingTarget(t, e) {
  7446. // Field indices are not supported with memory persistence.
  7447. return Rt.resolve(null);
  7448. }
  7449. getIndexType(t, e) {
  7450. // Field indices are not supported with memory persistence.
  7451. return Rt.resolve(0 /* IndexType.NONE */);
  7452. }
  7453. getFieldIndexes(t, e) {
  7454. // Field indices are not supported with memory persistence.
  7455. return Rt.resolve([]);
  7456. }
  7457. getNextCollectionGroupToUpdate(t) {
  7458. // Field indices are not supported with memory persistence.
  7459. return Rt.resolve(null);
  7460. }
  7461. getMinOffset(t, e) {
  7462. return Rt.resolve(pt.min());
  7463. }
  7464. getMinOffsetFromCollectionGroup(t, e) {
  7465. return Rt.resolve(pt.min());
  7466. }
  7467. updateCollectionGroup(t, e, n) {
  7468. // Field indices are not supported with memory persistence.
  7469. return Rt.resolve();
  7470. }
  7471. updateIndexEntries(t, e) {
  7472. // Field indices are not supported with memory persistence.
  7473. return Rt.resolve();
  7474. }
  7475. }
  7476. /**
  7477. * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
  7478. * Also used for in-memory caching by IndexedDbIndexManager and initial index population
  7479. * in indexeddb_schema.ts
  7480. */ class Mr {
  7481. constructor() {
  7482. this.index = {};
  7483. }
  7484. // Returns false if the entry already existed.
  7485. add(t) {
  7486. const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new He(ot.comparator), i = !s.has(n);
  7487. return this.index[e] = s.add(n), i;
  7488. }
  7489. has(t) {
  7490. const e = t.lastSegment(), n = t.popLast(), s = this.index[e];
  7491. return s && s.has(n);
  7492. }
  7493. getEntries(t) {
  7494. return (this.index[t] || new He(ot.comparator)).toArray();
  7495. }
  7496. }
  7497. /**
  7498. * @license
  7499. * Copyright 2019 Google LLC
  7500. *
  7501. * Licensed under the Apache License, Version 2.0 (the "License");
  7502. * you may not use this file except in compliance with the License.
  7503. * You may obtain a copy of the License at
  7504. *
  7505. * http://www.apache.org/licenses/LICENSE-2.0
  7506. *
  7507. * Unless required by applicable law or agreed to in writing, software
  7508. * distributed under the License is distributed on an "AS IS" BASIS,
  7509. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7510. * See the License for the specific language governing permissions and
  7511. * limitations under the License.
  7512. */ const Fr = new Uint8Array(0);
  7513. /**
  7514. * A persisted implementation of IndexManager.
  7515. *
  7516. * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index
  7517. * data as it supports multi-tab access.
  7518. */
  7519. class $r {
  7520. constructor(t, e) {
  7521. this.user = t, this.databaseId = e,
  7522. /**
  7523. * An in-memory copy of the index entries we've already written since the SDK
  7524. * launched. Used to avoid re-writing the same entry repeatedly.
  7525. *
  7526. * This is *NOT* a complete cache of what's in persistence and so can never be
  7527. * used to satisfy reads.
  7528. */
  7529. this.Ye = new Mr,
  7530. /**
  7531. * Maps from a target to its equivalent list of sub-targets. Each sub-target
  7532. * contains only one term from the target's disjunctive normal form (DNF).
  7533. */
  7534. this.Xe = new ds((t => rn(t)), ((t, e) => on(t, e))), this.uid = t.uid || "";
  7535. }
  7536. /**
  7537. * Adds a new entry to the collection parent index.
  7538. *
  7539. * Repeated calls for the same collectionPath should be avoided within a
  7540. * transaction as IndexedDbIndexManager only caches writes once a transaction
  7541. * has been committed.
  7542. */ addToCollectionParentIndex(t, e) {
  7543. if (!this.Ye.has(e)) {
  7544. const n = e.lastSegment(), s = e.popLast();
  7545. t.addOnCommittedListener((() => {
  7546. // Add the collection to the in memory cache only if the transaction was
  7547. // successfully committed.
  7548. this.Ye.add(e);
  7549. }));
  7550. const i = {
  7551. collectionId: n,
  7552. parent: yi(s)
  7553. };
  7554. return Br(t).put(i);
  7555. }
  7556. return Rt.resolve();
  7557. }
  7558. getCollectionParents(t, e) {
  7559. const n = [], s = IDBKeyRange.bound([ e, "" ], [ nt(e), "" ],
  7560. /*lowerOpen=*/ !1,
  7561. /*upperOpen=*/ !0);
  7562. return Br(t).W(s).next((t => {
  7563. for (const s of t) {
  7564. // This collectionId guard shouldn't be necessary (and isn't as long
  7565. // as we're running in a real browser), but there's a bug in
  7566. // indexeddbshim that breaks our range in our tests running in node:
  7567. // https://github.com/axemclion/IndexedDBShim/issues/334
  7568. if (s.collectionId !== e) break;
  7569. n.push(Ti(s.parent));
  7570. }
  7571. return n;
  7572. }));
  7573. }
  7574. addFieldIndex(t, e) {
  7575. // TODO(indexing): Verify that the auto-incrementing index ID works in
  7576. // Safari & Firefox.
  7577. const n = qr(t), s = function(t) {
  7578. return {
  7579. indexId: t.indexId,
  7580. collectionGroup: t.collectionGroup,
  7581. fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))
  7582. };
  7583. }(e);
  7584. delete s.indexId;
  7585. // `indexId` is auto-populated by IndexedDb
  7586. const i = n.add(s);
  7587. if (e.indexState) {
  7588. const n = Ur(t);
  7589. return i.next((t => {
  7590. n.put(ar(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));
  7591. }));
  7592. }
  7593. return i.next();
  7594. }
  7595. deleteFieldIndex(t, e) {
  7596. const n = qr(t), s = Ur(t), i = Lr(t);
  7597. return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7598. /*lowerOpen=*/ !1,
  7599. /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7600. /*lowerOpen=*/ !1,
  7601. /*upperOpen=*/ !0))));
  7602. }
  7603. getDocumentsMatchingTarget(t, e) {
  7604. const n = Lr(t);
  7605. let s = !0;
  7606. const i = new Map;
  7607. return Rt.forEach(this.Ze(e), (e => this.tn(t, e).next((t => {
  7608. s && (s = !!t), i.set(e, t);
  7609. })))).next((() => {
  7610. if (s) {
  7611. let t = Rs();
  7612. const s = [];
  7613. return Rt.forEach(i, ((i, r) => {
  7614. var o;
  7615. x("IndexedDbIndexManager", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(",")}`} to execute ${rn(e)}`);
  7616. const u = function(t, e) {
  7617. const n = lt(e);
  7618. if (void 0 === n) return null;
  7619. for (const e of cn(t, n.fieldPath)) switch (e.op) {
  7620. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  7621. return e.value.arrayValue.values || [];
  7622. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  7623. return [ e.value ];
  7624. // Remaining filters are not array filters.
  7625. }
  7626. return null;
  7627. }
  7628. /**
  7629. * Returns the list of values that are used in != or NOT_IN filters. Returns
  7630. * `null` if there are no such filters.
  7631. */ (r, i), c = function(t, e) {
  7632. const n = new Map;
  7633. for (const s of ft(e)) for (const e of cn(t, s.fieldPath)) switch (e.op) {
  7634. case "==" /* Operator.EQUAL */ :
  7635. case "in" /* Operator.IN */ :
  7636. // Encode equality prefix, which is encoded in the index value before
  7637. // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
  7638. // `value != 'ab'`).
  7639. n.set(s.fieldPath.canonicalString(), e.value);
  7640. break;
  7641. case "not-in" /* Operator.NOT_IN */ :
  7642. case "!=" /* Operator.NOT_EQUAL */ :
  7643. // NotIn/NotEqual is always a suffix. There cannot be any remaining
  7644. // segments and hence we can return early here.
  7645. return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());
  7646. // Remaining filters cannot be used as notIn bounds.
  7647. }
  7648. return null;
  7649. }
  7650. /**
  7651. * Returns a lower bound of field values that can be used as a starting point to
  7652. * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
  7653. * exists.
  7654. */ (r, i), a = function(t, e) {
  7655. const n = [];
  7656. let s = !0;
  7657. // For each segment, retrieve a lower bound if there is a suitable filter or
  7658. // startAt.
  7659. for (const i of ft(e)) {
  7660. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? an(t, i.fieldPath, t.startAt) : hn(t, i.fieldPath, t.startAt);
  7661. n.push(e.value), s && (s = e.inclusive);
  7662. }
  7663. return new Ee(n, s);
  7664. }
  7665. /**
  7666. * Returns an upper bound of field values that can be used as an ending point
  7667. * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
  7668. * upper bound exists.
  7669. */ (r, i), h = function(t, e) {
  7670. const n = [];
  7671. let s = !0;
  7672. // For each segment, retrieve an upper bound if there is a suitable filter or
  7673. // endAt.
  7674. for (const i of ft(e)) {
  7675. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? hn(t, i.fieldPath, t.endAt) : an(t, i.fieldPath, t.endAt);
  7676. n.push(e.value), s && (s = e.inclusive);
  7677. }
  7678. return new Ee(n, s);
  7679. }(r, i), l = this.en(i, r, a), f = this.en(i, r, h), d = this.nn(i, r, c), _ = this.sn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);
  7680. return Rt.forEach(_, (i => n.J(i, e.limit).next((e => {
  7681. e.forEach((e => {
  7682. const n = at.fromSegments(e.documentKey);
  7683. t.has(n) || (t = t.add(n), s.push(n));
  7684. }));
  7685. }))));
  7686. })).next((() => s));
  7687. }
  7688. return Rt.resolve(null);
  7689. }));
  7690. }
  7691. Ze(t) {
  7692. let e = this.Xe.get(t);
  7693. if (e) return e;
  7694. if (0 === t.filters.length) e = [ t ]; else {
  7695. e = vr(ve.create(t.filters, "and" /* CompositeOperator.AND */)).map((e => sn(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));
  7696. }
  7697. return this.Xe.set(t, e), e;
  7698. }
  7699. /**
  7700. * Constructs a key range query on `DbIndexEntryStore` that unions all
  7701. * bounds.
  7702. */ sn(t, e, n, s, i, r, o) {
  7703. // The number of total index scans we union together. This is similar to a
  7704. // distributed normal form, but adapted for array values. We create a single
  7705. // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
  7706. // combined with the values from the query bounds.
  7707. const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];
  7708. for (let h = 0; h < u; ++h) {
  7709. const u = e ? this.rn(e[h / c]) : Fr, l = this.on(t, u, n[h % c], s), f = this.un(t, u, i[h % c], r), d = o.map((e => this.on(t, u, e,
  7710. /* inclusive= */ !0)));
  7711. a.push(...this.createRange(l, f, d));
  7712. }
  7713. return a;
  7714. }
  7715. /** Generates the lower bound for `arrayValue` and `directionalValue`. */ on(t, e, n, s) {
  7716. const i = new Er(t, at.empty(), e, n);
  7717. return s ? i : i.Ue();
  7718. }
  7719. /** Generates the upper bound for `arrayValue` and `directionalValue`. */ un(t, e, n, s) {
  7720. const i = new Er(t, at.empty(), e, n);
  7721. return s ? i.Ue() : i;
  7722. }
  7723. tn(t, e) {
  7724. const n = new br(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();
  7725. return this.getFieldIndexes(t, s).next((t => {
  7726. // Return the index with the most number of segments.
  7727. let e = null;
  7728. for (const s of t) {
  7729. n.je(s) && (!e || s.fields.length > e.fields.length) && (e = s);
  7730. }
  7731. return e;
  7732. }));
  7733. }
  7734. getIndexType(t, e) {
  7735. let n = 2 /* IndexType.FULL */;
  7736. const s = this.Ze(e);
  7737. return Rt.forEach(s, (e => this.tn(t, e).next((t => {
  7738. t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {
  7739. let e = new He(ct.comparator), n = !1;
  7740. for (const s of t.filters) for (const t of s.getFlattenedFilters())
  7741. // __name__ is not an explicit segment of any index, so we don't need to
  7742. // count it.
  7743. t.field.isKeyField() || (
  7744. // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
  7745. // For instance, it is possible to have an index for "a ARRAY a ASC". Even
  7746. // though these are on the same field, they should be counted as two
  7747. // separate segments in an index.
  7748. "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));
  7749. for (const n of t.orderBy)
  7750. // __name__ is not an explicit segment of any index, so we don't need to
  7751. // count it.
  7752. n.field.isKeyField() || (e = e.add(n.field));
  7753. return e.size + (n ? 1 : 0);
  7754. }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;
  7755. })))).next((() =>
  7756. // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
  7757. // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
  7758. // and apply the limit in memory as a post-processing step.
  7759. function(t) {
  7760. return null !== t.limit;
  7761. }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));
  7762. }
  7763. /**
  7764. * Returns the byte encoded form of the directional values in the field index.
  7765. * Returns `null` if the document does not have all fields specified in the
  7766. * index.
  7767. */ cn(t, e) {
  7768. const n = new Tr;
  7769. for (const s of ft(t)) {
  7770. const t = e.data.field(s.fieldPath);
  7771. if (null == t) return null;
  7772. const i = n.qe(s.kind);
  7773. wr.Ie.ue(t, i);
  7774. }
  7775. return n.Fe();
  7776. }
  7777. /** Encodes a single value to the ascending index format. */ rn(t) {
  7778. const e = new Tr;
  7779. return wr.Ie.ue(t, e.qe(0 /* IndexKind.ASCENDING */)), e.Fe();
  7780. }
  7781. /**
  7782. * Returns an encoded form of the document key that sorts based on the key
  7783. * ordering of the field index.
  7784. */ an(t, e) {
  7785. const n = new Tr;
  7786. return wr.Ie.ue(he(this.databaseId, e), n.qe(function(t) {
  7787. const e = ft(t);
  7788. return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;
  7789. }(t))), n.Fe();
  7790. }
  7791. /**
  7792. * Encodes the given field values according to the specification in `target`.
  7793. * For IN queries, a list of possible values is returned.
  7794. */ nn(t, e, n) {
  7795. if (null === n) return [];
  7796. let s = [];
  7797. s.push(new Tr);
  7798. let i = 0;
  7799. for (const r of ft(t)) {
  7800. const t = n[i++];
  7801. for (const n of s) if (this.hn(e, r.fieldPath) && fe(t)) s = this.ln(s, r, t); else {
  7802. const e = n.qe(r.kind);
  7803. wr.Ie.ue(t, e);
  7804. }
  7805. }
  7806. return this.fn(s);
  7807. }
  7808. /**
  7809. * Encodes the given bounds according to the specification in `target`. For IN
  7810. * queries, a list of possible values is returned.
  7811. */ en(t, e, n) {
  7812. return this.nn(t, e, n.position);
  7813. }
  7814. /** Returns the byte representation for the provided encoders. */ fn(t) {
  7815. const e = [];
  7816. for (let n = 0; n < t.length; ++n) e[n] = t[n].Fe();
  7817. return e;
  7818. }
  7819. /**
  7820. * Creates a separate encoder for each element of an array.
  7821. *
  7822. * The method appends each value to all existing encoders (e.g. filter("a",
  7823. * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
  7824. * list of new encoders is returned.
  7825. */ ln(t, e, n) {
  7826. const s = [ ...t ], i = [];
  7827. for (const t of n.arrayValue.values || []) for (const n of s) {
  7828. const s = new Tr;
  7829. s.seed(n.Fe()), wr.Ie.ue(t, s.qe(e.kind)), i.push(s);
  7830. }
  7831. return i;
  7832. }
  7833. hn(t, e) {
  7834. return !!t.filters.find((t => t instanceof Pe && t.field.isEqual(e) && ("in" /* Operator.IN */ === t.op || "not-in" /* Operator.NOT_IN */ === t.op)));
  7835. }
  7836. getFieldIndexes(t, e) {
  7837. const n = qr(t), s = Ur(t);
  7838. return (e ? n.W("collectionGroupIndex", IDBKeyRange.bound(e, e)) : n.W()).next((t => {
  7839. const e = [];
  7840. return Rt.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {
  7841. e.push(function(t, e) {
  7842. const n = e ? new mt(e.sequenceNumber, new pt(nr(e.readTime), new at(Ti(e.documentKey)), e.largestBatchId)) : mt.empty(), s = t.fields.map((([t, e]) => new _t(ct.fromServerFormat(t), e)));
  7843. return new ht(t.indexId, t.collectionGroup, s, n);
  7844. }(t, n));
  7845. })))).next((() => e));
  7846. }));
  7847. }
  7848. getNextCollectionGroupToUpdate(t) {
  7849. return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {
  7850. const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;
  7851. return 0 !== n ? n : tt(t.collectionGroup, e.collectionGroup);
  7852. })), t[0].collectionGroup)));
  7853. }
  7854. updateCollectionGroup(t, e, n) {
  7855. const s = qr(t), i = Ur(t);
  7856. return this.dn(t).next((t => s.W("collectionGroupIndex", IDBKeyRange.bound(e, e)).next((e => Rt.forEach(e, (e => i.put(ar(e.indexId, this.user, t, n))))))));
  7857. }
  7858. updateIndexEntries(t, e) {
  7859. // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
  7860. // it could be used across different IndexedDB transactions. As any cached
  7861. // data might be invalidated by other multi-tab clients, we can only trust
  7862. // data within a single IndexedDB transaction. We therefore add a cache
  7863. // here.
  7864. const n = new Map;
  7865. return Rt.forEach(e, ((e, s) => {
  7866. const i = n.get(e.collectionGroup);
  7867. return (i ? Rt.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i),
  7868. Rt.forEach(i, (n => this._n(t, e, n).next((e => {
  7869. const i = this.wn(s, n);
  7870. return e.isEqual(i) ? Rt.resolve() : this.mn(t, s, n, e, i);
  7871. })))))));
  7872. }));
  7873. }
  7874. gn(t, e, n, s) {
  7875. return Lr(t).put({
  7876. indexId: s.indexId,
  7877. uid: this.uid,
  7878. arrayValue: s.arrayValue,
  7879. directionalValue: s.directionalValue,
  7880. orderedDocumentKey: this.an(n, e.key),
  7881. documentKey: e.key.path.toArray()
  7882. });
  7883. }
  7884. yn(t, e, n, s) {
  7885. return Lr(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.an(n, e.key), e.key.path.toArray() ]);
  7886. }
  7887. _n(t, e, n) {
  7888. const s = Lr(t);
  7889. let i = new He(Ar);
  7890. return s.Z({
  7891. index: "documentKeyIndex",
  7892. range: IDBKeyRange.only([ n.indexId, this.uid, this.an(n, e) ])
  7893. }, ((t, s) => {
  7894. i = i.add(new Er(n.indexId, e, s.arrayValue, s.directionalValue));
  7895. })).next((() => i));
  7896. }
  7897. /** Creates the index entries for the given document. */ wn(t, e) {
  7898. let n = new He(Ar);
  7899. const s = this.cn(e, t);
  7900. if (null == s) return n;
  7901. const i = lt(e);
  7902. if (null != i) {
  7903. const r = t.data.field(i.fieldPath);
  7904. if (fe(r)) for (const i of r.arrayValue.values || []) n = n.add(new Er(e.indexId, t.key, this.rn(i), s));
  7905. } else n = n.add(new Er(e.indexId, t.key, Fr, s));
  7906. return n;
  7907. }
  7908. /**
  7909. * Updates the index entries for the provided document by deleting entries
  7910. * that are no longer referenced in `newEntries` and adding all newly added
  7911. * entries.
  7912. */ mn(t, e, n, s, i) {
  7913. x("IndexedDbIndexManager", "Updating index entries for document '%s'", e.key);
  7914. const r = [];
  7915. return function(t, e, n, s, i) {
  7916. const r = t.getIterator(), o = e.getIterator();
  7917. let u = Ye(r), c = Ye(o);
  7918. // Walk through the two sets at the same time, using the ordering defined by
  7919. // `comparator`.
  7920. for (;u || c; ) {
  7921. let t = !1, e = !1;
  7922. if (u && c) {
  7923. const s = n(u, c);
  7924. s < 0 ?
  7925. // The element was removed if the next element in our ordered
  7926. // walkthrough is only in `before`.
  7927. e = !0 : s > 0 && (
  7928. // The element was added if the next element in our ordered walkthrough
  7929. // is only in `after`.
  7930. t = !0);
  7931. } else null != u ? e = !0 : t = !0;
  7932. t ? (s(c), c = Ye(o)) : e ? (i(u), u = Ye(r)) : (u = Ye(r), c = Ye(o));
  7933. }
  7934. }(s, i, Ar, (
  7935. /* onAdd= */ s => {
  7936. r.push(this.gn(t, e, n, s));
  7937. }), (
  7938. /* onRemove= */ s => {
  7939. r.push(this.yn(t, e, n, s));
  7940. })), Rt.waitFor(r);
  7941. }
  7942. dn(t) {
  7943. let e = 1;
  7944. return Ur(t).Z({
  7945. index: "sequenceNumberIndex",
  7946. reverse: !0,
  7947. range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
  7948. }, ((t, n, s) => {
  7949. s.done(), e = n.sequenceNumber + 1;
  7950. })).next((() => e));
  7951. }
  7952. /**
  7953. * Returns a new set of IDB ranges that splits the existing range and excludes
  7954. * any values that match the `notInValue` from these ranges. As an example,
  7955. * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
  7956. */ createRange(t, e, n) {
  7957. // The notIn values need to be sorted and unique so that we can return a
  7958. // sorted set of non-overlapping ranges.
  7959. n = n.sort(((t, e) => Ar(t, e))).filter(((t, e, n) => !e || 0 !== Ar(t, n[e - 1])));
  7960. const s = [];
  7961. s.push(t);
  7962. for (const i of n) {
  7963. const n = Ar(i, t), r = Ar(i, e);
  7964. if (0 === n)
  7965. // `notInValue` is the lower bound. We therefore need to raise the bound
  7966. // to the next value.
  7967. s[0] = t.Ue(); else if (n > 0 && r < 0)
  7968. // `notInValue` is in the middle of the range
  7969. s.push(i), s.push(i.Ue()); else if (r > 0)
  7970. // `notInValue` (and all following values) are out of the range
  7971. break;
  7972. }
  7973. s.push(e);
  7974. const i = [];
  7975. for (let t = 0; t < s.length; t += 2) {
  7976. // If we encounter two bounds that will create an unmatchable key range,
  7977. // then we return an empty set of key ranges.
  7978. if (this.pn(s[t], s[t + 1])) return [];
  7979. const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Fr, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Fr, [] ];
  7980. i.push(IDBKeyRange.bound(e, n));
  7981. }
  7982. return i;
  7983. }
  7984. pn(t, e) {
  7985. // If lower bound is greater than the upper bound, then the key
  7986. // range can never be matched.
  7987. return Ar(t, e) > 0;
  7988. }
  7989. getMinOffsetFromCollectionGroup(t, e) {
  7990. return this.getFieldIndexes(t, e).next(Kr);
  7991. }
  7992. getMinOffset(t, e) {
  7993. return Rt.mapArray(this.Ze(e), (e => this.tn(t, e).next((t => t || M())))).next(Kr);
  7994. }
  7995. }
  7996. /**
  7997. * Helper to get a typed SimpleDbStore for the collectionParents
  7998. * document store.
  7999. */ function Br(t) {
  8000. return ji(t, "collectionParents");
  8001. }
  8002. /**
  8003. * Helper to get a typed SimpleDbStore for the index entry object store.
  8004. */ function Lr(t) {
  8005. return ji(t, "indexEntries");
  8006. }
  8007. /**
  8008. * Helper to get a typed SimpleDbStore for the index configuration object store.
  8009. */ function qr(t) {
  8010. return ji(t, "indexConfiguration");
  8011. }
  8012. /**
  8013. * Helper to get a typed SimpleDbStore for the index state object store.
  8014. */ function Ur(t) {
  8015. return ji(t, "indexState");
  8016. }
  8017. function Kr(t) {
  8018. F(0 !== t.length);
  8019. let e = t[0].indexState.offset, n = e.largestBatchId;
  8020. for (let s = 1; s < t.length; s++) {
  8021. const i = t[s].indexState.offset;
  8022. It(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);
  8023. }
  8024. return new pt(e.readTime, e.documentKey, n);
  8025. }
  8026. /**
  8027. * @license
  8028. * Copyright 2018 Google LLC
  8029. *
  8030. * Licensed under the Apache License, Version 2.0 (the "License");
  8031. * you may not use this file except in compliance with the License.
  8032. * You may obtain a copy of the License at
  8033. *
  8034. * http://www.apache.org/licenses/LICENSE-2.0
  8035. *
  8036. * Unless required by applicable law or agreed to in writing, software
  8037. * distributed under the License is distributed on an "AS IS" BASIS,
  8038. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8039. * See the License for the specific language governing permissions and
  8040. * limitations under the License.
  8041. */ const Gr = {
  8042. didRun: !1,
  8043. sequenceNumbersCollected: 0,
  8044. targetsRemoved: 0,
  8045. documentsRemoved: 0
  8046. };
  8047. class Qr {
  8048. constructor(
  8049. // When we attempt to collect, we will only do so if the cache size is greater than this
  8050. // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
  8051. t,
  8052. // The percentage of sequence numbers that we will attempt to collect
  8053. e,
  8054. // A cap on the total number of sequence numbers that will be collected. This prevents
  8055. // us from collecting a huge number of sequence numbers if the cache has grown very large.
  8056. n) {
  8057. this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
  8058. }
  8059. static withCacheSize(t) {
  8060. return new Qr(t, Qr.DEFAULT_COLLECTION_PERCENTILE, Qr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  8061. }
  8062. }
  8063. /**
  8064. * @license
  8065. * Copyright 2020 Google LLC
  8066. *
  8067. * Licensed under the Apache License, Version 2.0 (the "License");
  8068. * you may not use this file except in compliance with the License.
  8069. * You may obtain a copy of the License at
  8070. *
  8071. * http://www.apache.org/licenses/LICENSE-2.0
  8072. *
  8073. * Unless required by applicable law or agreed to in writing, software
  8074. * distributed under the License is distributed on an "AS IS" BASIS,
  8075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8076. * See the License for the specific language governing permissions and
  8077. * limitations under the License.
  8078. */
  8079. /**
  8080. * Delete a mutation batch and the associated document mutations.
  8081. * @returns A PersistencePromise of the document mutations that were removed.
  8082. */
  8083. function jr(t, e, n) {
  8084. const s = t.store("mutations"), i = t.store("documentMutations"), r = [], o = IDBKeyRange.only(n.batchId);
  8085. let u = 0;
  8086. const c = s.Z({
  8087. range: o
  8088. }, ((t, e, n) => (u++, n.delete())));
  8089. r.push(c.next((() => {
  8090. F(1 === u);
  8091. })));
  8092. const a = [];
  8093. for (const t of n.mutations) {
  8094. const s = Ri(e, t.key.path, n.batchId);
  8095. r.push(i.delete(s)), a.push(t.key);
  8096. }
  8097. return Rt.waitFor(r).next((() => a));
  8098. }
  8099. /**
  8100. * Returns an approximate size for the given document.
  8101. */ function Wr(t) {
  8102. if (!t) return 0;
  8103. let e;
  8104. if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
  8105. if (!t.noDocument) throw M();
  8106. e = t.noDocument;
  8107. }
  8108. return JSON.stringify(e).length;
  8109. }
  8110. /**
  8111. * @license
  8112. * Copyright 2017 Google LLC
  8113. *
  8114. * Licensed under the Apache License, Version 2.0 (the "License");
  8115. * you may not use this file except in compliance with the License.
  8116. * You may obtain a copy of the License at
  8117. *
  8118. * http://www.apache.org/licenses/LICENSE-2.0
  8119. *
  8120. * Unless required by applicable law or agreed to in writing, software
  8121. * distributed under the License is distributed on an "AS IS" BASIS,
  8122. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8123. * See the License for the specific language governing permissions and
  8124. * limitations under the License.
  8125. */
  8126. /** A mutation queue for a specific user, backed by IndexedDB. */ Qr.DEFAULT_COLLECTION_PERCENTILE = 10,
  8127. Qr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, Qr.DEFAULT = new Qr(41943040, Qr.DEFAULT_COLLECTION_PERCENTILE, Qr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),
  8128. Qr.DISABLED = new Qr(-1, 0, 0);
  8129. class zr {
  8130. constructor(
  8131. /**
  8132. * The normalized userId (e.g. null UID => "" userId) used to store /
  8133. * retrieve mutations.
  8134. */
  8135. t, e, n, s) {
  8136. this.userId = t, this.yt = e, this.indexManager = n, this.referenceDelegate = s,
  8137. /**
  8138. * Caches the document keys for pending mutation batches. If the mutation
  8139. * has been removed from IndexedDb, the cached value may continue to
  8140. * be used to retrieve the batch's document keys. To remove a cached value
  8141. * locally, `removeCachedMutationKeys()` should be invoked either directly
  8142. * or through `removeMutationBatches()`.
  8143. *
  8144. * With multi-tab, when the primary client acknowledges or rejects a mutation,
  8145. * this cache is used by secondary clients to invalidate the local
  8146. * view of the documents that were previously affected by the mutation.
  8147. */
  8148. // PORTING NOTE: Multi-tab only.
  8149. this.In = {};
  8150. }
  8151. /**
  8152. * Creates a new mutation queue for the given user.
  8153. * @param user - The user for which to create a mutation queue.
  8154. * @param serializer - The serializer to use when persisting to IndexedDb.
  8155. */ static re(t, e, n, s) {
  8156. // TODO(mcg): Figure out what constraints there are on userIDs
  8157. // In particular, are there any reserved characters? are empty ids allowed?
  8158. // For the moment store these together in the same mutations table assuming
  8159. // that empty userIDs aren't allowed.
  8160. F("" !== t.uid);
  8161. const i = t.isAuthenticated() ? t.uid : "";
  8162. return new zr(i, e, n, s);
  8163. }
  8164. checkEmpty(t) {
  8165. let e = !0;
  8166. const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8167. return Jr(t).Z({
  8168. index: "userMutationsIndex",
  8169. range: n
  8170. }, ((t, n, s) => {
  8171. e = !1, s.done();
  8172. })).next((() => e));
  8173. }
  8174. addMutationBatch(t, e, n, s) {
  8175. const i = Yr(t), r = Jr(t);
  8176. // The IndexedDb implementation in Chrome (and Firefox) does not handle
  8177. // compound indices that include auto-generated keys correctly. To ensure
  8178. // that the index entry is added correctly in all browsers, we perform two
  8179. // writes: The first write is used to retrieve the next auto-generated Batch
  8180. // ID, and the second write populates the index and stores the actual
  8181. // mutation batch.
  8182. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
  8183. // We write an empty object to obtain key
  8184. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8185. return r.add({}).next((o => {
  8186. F("number" == typeof o);
  8187. const u = new Wi(o, e, n, s), c = function(t, e, n) {
  8188. const s = n.baseMutations.map((e => ni(t.ie, e))), i = n.mutations.map((e => ni(t.ie, e)));
  8189. return {
  8190. userId: e,
  8191. batchId: n.batchId,
  8192. localWriteTimeMs: n.localWriteTime.toMillis(),
  8193. baseMutations: s,
  8194. mutations: i
  8195. };
  8196. }(this.yt, this.userId, u), a = [];
  8197. let h = new He(((t, e) => tt(t.canonicalString(), e.canonicalString())));
  8198. for (const t of s) {
  8199. const e = Ri(this.userId, t.key.path, o);
  8200. h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, bi));
  8201. }
  8202. return h.forEach((e => {
  8203. a.push(this.indexManager.addToCollectionParentIndex(t, e));
  8204. })), t.addOnCommittedListener((() => {
  8205. this.In[o] = u.keys();
  8206. })), Rt.waitFor(a).next((() => u));
  8207. }));
  8208. }
  8209. lookupMutationBatch(t, e) {
  8210. return Jr(t).get(e).next((t => t ? (F(t.userId === this.userId), sr(this.yt, t)) : null));
  8211. }
  8212. /**
  8213. * Returns the document keys for the mutation batch with the given batchId.
  8214. * For primary clients, this method returns `null` after
  8215. * `removeMutationBatches()` has been called. Secondary clients return a
  8216. * cached result until `removeCachedMutationKeys()` is invoked.
  8217. */
  8218. // PORTING NOTE: Multi-tab only.
  8219. Tn(t, e) {
  8220. return this.In[e] ? Rt.resolve(this.In[e]) : this.lookupMutationBatch(t, e).next((t => {
  8221. if (t) {
  8222. const n = t.keys();
  8223. return this.In[e] = n, n;
  8224. }
  8225. return null;
  8226. }));
  8227. }
  8228. getNextMutationBatchAfterBatchId(t, e) {
  8229. const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);
  8230. let i = null;
  8231. return Jr(t).Z({
  8232. index: "userMutationsIndex",
  8233. range: s
  8234. }, ((t, e, s) => {
  8235. e.userId === this.userId && (F(e.batchId >= n), i = sr(this.yt, e)), s.done();
  8236. })).next((() => i));
  8237. }
  8238. getHighestUnacknowledgedBatchId(t) {
  8239. const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
  8240. let n = -1;
  8241. return Jr(t).Z({
  8242. index: "userMutationsIndex",
  8243. range: e,
  8244. reverse: !0
  8245. }, ((t, e, s) => {
  8246. n = e.batchId, s.done();
  8247. })).next((() => n));
  8248. }
  8249. getAllMutationBatches(t) {
  8250. const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8251. return Jr(t).W("userMutationsIndex", e).next((t => t.map((t => sr(this.yt, t)))));
  8252. }
  8253. getAllMutationBatchesAffectingDocumentKey(t, e) {
  8254. // Scan the document-mutation index starting with a prefix starting with
  8255. // the given documentKey.
  8256. const n = Ai(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];
  8257. return Yr(t).Z({
  8258. range: s
  8259. }, ((n, s, r) => {
  8260. const [o, u, c] = n, a = Ti(u);
  8261. // Only consider rows matching exactly the specific key of
  8262. // interest. Note that because we order by path first, and we
  8263. // order terminators before path separators, we'll encounter all
  8264. // the index rows for documentKey contiguously. In particular, all
  8265. // the rows for documentKey will occur before any rows for
  8266. // documents nested in a subcollection beneath documentKey so we
  8267. // can stop as soon as we hit any such row.
  8268. if (o === this.userId && e.path.isEqual(a))
  8269. // Look up the mutation batch in the store.
  8270. return Jr(t).get(c).next((t => {
  8271. if (!t) throw M();
  8272. F(t.userId === this.userId), i.push(sr(this.yt, t));
  8273. }));
  8274. r.done();
  8275. })).next((() => i));
  8276. }
  8277. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  8278. let n = new He(tt);
  8279. const s = [];
  8280. return e.forEach((e => {
  8281. const i = Ai(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = Yr(t).Z({
  8282. range: r
  8283. }, ((t, s, i) => {
  8284. const [r, o, u] = t, c = Ti(o);
  8285. // Only consider rows matching exactly the specific key of
  8286. // interest. Note that because we order by path first, and we
  8287. // order terminators before path separators, we'll encounter all
  8288. // the index rows for documentKey contiguously. In particular, all
  8289. // the rows for documentKey will occur before any rows for
  8290. // documents nested in a subcollection beneath documentKey so we
  8291. // can stop as soon as we hit any such row.
  8292. r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();
  8293. }));
  8294. s.push(o);
  8295. })), Rt.waitFor(s).next((() => this.En(t, n)));
  8296. }
  8297. getAllMutationBatchesAffectingQuery(t, e) {
  8298. const n = e.path, s = n.length + 1, i = Ai(this.userId, n), r = IDBKeyRange.lowerBound(i);
  8299. // Collect up unique batchIDs encountered during a scan of the index. Use a
  8300. // SortedSet to accumulate batch IDs so they can be traversed in order in a
  8301. // scan of the main table.
  8302. let o = new He(tt);
  8303. return Yr(t).Z({
  8304. range: r
  8305. }, ((t, e, i) => {
  8306. const [r, u, c] = t, a = Ti(u);
  8307. r === this.userId && n.isPrefixOf(a) ?
  8308. // Rows with document keys more than one segment longer than the
  8309. // query path can't be matches. For example, a query on 'rooms'
  8310. // can't match the document /rooms/abc/messages/xyx.
  8311. // TODO(mcg): we'll need a different scanner when we implement
  8312. // ancestor queries.
  8313. a.length === s && (o = o.add(c)) : i.done();
  8314. })).next((() => this.En(t, o)));
  8315. }
  8316. En(t, e) {
  8317. const n = [], s = [];
  8318. // TODO(rockwood): Implement this using iterate.
  8319. return e.forEach((e => {
  8320. s.push(Jr(t).get(e).next((t => {
  8321. if (null === t) throw M();
  8322. F(t.userId === this.userId), n.push(sr(this.yt, t));
  8323. })));
  8324. })), Rt.waitFor(s).next((() => n));
  8325. }
  8326. removeMutationBatch(t, e) {
  8327. return jr(t.se, this.userId, e).next((n => (t.addOnCommittedListener((() => {
  8328. this.An(e.batchId);
  8329. })), Rt.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));
  8330. }
  8331. /**
  8332. * Clears the cached keys for a mutation batch. This method should be
  8333. * called by secondary clients after they process mutation updates.
  8334. *
  8335. * Note that this method does not have to be called from primary clients as
  8336. * the corresponding cache entries are cleared when an acknowledged or
  8337. * rejected batch is removed from the mutation queue.
  8338. */
  8339. // PORTING NOTE: Multi-tab only
  8340. An(t) {
  8341. delete this.In[t];
  8342. }
  8343. performConsistencyCheck(t) {
  8344. return this.checkEmpty(t).next((e => {
  8345. if (!e) return Rt.resolve();
  8346. // Verify that there are no entries in the documentMutations index if
  8347. // the queue is empty.
  8348. const n = IDBKeyRange.lowerBound([ this.userId ]);
  8349. const s = [];
  8350. return Yr(t).Z({
  8351. range: n
  8352. }, ((t, e, n) => {
  8353. if (t[0] === this.userId) {
  8354. const e = Ti(t[1]);
  8355. s.push(e);
  8356. } else n.done();
  8357. })).next((() => {
  8358. F(0 === s.length);
  8359. }));
  8360. }));
  8361. }
  8362. containsKey(t, e) {
  8363. return Hr(t, this.userId, e);
  8364. }
  8365. // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  8366. /** Returns the mutation queue's metadata from IndexedDb. */
  8367. Rn(t) {
  8368. return Xr(t).get(this.userId).next((t => t || {
  8369. userId: this.userId,
  8370. lastAcknowledgedBatchId: -1,
  8371. lastStreamToken: ""
  8372. }));
  8373. }
  8374. }
  8375. /**
  8376. * @returns true if the mutation queue for the given user contains a pending
  8377. * mutation for the given key.
  8378. */ function Hr(t, e, n) {
  8379. const s = Ai(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);
  8380. let o = !1;
  8381. return Yr(t).Z({
  8382. range: r,
  8383. X: !0
  8384. }, ((t, n, s) => {
  8385. const [r, u, /*batchID*/ c] = t;
  8386. r === e && u === i && (o = !0), s.done();
  8387. })).next((() => o));
  8388. }
  8389. /** Returns true if any mutation queue contains the given document. */
  8390. /**
  8391. * Helper to get a typed SimpleDbStore for the mutations object store.
  8392. */
  8393. function Jr(t) {
  8394. return ji(t, "mutations");
  8395. }
  8396. /**
  8397. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8398. */ function Yr(t) {
  8399. return ji(t, "documentMutations");
  8400. }
  8401. /**
  8402. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8403. */ function Xr(t) {
  8404. return ji(t, "mutationQueues");
  8405. }
  8406. /**
  8407. * @license
  8408. * Copyright 2017 Google LLC
  8409. *
  8410. * Licensed under the Apache License, Version 2.0 (the "License");
  8411. * you may not use this file except in compliance with the License.
  8412. * You may obtain a copy of the License at
  8413. *
  8414. * http://www.apache.org/licenses/LICENSE-2.0
  8415. *
  8416. * Unless required by applicable law or agreed to in writing, software
  8417. * distributed under the License is distributed on an "AS IS" BASIS,
  8418. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8419. * See the License for the specific language governing permissions and
  8420. * limitations under the License.
  8421. */
  8422. /** Offset to ensure non-overlapping target ids. */
  8423. /**
  8424. * Generates monotonically increasing target IDs for sending targets to the
  8425. * watch stream.
  8426. *
  8427. * The client constructs two generators, one for the target cache, and one for
  8428. * for the sync engine (to generate limbo documents targets). These
  8429. * generators produce non-overlapping IDs (by using even and odd IDs
  8430. * respectively).
  8431. *
  8432. * By separating the target ID space, the query cache can generate target IDs
  8433. * that persist across client restarts, while sync engine can independently
  8434. * generate in-memory target IDs that are transient and can be reused after a
  8435. * restart.
  8436. */
  8437. class Zr {
  8438. constructor(t) {
  8439. this.bn = t;
  8440. }
  8441. next() {
  8442. return this.bn += 2, this.bn;
  8443. }
  8444. static Pn() {
  8445. // The target cache generator must return '2' in its first call to `next()`
  8446. // as there is no differentiation in the protocol layer between an unset
  8447. // number and the number '0'. If we were to sent a target with target ID
  8448. // '0', the backend would consider it unset and replace it with its own ID.
  8449. return new Zr(0);
  8450. }
  8451. static vn() {
  8452. // Sync engine assigns target IDs for limbo document detection.
  8453. return new Zr(-1);
  8454. }
  8455. }
  8456. /**
  8457. * @license
  8458. * Copyright 2017 Google LLC
  8459. *
  8460. * Licensed under the Apache License, Version 2.0 (the "License");
  8461. * you may not use this file except in compliance with the License.
  8462. * You may obtain a copy of the License at
  8463. *
  8464. * http://www.apache.org/licenses/LICENSE-2.0
  8465. *
  8466. * Unless required by applicable law or agreed to in writing, software
  8467. * distributed under the License is distributed on an "AS IS" BASIS,
  8468. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8469. * See the License for the specific language governing permissions and
  8470. * limitations under the License.
  8471. */ class to {
  8472. constructor(t, e) {
  8473. this.referenceDelegate = t, this.yt = e;
  8474. }
  8475. // PORTING NOTE: We don't cache global metadata for the target cache, since
  8476. // some of it (in particular `highestTargetId`) can be modified by secondary
  8477. // tabs. We could perhaps be more granular (and e.g. still cache
  8478. // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  8479. // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  8480. // out to have a meaningful performance impact.
  8481. allocateTargetId(t) {
  8482. return this.Vn(t).next((e => {
  8483. const n = new Zr(e.highestTargetId);
  8484. return e.highestTargetId = n.next(), this.Sn(t, e).next((() => e.highestTargetId));
  8485. }));
  8486. }
  8487. getLastRemoteSnapshotVersion(t) {
  8488. return this.Vn(t).next((t => it.fromTimestamp(new st(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));
  8489. }
  8490. getHighestSequenceNumber(t) {
  8491. return this.Vn(t).next((t => t.highestListenSequenceNumber));
  8492. }
  8493. setTargetsMetadata(t, e, n) {
  8494. return this.Vn(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()),
  8495. e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.Sn(t, s))));
  8496. }
  8497. addTargetData(t, e) {
  8498. return this.Dn(t, e).next((() => this.Vn(t).next((n => (n.targetCount += 1, this.Cn(e, n),
  8499. this.Sn(t, n))))));
  8500. }
  8501. updateTargetData(t, e) {
  8502. return this.Dn(t, e);
  8503. }
  8504. removeTargetData(t, e) {
  8505. return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => eo(t).delete(e.targetId))).next((() => this.Vn(t))).next((e => (F(e.targetCount > 0),
  8506. e.targetCount -= 1, this.Sn(t, e))));
  8507. }
  8508. /**
  8509. * Drops any targets with sequence number less than or equal to the upper bound, excepting those
  8510. * present in `activeTargetIds`. Document associations for the removed targets are also removed.
  8511. * Returns the number of targets removed.
  8512. */ removeTargets(t, e, n) {
  8513. let s = 0;
  8514. const i = [];
  8515. return eo(t).Z(((r, o) => {
  8516. const u = ir(o);
  8517. u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));
  8518. })).next((() => Rt.waitFor(i))).next((() => s));
  8519. }
  8520. /**
  8521. * Call provided function with each `TargetData` that we have cached.
  8522. */ forEachTarget(t, e) {
  8523. return eo(t).Z(((t, n) => {
  8524. const s = ir(n);
  8525. e(s);
  8526. }));
  8527. }
  8528. Vn(t) {
  8529. return no(t).get("targetGlobalKey").next((t => (F(null !== t), t)));
  8530. }
  8531. Sn(t, e) {
  8532. return no(t).put("targetGlobalKey", e);
  8533. }
  8534. Dn(t, e) {
  8535. return eo(t).put(rr(this.yt, e));
  8536. }
  8537. /**
  8538. * In-place updates the provided metadata to account for values in the given
  8539. * TargetData. Saving is done separately. Returns true if there were any
  8540. * changes to the metadata.
  8541. */ Cn(t, e) {
  8542. let n = !1;
  8543. return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0),
  8544. t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber,
  8545. n = !0), n;
  8546. }
  8547. getTargetCount(t) {
  8548. return this.Vn(t).next((t => t.targetCount));
  8549. }
  8550. getTargetData(t, e) {
  8551. // Iterating by the canonicalId may yield more than one result because
  8552. // canonicalId values are not required to be unique per target. This query
  8553. // depends on the queryTargets index to be efficient.
  8554. const n = rn(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);
  8555. let i = null;
  8556. return eo(t).Z({
  8557. range: s,
  8558. index: "queryTargetsIndex"
  8559. }, ((t, n, s) => {
  8560. const r = ir(n);
  8561. // After finding a potential match, check that the target is
  8562. // actually equal to the requested target.
  8563. on(e, r.target) && (i = r, s.done());
  8564. })).next((() => i));
  8565. }
  8566. addMatchingKeys(t, e, n) {
  8567. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8568. // IndexedDb.
  8569. const s = [], i = so(t);
  8570. return e.forEach((e => {
  8571. const r = yi(e.path);
  8572. s.push(i.put({
  8573. targetId: n,
  8574. path: r
  8575. })), s.push(this.referenceDelegate.addReference(t, n, e));
  8576. })), Rt.waitFor(s);
  8577. }
  8578. removeMatchingKeys(t, e, n) {
  8579. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8580. // IndexedDb.
  8581. const s = so(t);
  8582. return Rt.forEach(e, (e => {
  8583. const i = yi(e.path);
  8584. return Rt.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);
  8585. }));
  8586. }
  8587. removeMatchingKeysForTargetId(t, e) {
  8588. const n = so(t), s = IDBKeyRange.bound([ e ], [ e + 1 ],
  8589. /*lowerOpen=*/ !1,
  8590. /*upperOpen=*/ !0);
  8591. return n.delete(s);
  8592. }
  8593. getMatchingKeysForTargetId(t, e) {
  8594. const n = IDBKeyRange.bound([ e ], [ e + 1 ],
  8595. /*lowerOpen=*/ !1,
  8596. /*upperOpen=*/ !0), s = so(t);
  8597. let i = Rs();
  8598. return s.Z({
  8599. range: n,
  8600. X: !0
  8601. }, ((t, e, n) => {
  8602. const s = Ti(t[1]), r = new at(s);
  8603. i = i.add(r);
  8604. })).next((() => i));
  8605. }
  8606. containsKey(t, e) {
  8607. const n = yi(e.path), s = IDBKeyRange.bound([ n ], [ nt(n) ],
  8608. /*lowerOpen=*/ !1,
  8609. /*upperOpen=*/ !0);
  8610. let i = 0;
  8611. return so(t).Z({
  8612. index: "documentTargetsIndex",
  8613. X: !0,
  8614. range: s
  8615. }, (([t, e], n, s) => {
  8616. // Having a sentinel row for a document does not count as containing that document;
  8617. // For the target cache, containing the document means the document is part of some
  8618. // target.
  8619. 0 !== t && (i++, s.done());
  8620. })).next((() => i > 0));
  8621. }
  8622. /**
  8623. * Looks up a TargetData entry by target ID.
  8624. *
  8625. * @param targetId - The target ID of the TargetData entry to look up.
  8626. * @returns The cached TargetData entry, or null if the cache has no entry for
  8627. * the target.
  8628. */
  8629. // PORTING NOTE: Multi-tab only.
  8630. ne(t, e) {
  8631. return eo(t).get(e).next((t => t ? ir(t) : null));
  8632. }
  8633. }
  8634. /**
  8635. * Helper to get a typed SimpleDbStore for the queries object store.
  8636. */ function eo(t) {
  8637. return ji(t, "targets");
  8638. }
  8639. /**
  8640. * Helper to get a typed SimpleDbStore for the target globals object store.
  8641. */ function no(t) {
  8642. return ji(t, "targetGlobal");
  8643. }
  8644. /**
  8645. * Helper to get a typed SimpleDbStore for the document target object store.
  8646. */ function so(t) {
  8647. return ji(t, "targetDocuments");
  8648. }
  8649. /**
  8650. * @license
  8651. * Copyright 2020 Google LLC
  8652. *
  8653. * Licensed under the Apache License, Version 2.0 (the "License");
  8654. * you may not use this file except in compliance with the License.
  8655. * You may obtain a copy of the License at
  8656. *
  8657. * http://www.apache.org/licenses/LICENSE-2.0
  8658. *
  8659. * Unless required by applicable law or agreed to in writing, software
  8660. * distributed under the License is distributed on an "AS IS" BASIS,
  8661. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8662. * See the License for the specific language governing permissions and
  8663. * limitations under the License.
  8664. */ function io([t, e], [n, s]) {
  8665. const i = tt(t, n);
  8666. return 0 === i ? tt(e, s) : i;
  8667. }
  8668. /**
  8669. * Used to calculate the nth sequence number. Keeps a rolling buffer of the
  8670. * lowest n values passed to `addElement`, and finally reports the largest of
  8671. * them in `maxValue`.
  8672. */ class ro {
  8673. constructor(t) {
  8674. this.xn = t, this.buffer = new He(io), this.Nn = 0;
  8675. }
  8676. kn() {
  8677. return ++this.Nn;
  8678. }
  8679. On(t) {
  8680. const e = [ t, this.kn() ];
  8681. if (this.buffer.size < this.xn) this.buffer = this.buffer.add(e); else {
  8682. const t = this.buffer.last();
  8683. io(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));
  8684. }
  8685. }
  8686. get maxValue() {
  8687. // Guaranteed to be non-empty. If we decide we are not collecting any
  8688. // sequence numbers, nthSequenceNumber below short-circuits. If we have
  8689. // decided that we are collecting n sequence numbers, it's because n is some
  8690. // percentage of the existing sequence numbers. That means we should never
  8691. // be in a situation where we are collecting sequence numbers but don't
  8692. // actually have any.
  8693. return this.buffer.last()[0];
  8694. }
  8695. }
  8696. /**
  8697. * This class is responsible for the scheduling of LRU garbage collection. It handles checking
  8698. * whether or not GC is enabled, as well as which delay to use before the next run.
  8699. */ class oo {
  8700. constructor(t, e, n) {
  8701. this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Mn = null;
  8702. }
  8703. start() {
  8704. -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Fn(6e4);
  8705. }
  8706. stop() {
  8707. this.Mn && (this.Mn.cancel(), this.Mn = null);
  8708. }
  8709. get started() {
  8710. return null !== this.Mn;
  8711. }
  8712. Fn(t) {
  8713. x("LruGarbageCollector", `Garbage collection scheduled in ${t}ms`), this.Mn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , t, (async () => {
  8714. this.Mn = null;
  8715. try {
  8716. await this.localStore.collectGarbage(this.garbageCollector);
  8717. } catch (t) {
  8718. St(t) ? x("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await At(t);
  8719. }
  8720. await this.Fn(3e5);
  8721. }));
  8722. }
  8723. }
  8724. /** Implements the steps for LRU garbage collection. */ class uo {
  8725. constructor(t, e) {
  8726. this.$n = t, this.params = e;
  8727. }
  8728. calculateTargetCount(t, e) {
  8729. return this.$n.Bn(t).next((t => Math.floor(e / 100 * t)));
  8730. }
  8731. nthSequenceNumber(t, e) {
  8732. if (0 === e) return Rt.resolve(Mt.at);
  8733. const n = new ro(e);
  8734. return this.$n.forEachTarget(t, (t => n.On(t.sequenceNumber))).next((() => this.$n.Ln(t, (t => n.On(t))))).next((() => n.maxValue));
  8735. }
  8736. removeTargets(t, e, n) {
  8737. return this.$n.removeTargets(t, e, n);
  8738. }
  8739. removeOrphanedDocuments(t, e) {
  8740. return this.$n.removeOrphanedDocuments(t, e);
  8741. }
  8742. collect(t, e) {
  8743. return -1 === this.params.cacheSizeCollectionThreshold ? (x("LruGarbageCollector", "Garbage collection skipped; disabled"),
  8744. Rt.resolve(Gr)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (x("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),
  8745. Gr) : this.qn(t, e)));
  8746. }
  8747. getCacheSize(t) {
  8748. return this.$n.getCacheSize(t);
  8749. }
  8750. qn(t, e) {
  8751. let n, s, i, r, o, c, a;
  8752. const h = Date.now();
  8753. return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (
  8754. // Cap at the configured max
  8755. e > this.params.maximumSequenceNumbersToCollect ? (x("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),
  8756. s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s,
  8757. o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(),
  8758. this.removeOrphanedDocuments(t, n)))).next((t => {
  8759. if (a = Date.now(), D() <= u.DEBUG) {
  8760. x("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${r - h}ms\n\tDetermined least recently used ${s} in ` + (o - r) + "ms\n" + `\tRemoved ${i} targets in ` + (c - o) + "ms\n" + `\tRemoved ${t} documents in ` + (a - c) + "ms\n" + `Total Duration: ${a - h}ms`);
  8761. }
  8762. return Rt.resolve({
  8763. didRun: !0,
  8764. sequenceNumbersCollected: s,
  8765. targetsRemoved: i,
  8766. documentsRemoved: t
  8767. });
  8768. }));
  8769. }
  8770. }
  8771. /**
  8772. * @license
  8773. * Copyright 2020 Google LLC
  8774. *
  8775. * Licensed under the Apache License, Version 2.0 (the "License");
  8776. * you may not use this file except in compliance with the License.
  8777. * You may obtain a copy of the License at
  8778. *
  8779. * http://www.apache.org/licenses/LICENSE-2.0
  8780. *
  8781. * Unless required by applicable law or agreed to in writing, software
  8782. * distributed under the License is distributed on an "AS IS" BASIS,
  8783. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8784. * See the License for the specific language governing permissions and
  8785. * limitations under the License.
  8786. */
  8787. /** Provides LRU functionality for IndexedDB persistence. */
  8788. class co {
  8789. constructor(t, e) {
  8790. this.db = t, this.garbageCollector = function(t, e) {
  8791. return new uo(t, e);
  8792. }(this, e);
  8793. }
  8794. Bn(t) {
  8795. const e = this.Un(t);
  8796. return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  8797. }
  8798. Un(t) {
  8799. let e = 0;
  8800. return this.Ln(t, (t => {
  8801. e++;
  8802. })).next((() => e));
  8803. }
  8804. forEachTarget(t, e) {
  8805. return this.db.getTargetCache().forEachTarget(t, e);
  8806. }
  8807. Ln(t, e) {
  8808. return this.Kn(t, ((t, n) => e(n)));
  8809. }
  8810. addReference(t, e, n) {
  8811. return ao(t, n);
  8812. }
  8813. removeReference(t, e, n) {
  8814. return ao(t, n);
  8815. }
  8816. removeTargets(t, e, n) {
  8817. return this.db.getTargetCache().removeTargets(t, e, n);
  8818. }
  8819. markPotentiallyOrphaned(t, e) {
  8820. return ao(t, e);
  8821. }
  8822. /**
  8823. * Returns true if anything would prevent this document from being garbage
  8824. * collected, given that the document in question is not present in any
  8825. * targets and has a sequence number less than or equal to the upper bound for
  8826. * the collection run.
  8827. */ Gn(t, e) {
  8828. return function(t, e) {
  8829. let n = !1;
  8830. return Xr(t).tt((s => Hr(t, s, e).next((t => (t && (n = !0), Rt.resolve(!t)))))).next((() => n));
  8831. }(t, e);
  8832. }
  8833. removeOrphanedDocuments(t, e) {
  8834. const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];
  8835. let i = 0;
  8836. return this.Kn(t, ((r, o) => {
  8837. if (o <= e) {
  8838. const e = this.Gn(t, r).next((e => {
  8839. if (!e)
  8840. // Our size accounting requires us to read all documents before
  8841. // removing them.
  8842. return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, it.min()), so(t).delete([ 0, yi(r.path) ]))));
  8843. }));
  8844. s.push(e);
  8845. }
  8846. })).next((() => Rt.waitFor(s))).next((() => n.apply(t))).next((() => i));
  8847. }
  8848. removeTarget(t, e) {
  8849. const n = e.withSequenceNumber(t.currentSequenceNumber);
  8850. return this.db.getTargetCache().updateTargetData(t, n);
  8851. }
  8852. updateLimboDocument(t, e) {
  8853. return ao(t, e);
  8854. }
  8855. /**
  8856. * Call provided function for each document in the cache that is 'orphaned'. Orphaned
  8857. * means not a part of any target, so the only entry in the target-document index for
  8858. * that document will be the sentinel row (targetId 0), which will also have the sequence
  8859. * number for the last time the document was accessed.
  8860. */ Kn(t, e) {
  8861. const n = so(t);
  8862. let s, i = Mt.at;
  8863. return n.Z({
  8864. index: "documentTargetsIndex"
  8865. }, (([t, n], {path: r, sequenceNumber: o}) => {
  8866. 0 === t ? (
  8867. // if nextToReport is valid, report it, this is a new key so the
  8868. // last one must not be a member of any targets.
  8869. i !== Mt.at && e(new at(Ti(s)), i),
  8870. // set nextToReport to be this sequence number. It's the next one we
  8871. // might report, if we don't find any targets for this document.
  8872. // Note that the sequence number must be defined when the targetId
  8873. // is 0.
  8874. i = o, s = r) :
  8875. // set nextToReport to be invalid, we know we don't need to report
  8876. // this one since we found a target for it.
  8877. i = Mt.at;
  8878. })).next((() => {
  8879. // Since we report sequence numbers after getting to the next key, we
  8880. // need to check if the last key we iterated over was an orphaned
  8881. // document and report it.
  8882. i !== Mt.at && e(new at(Ti(s)), i);
  8883. }));
  8884. }
  8885. getCacheSize(t) {
  8886. return this.db.getRemoteDocumentCache().getSize(t);
  8887. }
  8888. }
  8889. function ao(t, e) {
  8890. return so(t).put(
  8891. /**
  8892. * @returns A value suitable for writing a sentinel row in the target-document
  8893. * store.
  8894. */
  8895. function(t, e) {
  8896. return {
  8897. targetId: 0,
  8898. path: yi(t.path),
  8899. sequenceNumber: e
  8900. };
  8901. }(e, t.currentSequenceNumber));
  8902. }
  8903. /**
  8904. * @license
  8905. * Copyright 2017 Google LLC
  8906. *
  8907. * Licensed under the Apache License, Version 2.0 (the "License");
  8908. * you may not use this file except in compliance with the License.
  8909. * You may obtain a copy of the License at
  8910. *
  8911. * http://www.apache.org/licenses/LICENSE-2.0
  8912. *
  8913. * Unless required by applicable law or agreed to in writing, software
  8914. * distributed under the License is distributed on an "AS IS" BASIS,
  8915. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8916. * See the License for the specific language governing permissions and
  8917. * limitations under the License.
  8918. */
  8919. /**
  8920. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  8921. * It can be used to batch up a set of changes to be written to the cache, but
  8922. * additionally supports reading entries back with the `getEntry()` method,
  8923. * falling back to the underlying RemoteDocumentCache if no entry is
  8924. * buffered.
  8925. *
  8926. * Entries added to the cache *must* be read first. This is to facilitate
  8927. * calculating the size delta of the pending changes.
  8928. *
  8929. * PORTING NOTE: This class was implemented then removed from other platforms.
  8930. * If byte-counting ends up being needed on the other platforms, consider
  8931. * porting this class as part of that implementation work.
  8932. */ class ho {
  8933. constructor() {
  8934. // A mapping of document key to the new cache entry that should be written.
  8935. this.changes = new ds((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;
  8936. }
  8937. /**
  8938. * Buffers a `RemoteDocumentCache.addEntry()` call.
  8939. *
  8940. * You can only modify documents that have already been retrieved via
  8941. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8942. */ addEntry(t) {
  8943. this.assertNotApplied(), this.changes.set(t.key, t);
  8944. }
  8945. /**
  8946. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  8947. *
  8948. * You can only remove documents that have already been retrieved via
  8949. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8950. */ removeEntry(t, e) {
  8951. this.assertNotApplied(), this.changes.set(t, en.newInvalidDocument(t).setReadTime(e));
  8952. }
  8953. /**
  8954. * Looks up an entry in the cache. The buffered changes will first be checked,
  8955. * and if no buffered change applies, this will forward to
  8956. * `RemoteDocumentCache.getEntry()`.
  8957. *
  8958. * @param transaction - The transaction in which to perform any persistence
  8959. * operations.
  8960. * @param documentKey - The key of the entry to look up.
  8961. * @returns The cached document or an invalid document if we have nothing
  8962. * cached.
  8963. */ getEntry(t, e) {
  8964. this.assertNotApplied();
  8965. const n = this.changes.get(e);
  8966. return void 0 !== n ? Rt.resolve(n) : this.getFromCache(t, e);
  8967. }
  8968. /**
  8969. * Looks up several entries in the cache, forwarding to
  8970. * `RemoteDocumentCache.getEntry()`.
  8971. *
  8972. * @param transaction - The transaction in which to perform any persistence
  8973. * operations.
  8974. * @param documentKeys - The keys of the entries to look up.
  8975. * @returns A map of cached documents, indexed by key. If an entry cannot be
  8976. * found, the corresponding key will be mapped to an invalid document.
  8977. */ getEntries(t, e) {
  8978. return this.getAllFromCache(t, e);
  8979. }
  8980. /**
  8981. * Applies buffered changes to the underlying RemoteDocumentCache, using
  8982. * the provided transaction.
  8983. */ apply(t) {
  8984. return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
  8985. }
  8986. /** Helper to assert this.changes is not null */ assertNotApplied() {}
  8987. }
  8988. /**
  8989. * @license
  8990. * Copyright 2017 Google LLC
  8991. *
  8992. * Licensed under the Apache License, Version 2.0 (the "License");
  8993. * you may not use this file except in compliance with the License.
  8994. * You may obtain a copy of the License at
  8995. *
  8996. * http://www.apache.org/licenses/LICENSE-2.0
  8997. *
  8998. * Unless required by applicable law or agreed to in writing, software
  8999. * distributed under the License is distributed on an "AS IS" BASIS,
  9000. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9001. * See the License for the specific language governing permissions and
  9002. * limitations under the License.
  9003. */
  9004. /**
  9005. * The RemoteDocumentCache for IndexedDb. To construct, invoke
  9006. * `newIndexedDbRemoteDocumentCache()`.
  9007. */ class lo {
  9008. constructor(t) {
  9009. this.yt = t;
  9010. }
  9011. setIndexManager(t) {
  9012. this.indexManager = t;
  9013. }
  9014. /**
  9015. * Adds the supplied entries to the cache.
  9016. *
  9017. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9018. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9019. */ addEntry(t, e, n) {
  9020. return mo(t).put(n);
  9021. }
  9022. /**
  9023. * Removes a document from the cache.
  9024. *
  9025. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9026. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9027. */ removeEntry(t, e, n) {
  9028. return mo(t).delete(
  9029. /**
  9030. * Returns a key that can be used for document lookups via the primary key of
  9031. * the DbRemoteDocument object store.
  9032. */
  9033. function(t, e) {
  9034. const n = t.path.toArray();
  9035. return [
  9036. /* prefix path */ n.slice(0, n.length - 2),
  9037. /* collection id */ n[n.length - 2], tr(e),
  9038. /* document id */ n[n.length - 1] ];
  9039. }
  9040. /**
  9041. * Returns a key that can be used for document lookups on the
  9042. * `DbRemoteDocumentDocumentCollectionGroupIndex` index.
  9043. */ (e, n));
  9044. }
  9045. /**
  9046. * Updates the current cache size.
  9047. *
  9048. * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
  9049. * cache's metadata.
  9050. */ updateMetadata(t, e) {
  9051. return this.getMetadata(t).next((n => (n.byteSize += e, this.Qn(t, n))));
  9052. }
  9053. getEntry(t, e) {
  9054. let n = en.newInvalidDocument(e);
  9055. return mo(t).Z({
  9056. index: "documentKeyIndex",
  9057. range: IDBKeyRange.only(go(e))
  9058. }, ((t, s) => {
  9059. n = this.jn(e, s);
  9060. })).next((() => n));
  9061. }
  9062. /**
  9063. * Looks up an entry in the cache.
  9064. *
  9065. * @param documentKey - The key of the entry to look up.
  9066. * @returns The cached document entry and its size.
  9067. */ Wn(t, e) {
  9068. let n = {
  9069. size: 0,
  9070. document: en.newInvalidDocument(e)
  9071. };
  9072. return mo(t).Z({
  9073. index: "documentKeyIndex",
  9074. range: IDBKeyRange.only(go(e))
  9075. }, ((t, s) => {
  9076. n = {
  9077. document: this.jn(e, s),
  9078. size: Wr(s)
  9079. };
  9080. })).next((() => n));
  9081. }
  9082. getEntries(t, e) {
  9083. let n = ws();
  9084. return this.zn(t, e, ((t, e) => {
  9085. const s = this.jn(t, e);
  9086. n = n.insert(t, s);
  9087. })).next((() => n));
  9088. }
  9089. /**
  9090. * Looks up several entries in the cache.
  9091. *
  9092. * @param documentKeys - The set of keys entries to look up.
  9093. * @returns A map of documents indexed by key and a map of sizes indexed by
  9094. * key (zero if the document does not exist).
  9095. */ Hn(t, e) {
  9096. let n = ws(), s = new je(at.comparator);
  9097. return this.zn(t, e, ((t, e) => {
  9098. const i = this.jn(t, e);
  9099. n = n.insert(t, i), s = s.insert(t, Wr(e));
  9100. })).next((() => ({
  9101. documents: n,
  9102. Jn: s
  9103. })));
  9104. }
  9105. zn(t, e, n) {
  9106. if (e.isEmpty()) return Rt.resolve();
  9107. let s = new He(po);
  9108. e.forEach((t => s = s.add(t)));
  9109. const i = IDBKeyRange.bound(go(s.first()), go(s.last())), r = s.getIterator();
  9110. let o = r.getNext();
  9111. return mo(t).Z({
  9112. index: "documentKeyIndex",
  9113. range: i
  9114. }, ((t, e, s) => {
  9115. const i = at.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);
  9116. // Go through keys not found in cache.
  9117. for (;o && po(o, i) < 0; ) n(o, null), o = r.getNext();
  9118. o && o.isEqual(i) && (
  9119. // Key found in cache.
  9120. n(o, e), o = r.hasNext() ? r.getNext() : null),
  9121. // Skip to the next key (if there is one).
  9122. o ? s.j(go(o)) : s.done();
  9123. })).next((() => {
  9124. // The rest of the keys are not in the cache. One case where `iterate`
  9125. // above won't go through them is when the cache is empty.
  9126. for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;
  9127. }));
  9128. }
  9129. getAllFromCollection(t, e, n) {
  9130. const s = [ e.popLast().toArray(), e.lastSegment(), tr(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], i = [ e.popLast().toArray(), e.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
  9131. return mo(t).W(IDBKeyRange.bound(s, i, !0)).next((t => {
  9132. let e = ws();
  9133. for (const n of t) {
  9134. const t = this.jn(at.fromSegments(n.prefixPath.concat(n.collectionGroup, n.documentId)), n);
  9135. e = e.insert(t.key, t);
  9136. }
  9137. return e;
  9138. }));
  9139. }
  9140. getAllFromCollectionGroup(t, e, n, s) {
  9141. let i = ws();
  9142. const r = yo(e, n), o = yo(e, pt.max());
  9143. return mo(t).Z({
  9144. index: "collectionGroupIndex",
  9145. range: IDBKeyRange.bound(r, o, !0)
  9146. }, ((t, e, n) => {
  9147. const r = this.jn(at.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);
  9148. i = i.insert(r.key, r), i.size === s && n.done();
  9149. })).next((() => i));
  9150. }
  9151. newChangeBuffer(t) {
  9152. return new _o(this, !!t && t.trackRemovals);
  9153. }
  9154. getSize(t) {
  9155. return this.getMetadata(t).next((t => t.byteSize));
  9156. }
  9157. getMetadata(t) {
  9158. return wo(t).get("remoteDocumentGlobalKey").next((t => (F(!!t), t)));
  9159. }
  9160. Qn(t, e) {
  9161. return wo(t).put("remoteDocumentGlobalKey", e);
  9162. }
  9163. /**
  9164. * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
  9165. * the document corresponds to the format used for sentinel deletes).
  9166. */ jn(t, e) {
  9167. if (e) {
  9168. const t = Xi(this.yt, e);
  9169. // Whether the document is a sentinel removal and should only be used in the
  9170. // `getNewDocumentChanges()`
  9171. if (!(t.isNoDocument() && t.version.isEqual(it.min()))) return t;
  9172. }
  9173. return en.newInvalidDocument(t);
  9174. }
  9175. }
  9176. /** Creates a new IndexedDbRemoteDocumentCache. */ function fo(t) {
  9177. return new lo(t);
  9178. }
  9179. /**
  9180. * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
  9181. *
  9182. * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
  9183. * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
  9184. * when we apply the changes.
  9185. */ class _o extends ho {
  9186. /**
  9187. * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
  9188. * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
  9189. * `getNewDocumentChanges()`.
  9190. */
  9191. constructor(t, e) {
  9192. super(), this.Yn = t, this.trackRemovals = e,
  9193. // A map of document sizes and read times prior to applying the changes in
  9194. // this buffer.
  9195. this.Xn = new ds((t => t.toString()), ((t, e) => t.isEqual(e)));
  9196. }
  9197. applyChanges(t) {
  9198. const e = [];
  9199. let n = 0, s = new He(((t, e) => tt(t.canonicalString(), e.canonicalString())));
  9200. return this.changes.forEach(((i, r) => {
  9201. const o = this.Xn.get(i);
  9202. if (e.push(this.Yn.removeEntry(t, i, o.readTime)), r.isValidDocument()) {
  9203. const u = Zi(this.Yn.yt, r);
  9204. s = s.add(i.path.popLast());
  9205. const c = Wr(u);
  9206. n += c - o.size, e.push(this.Yn.addEntry(t, i, u));
  9207. } else if (n -= o.size, this.trackRemovals) {
  9208. // In order to track removals, we store a "sentinel delete" in the
  9209. // RemoteDocumentCache. This entry is represented by a NoDocument
  9210. // with a version of 0 and ignored by `maybeDecodeDocument()` but
  9211. // preserved in `getNewDocumentChanges()`.
  9212. const n = Zi(this.Yn.yt, r.convertToNoDocument(it.min()));
  9213. e.push(this.Yn.addEntry(t, i, n));
  9214. }
  9215. })), s.forEach((n => {
  9216. e.push(this.Yn.indexManager.addToCollectionParentIndex(t, n));
  9217. })), e.push(this.Yn.updateMetadata(t, n)), Rt.waitFor(e);
  9218. }
  9219. getFromCache(t, e) {
  9220. // Record the size of everything we load from the cache so we can compute a delta later.
  9221. return this.Yn.Wn(t, e).next((t => (this.Xn.set(e, {
  9222. size: t.size,
  9223. readTime: t.document.readTime
  9224. }), t.document)));
  9225. }
  9226. getAllFromCache(t, e) {
  9227. // Record the size of everything we load from the cache so we can compute
  9228. // a delta later.
  9229. return this.Yn.Hn(t, e).next((({documents: t, Jn: e}) => (
  9230. // Note: `getAllFromCache` returns two maps instead of a single map from
  9231. // keys to `DocumentSizeEntry`s. This is to allow returning the
  9232. // `MutableDocumentMap` directly, without a conversion.
  9233. e.forEach(((e, n) => {
  9234. this.Xn.set(e, {
  9235. size: n,
  9236. readTime: t.get(e).readTime
  9237. });
  9238. })), t)));
  9239. }
  9240. }
  9241. function wo(t) {
  9242. return ji(t, "remoteDocumentGlobal");
  9243. }
  9244. /**
  9245. * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
  9246. */ function mo(t) {
  9247. return ji(t, "remoteDocumentsV14");
  9248. }
  9249. /**
  9250. * Returns a key that can be used for document lookups on the
  9251. * `DbRemoteDocumentDocumentKeyIndex` index.
  9252. */ function go(t) {
  9253. const e = t.path.toArray();
  9254. return [
  9255. /* prefix path */ e.slice(0, e.length - 2),
  9256. /* collection id */ e[e.length - 2],
  9257. /* document id */ e[e.length - 1] ];
  9258. }
  9259. function yo(t, e) {
  9260. const n = e.documentKey.path.toArray();
  9261. return [
  9262. /* collection id */ t, tr(e.readTime),
  9263. /* prefix path */ n.slice(0, n.length - 2),
  9264. /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
  9265. }
  9266. /**
  9267. * Comparator that compares document keys according to the primary key sorting
  9268. * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
  9269. * and then document ID).
  9270. *
  9271. * Visible for testing.
  9272. */ function po(t, e) {
  9273. const n = t.path.toArray(), s = e.path.toArray();
  9274. // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
  9275. let i = 0;
  9276. for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = tt(n[t], s[t]),
  9277. i) return i;
  9278. return i = tt(n.length, s.length), i || (i = tt(n[n.length - 2], s[s.length - 2]),
  9279. i || tt(n[n.length - 1], s[s.length - 1]));
  9280. }
  9281. /**
  9282. * @license
  9283. * Copyright 2017 Google LLC
  9284. *
  9285. * Licensed under the Apache License, Version 2.0 (the "License");
  9286. * you may not use this file except in compliance with the License.
  9287. * You may obtain a copy of the License at
  9288. *
  9289. * http://www.apache.org/licenses/LICENSE-2.0
  9290. *
  9291. * Unless required by applicable law or agreed to in writing, software
  9292. * distributed under the License is distributed on an "AS IS" BASIS,
  9293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9294. * See the License for the specific language governing permissions and
  9295. * limitations under the License.
  9296. */
  9297. /**
  9298. * Schema Version for the Web client:
  9299. * 1. Initial version including Mutation Queue, Query Cache, and Remote
  9300. * Document Cache
  9301. * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
  9302. * longer required because migration 3 unconditionally clears it.
  9303. * 3. Dropped and re-created Query Cache to deal with cache corruption related
  9304. * to limbo resolution. Addresses
  9305. * https://github.com/firebase/firebase-ios-sdk/issues/1548
  9306. * 4. Multi-Tab Support.
  9307. * 5. Removal of held write acks.
  9308. * 6. Create document global for tracking document cache size.
  9309. * 7. Ensure every cached document has a sentinel row with a sequence number.
  9310. * 8. Add collection-parent index for Collection Group queries.
  9311. * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
  9312. * an auto-incrementing ID. This is required for Index-Free queries.
  9313. * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
  9314. * 11. Add bundles and named_queries for bundle support.
  9315. * 12. Add document overlays.
  9316. * 13. Rewrite the keys of the remote document cache to allow for efficient
  9317. * document lookup via `getAll()`.
  9318. * 14. Add overlays.
  9319. * 15. Add indexing support.
  9320. */
  9321. /**
  9322. * @license
  9323. * Copyright 2022 Google LLC
  9324. *
  9325. * Licensed under the Apache License, Version 2.0 (the "License");
  9326. * you may not use this file except in compliance with the License.
  9327. * You may obtain a copy of the License at
  9328. *
  9329. * http://www.apache.org/licenses/LICENSE-2.0
  9330. *
  9331. * Unless required by applicable law or agreed to in writing, software
  9332. * distributed under the License is distributed on an "AS IS" BASIS,
  9333. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9334. * See the License for the specific language governing permissions and
  9335. * limitations under the License.
  9336. */
  9337. /**
  9338. * Represents a local view (overlay) of a document, and the fields that are
  9339. * locally mutated.
  9340. */
  9341. class Io {
  9342. constructor(t,
  9343. /**
  9344. * The fields that are locally mutated by patch mutations.
  9345. *
  9346. * If the overlayed document is from set or delete mutations, this is `null`.
  9347. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  9348. */
  9349. e) {
  9350. this.overlayedDocument = t, this.mutatedFields = e;
  9351. }
  9352. }
  9353. /**
  9354. * @license
  9355. * Copyright 2017 Google LLC
  9356. *
  9357. * Licensed under the Apache License, Version 2.0 (the "License");
  9358. * you may not use this file except in compliance with the License.
  9359. * You may obtain a copy of the License at
  9360. *
  9361. * http://www.apache.org/licenses/LICENSE-2.0
  9362. *
  9363. * Unless required by applicable law or agreed to in writing, software
  9364. * distributed under the License is distributed on an "AS IS" BASIS,
  9365. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9366. * See the License for the specific language governing permissions and
  9367. * limitations under the License.
  9368. */
  9369. /**
  9370. * A readonly view of the local state of all documents we're tracking (i.e. we
  9371. * have a cached version in remoteDocumentCache or local mutations for the
  9372. * document). The view is computed by applying the mutations in the
  9373. * MutationQueue to the RemoteDocumentCache.
  9374. */ class To {
  9375. constructor(t, e, n, s) {
  9376. this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n,
  9377. this.indexManager = s;
  9378. }
  9379. /**
  9380. * Get the local view of the document identified by `key`.
  9381. *
  9382. * @returns Local view of the document or null if we don't have any cached
  9383. * state for it.
  9384. */ getDocument(t, e) {
  9385. let n = null;
  9386. return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && Xn(n.mutation, t, Xe.empty(), st.now()),
  9387. t)));
  9388. }
  9389. /**
  9390. * Gets the local view of the documents identified by `keys`.
  9391. *
  9392. * If we don't have cached state for a document in `keys`, a NoDocument will
  9393. * be stored for that key in the resulting set.
  9394. */ getDocuments(t, e) {
  9395. return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, Rs()).next((() => e))));
  9396. }
  9397. /**
  9398. * Similar to `getDocuments`, but creates the local view from the given
  9399. * `baseDocs` without retrieving documents from the local store.
  9400. *
  9401. * @param transaction - The transaction this operation is scoped to.
  9402. * @param docs - The documents to apply local mutations to get the local views.
  9403. * @param existenceStateChanged - The set of document keys whose existence state
  9404. * is changed. This is useful to determine if some documents overlay needs
  9405. * to be recalculated.
  9406. */ getLocalViewOfDocuments(t, e, n = Rs()) {
  9407. const s = ps();
  9408. return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {
  9409. let e = gs();
  9410. return t.forEach(((t, n) => {
  9411. e = e.insert(t, n.overlayedDocument);
  9412. })), e;
  9413. }))));
  9414. }
  9415. /**
  9416. * Gets the overlayed documents for the given document map, which will include
  9417. * the local view of those documents and a `FieldMask` indicating which fields
  9418. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  9419. */ getOverlayedDocuments(t, e) {
  9420. const n = ps();
  9421. return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, Rs())));
  9422. }
  9423. /**
  9424. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  9425. * if the map does not already contain an entry for the given document key.
  9426. */ populateOverlays(t, e, n) {
  9427. const s = [];
  9428. return n.forEach((t => {
  9429. e.has(t) || s.push(t);
  9430. })), this.documentOverlayCache.getOverlays(t, s).next((t => {
  9431. t.forEach(((t, n) => {
  9432. e.set(t, n);
  9433. }));
  9434. }));
  9435. }
  9436. /**
  9437. * Computes the local view for the given documents.
  9438. *
  9439. * @param docs - The documents to compute views for. It also has the base
  9440. * version of the documents.
  9441. * @param overlays - The overlays that need to be applied to the given base
  9442. * version of the documents.
  9443. * @param existenceStateChanged - A set of documents whose existence states
  9444. * might have changed. This is used to determine if we need to re-calculate
  9445. * overlays from mutation queues.
  9446. * @return A map represents the local documents view.
  9447. */ computeViews(t, e, n, s) {
  9448. let i = ws();
  9449. const r = Ts(), o = Ts();
  9450. return e.forEach(((t, e) => {
  9451. const o = n.get(e.key);
  9452. // Recalculate an overlay if the document's existence state changed due to
  9453. // a remote event *and* the overlay is a PatchMutation. This is because
  9454. // document existence state can change if some patch mutation's
  9455. // preconditions are met.
  9456. // NOTE: we recalculate when `overlay` is undefined as well, because there
  9457. // might be a patch mutation whose precondition does not match before the
  9458. // change (hence overlay is undefined), but would now match.
  9459. s.has(e.key) && (void 0 === o || o.mutation instanceof ns) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()),
  9460. Xn(o.mutation, e, o.mutation.getFieldMask(), st.now())) :
  9461. // no overlay exists
  9462. // Using EMPTY to indicate there is no overlay for the document.
  9463. r.set(e.key, Xe.empty());
  9464. })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))),
  9465. e.forEach(((t, e) => {
  9466. var n;
  9467. return o.set(t, new Io(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));
  9468. })), o)));
  9469. }
  9470. recalculateAndSaveOverlays(t, e) {
  9471. const n = Ts();
  9472. // A reverse lookup map from batch id to the documents within that batch.
  9473. let s = new je(((t, e) => t - e)), i = Rs();
  9474. return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {
  9475. for (const i of t) i.keys().forEach((t => {
  9476. const r = e.get(t);
  9477. if (null === r) return;
  9478. let o = n.get(t) || Xe.empty();
  9479. o = i.applyToLocalView(r, o), n.set(t, o);
  9480. const u = (s.get(i.batchId) || Rs()).add(t);
  9481. s = s.insert(i.batchId, u);
  9482. }));
  9483. })).next((() => {
  9484. const r = [], o = s.getReverseIterator();
  9485. // Iterate in descending order of batch IDs, and skip documents that are
  9486. // already saved.
  9487. for (;o.hasNext(); ) {
  9488. const s = o.getNext(), u = s.key, c = s.value, a = Is();
  9489. c.forEach((t => {
  9490. if (!i.has(t)) {
  9491. const s = Jn(e.get(t), n.get(t));
  9492. null !== s && a.set(t, s), i = i.add(t);
  9493. }
  9494. })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));
  9495. }
  9496. return Rt.waitFor(r);
  9497. })).next((() => n));
  9498. }
  9499. /**
  9500. * Recalculates overlays by reading the documents from remote document cache
  9501. * first, and saves them after they are calculated.
  9502. */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {
  9503. return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));
  9504. }
  9505. /**
  9506. * Performs a query against the local view of all documents.
  9507. *
  9508. * @param transaction - The persistence transaction.
  9509. * @param query - The query to match documents against.
  9510. * @param offset - Read time and key to start scanning by (exclusive).
  9511. */ getDocumentsMatchingQuery(t, e, n) {
  9512. /**
  9513. * Returns whether the query matches a single document by path (rather than a
  9514. * collection).
  9515. */
  9516. return function(t) {
  9517. return at.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  9518. }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : gn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);
  9519. }
  9520. /**
  9521. * Given a collection group, returns the next documents that follow the provided offset, along
  9522. * with an updated batch ID.
  9523. *
  9524. * <p>The documents returned by this method are ordered by remote version from the provided
  9525. * offset. If there are no more remote documents after the provided offset, documents with
  9526. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  9527. * returned together, the total number of documents returned can exceed {@code count}.
  9528. *
  9529. * @param transaction
  9530. * @param collectionGroup The collection group for the documents.
  9531. * @param offset The offset to index into.
  9532. * @param count The number of documents to return
  9533. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  9534. */ getNextDocuments(t, e, n, s) {
  9535. return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {
  9536. const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : Rt.resolve(ps());
  9537. // The callsite will use the largest batch ID together with the latest read time to create
  9538. // a new index offset. Since we only process batch IDs if all remote documents have been read,
  9539. // no overlay will increase the overall read time. This is why we only need to special case
  9540. // the batch id.
  9541. let o = -1, u = i;
  9542. return r.next((e => Rt.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId),
  9543. i.get(e) ? Rt.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {
  9544. u = u.insert(e, t);
  9545. }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, Rs()))).next((t => ({
  9546. batchId: o,
  9547. changes: ys(t)
  9548. })))));
  9549. }));
  9550. }
  9551. getDocumentsMatchingDocumentQuery(t, e) {
  9552. // Just do a simple document lookup.
  9553. return this.getDocument(t, new at(e)).next((t => {
  9554. let e = gs();
  9555. return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
  9556. }));
  9557. }
  9558. getDocumentsMatchingCollectionGroupQuery(t, e, n) {
  9559. const s = e.collectionGroup;
  9560. let i = gs();
  9561. return this.indexManager.getCollectionParents(t, s).next((r => Rt.forEach(r, (r => {
  9562. const o = function(t, e) {
  9563. return new ln(e,
  9564. /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  9565. }(e, r.child(s));
  9566. return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {
  9567. t.forEach(((t, e) => {
  9568. i = i.insert(t, e);
  9569. }));
  9570. }));
  9571. })).next((() => i))));
  9572. }
  9573. getDocumentsMatchingCollectionQuery(t, e, n) {
  9574. // Query the remote documents and overlay mutations.
  9575. let s;
  9576. return this.remoteDocumentCache.getAllFromCollection(t, e.path, n).next((i => (s = i,
  9577. this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId)))).next((t => {
  9578. // As documents might match the query because of their overlay we need to
  9579. // include documents for all overlays in the initial document set.
  9580. t.forEach(((t, e) => {
  9581. const n = e.getKey();
  9582. null === s.get(n) && (s = s.insert(n, en.newInvalidDocument(n)));
  9583. }));
  9584. // Apply the overlays and match against the query.
  9585. let n = gs();
  9586. return s.forEach(((s, i) => {
  9587. const r = t.get(s);
  9588. void 0 !== r && Xn(r.mutation, i, Xe.empty(), st.now()),
  9589. // Finally, insert the documents that still match the query
  9590. bn(e, i) && (n = n.insert(s, i));
  9591. })), n;
  9592. }));
  9593. }
  9594. }
  9595. /**
  9596. * @license
  9597. * Copyright 2020 Google LLC
  9598. *
  9599. * Licensed under the Apache License, Version 2.0 (the "License");
  9600. * you may not use this file except in compliance with the License.
  9601. * You may obtain a copy of the License at
  9602. *
  9603. * http://www.apache.org/licenses/LICENSE-2.0
  9604. *
  9605. * Unless required by applicable law or agreed to in writing, software
  9606. * distributed under the License is distributed on an "AS IS" BASIS,
  9607. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9608. * See the License for the specific language governing permissions and
  9609. * limitations under the License.
  9610. */ class Eo {
  9611. constructor(t) {
  9612. this.yt = t, this.Zn = new Map, this.ts = new Map;
  9613. }
  9614. getBundleMetadata(t, e) {
  9615. return Rt.resolve(this.Zn.get(e));
  9616. }
  9617. saveBundleMetadata(t, e) {
  9618. /** Decodes a BundleMetadata proto into a BundleMetadata object. */
  9619. var n;
  9620. return this.Zn.set(e.id, {
  9621. id: (n = e).id,
  9622. version: n.version,
  9623. createTime: Ks(n.createTime)
  9624. }), Rt.resolve();
  9625. }
  9626. getNamedQuery(t, e) {
  9627. return Rt.resolve(this.ts.get(e));
  9628. }
  9629. saveNamedQuery(t, e) {
  9630. return this.ts.set(e.name, function(t) {
  9631. return {
  9632. name: t.name,
  9633. query: or(t.bundledQuery),
  9634. readTime: Ks(t.readTime)
  9635. };
  9636. }(e)), Rt.resolve();
  9637. }
  9638. }
  9639. /**
  9640. * @license
  9641. * Copyright 2022 Google LLC
  9642. *
  9643. * Licensed under the Apache License, Version 2.0 (the "License");
  9644. * you may not use this file except in compliance with the License.
  9645. * You may obtain a copy of the License at
  9646. *
  9647. * http://www.apache.org/licenses/LICENSE-2.0
  9648. *
  9649. * Unless required by applicable law or agreed to in writing, software
  9650. * distributed under the License is distributed on an "AS IS" BASIS,
  9651. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9652. * See the License for the specific language governing permissions and
  9653. * limitations under the License.
  9654. */
  9655. /**
  9656. * An in-memory implementation of DocumentOverlayCache.
  9657. */ class Ao {
  9658. constructor() {
  9659. // A map sorted by DocumentKey, whose value is a pair of the largest batch id
  9660. // for the overlay and the overlay itself.
  9661. this.overlays = new je(at.comparator), this.es = new Map;
  9662. }
  9663. getOverlay(t, e) {
  9664. return Rt.resolve(this.overlays.get(e));
  9665. }
  9666. getOverlays(t, e) {
  9667. const n = ps();
  9668. return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  9669. null !== t && n.set(e, t);
  9670. })))).next((() => n));
  9671. }
  9672. saveOverlays(t, e, n) {
  9673. return n.forEach(((n, s) => {
  9674. this.oe(t, e, s);
  9675. })), Rt.resolve();
  9676. }
  9677. removeOverlaysForBatchId(t, e, n) {
  9678. const s = this.es.get(n);
  9679. return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))),
  9680. this.es.delete(n)), Rt.resolve();
  9681. }
  9682. getOverlaysForCollection(t, e, n) {
  9683. const s = ps(), i = e.length + 1, r = new at(e.child("")), o = this.overlays.getIteratorFrom(r);
  9684. for (;o.hasNext(); ) {
  9685. const t = o.getNext().value, r = t.getKey();
  9686. if (!e.isPrefixOf(r.path)) break;
  9687. // Documents from sub-collections
  9688. r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));
  9689. }
  9690. return Rt.resolve(s);
  9691. }
  9692. getOverlaysForCollectionGroup(t, e, n, s) {
  9693. let i = new je(((t, e) => t - e));
  9694. const r = this.overlays.getIterator();
  9695. for (;r.hasNext(); ) {
  9696. const t = r.getNext().value;
  9697. if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {
  9698. let e = i.get(t.largestBatchId);
  9699. null === e && (e = ps(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);
  9700. }
  9701. }
  9702. const o = ps(), u = i.getIterator();
  9703. for (;u.hasNext(); ) {
  9704. if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;
  9705. }
  9706. return Rt.resolve(o);
  9707. }
  9708. oe(t, e, n) {
  9709. // Remove the association of the overlay to its batch id.
  9710. const s = this.overlays.get(n.key);
  9711. if (null !== s) {
  9712. const t = this.es.get(s.largestBatchId).delete(n.key);
  9713. this.es.set(s.largestBatchId, t);
  9714. }
  9715. this.overlays = this.overlays.insert(n.key, new Hi(e, n));
  9716. // Create the association of this overlay to the given largestBatchId.
  9717. let i = this.es.get(e);
  9718. void 0 === i && (i = Rs(), this.es.set(e, i)), this.es.set(e, i.add(n.key));
  9719. }
  9720. }
  9721. /**
  9722. * @license
  9723. * Copyright 2017 Google LLC
  9724. *
  9725. * Licensed under the Apache License, Version 2.0 (the "License");
  9726. * you may not use this file except in compliance with the License.
  9727. * You may obtain a copy of the License at
  9728. *
  9729. * http://www.apache.org/licenses/LICENSE-2.0
  9730. *
  9731. * Unless required by applicable law or agreed to in writing, software
  9732. * distributed under the License is distributed on an "AS IS" BASIS,
  9733. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9734. * See the License for the specific language governing permissions and
  9735. * limitations under the License.
  9736. */
  9737. /**
  9738. * A collection of references to a document from some kind of numbered entity
  9739. * (either a target ID or batch ID). As references are added to or removed from
  9740. * the set corresponding events are emitted to a registered garbage collector.
  9741. *
  9742. * Each reference is represented by a DocumentReference object. Each of them
  9743. * contains enough information to uniquely identify the reference. They are all
  9744. * stored primarily in a set sorted by key. A document is considered garbage if
  9745. * there's no references in that set (this can be efficiently checked thanks to
  9746. * sorting by key).
  9747. *
  9748. * ReferenceSet also keeps a secondary set that contains references sorted by
  9749. * IDs. This one is used to efficiently implement removal of all references by
  9750. * some target ID.
  9751. */ class Ro {
  9752. constructor() {
  9753. // A set of outstanding references to a document sorted by key.
  9754. this.ns = new He(bo.ss),
  9755. // A set of outstanding references to a document sorted by target id.
  9756. this.rs = new He(bo.os);
  9757. }
  9758. /** Returns true if the reference set contains no references. */ isEmpty() {
  9759. return this.ns.isEmpty();
  9760. }
  9761. /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {
  9762. const n = new bo(t, e);
  9763. this.ns = this.ns.add(n), this.rs = this.rs.add(n);
  9764. }
  9765. /** Add references to the given document keys for the given ID. */ us(t, e) {
  9766. t.forEach((t => this.addReference(t, e)));
  9767. }
  9768. /**
  9769. * Removes a reference to the given document key for the given
  9770. * ID.
  9771. */ removeReference(t, e) {
  9772. this.cs(new bo(t, e));
  9773. }
  9774. hs(t, e) {
  9775. t.forEach((t => this.removeReference(t, e)));
  9776. }
  9777. /**
  9778. * Clears all references with a given ID. Calls removeRef() for each key
  9779. * removed.
  9780. */ ls(t) {
  9781. const e = new at(new ot([])), n = new bo(e, t), s = new bo(e, t + 1), i = [];
  9782. return this.rs.forEachInRange([ n, s ], (t => {
  9783. this.cs(t), i.push(t.key);
  9784. })), i;
  9785. }
  9786. fs() {
  9787. this.ns.forEach((t => this.cs(t)));
  9788. }
  9789. cs(t) {
  9790. this.ns = this.ns.delete(t), this.rs = this.rs.delete(t);
  9791. }
  9792. ds(t) {
  9793. const e = new at(new ot([])), n = new bo(e, t), s = new bo(e, t + 1);
  9794. let i = Rs();
  9795. return this.rs.forEachInRange([ n, s ], (t => {
  9796. i = i.add(t.key);
  9797. })), i;
  9798. }
  9799. containsKey(t) {
  9800. const e = new bo(t, 0), n = this.ns.firstAfterOrEqual(e);
  9801. return null !== n && t.isEqual(n.key);
  9802. }
  9803. }
  9804. class bo {
  9805. constructor(t, e) {
  9806. this.key = t, this._s = e;
  9807. }
  9808. /** Compare by key then by ID */ static ss(t, e) {
  9809. return at.comparator(t.key, e.key) || tt(t._s, e._s);
  9810. }
  9811. /** Compare by ID then by key */ static os(t, e) {
  9812. return tt(t._s, e._s) || at.comparator(t.key, e.key);
  9813. }
  9814. }
  9815. /**
  9816. * @license
  9817. * Copyright 2017 Google LLC
  9818. *
  9819. * Licensed under the Apache License, Version 2.0 (the "License");
  9820. * you may not use this file except in compliance with the License.
  9821. * You may obtain a copy of the License at
  9822. *
  9823. * http://www.apache.org/licenses/LICENSE-2.0
  9824. *
  9825. * Unless required by applicable law or agreed to in writing, software
  9826. * distributed under the License is distributed on an "AS IS" BASIS,
  9827. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9828. * See the License for the specific language governing permissions and
  9829. * limitations under the License.
  9830. */ class Po {
  9831. constructor(t, e) {
  9832. this.indexManager = t, this.referenceDelegate = e,
  9833. /**
  9834. * The set of all mutations that have been sent but not yet been applied to
  9835. * the backend.
  9836. */
  9837. this.mutationQueue = [],
  9838. /** Next value to use when assigning sequential IDs to each mutation batch. */
  9839. this.ws = 1,
  9840. /** An ordered mapping between documents and the mutations batch IDs. */
  9841. this.gs = new He(bo.ss);
  9842. }
  9843. checkEmpty(t) {
  9844. return Rt.resolve(0 === this.mutationQueue.length);
  9845. }
  9846. addMutationBatch(t, e, n, s) {
  9847. const i = this.ws;
  9848. this.ws++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
  9849. const r = new Wi(i, e, n, s);
  9850. this.mutationQueue.push(r);
  9851. // Track references by document key and index collection parents.
  9852. for (const e of s) this.gs = this.gs.add(new bo(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());
  9853. return Rt.resolve(r);
  9854. }
  9855. lookupMutationBatch(t, e) {
  9856. return Rt.resolve(this.ys(e));
  9857. }
  9858. getNextMutationBatchAfterBatchId(t, e) {
  9859. const n = e + 1, s = this.ps(n), i = s < 0 ? 0 : s;
  9860. // The requested batchId may still be out of range so normalize it to the
  9861. // start of the queue.
  9862. return Rt.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
  9863. }
  9864. getHighestUnacknowledgedBatchId() {
  9865. return Rt.resolve(0 === this.mutationQueue.length ? -1 : this.ws - 1);
  9866. }
  9867. getAllMutationBatches(t) {
  9868. return Rt.resolve(this.mutationQueue.slice());
  9869. }
  9870. getAllMutationBatchesAffectingDocumentKey(t, e) {
  9871. const n = new bo(e, 0), s = new bo(e, Number.POSITIVE_INFINITY), i = [];
  9872. return this.gs.forEachInRange([ n, s ], (t => {
  9873. const e = this.ys(t._s);
  9874. i.push(e);
  9875. })), Rt.resolve(i);
  9876. }
  9877. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  9878. let n = new He(tt);
  9879. return e.forEach((t => {
  9880. const e = new bo(t, 0), s = new bo(t, Number.POSITIVE_INFINITY);
  9881. this.gs.forEachInRange([ e, s ], (t => {
  9882. n = n.add(t._s);
  9883. }));
  9884. })), Rt.resolve(this.Is(n));
  9885. }
  9886. getAllMutationBatchesAffectingQuery(t, e) {
  9887. // Use the query path as a prefix for testing if a document matches the
  9888. // query.
  9889. const n = e.path, s = n.length + 1;
  9890. // Construct a document reference for actually scanning the index. Unlike
  9891. // the prefix the document key in this reference must have an even number of
  9892. // segments. The empty segment can be used a suffix of the query path
  9893. // because it precedes all other segments in an ordered traversal.
  9894. let i = n;
  9895. at.isDocumentKey(i) || (i = i.child(""));
  9896. const r = new bo(new at(i), 0);
  9897. // Find unique batchIDs referenced by all documents potentially matching the
  9898. // query.
  9899. let o = new He(tt);
  9900. return this.gs.forEachWhile((t => {
  9901. const e = t.key.path;
  9902. return !!n.isPrefixOf(e) && (
  9903. // Rows with document keys more than one segment longer than the query
  9904. // path can't be matches. For example, a query on 'rooms' can't match
  9905. // the document /rooms/abc/messages/xyx.
  9906. // TODO(mcg): we'll need a different scanner when we implement
  9907. // ancestor queries.
  9908. e.length === s && (o = o.add(t._s)), !0);
  9909. }), r), Rt.resolve(this.Is(o));
  9910. }
  9911. Is(t) {
  9912. // Construct an array of matching batches, sorted by batchID to ensure that
  9913. // multiple mutations affecting the same document key are applied in order.
  9914. const e = [];
  9915. return t.forEach((t => {
  9916. const n = this.ys(t);
  9917. null !== n && e.push(n);
  9918. })), e;
  9919. }
  9920. removeMutationBatch(t, e) {
  9921. F(0 === this.Ts(e.batchId, "removed")), this.mutationQueue.shift();
  9922. let n = this.gs;
  9923. return Rt.forEach(e.mutations, (s => {
  9924. const i = new bo(s.key, e.batchId);
  9925. return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);
  9926. })).next((() => {
  9927. this.gs = n;
  9928. }));
  9929. }
  9930. An(t) {
  9931. // No-op since the memory mutation queue does not maintain a separate cache.
  9932. }
  9933. containsKey(t, e) {
  9934. const n = new bo(e, 0), s = this.gs.firstAfterOrEqual(n);
  9935. return Rt.resolve(e.isEqual(s && s.key));
  9936. }
  9937. performConsistencyCheck(t) {
  9938. return this.mutationQueue.length, Rt.resolve();
  9939. }
  9940. /**
  9941. * Finds the index of the given batchId in the mutation queue and asserts that
  9942. * the resulting index is within the bounds of the queue.
  9943. *
  9944. * @param batchId - The batchId to search for
  9945. * @param action - A description of what the caller is doing, phrased in passive
  9946. * form (e.g. "acknowledged" in a routine that acknowledges batches).
  9947. */ Ts(t, e) {
  9948. return this.ps(t);
  9949. }
  9950. /**
  9951. * Finds the index of the given batchId in the mutation queue. This operation
  9952. * is O(1).
  9953. *
  9954. * @returns The computed index of the batch with the given batchId, based on
  9955. * the state of the queue. Note this index can be negative if the requested
  9956. * batchId has already been remvoed from the queue or past the end of the
  9957. * queue if the batchId is larger than the last added batch.
  9958. */ ps(t) {
  9959. if (0 === this.mutationQueue.length)
  9960. // As an index this is past the end of the queue
  9961. return 0;
  9962. // Examine the front of the queue to figure out the difference between the
  9963. // batchId and indexes in the array. Note that since the queue is ordered
  9964. // by batchId, if the first batch has a larger batchId then the requested
  9965. // batchId doesn't exist in the queue.
  9966. return t - this.mutationQueue[0].batchId;
  9967. }
  9968. /**
  9969. * A version of lookupMutationBatch that doesn't return a promise, this makes
  9970. * other functions that uses this code easier to read and more efficent.
  9971. */ ys(t) {
  9972. const e = this.ps(t);
  9973. if (e < 0 || e >= this.mutationQueue.length) return null;
  9974. return this.mutationQueue[e];
  9975. }
  9976. }
  9977. /**
  9978. * @license
  9979. * Copyright 2017 Google LLC
  9980. *
  9981. * Licensed under the Apache License, Version 2.0 (the "License");
  9982. * you may not use this file except in compliance with the License.
  9983. * You may obtain a copy of the License at
  9984. *
  9985. * http://www.apache.org/licenses/LICENSE-2.0
  9986. *
  9987. * Unless required by applicable law or agreed to in writing, software
  9988. * distributed under the License is distributed on an "AS IS" BASIS,
  9989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9990. * See the License for the specific language governing permissions and
  9991. * limitations under the License.
  9992. */
  9993. /**
  9994. * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
  9995. * `newMemoryRemoteDocumentCache()`.
  9996. */
  9997. class vo {
  9998. /**
  9999. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10000. * expected to just return 0 to avoid unnecessarily doing the work of
  10001. * calculating the size.
  10002. */
  10003. constructor(t) {
  10004. this.Es = t,
  10005. /** Underlying cache of documents and their read times. */
  10006. this.docs = new je(at.comparator),
  10007. /** Size of all cached documents. */
  10008. this.size = 0;
  10009. }
  10010. setIndexManager(t) {
  10011. this.indexManager = t;
  10012. }
  10013. /**
  10014. * Adds the supplied entry to the cache and updates the cache size as appropriate.
  10015. *
  10016. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  10017. * returned by `newChangeBuffer()`.
  10018. */ addEntry(t, e) {
  10019. const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Es(e);
  10020. return this.docs = this.docs.insert(n, {
  10021. document: e.mutableCopy(),
  10022. size: r
  10023. }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());
  10024. }
  10025. /**
  10026. * Removes the specified entry from the cache and updates the cache size as appropriate.
  10027. *
  10028. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  10029. * returned by `newChangeBuffer()`.
  10030. */ removeEntry(t) {
  10031. const e = this.docs.get(t);
  10032. e && (this.docs = this.docs.remove(t), this.size -= e.size);
  10033. }
  10034. getEntry(t, e) {
  10035. const n = this.docs.get(e);
  10036. return Rt.resolve(n ? n.document.mutableCopy() : en.newInvalidDocument(e));
  10037. }
  10038. getEntries(t, e) {
  10039. let n = ws();
  10040. return e.forEach((t => {
  10041. const e = this.docs.get(t);
  10042. n = n.insert(t, e ? e.document.mutableCopy() : en.newInvalidDocument(t));
  10043. })), Rt.resolve(n);
  10044. }
  10045. getAllFromCollection(t, e, n) {
  10046. let s = ws();
  10047. // Documents are ordered by key, so we can use a prefix scan to narrow down
  10048. // the documents we need to match the query against.
  10049. const i = new at(e.child("")), r = this.docs.getIteratorFrom(i);
  10050. for (;r.hasNext(); ) {
  10051. const {key: t, value: {document: i}} = r.getNext();
  10052. if (!e.isPrefixOf(t.path)) break;
  10053. t.path.length > e.length + 1 || (It(yt(i), n) <= 0 || (s = s.insert(i.key, i.mutableCopy())));
  10054. }
  10055. return Rt.resolve(s);
  10056. }
  10057. getAllFromCollectionGroup(t, e, n, s) {
  10058. // This method should only be called from the IndexBackfiller if persistence
  10059. // is enabled.
  10060. M();
  10061. }
  10062. As(t, e) {
  10063. return Rt.forEach(this.docs, (t => e(t)));
  10064. }
  10065. newChangeBuffer(t) {
  10066. // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
  10067. // a separate changelog and does not need special handling for removals.
  10068. return new Vo(this);
  10069. }
  10070. getSize(t) {
  10071. return Rt.resolve(this.size);
  10072. }
  10073. }
  10074. /**
  10075. * Creates a new memory-only RemoteDocumentCache.
  10076. *
  10077. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10078. * expected to just return 0 to avoid unnecessarily doing the work of
  10079. * calculating the size.
  10080. */
  10081. /**
  10082. * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
  10083. */
  10084. class Vo extends ho {
  10085. constructor(t) {
  10086. super(), this.Yn = t;
  10087. }
  10088. applyChanges(t) {
  10089. const e = [];
  10090. return this.changes.forEach(((n, s) => {
  10091. s.isValidDocument() ? e.push(this.Yn.addEntry(t, s)) : this.Yn.removeEntry(n);
  10092. })), Rt.waitFor(e);
  10093. }
  10094. getFromCache(t, e) {
  10095. return this.Yn.getEntry(t, e);
  10096. }
  10097. getAllFromCache(t, e) {
  10098. return this.Yn.getEntries(t, e);
  10099. }
  10100. }
  10101. /**
  10102. * @license
  10103. * Copyright 2017 Google LLC
  10104. *
  10105. * Licensed under the Apache License, Version 2.0 (the "License");
  10106. * you may not use this file except in compliance with the License.
  10107. * You may obtain a copy of the License at
  10108. *
  10109. * http://www.apache.org/licenses/LICENSE-2.0
  10110. *
  10111. * Unless required by applicable law or agreed to in writing, software
  10112. * distributed under the License is distributed on an "AS IS" BASIS,
  10113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10114. * See the License for the specific language governing permissions and
  10115. * limitations under the License.
  10116. */ class So {
  10117. constructor(t) {
  10118. this.persistence = t,
  10119. /**
  10120. * Maps a target to the data about that target
  10121. */
  10122. this.Rs = new ds((t => rn(t)), on),
  10123. /** The last received snapshot version. */
  10124. this.lastRemoteSnapshotVersion = it.min(),
  10125. /** The highest numbered target ID encountered. */
  10126. this.highestTargetId = 0,
  10127. /** The highest sequence number encountered. */
  10128. this.bs = 0,
  10129. /**
  10130. * A ordered bidirectional mapping between documents and the remote target
  10131. * IDs.
  10132. */
  10133. this.Ps = new Ro, this.targetCount = 0, this.vs = Zr.Pn();
  10134. }
  10135. forEachTarget(t, e) {
  10136. return this.Rs.forEach(((t, n) => e(n))), Rt.resolve();
  10137. }
  10138. getLastRemoteSnapshotVersion(t) {
  10139. return Rt.resolve(this.lastRemoteSnapshotVersion);
  10140. }
  10141. getHighestSequenceNumber(t) {
  10142. return Rt.resolve(this.bs);
  10143. }
  10144. allocateTargetId(t) {
  10145. return this.highestTargetId = this.vs.next(), Rt.resolve(this.highestTargetId);
  10146. }
  10147. setTargetsMetadata(t, e, n) {
  10148. return n && (this.lastRemoteSnapshotVersion = n), e > this.bs && (this.bs = e),
  10149. Rt.resolve();
  10150. }
  10151. Dn(t) {
  10152. this.Rs.set(t.target, t);
  10153. const e = t.targetId;
  10154. e > this.highestTargetId && (this.vs = new Zr(e), this.highestTargetId = e), t.sequenceNumber > this.bs && (this.bs = t.sequenceNumber);
  10155. }
  10156. addTargetData(t, e) {
  10157. return this.Dn(e), this.targetCount += 1, Rt.resolve();
  10158. }
  10159. updateTargetData(t, e) {
  10160. return this.Dn(e), Rt.resolve();
  10161. }
  10162. removeTargetData(t, e) {
  10163. return this.Rs.delete(e.target), this.Ps.ls(e.targetId), this.targetCount -= 1,
  10164. Rt.resolve();
  10165. }
  10166. removeTargets(t, e, n) {
  10167. let s = 0;
  10168. const i = [];
  10169. return this.Rs.forEach(((r, o) => {
  10170. o.sequenceNumber <= e && null === n.get(o.targetId) && (this.Rs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)),
  10171. s++);
  10172. })), Rt.waitFor(i).next((() => s));
  10173. }
  10174. getTargetCount(t) {
  10175. return Rt.resolve(this.targetCount);
  10176. }
  10177. getTargetData(t, e) {
  10178. const n = this.Rs.get(e) || null;
  10179. return Rt.resolve(n);
  10180. }
  10181. addMatchingKeys(t, e, n) {
  10182. return this.Ps.us(e, n), Rt.resolve();
  10183. }
  10184. removeMatchingKeys(t, e, n) {
  10185. this.Ps.hs(e, n);
  10186. const s = this.persistence.referenceDelegate, i = [];
  10187. return s && e.forEach((e => {
  10188. i.push(s.markPotentiallyOrphaned(t, e));
  10189. })), Rt.waitFor(i);
  10190. }
  10191. removeMatchingKeysForTargetId(t, e) {
  10192. return this.Ps.ls(e), Rt.resolve();
  10193. }
  10194. getMatchingKeysForTargetId(t, e) {
  10195. const n = this.Ps.ds(e);
  10196. return Rt.resolve(n);
  10197. }
  10198. containsKey(t, e) {
  10199. return Rt.resolve(this.Ps.containsKey(e));
  10200. }
  10201. }
  10202. /**
  10203. * @license
  10204. * Copyright 2017 Google LLC
  10205. *
  10206. * Licensed under the Apache License, Version 2.0 (the "License");
  10207. * you may not use this file except in compliance with the License.
  10208. * You may obtain a copy of the License at
  10209. *
  10210. * http://www.apache.org/licenses/LICENSE-2.0
  10211. *
  10212. * Unless required by applicable law or agreed to in writing, software
  10213. * distributed under the License is distributed on an "AS IS" BASIS,
  10214. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10215. * See the License for the specific language governing permissions and
  10216. * limitations under the License.
  10217. */
  10218. /**
  10219. * A memory-backed instance of Persistence. Data is stored only in RAM and
  10220. * not persisted across sessions.
  10221. */
  10222. class Do {
  10223. /**
  10224. * The constructor accepts a factory for creating a reference delegate. This
  10225. * allows both the delegate and this instance to have strong references to
  10226. * each other without having nullable fields that would then need to be
  10227. * checked or asserted on every access.
  10228. */
  10229. constructor(t, e) {
  10230. this.Vs = {}, this.overlays = {}, this.Ss = new Mt(0), this.Ds = !1, this.Ds = !0,
  10231. this.referenceDelegate = t(this), this.Cs = new So(this);
  10232. this.indexManager = new Or, this.remoteDocumentCache = function(t) {
  10233. return new vo(t);
  10234. }((t => this.referenceDelegate.xs(t))), this.yt = new Yi(e), this.Ns = new Eo(this.yt);
  10235. }
  10236. start() {
  10237. return Promise.resolve();
  10238. }
  10239. shutdown() {
  10240. // No durable state to ensure is closed on shutdown.
  10241. return this.Ds = !1, Promise.resolve();
  10242. }
  10243. get started() {
  10244. return this.Ds;
  10245. }
  10246. setDatabaseDeletedListener() {
  10247. // No op.
  10248. }
  10249. setNetworkEnabled() {
  10250. // No op.
  10251. }
  10252. getIndexManager(t) {
  10253. // We do not currently support indices for memory persistence, so we can
  10254. // return the same shared instance of the memory index manager.
  10255. return this.indexManager;
  10256. }
  10257. getDocumentOverlayCache(t) {
  10258. let e = this.overlays[t.toKey()];
  10259. return e || (e = new Ao, this.overlays[t.toKey()] = e), e;
  10260. }
  10261. getMutationQueue(t, e) {
  10262. let n = this.Vs[t.toKey()];
  10263. return n || (n = new Po(e, this.referenceDelegate), this.Vs[t.toKey()] = n), n;
  10264. }
  10265. getTargetCache() {
  10266. return this.Cs;
  10267. }
  10268. getRemoteDocumentCache() {
  10269. return this.remoteDocumentCache;
  10270. }
  10271. getBundleCache() {
  10272. return this.Ns;
  10273. }
  10274. runTransaction(t, e, n) {
  10275. x("MemoryPersistence", "Starting transaction:", t);
  10276. const s = new Co(this.Ss.next());
  10277. return this.referenceDelegate.ks(), n(s).next((t => this.referenceDelegate.Os(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(),
  10278. t)));
  10279. }
  10280. Ms(t, e) {
  10281. return Rt.or(Object.values(this.Vs).map((n => () => n.containsKey(t, e))));
  10282. }
  10283. }
  10284. /**
  10285. * Memory persistence is not actually transactional, but future implementations
  10286. * may have transaction-scoped state.
  10287. */ class Co extends Et {
  10288. constructor(t) {
  10289. super(), this.currentSequenceNumber = t;
  10290. }
  10291. }
  10292. class xo {
  10293. constructor(t) {
  10294. this.persistence = t,
  10295. /** Tracks all documents that are active in Query views. */
  10296. this.Fs = new Ro,
  10297. /** The list of documents that are potentially GCed after each transaction. */
  10298. this.$s = null;
  10299. }
  10300. static Bs(t) {
  10301. return new xo(t);
  10302. }
  10303. get Ls() {
  10304. if (this.$s) return this.$s;
  10305. throw M();
  10306. }
  10307. addReference(t, e, n) {
  10308. return this.Fs.addReference(n, e), this.Ls.delete(n.toString()), Rt.resolve();
  10309. }
  10310. removeReference(t, e, n) {
  10311. return this.Fs.removeReference(n, e), this.Ls.add(n.toString()), Rt.resolve();
  10312. }
  10313. markPotentiallyOrphaned(t, e) {
  10314. return this.Ls.add(e.toString()), Rt.resolve();
  10315. }
  10316. removeTarget(t, e) {
  10317. this.Fs.ls(e.targetId).forEach((t => this.Ls.add(t.toString())));
  10318. const n = this.persistence.getTargetCache();
  10319. return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  10320. t.forEach((t => this.Ls.add(t.toString())));
  10321. })).next((() => n.removeTargetData(t, e)));
  10322. }
  10323. ks() {
  10324. this.$s = new Set;
  10325. }
  10326. Os(t) {
  10327. // Remove newly orphaned documents.
  10328. const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();
  10329. return Rt.forEach(this.Ls, (n => {
  10330. const s = at.fromPath(n);
  10331. return this.qs(t, s).next((t => {
  10332. t || e.removeEntry(s, it.min());
  10333. }));
  10334. })).next((() => (this.$s = null, e.apply(t))));
  10335. }
  10336. updateLimboDocument(t, e) {
  10337. return this.qs(t, e).next((t => {
  10338. t ? this.Ls.delete(e.toString()) : this.Ls.add(e.toString());
  10339. }));
  10340. }
  10341. xs(t) {
  10342. // For eager GC, we don't care about the document size, there are no size thresholds.
  10343. return 0;
  10344. }
  10345. qs(t, e) {
  10346. return Rt.or([ () => Rt.resolve(this.Fs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Ms(t, e) ]);
  10347. }
  10348. }
  10349. /**
  10350. * @license
  10351. * Copyright 2020 Google LLC
  10352. *
  10353. * Licensed under the Apache License, Version 2.0 (the "License");
  10354. * you may not use this file except in compliance with the License.
  10355. * You may obtain a copy of the License at
  10356. *
  10357. * http://www.apache.org/licenses/LICENSE-2.0
  10358. *
  10359. * Unless required by applicable law or agreed to in writing, software
  10360. * distributed under the License is distributed on an "AS IS" BASIS,
  10361. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10362. * See the License for the specific language governing permissions and
  10363. * limitations under the License.
  10364. */
  10365. /** Performs database creation and schema upgrades. */ class No {
  10366. constructor(t) {
  10367. this.yt = t;
  10368. }
  10369. /**
  10370. * Performs database creation and schema upgrades.
  10371. *
  10372. * Note that in production, this method is only ever used to upgrade the schema
  10373. * to SCHEMA_VERSION. Different values of toVersion are only used for testing
  10374. * and local feature development.
  10375. */ $(t, e, n, s) {
  10376. const i = new bt("createOrUpgrade", e);
  10377. n < 1 && s >= 1 && (function(t) {
  10378. t.createObjectStore("owner");
  10379. }(t), function(t) {
  10380. t.createObjectStore("mutationQueues", {
  10381. keyPath: "userId"
  10382. });
  10383. t.createObjectStore("mutations", {
  10384. keyPath: "batchId",
  10385. autoIncrement: !0
  10386. }).createIndex("userMutationsIndex", Ei, {
  10387. unique: !0
  10388. }), t.createObjectStore("documentMutations");
  10389. }
  10390. /**
  10391. * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
  10392. * and rewrites all data.
  10393. */ (t), ko(t), function(t) {
  10394. t.createObjectStore("remoteDocuments");
  10395. }(t));
  10396. // Migration 2 to populate the targetGlobal object no longer needed since
  10397. // migration 3 unconditionally clears it.
  10398. let r = Rt.resolve();
  10399. return n < 3 && s >= 3 && (
  10400. // Brand new clients don't need to drop and recreate--only clients that
  10401. // potentially have corrupt data.
  10402. 0 !== n && (!function(t) {
  10403. t.deleteObjectStore("targetDocuments"), t.deleteObjectStore("targets"), t.deleteObjectStore("targetGlobal");
  10404. }(t), ko(t)), r = r.next((() =>
  10405. /**
  10406. * Creates the target global singleton row.
  10407. *
  10408. * @param txn - The version upgrade transaction for indexeddb
  10409. */
  10410. function(t) {
  10411. const e = t.store("targetGlobal"), n = {
  10412. highestTargetId: 0,
  10413. highestListenSequenceNumber: 0,
  10414. lastRemoteSnapshotVersion: it.min().toTimestamp(),
  10415. targetCount: 0
  10416. };
  10417. return e.put("targetGlobalKey", n);
  10418. }(i)))), n < 4 && s >= 4 && (0 !== n && (
  10419. // Schema version 3 uses auto-generated keys to generate globally unique
  10420. // mutation batch IDs (this was previously ensured internally by the
  10421. // client). To migrate to the new schema, we have to read all mutations
  10422. // and write them back out. We preserve the existing batch IDs to guarantee
  10423. // consistency with other object stores. Any further mutation batch IDs will
  10424. // be auto-generated.
  10425. r = r.next((() => function(t, e) {
  10426. return e.store("mutations").W().next((n => {
  10427. t.deleteObjectStore("mutations");
  10428. t.createObjectStore("mutations", {
  10429. keyPath: "batchId",
  10430. autoIncrement: !0
  10431. }).createIndex("userMutationsIndex", Ei, {
  10432. unique: !0
  10433. });
  10434. const s = e.store("mutations"), i = n.map((t => s.put(t)));
  10435. return Rt.waitFor(i);
  10436. }));
  10437. }(t, i)))), r = r.next((() => {
  10438. !function(t) {
  10439. t.createObjectStore("clientMetadata", {
  10440. keyPath: "clientId"
  10441. });
  10442. }(t);
  10443. }))), n < 5 && s >= 5 && (r = r.next((() => this.Us(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {
  10444. t.createObjectStore("remoteDocumentGlobal");
  10445. }(t), this.Ks(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Gs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.Qs(t, i)))),
  10446. n < 9 && s >= 9 && (r = r.next((() => {
  10447. // Multi-Tab used to manage its own changelog, but this has been moved
  10448. // to the DbRemoteDocument object store itself. Since the previous change
  10449. // log only contained transient data, we can drop its object store.
  10450. !function(t) {
  10451. t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
  10452. }(t);
  10453. // Note: Schema version 9 used to create a read time index for the
  10454. // RemoteDocumentCache. This is now done with schema version 13.
  10455. }))), n < 10 && s >= 10 && (r = r.next((() => this.js(i)))), n < 11 && s >= 11 && (r = r.next((() => {
  10456. !function(t) {
  10457. t.createObjectStore("bundles", {
  10458. keyPath: "bundleId"
  10459. });
  10460. }(t), function(t) {
  10461. t.createObjectStore("namedQueries", {
  10462. keyPath: "name"
  10463. });
  10464. }(t);
  10465. }))), n < 12 && s >= 12 && (r = r.next((() => {
  10466. !function(t) {
  10467. const e = t.createObjectStore("documentOverlays", {
  10468. keyPath: Fi
  10469. });
  10470. e.createIndex("collectionPathOverlayIndex", $i, {
  10471. unique: !1
  10472. }), e.createIndex("collectionGroupOverlayIndex", Bi, {
  10473. unique: !1
  10474. });
  10475. }(t);
  10476. }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {
  10477. const e = t.createObjectStore("remoteDocumentsV14", {
  10478. keyPath: Pi
  10479. });
  10480. e.createIndex("documentKeyIndex", vi), e.createIndex("collectionGroupIndex", Vi);
  10481. }(t))).next((() => this.Ws(t, i))).next((() => t.deleteObjectStore("remoteDocuments")))),
  10482. n < 14 && s >= 14 && (r = r.next((() => this.zs(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {
  10483. t.createObjectStore("indexConfiguration", {
  10484. keyPath: "indexId",
  10485. autoIncrement: !0
  10486. }).createIndex("collectionGroupIndex", "collectionGroup", {
  10487. unique: !1
  10488. });
  10489. t.createObjectStore("indexState", {
  10490. keyPath: Ni
  10491. }).createIndex("sequenceNumberIndex", ki, {
  10492. unique: !1
  10493. });
  10494. t.createObjectStore("indexEntries", {
  10495. keyPath: Oi
  10496. }).createIndex("documentKeyIndex", Mi, {
  10497. unique: !1
  10498. });
  10499. }(t)))), r;
  10500. }
  10501. Ks(t) {
  10502. let e = 0;
  10503. return t.store("remoteDocuments").Z(((t, n) => {
  10504. e += Wr(n);
  10505. })).next((() => {
  10506. const n = {
  10507. byteSize: e
  10508. };
  10509. return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey", n);
  10510. }));
  10511. }
  10512. Us(t) {
  10513. const e = t.store("mutationQueues"), n = t.store("mutations");
  10514. return e.W().next((e => Rt.forEach(e, (e => {
  10515. const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
  10516. return n.W("userMutationsIndex", s).next((n => Rt.forEach(n, (n => {
  10517. F(n.userId === e.userId);
  10518. const s = sr(this.yt, n);
  10519. return jr(t, e.userId, s).next((() => {}));
  10520. }))));
  10521. }))));
  10522. }
  10523. /**
  10524. * Ensures that every document in the remote document cache has a corresponding sentinel row
  10525. * with a sequence number. Missing rows are given the most recently used sequence number.
  10526. */ Gs(t) {
  10527. const e = t.store("targetDocuments"), n = t.store("remoteDocuments");
  10528. return t.store("targetGlobal").get("targetGlobalKey").next((t => {
  10529. const s = [];
  10530. return n.Z(((n, i) => {
  10531. const r = new ot(n), o = function(t) {
  10532. return [ 0, yi(t) ];
  10533. }(r);
  10534. s.push(e.get(o).next((n => n ? Rt.resolve() : (n => e.put({
  10535. targetId: 0,
  10536. path: yi(n),
  10537. sequenceNumber: t.highestListenSequenceNumber
  10538. }))(r))));
  10539. })).next((() => Rt.waitFor(s)));
  10540. }));
  10541. }
  10542. Qs(t, e) {
  10543. // Create the index.
  10544. t.createObjectStore("collectionParents", {
  10545. keyPath: xi
  10546. });
  10547. const n = e.store("collectionParents"), s = new Mr, i = t => {
  10548. if (s.add(t)) {
  10549. const e = t.lastSegment(), s = t.popLast();
  10550. return n.put({
  10551. collectionId: e,
  10552. parent: yi(s)
  10553. });
  10554. }
  10555. };
  10556. // Helper to add an index entry iff we haven't already written it.
  10557. // Index existing remote documents.
  10558. return e.store("remoteDocuments").Z({
  10559. X: !0
  10560. }, ((t, e) => {
  10561. const n = new ot(t);
  10562. return i(n.popLast());
  10563. })).next((() => e.store("documentMutations").Z({
  10564. X: !0
  10565. }, (([t, e, n], s) => {
  10566. const r = Ti(e);
  10567. return i(r.popLast());
  10568. }))));
  10569. }
  10570. js(t) {
  10571. const e = t.store("targets");
  10572. return e.Z(((t, n) => {
  10573. const s = ir(n), i = rr(this.yt, s);
  10574. return e.put(i);
  10575. }));
  10576. }
  10577. Ws(t, e) {
  10578. const n = e.store("remoteDocuments"), s = [];
  10579. return n.Z(((t, n) => {
  10580. const i = e.store("remoteDocumentsV14"), r = (o = n, o.document ? new at(ot.fromString(o.document.name).popFirst(5)) : o.noDocument ? at.fromSegments(o.noDocument.path) : o.unknownDocument ? at.fromSegments(o.unknownDocument.path) : M()).path.toArray();
  10581. var o;
  10582. /**
  10583. * @license
  10584. * Copyright 2017 Google LLC
  10585. *
  10586. * Licensed under the Apache License, Version 2.0 (the "License");
  10587. * you may not use this file except in compliance with the License.
  10588. * You may obtain a copy of the License at
  10589. *
  10590. * http://www.apache.org/licenses/LICENSE-2.0
  10591. *
  10592. * Unless required by applicable law or agreed to in writing, software
  10593. * distributed under the License is distributed on an "AS IS" BASIS,
  10594. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10595. * See the License for the specific language governing permissions and
  10596. * limitations under the License.
  10597. */ const u = {
  10598. prefixPath: r.slice(0, r.length - 2),
  10599. collectionGroup: r[r.length - 2],
  10600. documentId: r[r.length - 1],
  10601. readTime: n.readTime || [ 0, 0 ],
  10602. unknownDocument: n.unknownDocument,
  10603. noDocument: n.noDocument,
  10604. document: n.document,
  10605. hasCommittedMutations: !!n.hasCommittedMutations
  10606. };
  10607. s.push(i.put(u));
  10608. })).next((() => Rt.waitFor(s)));
  10609. }
  10610. zs(t, e) {
  10611. const n = e.store("mutations"), s = fo(this.yt), i = new Do(xo.Bs, this.yt.ie);
  10612. return n.W().next((t => {
  10613. const n = new Map;
  10614. return t.forEach((t => {
  10615. var e;
  10616. let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : Rs();
  10617. sr(this.yt, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);
  10618. })), Rt.forEach(n, ((t, n) => {
  10619. const r = new v(n), o = dr.re(this.yt, r), u = i.getIndexManager(r), c = zr.re(r, this.yt, u, i.referenceDelegate);
  10620. return new To(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new Qi(e, Mt.at), t).next();
  10621. }));
  10622. }));
  10623. }
  10624. }
  10625. function ko(t) {
  10626. t.createObjectStore("targetDocuments", {
  10627. keyPath: Di
  10628. }).createIndex("documentTargetsIndex", Ci, {
  10629. unique: !0
  10630. });
  10631. // NOTE: This is unique only because the TargetId is the suffix.
  10632. t.createObjectStore("targets", {
  10633. keyPath: "targetId"
  10634. }).createIndex("queryTargetsIndex", Si, {
  10635. unique: !0
  10636. }), t.createObjectStore("targetGlobal");
  10637. }
  10638. const Oo = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";
  10639. /**
  10640. * Oldest acceptable age in milliseconds for client metadata before the client
  10641. * is considered inactive and its associated data is garbage collected.
  10642. */
  10643. /**
  10644. * An IndexedDB-backed instance of Persistence. Data is stored persistently
  10645. * across sessions.
  10646. *
  10647. * On Web only, the Firestore SDKs support shared access to its persistence
  10648. * layer. This allows multiple browser tabs to read and write to IndexedDb and
  10649. * to synchronize state even without network connectivity. Shared access is
  10650. * currently optional and not enabled unless all clients invoke
  10651. * `enablePersistence()` with `{synchronizeTabs:true}`.
  10652. *
  10653. * In multi-tab mode, if multiple clients are active at the same time, the SDK
  10654. * will designate one client as the “primary client”. An effort is made to pick
  10655. * a visible, network-connected and active client, and this client is
  10656. * responsible for letting other clients know about its presence. The primary
  10657. * client writes a unique client-generated identifier (the client ID) to
  10658. * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to
  10659. * update this entry, another client can acquire the lease and take over as
  10660. * primary.
  10661. *
  10662. * Some persistence operations in the SDK are designated as primary-client only
  10663. * operations. This includes the acknowledgment of mutations and all updates of
  10664. * remote documents. The effects of these operations are written to persistence
  10665. * and then broadcast to other tabs via LocalStorage (see
  10666. * `WebStorageSharedClientState`), which then refresh their state from
  10667. * persistence.
  10668. *
  10669. * Similarly, the primary client listens to notifications sent by secondary
  10670. * clients to discover persistence changes written by secondary clients, such as
  10671. * the addition of new mutations and query targets.
  10672. *
  10673. * If multi-tab is not enabled and another tab already obtained the primary
  10674. * lease, IndexedDbPersistence enters a failed state and all subsequent
  10675. * operations will automatically fail.
  10676. *
  10677. * Additionally, there is an optimization so that when a tab is closed, the
  10678. * primary lease is released immediately (this is especially important to make
  10679. * sure that a refreshed tab is able to immediately re-acquire the primary
  10680. * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
  10681. * since it is an asynchronous API. So in addition to attempting to give up the
  10682. * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
  10683. * LocalStorage which acts as an indicator that another tab should go ahead and
  10684. * take the primary lease immediately regardless of the current lease timestamp.
  10685. *
  10686. * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
  10687. * longer optional.
  10688. */
  10689. class Mo {
  10690. constructor(
  10691. /**
  10692. * Whether to synchronize the in-memory state of multiple tabs and share
  10693. * access to local persistence.
  10694. */
  10695. t, e, n, s, i, r, o, u, c,
  10696. /**
  10697. * If set to true, forcefully obtains database access. Existing tabs will
  10698. * no longer be able to access IndexedDB.
  10699. */
  10700. a, h = 15) {
  10701. if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n,
  10702. this.Hs = i, this.window = r, this.document = o, this.Js = c, this.Ys = a, this.Xs = h,
  10703. this.Ss = null, this.Ds = !1, this.isPrimary = !1, this.networkEnabled = !0,
  10704. /** Our window.unload handler, if registered. */
  10705. this.Zs = null, this.inForeground = !1,
  10706. /** Our 'visibilitychange' listener if registered. */
  10707. this.ti = null,
  10708. /** The client metadata refresh task. */
  10709. this.ei = null,
  10710. /** The last time we garbage collected the client metadata object store. */
  10711. this.ni = Number.NEGATIVE_INFINITY,
  10712. /** A listener to notify on primary state changes. */
  10713. this.si = t => Promise.resolve(), !Mo.C()) throw new q(L.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
  10714. this.referenceDelegate = new co(this, s), this.ii = e + "main", this.yt = new Yi(u),
  10715. this.ri = new Pt(this.ii, this.Xs, new No(this.yt)), this.Cs = new to(this.referenceDelegate, this.yt),
  10716. this.remoteDocumentCache = fo(this.yt), this.Ns = new hr, this.window && this.window.localStorage ? this.oi = this.window.localStorage : (this.oi = null,
  10717. !1 === a && N("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  10718. }
  10719. /**
  10720. * Attempt to start IndexedDb persistence.
  10721. *
  10722. * @returns Whether persistence was enabled.
  10723. */ start() {
  10724. // NOTE: This is expected to fail sometimes (in the case of another tab
  10725. // already having the persistence lock), so it's the first thing we should
  10726. // do.
  10727. return this.ui().then((() => {
  10728. if (!this.isPrimary && !this.allowTabSynchronization)
  10729. // Fail `start()` if `synchronizeTabs` is disabled and we cannot
  10730. // obtain the primary lease.
  10731. throw new q(L.FAILED_PRECONDITION, Oo);
  10732. return this.ci(), this.ai(), this.hi(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (t => this.Cs.getHighestSequenceNumber(t)));
  10733. })).then((t => {
  10734. this.Ss = new Mt(t, this.Js);
  10735. })).then((() => {
  10736. this.Ds = !0;
  10737. })).catch((t => (this.ri && this.ri.close(), Promise.reject(t))));
  10738. }
  10739. /**
  10740. * Registers a listener that gets called when the primary state of the
  10741. * instance changes. Upon registering, this listener is invoked immediately
  10742. * with the current primary state.
  10743. *
  10744. * PORTING NOTE: This is only used for Web multi-tab.
  10745. */ li(t) {
  10746. return this.si = async e => {
  10747. if (this.started) return t(e);
  10748. }, t(this.isPrimary);
  10749. }
  10750. /**
  10751. * Registers a listener that gets called when the database receives a
  10752. * version change event indicating that it has deleted.
  10753. *
  10754. * PORTING NOTE: This is only used for Web multi-tab.
  10755. */ setDatabaseDeletedListener(t) {
  10756. this.ri.L((async e => {
  10757. // Check if an attempt is made to delete IndexedDB.
  10758. null === e.newVersion && await t();
  10759. }));
  10760. }
  10761. /**
  10762. * Adjusts the current network state in the client's metadata, potentially
  10763. * affecting the primary lease.
  10764. *
  10765. * PORTING NOTE: This is only used for Web multi-tab.
  10766. */ setNetworkEnabled(t) {
  10767. this.networkEnabled !== t && (this.networkEnabled = t,
  10768. // Schedule a primary lease refresh for immediate execution. The eventual
  10769. // lease update will be propagated via `primaryStateListener`.
  10770. this.Hs.enqueueAndForget((async () => {
  10771. this.started && await this.ui();
  10772. })));
  10773. }
  10774. /**
  10775. * Updates the client metadata in IndexedDb and attempts to either obtain or
  10776. * extend the primary lease for the local client. Asynchronously notifies the
  10777. * primary state listener if the client either newly obtained or released its
  10778. * primary lease.
  10779. */ ui() {
  10780. return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (t => $o(t).put({
  10781. clientId: this.clientId,
  10782. updateTimeMs: Date.now(),
  10783. networkEnabled: this.networkEnabled,
  10784. inForeground: this.inForeground
  10785. }).next((() => {
  10786. if (this.isPrimary) return this.fi(t).next((t => {
  10787. t || (this.isPrimary = !1, this.Hs.enqueueRetryable((() => this.si(!1))));
  10788. }));
  10789. })).next((() => this.di(t))).next((e => this.isPrimary && !e ? this._i(t).next((() => !1)) : !!e && this.wi(t).next((() => !0)))))).catch((t => {
  10790. if (St(t))
  10791. // Proceed with the existing state. Any subsequent access to
  10792. // IndexedDB will verify the lease.
  10793. return x("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
  10794. if (!this.allowTabSynchronization) throw t;
  10795. return x("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t),
  10796. /* isPrimary= */ !1;
  10797. })).then((t => {
  10798. this.isPrimary !== t && this.Hs.enqueueRetryable((() => this.si(t))), this.isPrimary = t;
  10799. }));
  10800. }
  10801. fi(t) {
  10802. return Fo(t).get("owner").next((t => Rt.resolve(this.mi(t))));
  10803. }
  10804. gi(t) {
  10805. return $o(t).delete(this.clientId);
  10806. }
  10807. /**
  10808. * If the garbage collection threshold has passed, prunes the
  10809. * RemoteDocumentChanges and the ClientMetadata store based on the last update
  10810. * time of all clients.
  10811. */ async yi() {
  10812. if (this.isPrimary && !this.pi(this.ni, 18e5)) {
  10813. this.ni = Date.now();
  10814. const t = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (t => {
  10815. const e = ji(t, "clientMetadata");
  10816. return e.W().next((t => {
  10817. const n = this.Ii(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));
  10818. // Delete metadata for clients that are no longer considered active.
  10819. return Rt.forEach(s, (t => e.delete(t.clientId))).next((() => s));
  10820. }));
  10821. })).catch((() => []));
  10822. // Delete potential leftover entries that may continue to mark the
  10823. // inactive clients as zombied in LocalStorage.
  10824. // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
  10825. // the client atomically, but we can't. So we opt to delete the IndexedDb
  10826. // entries first to avoid potentially reviving a zombied client.
  10827. if (this.oi) for (const e of t) this.oi.removeItem(this.Ti(e.clientId));
  10828. }
  10829. }
  10830. /**
  10831. * Schedules a recurring timer to update the client metadata and to either
  10832. * extend or acquire the primary lease if the client is eligible.
  10833. */ hi() {
  10834. this.ei = this.Hs.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.ui().then((() => this.yi())).then((() => this.hi()))));
  10835. }
  10836. /** Checks whether `client` is the local client. */ mi(t) {
  10837. return !!t && t.ownerId === this.clientId;
  10838. }
  10839. /**
  10840. * Evaluate the state of all active clients and determine whether the local
  10841. * client is or can act as the holder of the primary lease. Returns whether
  10842. * the client is eligible for the lease, but does not actually acquire it.
  10843. * May return 'false' even if there is no active leaseholder and another
  10844. * (foreground) client should become leaseholder instead.
  10845. */ di(t) {
  10846. if (this.Ys) return Rt.resolve(!0);
  10847. return Fo(t).get("owner").next((e => {
  10848. // A client is eligible for the primary lease if:
  10849. // - its network is enabled and the client's tab is in the foreground.
  10850. // - its network is enabled and no other client's tab is in the
  10851. // foreground.
  10852. // - every clients network is disabled and the client's tab is in the
  10853. // foreground.
  10854. // - every clients network is disabled and no other client's tab is in
  10855. // the foreground.
  10856. // - the `forceOwningTab` setting was passed in.
  10857. if (null !== e && this.pi(e.leaseTimestampMs, 5e3) && !this.Ei(e.ownerId)) {
  10858. if (this.mi(e) && this.networkEnabled) return !0;
  10859. if (!this.mi(e)) {
  10860. if (!e.allowTabSynchronization)
  10861. // Fail the `canActAsPrimary` check if the current leaseholder has
  10862. // not opted into multi-tab synchronization. If this happens at
  10863. // client startup, we reject the Promise returned by
  10864. // `enablePersistence()` and the user can continue to use Firestore
  10865. // with in-memory persistence.
  10866. // If this fails during a lease refresh, we will instead block the
  10867. // AsyncQueue from executing further operations. Note that this is
  10868. // acceptable since mixing & matching different `synchronizeTabs`
  10869. // settings is not supported.
  10870. // TODO(b/114226234): Remove this check when `synchronizeTabs` can
  10871. // no longer be turned off.
  10872. throw new q(L.FAILED_PRECONDITION, Oo);
  10873. return !1;
  10874. }
  10875. }
  10876. return !(!this.networkEnabled || !this.inForeground) || $o(t).W().next((t => void 0 === this.Ii(t, 5e3).find((t => {
  10877. if (this.clientId !== t.clientId) {
  10878. const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;
  10879. if (e || n && s) return !0;
  10880. }
  10881. return !1;
  10882. }))));
  10883. })).next((t => (this.isPrimary !== t && x("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`),
  10884. t)));
  10885. }
  10886. async shutdown() {
  10887. // The shutdown() operations are idempotent and can be called even when
  10888. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  10889. this.Ds = !1, this.Ai(), this.ei && (this.ei.cancel(), this.ei = null), this.Ri(),
  10890. this.bi(),
  10891. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  10892. // has obtained the primary lease.
  10893. await this.ri.runTransaction("shutdown", "readwrite", [ "owner", "clientMetadata" ], (t => {
  10894. const e = new Qi(t, Mt.at);
  10895. return this._i(e).next((() => this.gi(e)));
  10896. })), this.ri.close(),
  10897. // Remove the entry marking the client as zombied from LocalStorage since
  10898. // we successfully deleted its metadata from IndexedDb.
  10899. this.Pi();
  10900. }
  10901. /**
  10902. * Returns clients that are not zombied and have an updateTime within the
  10903. * provided threshold.
  10904. */ Ii(t, e) {
  10905. return t.filter((t => this.pi(t.updateTimeMs, e) && !this.Ei(t.clientId)));
  10906. }
  10907. /**
  10908. * Returns the IDs of the clients that are currently active. If multi-tab
  10909. * is not supported, returns an array that only contains the local client's
  10910. * ID.
  10911. *
  10912. * PORTING NOTE: This is only used for Web multi-tab.
  10913. */ vi() {
  10914. return this.runTransaction("getActiveClients", "readonly", (t => $o(t).W().next((t => this.Ii(t, 18e5).map((t => t.clientId))))));
  10915. }
  10916. get started() {
  10917. return this.Ds;
  10918. }
  10919. getMutationQueue(t, e) {
  10920. return zr.re(t, this.yt, e, this.referenceDelegate);
  10921. }
  10922. getTargetCache() {
  10923. return this.Cs;
  10924. }
  10925. getRemoteDocumentCache() {
  10926. return this.remoteDocumentCache;
  10927. }
  10928. getIndexManager(t) {
  10929. return new $r(t, this.yt.ie.databaseId);
  10930. }
  10931. getDocumentOverlayCache(t) {
  10932. return dr.re(this.yt, t);
  10933. }
  10934. getBundleCache() {
  10935. return this.Ns;
  10936. }
  10937. runTransaction(t, e, n) {
  10938. x("IndexedDbPersistence", "Starting transaction:", t);
  10939. const s = "readonly" === e ? "readonly" : "readwrite", i = 15 === (r = this.Xs) ? Gi : 14 === r ? Ki : 13 === r ? Ui : 12 === r ? qi : 11 === r ? Li : void M();
  10940. /** Returns the object stores for the provided schema. */
  10941. var r;
  10942. let o;
  10943. // Do all transactions as readwrite against all object stores, since we
  10944. // are the only reader/writer.
  10945. return this.ri.runTransaction(t, s, i, (s => (o = new Qi(s, this.Ss ? this.Ss.next() : Mt.at),
  10946. "readwrite-primary" === e ? this.fi(o).next((t => !!t || this.di(o))).next((e => {
  10947. if (!e) throw N(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1,
  10948. this.Hs.enqueueRetryable((() => this.si(!1))), new q(L.FAILED_PRECONDITION, Tt);
  10949. return n(o);
  10950. })).next((t => this.wi(o).next((() => t)))) : this.Vi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(),
  10951. t)));
  10952. }
  10953. /**
  10954. * Verifies that the current tab is the primary leaseholder or alternatively
  10955. * that the leaseholder has opted into multi-tab synchronization.
  10956. */
  10957. // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  10958. // be turned off.
  10959. Vi(t) {
  10960. return Fo(t).get("owner").next((t => {
  10961. if (null !== t && this.pi(t.leaseTimestampMs, 5e3) && !this.Ei(t.ownerId) && !this.mi(t) && !(this.Ys || this.allowTabSynchronization && t.allowTabSynchronization)) throw new q(L.FAILED_PRECONDITION, Oo);
  10962. }));
  10963. }
  10964. /**
  10965. * Obtains or extends the new primary lease for the local client. This
  10966. * method does not verify that the client is eligible for this lease.
  10967. */ wi(t) {
  10968. const e = {
  10969. ownerId: this.clientId,
  10970. allowTabSynchronization: this.allowTabSynchronization,
  10971. leaseTimestampMs: Date.now()
  10972. };
  10973. return Fo(t).put("owner", e);
  10974. }
  10975. static C() {
  10976. return Pt.C();
  10977. }
  10978. /** Checks the primary lease and removes it if we are the current primary. */ _i(t) {
  10979. const e = Fo(t);
  10980. return e.get("owner").next((t => this.mi(t) ? (x("IndexedDbPersistence", "Releasing primary lease."),
  10981. e.delete("owner")) : Rt.resolve()));
  10982. }
  10983. /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ pi(t, e) {
  10984. const n = Date.now();
  10985. return !(t < n - e) && (!(t > n) || (N(`Detected an update time that is in the future: ${t} > ${n}`),
  10986. !1));
  10987. }
  10988. ci() {
  10989. null !== this.document && "function" == typeof this.document.addEventListener && (this.ti = () => {
  10990. this.Hs.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState,
  10991. this.ui())));
  10992. }, this.document.addEventListener("visibilitychange", this.ti), this.inForeground = "visible" === this.document.visibilityState);
  10993. }
  10994. Ri() {
  10995. this.ti && (this.document.removeEventListener("visibilitychange", this.ti), this.ti = null);
  10996. }
  10997. /**
  10998. * Attaches a window.unload handler that will synchronously write our
  10999. * clientId to a "zombie client id" location in LocalStorage. This can be used
  11000. * by tabs trying to acquire the primary lease to determine that the lease
  11001. * is no longer valid even if the timestamp is recent. This is particularly
  11002. * important for the refresh case (so the tab correctly re-acquires the
  11003. * primary lease). LocalStorage is used for this rather than IndexedDb because
  11004. * it is a synchronous API and so can be used reliably from an unload
  11005. * handler.
  11006. */ ai() {
  11007. var t;
  11008. "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.Zs = () => {
  11009. // Note: In theory, this should be scheduled on the AsyncQueue since it
  11010. // accesses internal state. We execute this code directly during shutdown
  11011. // to make sure it gets a chance to run.
  11012. this.Ai(), f() && navigator.appVersion.match(/Version\/1[45]/) &&
  11013. // On Safari 14 and 15, we do not run any cleanup actions as it might
  11014. // trigger a bug that prevents Safari from re-opening IndexedDB during
  11015. // the next page load.
  11016. // See https://bugs.webkit.org/show_bug.cgi?id=226547
  11017. this.Hs.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Hs.enqueueAndForget((() => this.shutdown()));
  11018. }, this.window.addEventListener("pagehide", this.Zs));
  11019. }
  11020. bi() {
  11021. this.Zs && (this.window.removeEventListener("pagehide", this.Zs), this.Zs = null);
  11022. }
  11023. /**
  11024. * Returns whether a client is "zombied" based on its LocalStorage entry.
  11025. * Clients become zombied when their tab closes without running all of the
  11026. * cleanup logic in `shutdown()`.
  11027. */ Ei(t) {
  11028. var e;
  11029. try {
  11030. const n = null !== (null === (e = this.oi) || void 0 === e ? void 0 : e.getItem(this.Ti(t)));
  11031. return x("IndexedDbPersistence", `Client '${t}' ${n ? "is" : "is not"} zombied in LocalStorage`),
  11032. n;
  11033. } catch (t) {
  11034. // Gracefully handle if LocalStorage isn't working.
  11035. return N("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
  11036. }
  11037. }
  11038. /**
  11039. * Record client as zombied (a client that had its tab closed). Zombied
  11040. * clients are ignored during primary tab selection.
  11041. */ Ai() {
  11042. if (this.oi) try {
  11043. this.oi.setItem(this.Ti(this.clientId), String(Date.now()));
  11044. } catch (t) {
  11045. // Gracefully handle if LocalStorage isn't available / working.
  11046. N("Failed to set zombie client id.", t);
  11047. }
  11048. }
  11049. /** Removes the zombied client entry if it exists. */ Pi() {
  11050. if (this.oi) try {
  11051. this.oi.removeItem(this.Ti(this.clientId));
  11052. } catch (t) {
  11053. // Ignore
  11054. }
  11055. }
  11056. Ti(t) {
  11057. return `firestore_zombie_${this.persistenceKey}_${t}`;
  11058. }
  11059. }
  11060. /**
  11061. * Helper to get a typed SimpleDbStore for the primary client object store.
  11062. */ function Fo(t) {
  11063. return ji(t, "owner");
  11064. }
  11065. /**
  11066. * Helper to get a typed SimpleDbStore for the client metadata object store.
  11067. */ function $o(t) {
  11068. return ji(t, "clientMetadata");
  11069. }
  11070. /**
  11071. * Generates a string used as a prefix when storing data in IndexedDB and
  11072. * LocalStorage.
  11073. */ function Bo(t, e) {
  11074. // Use two different prefix formats:
  11075. // * firestore / persistenceKey / projectID . databaseID / ...
  11076. // * firestore / persistenceKey / projectID / ...
  11077. // projectIDs are DNS-compatible names and cannot contain dots
  11078. // so there's no danger of collisions.
  11079. let n = t.projectId;
  11080. return t.isDefaultDatabase || (n += "." + t.database), "firestore/" + e + "/" + n + "/";
  11081. }
  11082. /**
  11083. * @license
  11084. * Copyright 2017 Google LLC
  11085. *
  11086. * Licensed under the Apache License, Version 2.0 (the "License");
  11087. * you may not use this file except in compliance with the License.
  11088. * You may obtain a copy of the License at
  11089. *
  11090. * http://www.apache.org/licenses/LICENSE-2.0
  11091. *
  11092. * Unless required by applicable law or agreed to in writing, software
  11093. * distributed under the License is distributed on an "AS IS" BASIS,
  11094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11095. * See the License for the specific language governing permissions and
  11096. * limitations under the License.
  11097. */
  11098. /**
  11099. * A set of changes to what documents are currently in view and out of view for
  11100. * a given query. These changes are sent to the LocalStore by the View (via
  11101. * the SyncEngine) and are used to pin / unpin documents as appropriate.
  11102. */
  11103. class Lo {
  11104. constructor(t, e, n, s) {
  11105. this.targetId = t, this.fromCache = e, this.Si = n, this.Di = s;
  11106. }
  11107. static Ci(t, e) {
  11108. let n = Rs(), s = Rs();
  11109. for (const t of e.docChanges) switch (t.type) {
  11110. case 0 /* ChangeType.Added */ :
  11111. n = n.add(t.doc.key);
  11112. break;
  11113. case 1 /* ChangeType.Removed */ :
  11114. s = s.add(t.doc.key);
  11115. // do nothing
  11116. }
  11117. return new Lo(t, e.fromCache, n, s);
  11118. }
  11119. }
  11120. /**
  11121. * @license
  11122. * Copyright 2019 Google LLC
  11123. *
  11124. * Licensed under the Apache License, Version 2.0 (the "License");
  11125. * you may not use this file except in compliance with the License.
  11126. * You may obtain a copy of the License at
  11127. *
  11128. * http://www.apache.org/licenses/LICENSE-2.0
  11129. *
  11130. * Unless required by applicable law or agreed to in writing, software
  11131. * distributed under the License is distributed on an "AS IS" BASIS,
  11132. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11133. * See the License for the specific language governing permissions and
  11134. * limitations under the License.
  11135. */
  11136. /**
  11137. * The Firestore query engine.
  11138. *
  11139. * Firestore queries can be executed in three modes. The Query Engine determines
  11140. * what mode to use based on what data is persisted. The mode only determines
  11141. * the runtime complexity of the query - the result set is equivalent across all
  11142. * implementations.
  11143. *
  11144. * The Query engine will use indexed-based execution if a user has configured
  11145. * any index that can be used to execute query (via `setIndexConfiguration()`).
  11146. * Otherwise, the engine will try to optimize the query by re-using a previously
  11147. * persisted query result. If that is not possible, the query will be executed
  11148. * via a full collection scan.
  11149. *
  11150. * Index-based execution is the default when available. The query engine
  11151. * supports partial indexed execution and merges the result from the index
  11152. * lookup with documents that have not yet been indexed. The index evaluation
  11153. * matches the backend's format and as such, the SDK can use indexing for all
  11154. * queries that the backend supports.
  11155. *
  11156. * If no index exists, the query engine tries to take advantage of the target
  11157. * document mapping in the TargetCache. These mappings exists for all queries
  11158. * that have been synced with the backend at least once and allow the query
  11159. * engine to only read documents that previously matched a query plus any
  11160. * documents that were edited after the query was last listened to.
  11161. *
  11162. * There are some cases when this optimization is not guaranteed to produce
  11163. * the same results as full collection scans. In these cases, query
  11164. * processing falls back to full scans. These cases are:
  11165. *
  11166. * - Limit queries where a document that matched the query previously no longer
  11167. * matches the query.
  11168. *
  11169. * - Limit queries where a document edit may cause the document to sort below
  11170. * another document that is in the local cache.
  11171. *
  11172. * - Queries that have never been CURRENT or free of limbo documents.
  11173. */ class qo {
  11174. constructor() {
  11175. this.xi = !1;
  11176. }
  11177. /** Sets the document view to query against. */ initialize(t, e) {
  11178. this.Ni = t, this.indexManager = e, this.xi = !0;
  11179. }
  11180. /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {
  11181. return this.ki(t, e).next((i => i || this.Oi(t, e, s, n))).next((n => n || this.Mi(t, e)));
  11182. }
  11183. /**
  11184. * Performs an indexed query that evaluates the query based on a collection's
  11185. * persisted index values. Returns `null` if an index is not available.
  11186. */ ki(t, e) {
  11187. if (_n(e))
  11188. // Queries that match all documents don't benefit from using
  11189. // key-based lookups. It is more efficient to scan all documents in a
  11190. // collection, rather than to perform individual lookups.
  11191. return Rt.resolve(null);
  11192. let n = pn(e);
  11193. return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (
  11194. // We cannot apply a limit for targets that are served using a partial
  11195. // index. If a partial index will be used to serve the target, the
  11196. // query may return a superset of documents that match the target
  11197. // (e.g. if the index doesn't include all the target's filters), or
  11198. // may return the correct set of documents in the wrong order (e.g. if
  11199. // the index doesn't include a segment for one of the orderBys).
  11200. // Therefore, a limit should not be applied in such cases.
  11201. e = Tn(e, null, "F" /* LimitType.First */), n = pn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {
  11202. const i = Rs(...s);
  11203. return this.Ni.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {
  11204. const r = this.Fi(e, s);
  11205. return this.$i(e, r, i, n.readTime) ? this.ki(t, Tn(e, null, "F" /* LimitType.First */)) : this.Bi(t, r, e, n);
  11206. }))));
  11207. })))));
  11208. }
  11209. /**
  11210. * Performs a query based on the target's persisted query mapping. Returns
  11211. * `null` if the mapping is not available or cannot be used.
  11212. */ Oi(t, e, n, s) {
  11213. return _n(e) || s.isEqual(it.min()) ? this.Mi(t, e) : this.Ni.getDocuments(t, n).next((i => {
  11214. const r = this.Fi(e, i);
  11215. return this.$i(e, r, n, s) ? this.Mi(t, e) : (D() <= u.DEBUG && x("QueryEngine", "Re-using previous result from %s to execute query: %s", s.toString(), Rn(e)),
  11216. this.Bi(t, r, e, gt(s, -1)));
  11217. }));
  11218. // Queries that have never seen a snapshot without limbo free documents
  11219. // should also be run as a full collection scan.
  11220. }
  11221. /** Applies the query filter and sorting to the provided documents. */ Fi(t, e) {
  11222. // Sort the documents and re-apply the query filter since previously
  11223. // matching documents do not necessarily still match the query.
  11224. let n = new He(vn(t));
  11225. return e.forEach(((e, s) => {
  11226. bn(t, s) && (n = n.add(s));
  11227. })), n;
  11228. }
  11229. /**
  11230. * Determines if a limit query needs to be refilled from cache, making it
  11231. * ineligible for index-free execution.
  11232. *
  11233. * @param query - The query.
  11234. * @param sortedPreviousResults - The documents that matched the query when it
  11235. * was last synchronized, sorted by the query's comparator.
  11236. * @param remoteKeys - The document keys that matched the query at the last
  11237. * snapshot.
  11238. * @param limboFreeSnapshotVersion - The version of the snapshot when the
  11239. * query was last synchronized.
  11240. */ $i(t, e, n, s) {
  11241. if (null === t.limit)
  11242. // Queries without limits do not need to be refilled.
  11243. return !1;
  11244. if (n.size !== e.size)
  11245. // The query needs to be refilled if a previously matching document no
  11246. // longer matches.
  11247. return !0;
  11248. // Limit queries are not eligible for index-free query execution if there is
  11249. // a potential that an older document from cache now sorts before a document
  11250. // that was previously part of the limit. This, however, can only happen if
  11251. // the document at the edge of the limit goes out of limit.
  11252. // If a document that is not the limit boundary sorts differently,
  11253. // the boundary of the limit itself did not change and documents from cache
  11254. // will continue to be "rejected" by this boundary. Therefore, we can ignore
  11255. // any modifications that don't affect the last document.
  11256. const i = "F" /* LimitType.First */ === t.limitType ? e.last() : e.first();
  11257. return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);
  11258. }
  11259. Mi(t, e) {
  11260. return D() <= u.DEBUG && x("QueryEngine", "Using full collection scan to execute query:", Rn(e)),
  11261. this.Ni.getDocumentsMatchingQuery(t, e, pt.min());
  11262. }
  11263. /**
  11264. * Combines the results from an indexed execution with the remaining documents
  11265. * that have not yet been indexed.
  11266. */ Bi(t, e, n, s) {
  11267. // Retrieve all results for documents that were updated since the offset.
  11268. return this.Ni.getDocumentsMatchingQuery(t, n, s).next((t => (
  11269. // Merge with existing results
  11270. e.forEach((e => {
  11271. t = t.insert(e.key, e);
  11272. })), t)));
  11273. }
  11274. }
  11275. /**
  11276. * @license
  11277. * Copyright 2020 Google LLC
  11278. *
  11279. * Licensed under the Apache License, Version 2.0 (the "License");
  11280. * you may not use this file except in compliance with the License.
  11281. * You may obtain a copy of the License at
  11282. *
  11283. * http://www.apache.org/licenses/LICENSE-2.0
  11284. *
  11285. * Unless required by applicable law or agreed to in writing, software
  11286. * distributed under the License is distributed on an "AS IS" BASIS,
  11287. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11288. * See the License for the specific language governing permissions and
  11289. * limitations under the License.
  11290. */
  11291. /**
  11292. * Implements `LocalStore` interface.
  11293. *
  11294. * Note: some field defined in this class might have public access level, but
  11295. * the class is not exported so they are only accessible from this module.
  11296. * This is useful to implement optional features (like bundles) in free
  11297. * functions, such that they are tree-shakeable.
  11298. */
  11299. class Uo {
  11300. constructor(
  11301. /** Manages our in-memory or durable persistence. */
  11302. t, e, n, s) {
  11303. this.persistence = t, this.Li = e, this.yt = s,
  11304. /**
  11305. * Maps a targetID to data about its target.
  11306. *
  11307. * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
  11308. * of `applyRemoteEvent()` idempotent.
  11309. */
  11310. this.qi = new je(tt),
  11311. /** Maps a target to its targetID. */
  11312. // TODO(wuandy): Evaluate if TargetId can be part of Target.
  11313. this.Ui = new ds((t => rn(t)), on),
  11314. /**
  11315. * A per collection group index of the last read time processed by
  11316. * `getNewDocumentChanges()`.
  11317. *
  11318. * PORTING NOTE: This is only used for multi-tab synchronization.
  11319. */
  11320. this.Ki = new Map, this.Gi = t.getRemoteDocumentCache(), this.Cs = t.getTargetCache(),
  11321. this.Ns = t.getBundleCache(), this.Qi(n);
  11322. }
  11323. Qi(t) {
  11324. // TODO(indexing): Add spec tests that test these components change after a
  11325. // user change
  11326. this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t),
  11327. this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new To(this.Gi, this.mutationQueue, this.documentOverlayCache, this.indexManager),
  11328. this.Gi.setIndexManager(this.indexManager), this.Li.initialize(this.localDocuments, this.indexManager);
  11329. }
  11330. collectGarbage(t) {
  11331. return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (e => t.collect(e, this.qi)));
  11332. }
  11333. }
  11334. function Ko(
  11335. /** Manages our in-memory or durable persistence. */
  11336. t, e, n, s) {
  11337. return new Uo(t, e, n, s);
  11338. }
  11339. /**
  11340. * Tells the LocalStore that the currently authenticated user has changed.
  11341. *
  11342. * In response the local store switches the mutation queue to the new user and
  11343. * returns any resulting document changes.
  11344. */
  11345. // PORTING NOTE: Android and iOS only return the documents affected by the
  11346. // change.
  11347. async function Go(t, e) {
  11348. const n = B(t);
  11349. return await n.persistence.runTransaction("Handle user change", "readonly", (t => {
  11350. // Swap out the mutation queue, grabbing the pending mutation batches
  11351. // before and after.
  11352. let s;
  11353. return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.Qi(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {
  11354. const i = [], r = [];
  11355. // Union the old/new changed keys.
  11356. let o = Rs();
  11357. for (const t of s) {
  11358. i.push(t.batchId);
  11359. for (const e of t.mutations) o = o.add(e.key);
  11360. }
  11361. for (const t of e) {
  11362. r.push(t.batchId);
  11363. for (const e of t.mutations) o = o.add(e.key);
  11364. }
  11365. // Return the set of all (potentially) changed documents and the list
  11366. // of mutation batch IDs that were affected by change.
  11367. return n.localDocuments.getDocuments(t, o).next((t => ({
  11368. ji: t,
  11369. removedBatchIds: i,
  11370. addedBatchIds: r
  11371. })));
  11372. }));
  11373. }));
  11374. }
  11375. /* Accepts locally generated Mutations and commit them to storage. */
  11376. /**
  11377. * Acknowledges the given batch.
  11378. *
  11379. * On the happy path when a batch is acknowledged, the local store will
  11380. *
  11381. * + remove the batch from the mutation queue;
  11382. * + apply the changes to the remote document cache;
  11383. * + recalculate the latency compensated view implied by those changes (there
  11384. * may be mutations in the queue that affect the documents but haven't been
  11385. * acknowledged yet); and
  11386. * + give the changed documents back the sync engine
  11387. *
  11388. * @returns The resulting (modified) documents.
  11389. */
  11390. function Qo(t, e) {
  11391. const n = B(t);
  11392. return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (t => {
  11393. const s = e.batch.keys(), i = n.Gi.newChangeBuffer({
  11394. trackRemovals: !0
  11395. });
  11396. return function(t, e, n, s) {
  11397. const i = n.batch, r = i.keys();
  11398. let o = Rt.resolve();
  11399. return r.forEach((t => {
  11400. o = o.next((() => s.getEntry(e, t))).next((e => {
  11401. const r = n.docVersions.get(t);
  11402. F(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (
  11403. // We use the commitVersion as the readTime rather than the
  11404. // document's updateTime since the updateTime is not advanced
  11405. // for updates that do not modify the underlying document.
  11406. e.setReadTime(n.commitVersion), s.addEntry(e)));
  11407. }));
  11408. })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));
  11409. }
  11410. /** Returns the local view of the documents affected by a mutation batch. */
  11411. // PORTING NOTE: Multi-Tab only.
  11412. (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {
  11413. let e = Rs();
  11414. for (let n = 0; n < t.mutationResults.length; ++n) {
  11415. t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));
  11416. }
  11417. return e;
  11418. }
  11419. /**
  11420. * Removes mutations from the MutationQueue for the specified batch;
  11421. * LocalDocuments will be recalculated.
  11422. *
  11423. * @returns The resulting modified documents.
  11424. */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));
  11425. }));
  11426. }
  11427. /**
  11428. * Returns the last consistent snapshot processed (used by the RemoteStore to
  11429. * determine whether to buffer incoming snapshots from the backend).
  11430. */
  11431. function jo(t) {
  11432. const e = B(t);
  11433. return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (t => e.Cs.getLastRemoteSnapshotVersion(t)));
  11434. }
  11435. /**
  11436. * Updates the "ground-state" (remote) documents. We assume that the remote
  11437. * event reflects any write batches that have been acknowledged or rejected
  11438. * (i.e. we do not re-apply local mutations to updates from this event).
  11439. *
  11440. * LocalDocuments are re-calculated if there are remaining mutations in the
  11441. * queue.
  11442. */ function Wo(t, e) {
  11443. const n = B(t), s = e.snapshotVersion;
  11444. let i = n.qi;
  11445. return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (t => {
  11446. const r = n.Gi.newChangeBuffer({
  11447. trackRemovals: !0
  11448. });
  11449. // Reset newTargetDataByTargetMap in case this transaction gets re-run.
  11450. i = n.qi;
  11451. const o = [];
  11452. e.targetChanges.forEach(((r, u) => {
  11453. const c = i.get(u);
  11454. if (!c) return;
  11455. // Only update the remote keys if the target is still active. This
  11456. // ensures that we can persist the updated target data along with
  11457. // the updated assignment.
  11458. o.push(n.Cs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Cs.addMatchingKeys(t, r.addedDocuments, u))));
  11459. let a = c.withSequenceNumber(t.currentSequenceNumber);
  11460. e.targetMismatches.has(u) ? a = a.withResumeToken(Wt.EMPTY_BYTE_STRING, it.min()).withLastLimboFreeSnapshotVersion(it.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)),
  11461. i = i.insert(u, a),
  11462. // Update the target data if there are target changes (or if
  11463. // sufficient time has passed since the last update).
  11464. /**
  11465. * Returns true if the newTargetData should be persisted during an update of
  11466. * an active target. TargetData should always be persisted when a target is
  11467. * being released and should not call this function.
  11468. *
  11469. * While the target is active, TargetData updates can be omitted when nothing
  11470. * about the target has changed except metadata like the resume token or
  11471. * snapshot version. Occasionally it's worth the extra write to prevent these
  11472. * values from getting too stale after a crash, but this doesn't have to be
  11473. * too frequent.
  11474. */
  11475. function(t, e, n) {
  11476. // Always persist target data if we don't already have a resume token.
  11477. if (0 === t.resumeToken.approximateByteSize()) return !0;
  11478. // Don't allow resume token changes to be buffered indefinitely. This
  11479. // allows us to be reasonably up-to-date after a crash and avoids needing
  11480. // to loop over all active queries on shutdown. Especially in the browser
  11481. // we may not get time to do anything interesting while the current tab is
  11482. // closing.
  11483. if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;
  11484. // Otherwise if the only thing that has changed about a target is its resume
  11485. // token it's not worth persisting. Note that the RemoteStore keeps an
  11486. // in-memory view of the currently active targets which includes the current
  11487. // resume token, so stream failure or user changes will still use an
  11488. // up-to-date resume token regardless of what we do here.
  11489. return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;
  11490. }
  11491. /**
  11492. * Notifies local store of the changed views to locally pin documents.
  11493. */ (c, a, r) && o.push(n.Cs.updateTargetData(t, a));
  11494. }));
  11495. let u = ws(), c = Rs();
  11496. // HACK: The only reason we allow a null snapshot version is so that we
  11497. // can synthesize remote events when we get permission denied errors while
  11498. // trying to resolve the state of a locally cached document that is in
  11499. // limbo.
  11500. if (e.documentUpdates.forEach((s => {
  11501. e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));
  11502. })),
  11503. // Each loop iteration only affects its "own" doc, so it's safe to get all
  11504. // the remote documents in advance in a single call.
  11505. o.push(zo(t, r, e.documentUpdates).next((t => {
  11506. u = t.Wi, c = t.zi;
  11507. }))), !s.isEqual(it.min())) {
  11508. const e = n.Cs.getLastRemoteSnapshotVersion(t).next((e => n.Cs.setTargetsMetadata(t, t.currentSequenceNumber, s)));
  11509. o.push(e);
  11510. }
  11511. return Rt.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));
  11512. })).then((t => (n.qi = i, t)));
  11513. }
  11514. /**
  11515. * Populates document change buffer with documents from backend or a bundle.
  11516. * Returns the document changes resulting from applying those documents, and
  11517. * also a set of documents whose existence state are changed as a result.
  11518. *
  11519. * @param txn - Transaction to use to read existing documents from storage.
  11520. * @param documentBuffer - Document buffer to collect the resulted changes to be
  11521. * applied to storage.
  11522. * @param documents - Documents to be applied.
  11523. */ function zo(t, e, n) {
  11524. let s = Rs(), i = Rs();
  11525. return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {
  11526. let s = ws();
  11527. return n.forEach(((n, r) => {
  11528. const o = t.get(n);
  11529. // Check if see if there is a existence state change for this document.
  11530. r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)),
  11531. // Note: The order of the steps below is important, since we want
  11532. // to ensure that rejected limbo resolutions (which fabricate
  11533. // NoDocuments with SnapshotVersion.min()) never add documents to
  11534. // cache.
  11535. r.isNoDocument() && r.version.isEqual(it.min()) ? (
  11536. // NoDocuments with SnapshotVersion.min() are used in manufactured
  11537. // events. We remove these documents from cache since we lost
  11538. // access.
  11539. e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r),
  11540. s = s.insert(n, r)) : x("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", r.version);
  11541. })), {
  11542. Wi: s,
  11543. zi: i
  11544. };
  11545. }));
  11546. }
  11547. /**
  11548. * Gets the mutation batch after the passed in batchId in the mutation queue
  11549. * or null if empty.
  11550. * @param afterBatchId - If provided, the batch to search after.
  11551. * @returns The next mutation or null if there wasn't one.
  11552. */
  11553. function Ho(t, e) {
  11554. const n = B(t);
  11555. return n.persistence.runTransaction("Get next mutation batch", "readonly", (t => (void 0 === e && (e = -1),
  11556. n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));
  11557. }
  11558. /**
  11559. * Reads the current value of a Document with a given key or null if not
  11560. * found - used for testing.
  11561. */
  11562. /**
  11563. * Assigns the given target an internal ID so that its results can be pinned so
  11564. * they don't get GC'd. A target must be allocated in the local store before
  11565. * the store can be used to manage its view.
  11566. *
  11567. * Allocating an already allocated `Target` will return the existing `TargetData`
  11568. * for that `Target`.
  11569. */
  11570. function Jo(t, e) {
  11571. const n = B(t);
  11572. return n.persistence.runTransaction("Allocate target", "readwrite", (t => {
  11573. let s;
  11574. return n.Cs.getTargetData(t, e).next((i => i ? (
  11575. // This target has been listened to previously, so reuse the
  11576. // previous targetID.
  11577. // TODO(mcg): freshen last accessed date?
  11578. s = i, Rt.resolve(s)) : n.Cs.allocateTargetId(t).next((i => (s = new Ji(e, i, 0 /* TargetPurpose.Listen */ , t.currentSequenceNumber),
  11579. n.Cs.addTargetData(t, s).next((() => s)))))));
  11580. })).then((t => {
  11581. // If Multi-Tab is enabled, the existing target data may be newer than
  11582. // the in-memory data
  11583. const s = n.qi.get(t.targetId);
  11584. return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.qi = n.qi.insert(t.targetId, t),
  11585. n.Ui.set(e, t.targetId)), t;
  11586. }));
  11587. }
  11588. /**
  11589. * Returns the TargetData as seen by the LocalStore, including updates that may
  11590. * have not yet been persisted to the TargetCache.
  11591. */
  11592. // Visible for testing.
  11593. /**
  11594. * Unpins all the documents associated with the given target. If
  11595. * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
  11596. * directly removes the associated target data from the target cache.
  11597. *
  11598. * Releasing a non-existing `Target` is a no-op.
  11599. */
  11600. // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
  11601. async function Yo(t, e, n) {
  11602. const s = B(t), i = s.qi.get(e), r = n ? "readwrite" : "readwrite-primary";
  11603. try {
  11604. n || await s.persistence.runTransaction("Release target", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));
  11605. } catch (t) {
  11606. if (!St(t)) throw t;
  11607. // All `releaseTarget` does is record the final metadata state for the
  11608. // target, but we've been recording this periodically during target
  11609. // activity. If we lose this write this could cause a very slight
  11610. // difference in the order of target deletion during GC, but we
  11611. // don't define exact LRU semantics so this is acceptable.
  11612. x("LocalStore", `Failed to update sequence numbers for target ${e}: ${t}`);
  11613. }
  11614. s.qi = s.qi.remove(e), s.Ui.delete(i.target);
  11615. }
  11616. /**
  11617. * Runs the specified query against the local store and returns the results,
  11618. * potentially taking advantage of query data from previous executions (such
  11619. * as the set of remote keys).
  11620. *
  11621. * @param usePreviousResults - Whether results from previous executions can
  11622. * be used to optimize this query execution.
  11623. */ function Xo(t, e, n) {
  11624. const s = B(t);
  11625. let i = it.min(), r = Rs();
  11626. return s.persistence.runTransaction("Execute query", "readonly", (t => function(t, e, n) {
  11627. const s = B(t), i = s.Ui.get(n);
  11628. return void 0 !== i ? Rt.resolve(s.qi.get(i)) : s.Cs.getTargetData(e, n);
  11629. }(s, t, pn(e)).next((e => {
  11630. if (e) return i = e.lastLimboFreeSnapshotVersion, s.Cs.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  11631. r = t;
  11632. }));
  11633. })).next((() => s.Li.getDocumentsMatchingQuery(t, e, n ? i : it.min(), n ? r : Rs()))).next((t => (eu(s, Pn(e), t),
  11634. {
  11635. documents: t,
  11636. Hi: r
  11637. })))));
  11638. }
  11639. // PORTING NOTE: Multi-Tab only.
  11640. function Zo(t, e) {
  11641. const n = B(t), s = B(n.Cs), i = n.qi.get(e);
  11642. return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (t => s.ne(t, e).next((t => t ? t.target : null))));
  11643. }
  11644. /**
  11645. * Returns the set of documents that have been updated since the last call.
  11646. * If this is the first call, returns the set of changes since client
  11647. * initialization. Further invocations will return document that have changed
  11648. * since the prior call.
  11649. */
  11650. // PORTING NOTE: Multi-Tab only.
  11651. function tu(t, e) {
  11652. const n = B(t), s = n.Ki.get(e) || it.min();
  11653. // Get the current maximum read time for the collection. This should always
  11654. // exist, but to reduce the chance for regressions we default to
  11655. // SnapshotVersion.Min()
  11656. // TODO(indexing): Consider removing the default value.
  11657. return n.persistence.runTransaction("Get new document changes", "readonly", (t => n.Gi.getAllFromCollectionGroup(t, e, gt(s, -1),
  11658. /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (eu(n, e, t), t)));
  11659. }
  11660. /** Sets the collection group's maximum read time from the given documents. */
  11661. // PORTING NOTE: Multi-Tab only.
  11662. function eu(t, e, n) {
  11663. let s = t.Ki.get(e) || it.min();
  11664. n.forEach(((t, e) => {
  11665. e.readTime.compareTo(s) > 0 && (s = e.readTime);
  11666. })), t.Ki.set(e, s);
  11667. }
  11668. /**
  11669. * Creates a new target using the given bundle name, which will be used to
  11670. * hold the keys of all documents from the bundle in query-document mappings.
  11671. * This ensures that the loaded documents do not get garbage collected
  11672. * right away.
  11673. */
  11674. /**
  11675. * Applies the documents from a bundle to the "ground-state" (remote)
  11676. * documents.
  11677. *
  11678. * LocalDocuments are re-calculated if there are remaining mutations in the
  11679. * queue.
  11680. */
  11681. async function nu(t, e, n, s) {
  11682. const i = B(t);
  11683. let r = Rs(), o = ws();
  11684. for (const t of n) {
  11685. const n = e.Ji(t.metadata.name);
  11686. t.document && (r = r.add(n));
  11687. const s = e.Yi(t);
  11688. s.setReadTime(e.Xi(t.metadata.readTime)), o = o.insert(n, s);
  11689. }
  11690. const u = i.Gi.newChangeBuffer({
  11691. trackRemovals: !0
  11692. }), c = await Jo(i, function(t) {
  11693. // It is OK that the path used for the query is not valid, because this will
  11694. // not be read and queried.
  11695. return pn(dn(ot.fromString(`__bundle__/docs/${t}`)));
  11696. }(s));
  11697. // Allocates a target to hold all document keys from the bundle, such that
  11698. // they will not get garbage collected right away.
  11699. return i.persistence.runTransaction("Apply bundle documents", "readwrite", (t => zo(t, u, o).next((e => (u.apply(t),
  11700. e))).next((e => i.Cs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Cs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.Wi, e.zi))).next((() => e.Wi))))));
  11701. }
  11702. /**
  11703. * Returns a promise of a boolean to indicate if the given bundle has already
  11704. * been loaded and the create time is newer than the current loading bundle.
  11705. */
  11706. /**
  11707. * Saves the given `NamedQuery` to local persistence.
  11708. */
  11709. async function su(t, e, n = Rs()) {
  11710. // Allocate a target for the named query such that it can be resumed
  11711. // from associated read time if users use it to listen.
  11712. // NOTE: this also means if no corresponding target exists, the new target
  11713. // will remain active and will not get collected, unless users happen to
  11714. // unlisten the query somehow.
  11715. const s = await Jo(t, pn(or(e.bundledQuery))), i = B(t);
  11716. return i.persistence.runTransaction("Save named query", "readwrite", (t => {
  11717. const r = Ks(e.readTime);
  11718. // Simply save the query itself if it is older than what the SDK already
  11719. // has.
  11720. if (s.snapshotVersion.compareTo(r) >= 0) return i.Ns.saveNamedQuery(t, e);
  11721. // Update existing target data because the query from the bundle is newer.
  11722. const o = s.withResumeToken(Wt.EMPTY_BYTE_STRING, r);
  11723. return i.qi = i.qi.insert(o.targetId, o), i.Cs.updateTargetData(t, o).next((() => i.Cs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Cs.addMatchingKeys(t, n, s.targetId))).next((() => i.Ns.saveNamedQuery(t, e)));
  11724. }));
  11725. }
  11726. /** Assembles the key for a client state in WebStorage */
  11727. function iu(t, e) {
  11728. return `firestore_clients_${t}_${e}`;
  11729. }
  11730. // The format of the WebStorage key that stores the mutation state is:
  11731. // firestore_mutations_<persistence_prefix>_<batch_id>
  11732. // (for unauthenticated users)
  11733. // or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>
  11734. // 'user_uid' is last to avoid needing to escape '_' characters that it might
  11735. // contain.
  11736. /** Assembles the key for a mutation batch in WebStorage */
  11737. function ru(t, e, n) {
  11738. let s = `firestore_mutations_${t}_${n}`;
  11739. return e.isAuthenticated() && (s += `_${e.uid}`), s;
  11740. }
  11741. // The format of the WebStorage key that stores a query target's metadata is:
  11742. // firestore_targets_<persistence_prefix>_<target_id>
  11743. /** Assembles the key for a query state in WebStorage */
  11744. function ou(t, e) {
  11745. return `firestore_targets_${t}_${e}`;
  11746. }
  11747. // The WebStorage prefix that stores the primary tab's online state. The
  11748. // format of the key is:
  11749. // firestore_online_state_<persistence_prefix>
  11750. /**
  11751. * Holds the state of a mutation batch, including its user ID, batch ID and
  11752. * whether the batch is 'pending', 'acknowledged' or 'rejected'.
  11753. */
  11754. // Visible for testing
  11755. class uu {
  11756. constructor(t, e, n, s) {
  11757. this.user = t, this.batchId = e, this.state = n, this.error = s;
  11758. }
  11759. /**
  11760. * Parses a MutationMetadata from its JSON representation in WebStorage.
  11761. * Logs a warning and returns null if the format of the data is not valid.
  11762. */ static Zi(t, e, n) {
  11763. const s = JSON.parse(n);
  11764. let i, r = "object" == typeof s && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error);
  11765. return r && s.error && (r = "string" == typeof s.error.message && "string" == typeof s.error.code,
  11766. r && (i = new q(s.error.code, s.error.message))), r ? new uu(t, e, s.state, i) : (N("SharedClientState", `Failed to parse mutation state for ID '${e}': ${n}`),
  11767. null);
  11768. }
  11769. tr() {
  11770. const t = {
  11771. state: this.state,
  11772. updateTimeMs: Date.now()
  11773. };
  11774. return this.error && (t.error = {
  11775. code: this.error.code,
  11776. message: this.error.message
  11777. }), JSON.stringify(t);
  11778. }
  11779. }
  11780. /**
  11781. * Holds the state of a query target, including its target ID and whether the
  11782. * target is 'not-current', 'current' or 'rejected'.
  11783. */
  11784. // Visible for testing
  11785. class cu {
  11786. constructor(t, e, n) {
  11787. this.targetId = t, this.state = e, this.error = n;
  11788. }
  11789. /**
  11790. * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
  11791. * Logs a warning and returns null if the format of the data is not valid.
  11792. */ static Zi(t, e) {
  11793. const n = JSON.parse(e);
  11794. let s, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error);
  11795. return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code,
  11796. i && (s = new q(n.error.code, n.error.message))), i ? new cu(t, n.state, s) : (N("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`),
  11797. null);
  11798. }
  11799. tr() {
  11800. const t = {
  11801. state: this.state,
  11802. updateTimeMs: Date.now()
  11803. };
  11804. return this.error && (t.error = {
  11805. code: this.error.code,
  11806. message: this.error.message
  11807. }), JSON.stringify(t);
  11808. }
  11809. }
  11810. /**
  11811. * This class represents the immutable ClientState for a client read from
  11812. * WebStorage, containing the list of active query targets.
  11813. */ class au {
  11814. constructor(t, e) {
  11815. this.clientId = t, this.activeTargetIds = e;
  11816. }
  11817. /**
  11818. * Parses a RemoteClientState from the JSON representation in WebStorage.
  11819. * Logs a warning and returns null if the format of the data is not valid.
  11820. */ static Zi(t, e) {
  11821. const n = JSON.parse(e);
  11822. let s = "object" == typeof n && n.activeTargetIds instanceof Array, i = Ps();
  11823. for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Gt(n.activeTargetIds[t]),
  11824. i = i.add(n.activeTargetIds[t]);
  11825. return s ? new au(t, i) : (N("SharedClientState", `Failed to parse client data for instance '${t}': ${e}`),
  11826. null);
  11827. }
  11828. }
  11829. /**
  11830. * This class represents the online state for all clients participating in
  11831. * multi-tab. The online state is only written to by the primary client, and
  11832. * used in secondary clients to update their query views.
  11833. */ class hu {
  11834. constructor(t, e) {
  11835. this.clientId = t, this.onlineState = e;
  11836. }
  11837. /**
  11838. * Parses a SharedOnlineState from its JSON representation in WebStorage.
  11839. * Logs a warning and returns null if the format of the data is not valid.
  11840. */ static Zi(t) {
  11841. const e = JSON.parse(t);
  11842. return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new hu(e.clientId, e.onlineState) : (N("SharedClientState", `Failed to parse online state: ${t}`),
  11843. null);
  11844. }
  11845. }
  11846. /**
  11847. * Metadata state of the local client. Unlike `RemoteClientState`, this class is
  11848. * mutable and keeps track of all pending mutations, which allows us to
  11849. * update the range of pending mutation batch IDs as new mutations are added or
  11850. * removed.
  11851. *
  11852. * The data in `LocalClientState` is not read from WebStorage and instead
  11853. * updated via its instance methods. The updated state can be serialized via
  11854. * `toWebStorageJSON()`.
  11855. */
  11856. // Visible for testing.
  11857. class lu {
  11858. constructor() {
  11859. this.activeTargetIds = Ps();
  11860. }
  11861. er(t) {
  11862. this.activeTargetIds = this.activeTargetIds.add(t);
  11863. }
  11864. nr(t) {
  11865. this.activeTargetIds = this.activeTargetIds.delete(t);
  11866. }
  11867. /**
  11868. * Converts this entry into a JSON-encoded format we can use for WebStorage.
  11869. * Does not encode `clientId` as it is part of the key in WebStorage.
  11870. */ tr() {
  11871. const t = {
  11872. activeTargetIds: this.activeTargetIds.toArray(),
  11873. updateTimeMs: Date.now()
  11874. };
  11875. return JSON.stringify(t);
  11876. }
  11877. }
  11878. /**
  11879. * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the
  11880. * backing store for the SharedClientState. It keeps track of all active
  11881. * clients and supports modifications of the local client's data.
  11882. */ class fu {
  11883. constructor(t, e, n, s, i) {
  11884. this.window = t, this.Hs = e, this.persistenceKey = n, this.sr = s, this.syncEngine = null,
  11885. this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.ir = this.rr.bind(this),
  11886. this.ur = new je(tt), this.started = !1,
  11887. /**
  11888. * Captures WebStorage events that occur before `start()` is called. These
  11889. * events are replayed once `WebStorageSharedClientState` is started.
  11890. */
  11891. this.cr = [];
  11892. // Escape the special characters mentioned here:
  11893. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  11894. const r = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  11895. this.storage = this.window.localStorage, this.currentUser = i, this.ar = iu(this.persistenceKey, this.sr),
  11896. this.hr =
  11897. /** Assembles the key for the current sequence number. */
  11898. function(t) {
  11899. return `firestore_sequence_number_${t}`;
  11900. }
  11901. /**
  11902. * @license
  11903. * Copyright 2018 Google LLC
  11904. *
  11905. * Licensed under the Apache License, Version 2.0 (the "License");
  11906. * you may not use this file except in compliance with the License.
  11907. * You may obtain a copy of the License at
  11908. *
  11909. * http://www.apache.org/licenses/LICENSE-2.0
  11910. *
  11911. * Unless required by applicable law or agreed to in writing, software
  11912. * distributed under the License is distributed on an "AS IS" BASIS,
  11913. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11914. * See the License for the specific language governing permissions and
  11915. * limitations under the License.
  11916. */ (this.persistenceKey), this.ur = this.ur.insert(this.sr, new lu), this.lr = new RegExp(`^firestore_clients_${r}_([^_]*)$`),
  11917. this.dr = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this._r = new RegExp(`^firestore_targets_${r}_(\\d+)$`),
  11918. this.wr =
  11919. /** Assembles the key for the online state of the primary tab. */
  11920. function(t) {
  11921. return `firestore_online_state_${t}`;
  11922. }
  11923. // The WebStorage prefix that plays as a event to indicate the remote documents
  11924. // might have changed due to some secondary tabs loading a bundle.
  11925. // format of the key is:
  11926. // firestore_bundle_loaded_v2_<persistenceKey>
  11927. // The version ending with "v2" stores the list of modified collection groups.
  11928. (this.persistenceKey), this.mr = function(t) {
  11929. return `firestore_bundle_loaded_v2_${t}`;
  11930. }
  11931. // The WebStorage key prefix for the key that stores the last sequence number allocated. The key
  11932. // looks like 'firestore_sequence_number_<persistence_prefix>'.
  11933. (this.persistenceKey),
  11934. // Rather than adding the storage observer during start(), we add the
  11935. // storage observer during initialization. This ensures that we collect
  11936. // events before other components populate their initial state (during their
  11937. // respective start() calls). Otherwise, we might for example miss a
  11938. // mutation that is added after LocalStore's start() processed the existing
  11939. // mutations but before we observe WebStorage events.
  11940. this.window.addEventListener("storage", this.ir);
  11941. }
  11942. /** Returns 'true' if WebStorage is available in the current environment. */ static C(t) {
  11943. return !(!t || !t.localStorage);
  11944. }
  11945. async start() {
  11946. // Retrieve the list of existing clients to backfill the data in
  11947. // SharedClientState.
  11948. const t = await this.syncEngine.vi();
  11949. for (const e of t) {
  11950. if (e === this.sr) continue;
  11951. const t = this.getItem(iu(this.persistenceKey, e));
  11952. if (t) {
  11953. const n = au.Zi(e, t);
  11954. n && (this.ur = this.ur.insert(n.clientId, n));
  11955. }
  11956. }
  11957. this.gr();
  11958. // Check if there is an existing online state and call the callback handler
  11959. // if applicable.
  11960. const e = this.storage.getItem(this.wr);
  11961. if (e) {
  11962. const t = this.yr(e);
  11963. t && this.pr(t);
  11964. }
  11965. for (const t of this.cr) this.rr(t);
  11966. this.cr = [],
  11967. // Register a window unload hook to remove the client metadata entry from
  11968. // WebStorage even if `shutdown()` was not called.
  11969. this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0;
  11970. }
  11971. writeSequenceNumber(t) {
  11972. this.setItem(this.hr, JSON.stringify(t));
  11973. }
  11974. getAllActiveQueryTargets() {
  11975. return this.Ir(this.ur);
  11976. }
  11977. isActiveQueryTarget(t) {
  11978. let e = !1;
  11979. return this.ur.forEach(((n, s) => {
  11980. s.activeTargetIds.has(t) && (e = !0);
  11981. })), e;
  11982. }
  11983. addPendingMutation(t) {
  11984. this.Tr(t, "pending");
  11985. }
  11986. updateMutationState(t, e, n) {
  11987. this.Tr(t, e, n),
  11988. // Once a final mutation result is observed by other clients, they no longer
  11989. // access the mutation's metadata entry. Since WebStorage replays events
  11990. // in order, it is safe to delete the entry right after updating it.
  11991. this.Er(t);
  11992. }
  11993. addLocalQueryTarget(t) {
  11994. let e = "not-current";
  11995. // Lookup an existing query state if the target ID was already registered
  11996. // by another tab
  11997. if (this.isActiveQueryTarget(t)) {
  11998. const n = this.storage.getItem(ou(this.persistenceKey, t));
  11999. if (n) {
  12000. const s = cu.Zi(t, n);
  12001. s && (e = s.state);
  12002. }
  12003. }
  12004. return this.Ar.er(t), this.gr(), e;
  12005. }
  12006. removeLocalQueryTarget(t) {
  12007. this.Ar.nr(t), this.gr();
  12008. }
  12009. isLocalQueryTarget(t) {
  12010. return this.Ar.activeTargetIds.has(t);
  12011. }
  12012. clearQueryState(t) {
  12013. this.removeItem(ou(this.persistenceKey, t));
  12014. }
  12015. updateQueryState(t, e, n) {
  12016. this.Rr(t, e, n);
  12017. }
  12018. handleUserChange(t, e, n) {
  12019. e.forEach((t => {
  12020. this.Er(t);
  12021. })), this.currentUser = t, n.forEach((t => {
  12022. this.addPendingMutation(t);
  12023. }));
  12024. }
  12025. setOnlineState(t) {
  12026. this.br(t);
  12027. }
  12028. notifyBundleLoaded(t) {
  12029. this.Pr(t);
  12030. }
  12031. shutdown() {
  12032. this.started && (this.window.removeEventListener("storage", this.ir), this.removeItem(this.ar),
  12033. this.started = !1);
  12034. }
  12035. getItem(t) {
  12036. const e = this.storage.getItem(t);
  12037. return x("SharedClientState", "READ", t, e), e;
  12038. }
  12039. setItem(t, e) {
  12040. x("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
  12041. }
  12042. removeItem(t) {
  12043. x("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
  12044. }
  12045. rr(t) {
  12046. // Note: The function is typed to take Event to be interface-compatible with
  12047. // `Window.addEventListener`.
  12048. const e = t;
  12049. if (e.storageArea === this.storage) {
  12050. if (x("SharedClientState", "EVENT", e.key, e.newValue), e.key === this.ar) return void N("Received WebStorage notification for local change. Another client might have garbage-collected our state");
  12051. this.Hs.enqueueRetryable((async () => {
  12052. if (this.started) {
  12053. if (null !== e.key) if (this.lr.test(e.key)) {
  12054. if (null == e.newValue) {
  12055. const t = this.vr(e.key);
  12056. return this.Vr(t, null);
  12057. }
  12058. {
  12059. const t = this.Sr(e.key, e.newValue);
  12060. if (t) return this.Vr(t.clientId, t);
  12061. }
  12062. } else if (this.dr.test(e.key)) {
  12063. if (null !== e.newValue) {
  12064. const t = this.Dr(e.key, e.newValue);
  12065. if (t) return this.Cr(t);
  12066. }
  12067. } else if (this._r.test(e.key)) {
  12068. if (null !== e.newValue) {
  12069. const t = this.Nr(e.key, e.newValue);
  12070. if (t) return this.kr(t);
  12071. }
  12072. } else if (e.key === this.wr) {
  12073. if (null !== e.newValue) {
  12074. const t = this.yr(e.newValue);
  12075. if (t) return this.pr(t);
  12076. }
  12077. } else if (e.key === this.hr) {
  12078. const t = function(t) {
  12079. let e = Mt.at;
  12080. if (null != t) try {
  12081. const n = JSON.parse(t);
  12082. F("number" == typeof n), e = n;
  12083. } catch (t) {
  12084. N("SharedClientState", "Failed to read sequence number from WebStorage", t);
  12085. }
  12086. return e;
  12087. }
  12088. /**
  12089. * `MemorySharedClientState` is a simple implementation of SharedClientState for
  12090. * clients using memory persistence. The state in this class remains fully
  12091. * isolated and no synchronization is performed.
  12092. */ (e.newValue);
  12093. t !== Mt.at && this.sequenceNumberHandler(t);
  12094. } else if (e.key === this.mr) {
  12095. const t = this.Or(e.newValue);
  12096. await Promise.all(t.map((t => this.syncEngine.Mr(t))));
  12097. }
  12098. } else this.cr.push(e);
  12099. }));
  12100. }
  12101. }
  12102. get Ar() {
  12103. return this.ur.get(this.sr);
  12104. }
  12105. gr() {
  12106. this.setItem(this.ar, this.Ar.tr());
  12107. }
  12108. Tr(t, e, n) {
  12109. const s = new uu(this.currentUser, t, e, n), i = ru(this.persistenceKey, this.currentUser, t);
  12110. this.setItem(i, s.tr());
  12111. }
  12112. Er(t) {
  12113. const e = ru(this.persistenceKey, this.currentUser, t);
  12114. this.removeItem(e);
  12115. }
  12116. br(t) {
  12117. const e = {
  12118. clientId: this.sr,
  12119. onlineState: t
  12120. };
  12121. this.storage.setItem(this.wr, JSON.stringify(e));
  12122. }
  12123. Rr(t, e, n) {
  12124. const s = ou(this.persistenceKey, t), i = new cu(t, e, n);
  12125. this.setItem(s, i.tr());
  12126. }
  12127. Pr(t) {
  12128. const e = JSON.stringify(Array.from(t));
  12129. this.setItem(this.mr, e);
  12130. }
  12131. /**
  12132. * Parses a client state key in WebStorage. Returns null if the key does not
  12133. * match the expected key format.
  12134. */ vr(t) {
  12135. const e = this.lr.exec(t);
  12136. return e ? e[1] : null;
  12137. }
  12138. /**
  12139. * Parses a client state in WebStorage. Returns 'null' if the value could not
  12140. * be parsed.
  12141. */ Sr(t, e) {
  12142. const n = this.vr(t);
  12143. return au.Zi(n, e);
  12144. }
  12145. /**
  12146. * Parses a mutation batch state in WebStorage. Returns 'null' if the value
  12147. * could not be parsed.
  12148. */ Dr(t, e) {
  12149. const n = this.dr.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
  12150. return uu.Zi(new v(i), s, e);
  12151. }
  12152. /**
  12153. * Parses a query target state from WebStorage. Returns 'null' if the value
  12154. * could not be parsed.
  12155. */ Nr(t, e) {
  12156. const n = this._r.exec(t), s = Number(n[1]);
  12157. return cu.Zi(s, e);
  12158. }
  12159. /**
  12160. * Parses an online state from WebStorage. Returns 'null' if the value
  12161. * could not be parsed.
  12162. */ yr(t) {
  12163. return hu.Zi(t);
  12164. }
  12165. Or(t) {
  12166. return JSON.parse(t);
  12167. }
  12168. async Cr(t) {
  12169. if (t.user.uid === this.currentUser.uid) return this.syncEngine.Fr(t.batchId, t.state, t.error);
  12170. x("SharedClientState", `Ignoring mutation for non-active user ${t.user.uid}`);
  12171. }
  12172. kr(t) {
  12173. return this.syncEngine.$r(t.targetId, t.state, t.error);
  12174. }
  12175. Vr(t, e) {
  12176. const n = e ? this.ur.insert(t, e) : this.ur.remove(t), s = this.Ir(this.ur), i = this.Ir(n), r = [], o = [];
  12177. return i.forEach((t => {
  12178. s.has(t) || r.push(t);
  12179. })), s.forEach((t => {
  12180. i.has(t) || o.push(t);
  12181. })), this.syncEngine.Br(r, o).then((() => {
  12182. this.ur = n;
  12183. }));
  12184. }
  12185. pr(t) {
  12186. // We check whether the client that wrote this online state is still active
  12187. // by comparing its client ID to the list of clients kept active in
  12188. // IndexedDb. If a client does not update their IndexedDb client state
  12189. // within 5 seconds, it is considered inactive and we don't emit an online
  12190. // state event.
  12191. this.ur.get(t.clientId) && this.onlineStateHandler(t.onlineState);
  12192. }
  12193. Ir(t) {
  12194. let e = Ps();
  12195. return t.forEach(((t, n) => {
  12196. e = e.unionWith(n.activeTargetIds);
  12197. })), e;
  12198. }
  12199. }
  12200. class du {
  12201. constructor() {
  12202. this.Lr = new lu, this.qr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  12203. }
  12204. addPendingMutation(t) {
  12205. // No op.
  12206. }
  12207. updateMutationState(t, e, n) {
  12208. // No op.
  12209. }
  12210. addLocalQueryTarget(t) {
  12211. return this.Lr.er(t), this.qr[t] || "not-current";
  12212. }
  12213. updateQueryState(t, e, n) {
  12214. this.qr[t] = e;
  12215. }
  12216. removeLocalQueryTarget(t) {
  12217. this.Lr.nr(t);
  12218. }
  12219. isLocalQueryTarget(t) {
  12220. return this.Lr.activeTargetIds.has(t);
  12221. }
  12222. clearQueryState(t) {
  12223. delete this.qr[t];
  12224. }
  12225. getAllActiveQueryTargets() {
  12226. return this.Lr.activeTargetIds;
  12227. }
  12228. isActiveQueryTarget(t) {
  12229. return this.Lr.activeTargetIds.has(t);
  12230. }
  12231. start() {
  12232. return this.Lr = new lu, Promise.resolve();
  12233. }
  12234. handleUserChange(t, e, n) {
  12235. // No op.
  12236. }
  12237. setOnlineState(t) {
  12238. // No op.
  12239. }
  12240. shutdown() {}
  12241. writeSequenceNumber(t) {}
  12242. notifyBundleLoaded(t) {
  12243. // No op.
  12244. }
  12245. }
  12246. /**
  12247. * @license
  12248. * Copyright 2019 Google LLC
  12249. *
  12250. * Licensed under the Apache License, Version 2.0 (the "License");
  12251. * you may not use this file except in compliance with the License.
  12252. * You may obtain a copy of the License at
  12253. *
  12254. * http://www.apache.org/licenses/LICENSE-2.0
  12255. *
  12256. * Unless required by applicable law or agreed to in writing, software
  12257. * distributed under the License is distributed on an "AS IS" BASIS,
  12258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12259. * See the License for the specific language governing permissions and
  12260. * limitations under the License.
  12261. */ class _u {
  12262. Ur(t) {
  12263. // No-op.
  12264. }
  12265. shutdown() {
  12266. // No-op.
  12267. }
  12268. }
  12269. /**
  12270. * @license
  12271. * Copyright 2019 Google LLC
  12272. *
  12273. * Licensed under the Apache License, Version 2.0 (the "License");
  12274. * you may not use this file except in compliance with the License.
  12275. * You may obtain a copy of the License at
  12276. *
  12277. * http://www.apache.org/licenses/LICENSE-2.0
  12278. *
  12279. * Unless required by applicable law or agreed to in writing, software
  12280. * distributed under the License is distributed on an "AS IS" BASIS,
  12281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12282. * See the License for the specific language governing permissions and
  12283. * limitations under the License.
  12284. */
  12285. // References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
  12286. /* eslint-disable no-restricted-globals */
  12287. /**
  12288. * Browser implementation of ConnectivityMonitor.
  12289. */
  12290. class wu {
  12291. constructor() {
  12292. this.Kr = () => this.Gr(), this.Qr = () => this.jr(), this.Wr = [], this.zr();
  12293. }
  12294. Ur(t) {
  12295. this.Wr.push(t);
  12296. }
  12297. shutdown() {
  12298. window.removeEventListener("online", this.Kr), window.removeEventListener("offline", this.Qr);
  12299. }
  12300. zr() {
  12301. window.addEventListener("online", this.Kr), window.addEventListener("offline", this.Qr);
  12302. }
  12303. Gr() {
  12304. x("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
  12305. for (const t of this.Wr) t(0 /* NetworkStatus.AVAILABLE */);
  12306. }
  12307. jr() {
  12308. x("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
  12309. for (const t of this.Wr) t(1 /* NetworkStatus.UNAVAILABLE */);
  12310. }
  12311. // TODO(chenbrian): Consider passing in window either into this component or
  12312. // here for testing via FakeWindow.
  12313. /** Checks that all used attributes of window are available. */
  12314. static C() {
  12315. return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  12316. }
  12317. }
  12318. /**
  12319. * @license
  12320. * Copyright 2020 Google LLC
  12321. *
  12322. * Licensed under the Apache License, Version 2.0 (the "License");
  12323. * you may not use this file except in compliance with the License.
  12324. * You may obtain a copy of the License at
  12325. *
  12326. * http://www.apache.org/licenses/LICENSE-2.0
  12327. *
  12328. * Unless required by applicable law or agreed to in writing, software
  12329. * distributed under the License is distributed on an "AS IS" BASIS,
  12330. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12331. * See the License for the specific language governing permissions and
  12332. * limitations under the License.
  12333. */ const mu = {
  12334. BatchGetDocuments: "batchGet",
  12335. Commit: "commit",
  12336. RunQuery: "runQuery",
  12337. RunAggregationQuery: "runAggregationQuery"
  12338. };
  12339. /**
  12340. * Maps RPC names to the corresponding REST endpoint name.
  12341. *
  12342. * We use array notation to avoid mangling.
  12343. */
  12344. /**
  12345. * @license
  12346. * Copyright 2017 Google LLC
  12347. *
  12348. * Licensed under the Apache License, Version 2.0 (the "License");
  12349. * you may not use this file except in compliance with the License.
  12350. * You may obtain a copy of the License at
  12351. *
  12352. * http://www.apache.org/licenses/LICENSE-2.0
  12353. *
  12354. * Unless required by applicable law or agreed to in writing, software
  12355. * distributed under the License is distributed on an "AS IS" BASIS,
  12356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12357. * See the License for the specific language governing permissions and
  12358. * limitations under the License.
  12359. */
  12360. /**
  12361. * Provides a simple helper class that implements the Stream interface to
  12362. * bridge to other implementations that are streams but do not implement the
  12363. * interface. The stream callbacks are invoked with the callOn... methods.
  12364. */
  12365. class gu {
  12366. constructor(t) {
  12367. this.Hr = t.Hr, this.Jr = t.Jr;
  12368. }
  12369. Yr(t) {
  12370. this.Xr = t;
  12371. }
  12372. Zr(t) {
  12373. this.eo = t;
  12374. }
  12375. onMessage(t) {
  12376. this.no = t;
  12377. }
  12378. close() {
  12379. this.Jr();
  12380. }
  12381. send(t) {
  12382. this.Hr(t);
  12383. }
  12384. so() {
  12385. this.Xr();
  12386. }
  12387. io(t) {
  12388. this.eo(t);
  12389. }
  12390. ro(t) {
  12391. this.no(t);
  12392. }
  12393. }
  12394. /**
  12395. * @license
  12396. * Copyright 2017 Google LLC
  12397. *
  12398. * Licensed under the Apache License, Version 2.0 (the "License");
  12399. * you may not use this file except in compliance with the License.
  12400. * You may obtain a copy of the License at
  12401. *
  12402. * http://www.apache.org/licenses/LICENSE-2.0
  12403. *
  12404. * Unless required by applicable law or agreed to in writing, software
  12405. * distributed under the License is distributed on an "AS IS" BASIS,
  12406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12407. * See the License for the specific language governing permissions and
  12408. * limitations under the License.
  12409. */ class yu extends
  12410. /**
  12411. * Base class for all Rest-based connections to the backend (WebChannel and
  12412. * HTTP).
  12413. */
  12414. class {
  12415. constructor(t) {
  12416. this.databaseInfo = t, this.databaseId = t.databaseId;
  12417. const e = t.ssl ? "https" : "http";
  12418. this.oo = e + "://" + t.host, this.uo = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  12419. }
  12420. get co() {
  12421. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  12422. // where to run the query, and expect the `request` to NOT specify the "path".
  12423. return !1;
  12424. }
  12425. ao(t, e, n, s, i) {
  12426. const r = this.ho(t, e);
  12427. x("RestConnection", "Sending: ", r, n);
  12428. const o = {};
  12429. return this.lo(o, s, i), this.fo(t, r, o, n).then((t => (x("RestConnection", "Received: ", t),
  12430. t)), (e => {
  12431. throw k("RestConnection", `${t} failed with error: `, e, "url: ", r, "request:", n),
  12432. e;
  12433. }));
  12434. }
  12435. _o(t, e, n, s, i, r) {
  12436. // The REST API automatically aggregates all of the streamed results, so we
  12437. // can just use the normal invoke() method.
  12438. return this.ao(t, e, n, s, i);
  12439. }
  12440. /**
  12441. * Modifies the headers for a request, adding any authorization token if
  12442. * present and any additional headers for the request.
  12443. */ lo(t, e, n) {
  12444. t["X-Goog-Api-Client"] = "gl-js/ fire/" + V,
  12445. // Content-Type: text/plain will avoid preflight requests which might
  12446. // mess with CORS and redirects by proxies. If we add custom headers
  12447. // we will need to change this code to potentially use the $httpOverwrite
  12448. // parameter supported by ESF to avoid triggering preflight requests.
  12449. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  12450. e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));
  12451. }
  12452. ho(t, e) {
  12453. const n = mu[t];
  12454. return `${this.oo}/v1/${e}:${n}`;
  12455. }
  12456. } {
  12457. constructor(t) {
  12458. super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling,
  12459. this.useFetchStreams = t.useFetchStreams;
  12460. }
  12461. fo(t, e, n, s) {
  12462. return new Promise(((i, r) => {
  12463. const o = new g;
  12464. o.setWithCredentials(!0), o.listenOnce(y.COMPLETE, (() => {
  12465. try {
  12466. switch (o.getLastErrorCode()) {
  12467. case p.NO_ERROR:
  12468. const e = o.getResponseJson();
  12469. x("Connection", "XHR received:", JSON.stringify(e)), i(e);
  12470. break;
  12471. case p.TIMEOUT:
  12472. x("Connection", 'RPC "' + t + '" timed out'), r(new q(L.DEADLINE_EXCEEDED, "Request time out"));
  12473. break;
  12474. case p.HTTP_ERROR:
  12475. const n = o.getStatus();
  12476. if (x("Connection", 'RPC "' + t + '" failed with status:', n, "response text:", o.getResponseText()),
  12477. n > 0) {
  12478. let t = o.getResponseJson();
  12479. Array.isArray(t) && (t = t[0]);
  12480. const e = null == t ? void 0 : t.error;
  12481. if (e && e.status && e.message) {
  12482. const t = function(t) {
  12483. const e = t.toLowerCase().replace(/_/g, "-");
  12484. return Object.values(L).indexOf(e) >= 0 ? e : L.UNKNOWN;
  12485. }(e.status);
  12486. r(new q(t, e.message));
  12487. } else r(new q(L.UNKNOWN, "Server responded with status " + o.getStatus()));
  12488. } else
  12489. // If we received an HTTP_ERROR but there's no status code,
  12490. // it's most probably a connection issue
  12491. r(new q(L.UNAVAILABLE, "Connection failed."));
  12492. break;
  12493. default:
  12494. M();
  12495. }
  12496. } finally {
  12497. x("Connection", 'RPC "' + t + '" completed.');
  12498. }
  12499. }));
  12500. const u = JSON.stringify(s);
  12501. o.send(e, "POST", u, n, 15);
  12502. }));
  12503. }
  12504. wo(t, e, n) {
  12505. const s = [ this.oo, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], i = I(), r = T(), o = {
  12506. // Required for backend stickiness, routing behavior is based on this
  12507. // parameter.
  12508. httpSessionIdParam: "gsessionid",
  12509. initMessageHeaders: {},
  12510. messageUrlParams: {
  12511. // This param is used to improve routing and project isolation by the
  12512. // backend and must be included in every request.
  12513. database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
  12514. },
  12515. sendRawJson: !0,
  12516. supportsCrossDomainXhr: !0,
  12517. internalChannelParams: {
  12518. // Override the default timeout (randomized between 10-20 seconds) since
  12519. // a large write batch on a slow internet connection may take a long
  12520. // time to send to the backend. Rather than have WebChannel impose a
  12521. // tight timeout which could lead to infinite timeouts and retries, we
  12522. // set it very large (5-10 minutes) and rely on the browser's builtin
  12523. // timeouts to kick in if the request isn't working.
  12524. forwardChannelRequestTimeoutMs: 6e5
  12525. },
  12526. forceLongPolling: this.forceLongPolling,
  12527. detectBufferingProxy: this.autoDetectLongPolling
  12528. };
  12529. this.useFetchStreams && (o.xmlHttpFactory = new E({})), this.lo(o.initMessageHeaders, e, n),
  12530. // Sending the custom headers we just added to request.initMessageHeaders
  12531. // (Authorization, etc.) will trigger the browser to make a CORS preflight
  12532. // request because the XHR will no longer meet the criteria for a "simple"
  12533. // CORS request:
  12534. // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
  12535. // Therefore to avoid the CORS preflight request (an extra network
  12536. // roundtrip), we use the encodeInitMessageHeaders option to specify that
  12537. // the headers should instead be encoded in the request's POST payload,
  12538. // which is recognized by the webchannel backend.
  12539. o.encodeInitMessageHeaders = !0;
  12540. const u = s.join("");
  12541. x("Connection", "Creating WebChannel: " + u, o);
  12542. const c = i.createWebChannel(u, o);
  12543. // WebChannel supports sending the first message with the handshake - saving
  12544. // a network round trip. However, it will have to call send in the same
  12545. // JS event loop as open. In order to enforce this, we delay actually
  12546. // opening the WebChannel until send is called. Whether we have called
  12547. // open is tracked with this variable.
  12548. let a = !1, h = !1;
  12549. // A flag to determine whether the stream was closed (by us or through an
  12550. // error/close event) to avoid delivering multiple close events or sending
  12551. // on a closed stream
  12552. const l = new gu({
  12553. Hr: t => {
  12554. h ? x("Connection", "Not sending because WebChannel is closed:", t) : (a || (x("Connection", "Opening WebChannel transport."),
  12555. c.open(), a = !0), x("Connection", "WebChannel sending:", t), c.send(t));
  12556. },
  12557. Jr: () => c.close()
  12558. }), f = (t, e, n) => {
  12559. // TODO(dimond): closure typing seems broken because WebChannel does
  12560. // not implement goog.events.Listenable
  12561. t.listen(e, (t => {
  12562. try {
  12563. n(t);
  12564. } catch (t) {
  12565. setTimeout((() => {
  12566. throw t;
  12567. }), 0);
  12568. }
  12569. }));
  12570. };
  12571. // Closure events are guarded and exceptions are swallowed, so catch any
  12572. // exception and rethrow using a setTimeout so they become visible again.
  12573. // Note that eventually this function could go away if we are confident
  12574. // enough the code is exception free.
  12575. return f(c, A.EventType.OPEN, (() => {
  12576. h || x("Connection", "WebChannel transport opened.");
  12577. })), f(c, A.EventType.CLOSE, (() => {
  12578. h || (h = !0, x("Connection", "WebChannel transport closed"), l.io());
  12579. })), f(c, A.EventType.ERROR, (t => {
  12580. h || (h = !0, k("Connection", "WebChannel transport errored:", t), l.io(new q(L.UNAVAILABLE, "The operation could not be completed")));
  12581. })), f(c, A.EventType.MESSAGE, (t => {
  12582. var e;
  12583. if (!h) {
  12584. const n = t.data[0];
  12585. F(!!n);
  12586. // TODO(b/35143891): There is a bug in One Platform that caused errors
  12587. // (and only errors) to be wrapped in an extra array. To be forward
  12588. // compatible with the bug we need to check either condition. The latter
  12589. // can be removed once the fix has been rolled out.
  12590. // Use any because msgData.error is not typed.
  12591. const s = n, i = s.error || (null === (e = s[0]) || void 0 === e ? void 0 : e.error);
  12592. if (i) {
  12593. x("Connection", "WebChannel received error:", i);
  12594. // error.status will be a string like 'OK' or 'NOT_FOUND'.
  12595. const t = i.status;
  12596. let e =
  12597. /**
  12598. * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
  12599. *
  12600. * @returns The Code equivalent to the given status string or undefined if
  12601. * there is no match.
  12602. */
  12603. function(t) {
  12604. // lookup by string
  12605. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12606. const e = as[t];
  12607. if (void 0 !== e) return fs(e);
  12608. }(t), n = i.message;
  12609. void 0 === e && (e = L.INTERNAL, n = "Unknown error status: " + t + " with message " + i.message),
  12610. // Mark closed so no further events are propagated
  12611. h = !0, l.io(new q(e, n)), c.close();
  12612. } else x("Connection", "WebChannel received:", n), l.ro(n);
  12613. }
  12614. })), f(r, R.STAT_EVENT, (t => {
  12615. t.stat === b.PROXY ? x("Connection", "Detected buffering proxy") : t.stat === b.NOPROXY && x("Connection", "Detected no buffering proxy");
  12616. })), setTimeout((() => {
  12617. // Technically we could/should wait for the WebChannel opened event,
  12618. // but because we want to send the first message with the WebChannel
  12619. // handshake we pretend the channel opened here (asynchronously), and
  12620. // then delay the actual open until the first message is sent.
  12621. l.so();
  12622. }), 0), l;
  12623. }
  12624. }
  12625. /**
  12626. * @license
  12627. * Copyright 2020 Google LLC
  12628. *
  12629. * Licensed under the Apache License, Version 2.0 (the "License");
  12630. * you may not use this file except in compliance with the License.
  12631. * You may obtain a copy of the License at
  12632. *
  12633. * http://www.apache.org/licenses/LICENSE-2.0
  12634. *
  12635. * Unless required by applicable law or agreed to in writing, software
  12636. * distributed under the License is distributed on an "AS IS" BASIS,
  12637. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12638. * See the License for the specific language governing permissions and
  12639. * limitations under the License.
  12640. */
  12641. /** Initializes the WebChannelConnection for the browser. */
  12642. /**
  12643. * @license
  12644. * Copyright 2020 Google LLC
  12645. *
  12646. * Licensed under the Apache License, Version 2.0 (the "License");
  12647. * you may not use this file except in compliance with the License.
  12648. * You may obtain a copy of the License at
  12649. *
  12650. * http://www.apache.org/licenses/LICENSE-2.0
  12651. *
  12652. * Unless required by applicable law or agreed to in writing, software
  12653. * distributed under the License is distributed on an "AS IS" BASIS,
  12654. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12655. * See the License for the specific language governing permissions and
  12656. * limitations under the License.
  12657. */
  12658. /** The Platform's 'window' implementation or null if not available. */
  12659. function pu() {
  12660. // `window` is not always available, e.g. in ReactNative and WebWorkers.
  12661. // eslint-disable-next-line no-restricted-globals
  12662. return "undefined" != typeof window ? window : null;
  12663. }
  12664. /** The Platform's 'document' implementation or null if not available. */ function Iu() {
  12665. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  12666. // eslint-disable-next-line no-restricted-globals
  12667. return "undefined" != typeof document ? document : null;
  12668. }
  12669. /**
  12670. * @license
  12671. * Copyright 2020 Google LLC
  12672. *
  12673. * Licensed under the Apache License, Version 2.0 (the "License");
  12674. * you may not use this file except in compliance with the License.
  12675. * You may obtain a copy of the License at
  12676. *
  12677. * http://www.apache.org/licenses/LICENSE-2.0
  12678. *
  12679. * Unless required by applicable law or agreed to in writing, software
  12680. * distributed under the License is distributed on an "AS IS" BASIS,
  12681. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12682. * See the License for the specific language governing permissions and
  12683. * limitations under the License.
  12684. */ function Tu(t) {
  12685. return new Bs(t, /* useProto3Json= */ !0);
  12686. }
  12687. /**
  12688. * An instance of the Platform's 'TextEncoder' implementation.
  12689. */
  12690. /**
  12691. * A helper for running delayed tasks following an exponential backoff curve
  12692. * between attempts.
  12693. *
  12694. * Each delay is made up of a "base" delay which follows the exponential
  12695. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  12696. * base delay. This prevents clients from accidentally synchronizing their
  12697. * delays causing spikes of load to the backend.
  12698. */
  12699. class Eu {
  12700. constructor(
  12701. /**
  12702. * The AsyncQueue to run backoff operations on.
  12703. */
  12704. t,
  12705. /**
  12706. * The ID to use when scheduling backoff operations on the AsyncQueue.
  12707. */
  12708. e,
  12709. /**
  12710. * The initial delay (used as the base delay on the first retry attempt).
  12711. * Note that jitter will still be applied, so the actual delay could be as
  12712. * little as 0.5*initialDelayMs.
  12713. */
  12714. n = 1e3
  12715. /**
  12716. * The multiplier to use to determine the extended base delay after each
  12717. * attempt.
  12718. */ , s = 1.5
  12719. /**
  12720. * The maximum base delay after which no further backoff is performed.
  12721. * Note that jitter will still be applied, so the actual delay could be as
  12722. * much as 1.5*maxDelayMs.
  12723. */ , i = 6e4) {
  12724. this.Hs = t, this.timerId = e, this.mo = n, this.yo = s, this.po = i, this.Io = 0,
  12725. this.To = null,
  12726. /** The last backoff attempt, as epoch milliseconds. */
  12727. this.Eo = Date.now(), this.reset();
  12728. }
  12729. /**
  12730. * Resets the backoff delay.
  12731. *
  12732. * The very next backoffAndWait() will have no delay. If it is called again
  12733. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  12734. * subsequent ones will increase according to the backoffFactor.
  12735. */ reset() {
  12736. this.Io = 0;
  12737. }
  12738. /**
  12739. * Resets the backoff delay to the maximum delay (e.g. for use after a
  12740. * RESOURCE_EXHAUSTED error).
  12741. */ Ao() {
  12742. this.Io = this.po;
  12743. }
  12744. /**
  12745. * Returns a promise that resolves after currentDelayMs, and increases the
  12746. * delay for any subsequent attempts. If there was a pending backoff operation
  12747. * already, it will be canceled.
  12748. */ Ro(t) {
  12749. // Cancel any pending backoff operation.
  12750. this.cancel();
  12751. // First schedule using the current base (which may be 0 and should be
  12752. // honored as such).
  12753. const e = Math.floor(this.Io + this.bo()), n = Math.max(0, Date.now() - this.Eo), s = Math.max(0, e - n);
  12754. // Guard against lastAttemptTime being in the future due to a clock change.
  12755. s > 0 && x("ExponentialBackoff", `Backing off for ${s} ms (base delay: ${this.Io} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),
  12756. this.To = this.Hs.enqueueAfterDelay(this.timerId, s, (() => (this.Eo = Date.now(),
  12757. t()))),
  12758. // Apply backoff factor to determine next delay and ensure it is within
  12759. // bounds.
  12760. this.Io *= this.yo, this.Io < this.mo && (this.Io = this.mo), this.Io > this.po && (this.Io = this.po);
  12761. }
  12762. Po() {
  12763. null !== this.To && (this.To.skipDelay(), this.To = null);
  12764. }
  12765. cancel() {
  12766. null !== this.To && (this.To.cancel(), this.To = null);
  12767. }
  12768. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ bo() {
  12769. return (Math.random() - .5) * this.Io;
  12770. }
  12771. }
  12772. /**
  12773. * @license
  12774. * Copyright 2017 Google LLC
  12775. *
  12776. * Licensed under the Apache License, Version 2.0 (the "License");
  12777. * you may not use this file except in compliance with the License.
  12778. * You may obtain a copy of the License at
  12779. *
  12780. * http://www.apache.org/licenses/LICENSE-2.0
  12781. *
  12782. * Unless required by applicable law or agreed to in writing, software
  12783. * distributed under the License is distributed on an "AS IS" BASIS,
  12784. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12785. * See the License for the specific language governing permissions and
  12786. * limitations under the License.
  12787. */
  12788. /**
  12789. * A PersistentStream is an abstract base class that represents a streaming RPC
  12790. * to the Firestore backend. It's built on top of the connections own support
  12791. * for streaming RPCs, and adds several critical features for our clients:
  12792. *
  12793. * - Exponential backoff on failure
  12794. * - Authentication via CredentialsProvider
  12795. * - Dispatching all callbacks into the shared worker queue
  12796. * - Closing idle streams after 60 seconds of inactivity
  12797. *
  12798. * Subclasses of PersistentStream implement serialization of models to and
  12799. * from the JSON representation of the protocol buffers for a specific
  12800. * streaming RPC.
  12801. *
  12802. * ## Starting and Stopping
  12803. *
  12804. * Streaming RPCs are stateful and need to be start()ed before messages can
  12805. * be sent and received. The PersistentStream will call the onOpen() function
  12806. * of the listener once the stream is ready to accept requests.
  12807. *
  12808. * Should a start() fail, PersistentStream will call the registered onClose()
  12809. * listener with a FirestoreError indicating what went wrong.
  12810. *
  12811. * A PersistentStream can be started and stopped repeatedly.
  12812. *
  12813. * Generic types:
  12814. * SendType: The type of the outgoing message of the underlying
  12815. * connection stream
  12816. * ReceiveType: The type of the incoming message of the underlying
  12817. * connection stream
  12818. * ListenerType: The type of the listener that will be used for callbacks
  12819. */
  12820. class Au {
  12821. constructor(t, e, n, s, i, r, o, u) {
  12822. this.Hs = t, this.vo = n, this.Vo = s, this.connection = i, this.authCredentialsProvider = r,
  12823. this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ ,
  12824. /**
  12825. * A close count that's incremented every time the stream is closed; used by
  12826. * getCloseGuardedDispatcher() to invalidate callbacks that happen after
  12827. * close.
  12828. */
  12829. this.So = 0, this.Do = null, this.Co = null, this.stream = null, this.xo = new Eu(t, e);
  12830. }
  12831. /**
  12832. * Returns true if start() has been called and no error has occurred. True
  12833. * indicates the stream is open or in the process of opening (which
  12834. * encompasses respecting backoff, getting auth tokens, and starting the
  12835. * actual RPC). Use isOpen() to determine if the stream is open and ready for
  12836. * outbound requests.
  12837. */ No() {
  12838. return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.ko();
  12839. }
  12840. /**
  12841. * Returns true if the underlying RPC is open (the onOpen() listener has been
  12842. * called) and the stream is ready for outbound requests.
  12843. */ ko() {
  12844. return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
  12845. }
  12846. /**
  12847. * Starts the RPC. Only allowed if isStarted() returns false. The stream is
  12848. * not immediately ready for use: onOpen() will be invoked when the RPC is
  12849. * ready for outbound requests, at which point isOpen() will return true.
  12850. *
  12851. * When start returns, isStarted() will return true.
  12852. */ start() {
  12853. 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Oo();
  12854. }
  12855. /**
  12856. * Stops the RPC. This call is idempotent and allowed regardless of the
  12857. * current isStarted() state.
  12858. *
  12859. * When stop returns, isStarted() and isOpen() will both return false.
  12860. */ async stop() {
  12861. this.No() && await this.close(0 /* PersistentStreamState.Initial */);
  12862. }
  12863. /**
  12864. * After an error the stream will usually back off on the next attempt to
  12865. * start it. If the error warrants an immediate restart of the stream, the
  12866. * sender can use this to indicate that the receiver should not back off.
  12867. *
  12868. * Each error will call the onClose() listener. That function can decide to
  12869. * inhibit backoff if required.
  12870. */ Mo() {
  12871. this.state = 0 /* PersistentStreamState.Initial */ , this.xo.reset();
  12872. }
  12873. /**
  12874. * Marks this stream as idle. If no further actions are performed on the
  12875. * stream for one minute, the stream will automatically close itself and
  12876. * notify the stream's onClose() handler with Status.OK. The stream will then
  12877. * be in a !isStarted() state, requiring the caller to start the stream again
  12878. * before further use.
  12879. *
  12880. * Only streams that are in state 'Open' can be marked idle, as all other
  12881. * states imply pending network operations.
  12882. */ Fo() {
  12883. // Starts the idle time if we are in state 'Open' and are not yet already
  12884. // running a timer (in which case the previous idle timeout still applies).
  12885. this.ko() && null === this.Do && (this.Do = this.Hs.enqueueAfterDelay(this.vo, 6e4, (() => this.$o())));
  12886. }
  12887. /** Sends a message to the underlying stream. */ Bo(t) {
  12888. this.Lo(), this.stream.send(t);
  12889. }
  12890. /** Called by the idle timer when the stream should close due to inactivity. */ async $o() {
  12891. if (this.ko())
  12892. // When timing out an idle stream there's no reason to force the stream into backoff when
  12893. // it restarts so set the stream state to Initial instead of Error.
  12894. return this.close(0 /* PersistentStreamState.Initial */);
  12895. }
  12896. /** Marks the stream as active again. */ Lo() {
  12897. this.Do && (this.Do.cancel(), this.Do = null);
  12898. }
  12899. /** Cancels the health check delayed operation. */ qo() {
  12900. this.Co && (this.Co.cancel(), this.Co = null);
  12901. }
  12902. /**
  12903. * Closes the stream and cleans up as necessary:
  12904. *
  12905. * * closes the underlying GRPC stream;
  12906. * * calls the onClose handler with the given 'error';
  12907. * * sets internal stream state to 'finalState';
  12908. * * adjusts the backoff timer based on the error
  12909. *
  12910. * A new stream can be opened by calling start().
  12911. *
  12912. * @param finalState - the intended state of the stream after closing.
  12913. * @param error - the error the connection was closed with.
  12914. */ async close(t, e) {
  12915. // Cancel any outstanding timers (they're guaranteed not to execute).
  12916. this.Lo(), this.qo(), this.xo.cancel(),
  12917. // Invalidates any stream-related callbacks (e.g. from auth or the
  12918. // underlying stream), guaranteeing they won't execute.
  12919. this.So++, 4 /* PersistentStreamState.Error */ !== t ?
  12920. // If this is an intentional close ensure we don't delay our next connection attempt.
  12921. this.xo.reset() : e && e.code === L.RESOURCE_EXHAUSTED ? (
  12922. // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
  12923. N(e.toString()), N("Using maximum backoff delay to prevent overloading the backend."),
  12924. this.xo.Ao()) : e && e.code === L.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
  12925. // "unauthenticated" error means the token was rejected. This should rarely
  12926. // happen since both Auth and AppCheck ensure a sufficient TTL when we
  12927. // request a token. If a user manually resets their system clock this can
  12928. // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
  12929. // before we received the first message and we need to invalidate the token
  12930. // to ensure that we fetch a new token.
  12931. this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()),
  12932. // Clean up the underlying stream because we are no longer interested in events.
  12933. null !== this.stream && (this.Uo(), this.stream.close(), this.stream = null),
  12934. // This state must be assigned before calling onClose() to allow the callback to
  12935. // inhibit backoff or otherwise manipulate the state in its non-started state.
  12936. this.state = t,
  12937. // Notify the listener that the stream closed.
  12938. await this.listener.Zr(e);
  12939. }
  12940. /**
  12941. * Can be overridden to perform additional cleanup before the stream is closed.
  12942. * Calling super.tearDown() is not required.
  12943. */ Uo() {}
  12944. auth() {
  12945. this.state = 1 /* PersistentStreamState.Starting */;
  12946. const t = this.Ko(this.So), e = this.So;
  12947. // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
  12948. Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {
  12949. // Stream can be stopped while waiting for authentication.
  12950. // TODO(mikelehen): We really should just use dispatchIfNotClosed
  12951. // and let this dispatch onto the queue, but that opened a spec test can
  12952. // of worms that I don't want to deal with in this PR.
  12953. this.So === e &&
  12954. // Normally we'd have to schedule the callback on the AsyncQueue.
  12955. // However, the following calls are safe to be called outside the
  12956. // AsyncQueue since they don't chain asynchronous calls
  12957. this.Go(t, n);
  12958. }), (e => {
  12959. t((() => {
  12960. const t = new q(L.UNKNOWN, "Fetching auth token failed: " + e.message);
  12961. return this.Qo(t);
  12962. }));
  12963. }));
  12964. }
  12965. Go(t, e) {
  12966. const n = this.Ko(this.So);
  12967. this.stream = this.jo(t, e), this.stream.Yr((() => {
  12968. n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Co = this.Hs.enqueueAfterDelay(this.Vo, 1e4, (() => (this.ko() && (this.state = 3 /* PersistentStreamState.Healthy */),
  12969. Promise.resolve()))), this.listener.Yr())));
  12970. })), this.stream.Zr((t => {
  12971. n((() => this.Qo(t)));
  12972. })), this.stream.onMessage((t => {
  12973. n((() => this.onMessage(t)));
  12974. }));
  12975. }
  12976. Oo() {
  12977. this.state = 5 /* PersistentStreamState.Backoff */ , this.xo.Ro((async () => {
  12978. this.state = 0 /* PersistentStreamState.Initial */ , this.start();
  12979. }));
  12980. }
  12981. // Visible for tests
  12982. Qo(t) {
  12983. // In theory the stream could close cleanly, however, in our current model
  12984. // we never expect this to happen because if we stop a stream ourselves,
  12985. // this callback will never be called. To prevent cases where we retry
  12986. // without a backoff accidentally, we set the stream to error in all cases.
  12987. return x("PersistentStream", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);
  12988. }
  12989. /**
  12990. * Returns a "dispatcher" function that dispatches operations onto the
  12991. * AsyncQueue but only runs them if closeCount remains unchanged. This allows
  12992. * us to turn auth / stream callbacks into no-ops if the stream is closed /
  12993. * re-opened, etc.
  12994. */ Ko(t) {
  12995. return e => {
  12996. this.Hs.enqueueAndForget((() => this.So === t ? e() : (x("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."),
  12997. Promise.resolve())));
  12998. };
  12999. }
  13000. }
  13001. /**
  13002. * A PersistentStream that implements the Listen RPC.
  13003. *
  13004. * Once the Listen stream has called the onOpen() listener, any number of
  13005. * listen() and unlisten() calls can be made to control what changes will be
  13006. * sent from the server for ListenResponses.
  13007. */ class Ru extends Au {
  13008. constructor(t, e, n, s, i, r) {
  13009. super(t, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13010. this.yt = i;
  13011. }
  13012. jo(t, e) {
  13013. return this.connection.wo("Listen", t, e);
  13014. }
  13015. onMessage(t) {
  13016. // A successful response means the stream is healthy
  13017. this.xo.reset();
  13018. const e = ei(this.yt, t), n = function(t) {
  13019. // We have only reached a consistent snapshot for the entire stream if there
  13020. // is a read_time set and it applies to all targets (i.e. the list of
  13021. // targets is empty). The backend is guaranteed to send such responses.
  13022. if (!("targetChange" in t)) return it.min();
  13023. const e = t.targetChange;
  13024. return e.targetIds && e.targetIds.length ? it.min() : e.readTime ? Ks(e.readTime) : it.min();
  13025. }(t);
  13026. return this.listener.Wo(e, n);
  13027. }
  13028. /**
  13029. * Registers interest in the results of the given target. If the target
  13030. * includes a resumeToken it will be included in the request. Results that
  13031. * affect the target will be streamed back as WatchChange messages that
  13032. * reference the targetId.
  13033. */ zo(t) {
  13034. const e = {};
  13035. e.database = Js(this.yt), e.addTarget = function(t, e) {
  13036. let n;
  13037. const s = e.target;
  13038. return n = un(s) ? {
  13039. documents: ri(t, s)
  13040. } : {
  13041. query: oi(t, s)
  13042. }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0 ? n.resumeToken = qs(t, e.resumeToken) : e.snapshotVersion.compareTo(it.min()) > 0 && (
  13043. // TODO(wuandy): Consider removing above check because it is most likely true.
  13044. // Right now, many tests depend on this behaviour though (leaving min() out
  13045. // of serialization).
  13046. n.readTime = Ls(t, e.snapshotVersion.toTimestamp())), n;
  13047. }(this.yt, t);
  13048. const n = ci(this.yt, t);
  13049. n && (e.labels = n), this.Bo(e);
  13050. }
  13051. /**
  13052. * Unregisters interest in the results of the target associated with the
  13053. * given targetId.
  13054. */ Ho(t) {
  13055. const e = {};
  13056. e.database = Js(this.yt), e.removeTarget = t, this.Bo(e);
  13057. }
  13058. }
  13059. /**
  13060. * A Stream that implements the Write RPC.
  13061. *
  13062. * The Write RPC requires the caller to maintain special streamToken
  13063. * state in between calls, to help the server understand which responses the
  13064. * client has processed by the time the next request is made. Every response
  13065. * will contain a streamToken; this value must be passed to the next
  13066. * request.
  13067. *
  13068. * After calling start() on this stream, the next request must be a handshake,
  13069. * containing whatever streamToken is on hand. Once a response to this
  13070. * request is received, all pending mutations may be submitted. When
  13071. * submitting multiple batches of mutations at the same time, it's
  13072. * okay to use the same streamToken for the calls to writeMutations.
  13073. *
  13074. * TODO(b/33271235): Use proto types
  13075. */ class bu extends Au {
  13076. constructor(t, e, n, s, i, r) {
  13077. super(t, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13078. this.yt = i, this.Jo = !1;
  13079. }
  13080. /**
  13081. * Tracks whether or not a handshake has been successfully exchanged and
  13082. * the stream is ready to accept mutations.
  13083. */ get Yo() {
  13084. return this.Jo;
  13085. }
  13086. // Override of PersistentStream.start
  13087. start() {
  13088. this.Jo = !1, this.lastStreamToken = void 0, super.start();
  13089. }
  13090. Uo() {
  13091. this.Jo && this.Xo([]);
  13092. }
  13093. jo(t, e) {
  13094. return this.connection.wo("Write", t, e);
  13095. }
  13096. onMessage(t) {
  13097. if (
  13098. // Always capture the last stream token.
  13099. F(!!t.streamToken), this.lastStreamToken = t.streamToken, this.Jo) {
  13100. // A successful first write response means the stream is healthy,
  13101. // Note, that we could consider a successful handshake healthy, however,
  13102. // the write itself might be causing an error we want to back off from.
  13103. this.xo.reset();
  13104. const e = ii(t.writeResults, t.commitTime), n = Ks(t.commitTime);
  13105. return this.listener.Zo(n, e);
  13106. }
  13107. // The first response is always the handshake response
  13108. return F(!t.writeResults || 0 === t.writeResults.length), this.Jo = !0, this.listener.tu();
  13109. }
  13110. /**
  13111. * Sends an initial streamToken to the server, performing the handshake
  13112. * required to make the StreamingWrite RPC work. Subsequent
  13113. * calls should wait until onHandshakeComplete was called.
  13114. */ eu() {
  13115. // TODO(dimond): Support stream resumption. We intentionally do not set the
  13116. // stream token on the handshake, ignoring any stream token we might have.
  13117. const t = {};
  13118. t.database = Js(this.yt), this.Bo(t);
  13119. }
  13120. /** Sends a group of mutations to the Firestore backend to apply. */ Xo(t) {
  13121. const e = {
  13122. streamToken: this.lastStreamToken,
  13123. writes: t.map((t => ni(this.yt, t)))
  13124. };
  13125. this.Bo(e);
  13126. }
  13127. }
  13128. /**
  13129. * @license
  13130. * Copyright 2017 Google LLC
  13131. *
  13132. * Licensed under the Apache License, Version 2.0 (the "License");
  13133. * you may not use this file except in compliance with the License.
  13134. * You may obtain a copy of the License at
  13135. *
  13136. * http://www.apache.org/licenses/LICENSE-2.0
  13137. *
  13138. * Unless required by applicable law or agreed to in writing, software
  13139. * distributed under the License is distributed on an "AS IS" BASIS,
  13140. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13141. * See the License for the specific language governing permissions and
  13142. * limitations under the License.
  13143. */
  13144. /**
  13145. * Datastore and its related methods are a wrapper around the external Google
  13146. * Cloud Datastore grpc API, which provides an interface that is more convenient
  13147. * for the rest of the client SDK architecture to consume.
  13148. */
  13149. /**
  13150. * An implementation of Datastore that exposes additional state for internal
  13151. * consumption.
  13152. */
  13153. class Pu extends class {} {
  13154. constructor(t, e, n, s) {
  13155. super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n,
  13156. this.yt = s, this.nu = !1;
  13157. }
  13158. su() {
  13159. if (this.nu) throw new q(L.FAILED_PRECONDITION, "The client has already been terminated.");
  13160. }
  13161. /** Invokes the provided RPC with auth and AppCheck tokens. */ ao(t, e, n) {
  13162. return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.ao(t, e, n, s, i))).catch((t => {
  13163. throw "FirebaseError" === t.name ? (t.code === L.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13164. this.appCheckCredentials.invalidateToken()), t) : new q(L.UNKNOWN, t.toString());
  13165. }));
  13166. }
  13167. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ _o(t, e, n, s) {
  13168. return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection._o(t, e, n, i, r, s))).catch((t => {
  13169. throw "FirebaseError" === t.name ? (t.code === L.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13170. this.appCheckCredentials.invalidateToken()), t) : new q(L.UNKNOWN, t.toString());
  13171. }));
  13172. }
  13173. terminate() {
  13174. this.nu = !0;
  13175. }
  13176. }
  13177. // TODO(firestorexp): Make sure there is only one Datastore instance per
  13178. // firestore-exp client.
  13179. async function vu(t, e) {
  13180. const n = B(t), s = function(t, e) {
  13181. const n = oi(t, e);
  13182. return {
  13183. structuredAggregationQuery: {
  13184. aggregations: [ {
  13185. count: {},
  13186. alias: "count_alias"
  13187. } ],
  13188. structuredQuery: n.structuredQuery
  13189. },
  13190. parent: n.parent
  13191. };
  13192. }(n.yt, pn(e)), i = s.parent;
  13193. n.connection.co || delete s.parent;
  13194. return (await n._o("RunAggregationQuery", i, s, /*expectedResponseCount=*/ 1)).filter((t => !!t.result)).map((t => t.result.aggregateFields));
  13195. }
  13196. /**
  13197. * A component used by the RemoteStore to track the OnlineState (that is,
  13198. * whether or not the client as a whole should be considered to be online or
  13199. * offline), implementing the appropriate heuristics.
  13200. *
  13201. * In particular, when the client is trying to connect to the backend, we
  13202. * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
  13203. * a connection to succeed. If we have too many failures or the timeout elapses,
  13204. * then we set the OnlineState to Offline, and the client will behave as if
  13205. * it is offline (get()s will return cached data, etc.).
  13206. */
  13207. class Vu {
  13208. constructor(t, e) {
  13209. this.asyncQueue = t, this.onlineStateHandler = e,
  13210. /** The current OnlineState. */
  13211. this.state = "Unknown" /* OnlineState.Unknown */ ,
  13212. /**
  13213. * A count of consecutive failures to open the stream. If it reaches the
  13214. * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
  13215. * Offline.
  13216. */
  13217. this.iu = 0,
  13218. /**
  13219. * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
  13220. * transition from OnlineState.Unknown to OnlineState.Offline without waiting
  13221. * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
  13222. */
  13223. this.ru = null,
  13224. /**
  13225. * Whether the client should log a warning message if it fails to connect to
  13226. * the backend (initially true, cleared after a successful stream, or if we've
  13227. * logged the message already).
  13228. */
  13229. this.ou = !0;
  13230. }
  13231. /**
  13232. * Called by RemoteStore when a watch stream is started (including on each
  13233. * backoff attempt).
  13234. *
  13235. * If this is the first attempt, it sets the OnlineState to Unknown and starts
  13236. * the onlineStateTimer.
  13237. */ uu() {
  13238. 0 === this.iu && (this.cu("Unknown" /* OnlineState.Unknown */), this.ru = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.ru = null,
  13239. this.au("Backend didn't respond within 10 seconds."), this.cu("Offline" /* OnlineState.Offline */),
  13240. Promise.resolve()))));
  13241. }
  13242. /**
  13243. * Updates our OnlineState as appropriate after the watch stream reports a
  13244. * failure. The first failure moves us to the 'Unknown' state. We then may
  13245. * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
  13246. * actually transition to the 'Offline' state.
  13247. */ hu(t) {
  13248. "Online" /* OnlineState.Online */ === this.state ? this.cu("Unknown" /* OnlineState.Unknown */) : (this.iu++,
  13249. this.iu >= 1 && (this.lu(), this.au(`Connection failed 1 times. Most recent error: ${t.toString()}`),
  13250. this.cu("Offline" /* OnlineState.Offline */)));
  13251. }
  13252. /**
  13253. * Explicitly sets the OnlineState to the specified state.
  13254. *
  13255. * Note that this resets our timers / failure counters, etc. used by our
  13256. * Offline heuristics, so must not be used in place of
  13257. * handleWatchStreamStart() and handleWatchStreamFailure().
  13258. */ set(t) {
  13259. this.lu(), this.iu = 0, "Online" /* OnlineState.Online */ === t && (
  13260. // We've connected to watch at least once. Don't warn the developer
  13261. // about being offline going forward.
  13262. this.ou = !1), this.cu(t);
  13263. }
  13264. cu(t) {
  13265. t !== this.state && (this.state = t, this.onlineStateHandler(t));
  13266. }
  13267. au(t) {
  13268. const e = `Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
  13269. this.ou ? (N(e), this.ou = !1) : x("OnlineStateTracker", e);
  13270. }
  13271. lu() {
  13272. null !== this.ru && (this.ru.cancel(), this.ru = null);
  13273. }
  13274. }
  13275. /**
  13276. * @license
  13277. * Copyright 2017 Google LLC
  13278. *
  13279. * Licensed under the Apache License, Version 2.0 (the "License");
  13280. * you may not use this file except in compliance with the License.
  13281. * You may obtain a copy of the License at
  13282. *
  13283. * http://www.apache.org/licenses/LICENSE-2.0
  13284. *
  13285. * Unless required by applicable law or agreed to in writing, software
  13286. * distributed under the License is distributed on an "AS IS" BASIS,
  13287. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13288. * See the License for the specific language governing permissions and
  13289. * limitations under the License.
  13290. */ class Su {
  13291. constructor(
  13292. /**
  13293. * The local store, used to fill the write pipeline with outbound mutations.
  13294. */
  13295. t,
  13296. /** The client-side proxy for interacting with the backend. */
  13297. e, n, s, i) {
  13298. this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {},
  13299. /**
  13300. * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
  13301. * LocalStore via fillWritePipeline() and have or will send to the write
  13302. * stream.
  13303. *
  13304. * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
  13305. * restart the write stream. When the stream is established the writes in the
  13306. * pipeline will be sent in order.
  13307. *
  13308. * Writes remain in writePipeline until they are acknowledged by the backend
  13309. * and thus will automatically be re-sent if the stream is interrupted /
  13310. * restarted before they're acknowledged.
  13311. *
  13312. * Write responses from the backend are linked to their originating request
  13313. * purely based on order, and so we can just shift() writes from the front of
  13314. * the writePipeline as we receive responses.
  13315. */
  13316. this.fu = [],
  13317. /**
  13318. * A mapping of watched targets that the client cares about tracking and the
  13319. * user has explicitly called a 'listen' for this target.
  13320. *
  13321. * These targets may or may not have been sent to or acknowledged by the
  13322. * server. On re-establishing the listen stream, these targets should be sent
  13323. * to the server. The targets removed with unlistens are removed eagerly
  13324. * without waiting for confirmation from the listen stream.
  13325. */
  13326. this.du = new Map,
  13327. /**
  13328. * A set of reasons for why the RemoteStore may be offline. If empty, the
  13329. * RemoteStore may start its network connections.
  13330. */
  13331. this._u = new Set,
  13332. /**
  13333. * Event handlers that get called when the network is disabled or enabled.
  13334. *
  13335. * PORTING NOTE: These functions are used on the Web client to create the
  13336. * underlying streams (to support tree-shakeable streams). On Android and iOS,
  13337. * the streams are created during construction of RemoteStore.
  13338. */
  13339. this.wu = [], this.mu = i, this.mu.Ur((t => {
  13340. n.enqueueAndForget((async () => {
  13341. // Porting Note: Unlike iOS, `restartNetwork()` is called even when the
  13342. // network becomes unreachable as we don't have any other way to tear
  13343. // down our streams.
  13344. $u(this) && (x("RemoteStore", "Restarting streams for network reachability change."),
  13345. await async function(t) {
  13346. const e = B(t);
  13347. e._u.add(4 /* OfflineCause.ConnectivityChange */), await Cu(e), e.gu.set("Unknown" /* OnlineState.Unknown */),
  13348. e._u.delete(4 /* OfflineCause.ConnectivityChange */), await Du(e);
  13349. }(this));
  13350. }));
  13351. })), this.gu = new Vu(n, s);
  13352. }
  13353. }
  13354. async function Du(t) {
  13355. if ($u(t)) for (const e of t.wu) await e(/* enabled= */ !0);
  13356. }
  13357. /**
  13358. * Temporarily disables the network. The network can be re-enabled using
  13359. * enableNetwork().
  13360. */ async function Cu(t) {
  13361. for (const e of t.wu) await e(/* enabled= */ !1);
  13362. }
  13363. /**
  13364. * Starts new listen for the given target. Uses resume token if provided. It
  13365. * is a no-op if the target of given `TargetData` is already being listened to.
  13366. */
  13367. function xu(t, e) {
  13368. const n = B(t);
  13369. n.du.has(e.targetId) || (
  13370. // Mark this as something the client is currently listening for.
  13371. n.du.set(e.targetId, e), Fu(n) ?
  13372. // The listen will be sent in onWatchStreamOpen
  13373. Mu(n) : nc(n).ko() && ku(n, e));
  13374. }
  13375. /**
  13376. * Removes the listen from server. It is a no-op if the given target id is
  13377. * not being listened to.
  13378. */ function Nu(t, e) {
  13379. const n = B(t), s = nc(n);
  13380. n.du.delete(e), s.ko() && Ou(n, e), 0 === n.du.size && (s.ko() ? s.Fo() : $u(n) &&
  13381. // Revert to OnlineState.Unknown if the watch stream is not open and we
  13382. // have no listeners, since without any listens to send we cannot
  13383. // confirm if the stream is healthy and upgrade to OnlineState.Online.
  13384. n.gu.set("Unknown" /* OnlineState.Unknown */));
  13385. }
  13386. /**
  13387. * We need to increment the the expected number of pending responses we're due
  13388. * from watch so we wait for the ack to process any messages from this target.
  13389. */ function ku(t, e) {
  13390. t.yu.Ot(e.targetId), nc(t).zo(e);
  13391. }
  13392. /**
  13393. * We need to increment the expected number of pending responses we're due
  13394. * from watch so we wait for the removal on the server before we process any
  13395. * messages from this target.
  13396. */ function Ou(t, e) {
  13397. t.yu.Ot(e), nc(t).Ho(e);
  13398. }
  13399. function Mu(t) {
  13400. t.yu = new Ns({
  13401. getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),
  13402. ne: e => t.du.get(e) || null
  13403. }), nc(t).start(), t.gu.uu();
  13404. }
  13405. /**
  13406. * Returns whether the watch stream should be started because it's necessary
  13407. * and has not yet been started.
  13408. */ function Fu(t) {
  13409. return $u(t) && !nc(t).No() && t.du.size > 0;
  13410. }
  13411. function $u(t) {
  13412. return 0 === B(t)._u.size;
  13413. }
  13414. function Bu(t) {
  13415. t.yu = void 0;
  13416. }
  13417. async function Lu(t) {
  13418. t.du.forEach(((e, n) => {
  13419. ku(t, e);
  13420. }));
  13421. }
  13422. async function qu(t, e) {
  13423. Bu(t),
  13424. // If we still need the watch stream, retry the connection.
  13425. Fu(t) ? (t.gu.hu(e), Mu(t)) :
  13426. // No need to restart watch stream because there are no active targets.
  13427. // The online state is set to unknown because there is no active attempt
  13428. // at establishing a connection
  13429. t.gu.set("Unknown" /* OnlineState.Unknown */);
  13430. }
  13431. async function Uu(t, e, n) {
  13432. if (
  13433. // Mark the client as online since we got a message from the server
  13434. t.gu.set("Online" /* OnlineState.Online */), e instanceof Cs && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause)
  13435. // There was an error on a target, don't wait for a consistent snapshot
  13436. // to raise events
  13437. try {
  13438. await
  13439. /** Handles an error on a target */
  13440. async function(t, e) {
  13441. const n = e.cause;
  13442. for (const s of e.targetIds)
  13443. // A watched target might have been removed already.
  13444. t.du.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.du.delete(s), t.yu.removeTarget(s));
  13445. }
  13446. /**
  13447. * Attempts to fill our write pipeline with writes from the LocalStore.
  13448. *
  13449. * Called internally to bootstrap or refill the write pipeline and by
  13450. * SyncEngine whenever there are new mutations to process.
  13451. *
  13452. * Starts the write stream if necessary.
  13453. */ (t, e);
  13454. } catch (n) {
  13455. x("RemoteStore", "Failed to remove targets %s: %s ", e.targetIds.join(","), n),
  13456. await Ku(t, n);
  13457. } else if (e instanceof Ss ? t.yu.Kt(e) : e instanceof Ds ? t.yu.Jt(e) : t.yu.jt(e),
  13458. !n.isEqual(it.min())) try {
  13459. const e = await jo(t.localStore);
  13460. n.compareTo(e) >= 0 &&
  13461. // We have received a target change with a global snapshot if the snapshot
  13462. // version is not equal to SnapshotVersion.min().
  13463. await
  13464. /**
  13465. * Takes a batch of changes from the Datastore, repackages them as a
  13466. * RemoteEvent, and passes that on to the listener, which is typically the
  13467. * SyncEngine.
  13468. */
  13469. function(t, e) {
  13470. const n = t.yu.Zt(e);
  13471. // Update in-memory resume tokens. LocalStore will update the
  13472. // persistent view of these when applying the completed RemoteEvent.
  13473. return n.targetChanges.forEach(((n, s) => {
  13474. if (n.resumeToken.approximateByteSize() > 0) {
  13475. const i = t.du.get(s);
  13476. // A watched target might have been removed already.
  13477. i && t.du.set(s, i.withResumeToken(n.resumeToken, e));
  13478. }
  13479. })),
  13480. // Re-establish listens for the targets that have been invalidated by
  13481. // existence filter mismatches.
  13482. n.targetMismatches.forEach((e => {
  13483. const n = t.du.get(e);
  13484. if (!n)
  13485. // A watched target might have been removed already.
  13486. return;
  13487. // Clear the resume token for the target, since we're in a known mismatch
  13488. // state.
  13489. t.du.set(e, n.withResumeToken(Wt.EMPTY_BYTE_STRING, n.snapshotVersion)),
  13490. // Cause a hard reset by unwatching and rewatching immediately, but
  13491. // deliberately don't send a resume token so that we get a full update.
  13492. Ou(t, e);
  13493. // Mark the target we send as being on behalf of an existence filter
  13494. // mismatch, but don't actually retain that in listenTargets. This ensures
  13495. // that we flag the first re-listen this way without impacting future
  13496. // listens of this target (that might happen e.g. on reconnect).
  13497. const s = new Ji(n.target, e, 1 /* TargetPurpose.ExistenceFilterMismatch */ , n.sequenceNumber);
  13498. ku(t, s);
  13499. })), t.remoteSyncer.applyRemoteEvent(n);
  13500. }(t, n);
  13501. } catch (e) {
  13502. x("RemoteStore", "Failed to raise snapshot:", e), await Ku(t, e);
  13503. }
  13504. }
  13505. /**
  13506. * Recovery logic for IndexedDB errors that takes the network offline until
  13507. * `op` succeeds. Retries are scheduled with backoff using
  13508. * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
  13509. * validated via a generic operation.
  13510. *
  13511. * The returned Promise is resolved once the network is disabled and before
  13512. * any retry attempt.
  13513. */ async function Ku(t, e, n) {
  13514. if (!St(e)) throw e;
  13515. t._u.add(1 /* OfflineCause.IndexedDbFailed */),
  13516. // Disable network and raise offline snapshots
  13517. await Cu(t), t.gu.set("Offline" /* OnlineState.Offline */), n || (
  13518. // Use a simple read operation to determine if IndexedDB recovered.
  13519. // Ideally, we would expose a health check directly on SimpleDb, but
  13520. // RemoteStore only has access to persistence through LocalStore.
  13521. n = () => jo(t.localStore)),
  13522. // Probe IndexedDB periodically and re-enable network
  13523. t.asyncQueue.enqueueRetryable((async () => {
  13524. x("RemoteStore", "Retrying IndexedDB access"), await n(), t._u.delete(1 /* OfflineCause.IndexedDbFailed */),
  13525. await Du(t);
  13526. }));
  13527. }
  13528. /**
  13529. * Executes `op`. If `op` fails, takes the network offline until `op`
  13530. * succeeds. Returns after the first attempt.
  13531. */ function Gu(t, e) {
  13532. return e().catch((n => Ku(t, n, e)));
  13533. }
  13534. async function Qu(t) {
  13535. const e = B(t), n = sc(e);
  13536. let s = e.fu.length > 0 ? e.fu[e.fu.length - 1].batchId : -1;
  13537. for (;ju(e); ) try {
  13538. const t = await Ho(e.localStore, s);
  13539. if (null === t) {
  13540. 0 === e.fu.length && n.Fo();
  13541. break;
  13542. }
  13543. s = t.batchId, Wu(e, t);
  13544. } catch (t) {
  13545. await Ku(e, t);
  13546. }
  13547. zu(e) && Hu(e);
  13548. }
  13549. /**
  13550. * Returns true if we can add to the write pipeline (i.e. the network is
  13551. * enabled and the write pipeline is not full).
  13552. */ function ju(t) {
  13553. return $u(t) && t.fu.length < 10;
  13554. }
  13555. /**
  13556. * Queues additional writes to be sent to the write stream, sending them
  13557. * immediately if the write stream is established.
  13558. */ function Wu(t, e) {
  13559. t.fu.push(e);
  13560. const n = sc(t);
  13561. n.ko() && n.Yo && n.Xo(e.mutations);
  13562. }
  13563. function zu(t) {
  13564. return $u(t) && !sc(t).No() && t.fu.length > 0;
  13565. }
  13566. function Hu(t) {
  13567. sc(t).start();
  13568. }
  13569. async function Ju(t) {
  13570. sc(t).eu();
  13571. }
  13572. async function Yu(t) {
  13573. const e = sc(t);
  13574. // Send the write pipeline now that the stream is established.
  13575. for (const n of t.fu) e.Xo(n.mutations);
  13576. }
  13577. async function Xu(t, e, n) {
  13578. const s = t.fu.shift(), i = zi.from(s, e, n);
  13579. await Gu(t, (() => t.remoteSyncer.applySuccessfulWrite(i))),
  13580. // It's possible that with the completion of this mutation another
  13581. // slot has freed up.
  13582. await Qu(t);
  13583. }
  13584. async function Zu(t, e) {
  13585. // If the write stream closed after the write handshake completes, a write
  13586. // operation failed and we fail the pending operation.
  13587. e && sc(t).Yo &&
  13588. // This error affects the actual write.
  13589. await async function(t, e) {
  13590. // Only handle permanent errors here. If it's transient, just let the retry
  13591. // logic kick in.
  13592. if (n = e.code, ls(n) && n !== L.ABORTED) {
  13593. // This was a permanent error, the request itself was the problem
  13594. // so it's not going to succeed if we resend it.
  13595. const n = t.fu.shift();
  13596. // In this case it's also unlikely that the server itself is melting
  13597. // down -- this was just a bad request so inhibit backoff on the next
  13598. // restart.
  13599. sc(t).Mo(), await Gu(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))),
  13600. // It's possible that with the completion of this mutation
  13601. // another slot has freed up.
  13602. await Qu(t);
  13603. }
  13604. var n;
  13605. }(t, e),
  13606. // The write stream might have been started by refilling the write
  13607. // pipeline for failed writes
  13608. zu(t) && Hu(t);
  13609. }
  13610. async function tc(t, e) {
  13611. const n = B(t);
  13612. n.asyncQueue.verifyOperationInProgress(), x("RemoteStore", "RemoteStore received new credentials");
  13613. const s = $u(n);
  13614. // Tear down and re-create our network streams. This will ensure we get a
  13615. // fresh auth token for the new user and re-fill the write pipeline with
  13616. // new mutations from the LocalStore (since mutations are per-user).
  13617. n._u.add(3 /* OfflineCause.CredentialChange */), await Cu(n), s &&
  13618. // Don't set the network status to Unknown if we are offline.
  13619. n.gu.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e),
  13620. n._u.delete(3 /* OfflineCause.CredentialChange */), await Du(n);
  13621. }
  13622. /**
  13623. * Toggles the network state when the client gains or loses its primary lease.
  13624. */ async function ec(t, e) {
  13625. const n = B(t);
  13626. e ? (n._u.delete(2 /* OfflineCause.IsSecondary */), await Du(n)) : e || (n._u.add(2 /* OfflineCause.IsSecondary */),
  13627. await Cu(n), n.gu.set("Unknown" /* OnlineState.Unknown */));
  13628. }
  13629. /**
  13630. * If not yet initialized, registers the WatchStream and its network state
  13631. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  13632. * already available.
  13633. *
  13634. * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
  13635. * This is not done on Web to allow it to be tree-shaken.
  13636. */ function nc(t) {
  13637. return t.pu || (
  13638. // Create stream (but note that it is not started yet).
  13639. t.pu = function(t, e, n) {
  13640. const s = B(t);
  13641. return s.su(), new Ru(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);
  13642. }
  13643. /**
  13644. * @license
  13645. * Copyright 2018 Google LLC
  13646. *
  13647. * Licensed under the Apache License, Version 2.0 (the "License");
  13648. * you may not use this file except in compliance with the License.
  13649. * You may obtain a copy of the License at
  13650. *
  13651. * http://www.apache.org/licenses/LICENSE-2.0
  13652. *
  13653. * Unless required by applicable law or agreed to in writing, software
  13654. * distributed under the License is distributed on an "AS IS" BASIS,
  13655. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13656. * See the License for the specific language governing permissions and
  13657. * limitations under the License.
  13658. */ (t.datastore, t.asyncQueue, {
  13659. Yr: Lu.bind(null, t),
  13660. Zr: qu.bind(null, t),
  13661. Wo: Uu.bind(null, t)
  13662. }), t.wu.push((async e => {
  13663. e ? (t.pu.Mo(), Fu(t) ? Mu(t) : t.gu.set("Unknown" /* OnlineState.Unknown */)) : (await t.pu.stop(),
  13664. Bu(t));
  13665. }))), t.pu;
  13666. }
  13667. /**
  13668. * If not yet initialized, registers the WriteStream and its network state
  13669. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  13670. * already available.
  13671. *
  13672. * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
  13673. * This is not done on Web to allow it to be tree-shaken.
  13674. */ function sc(t) {
  13675. return t.Iu || (
  13676. // Create stream (but note that it is not started yet).
  13677. t.Iu = function(t, e, n) {
  13678. const s = B(t);
  13679. return s.su(), new bu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);
  13680. }(t.datastore, t.asyncQueue, {
  13681. Yr: Ju.bind(null, t),
  13682. Zr: Zu.bind(null, t),
  13683. tu: Yu.bind(null, t),
  13684. Zo: Xu.bind(null, t)
  13685. }), t.wu.push((async e => {
  13686. e ? (t.Iu.Mo(),
  13687. // This will start the write stream if necessary.
  13688. await Qu(t)) : (await t.Iu.stop(), t.fu.length > 0 && (x("RemoteStore", `Stopping write stream with ${t.fu.length} pending writes`),
  13689. t.fu = []));
  13690. }))), t.Iu;
  13691. }
  13692. /**
  13693. * @license
  13694. * Copyright 2017 Google LLC
  13695. *
  13696. * Licensed under the Apache License, Version 2.0 (the "License");
  13697. * you may not use this file except in compliance with the License.
  13698. * You may obtain a copy of the License at
  13699. *
  13700. * http://www.apache.org/licenses/LICENSE-2.0
  13701. *
  13702. * Unless required by applicable law or agreed to in writing, software
  13703. * distributed under the License is distributed on an "AS IS" BASIS,
  13704. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13705. * See the License for the specific language governing permissions and
  13706. * limitations under the License.
  13707. */
  13708. /**
  13709. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  13710. *
  13711. * It is created via DelayedOperation.createAndSchedule().
  13712. *
  13713. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  13714. *
  13715. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  13716. * in newer versions of TypeScript defines `finally`, which is not available in
  13717. * IE.
  13718. */
  13719. class ic {
  13720. constructor(t, e, n, s, i) {
  13721. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i,
  13722. this.deferred = new U, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  13723. // It's normal for the deferred promise to be canceled (due to cancellation)
  13724. // and so we attach a dummy catch callback to avoid
  13725. // 'UnhandledPromiseRejectionWarning' log spam.
  13726. this.deferred.promise.catch((t => {}));
  13727. }
  13728. /**
  13729. * Creates and returns a DelayedOperation that has been scheduled to be
  13730. * executed on the provided asyncQueue after the provided delayMs.
  13731. *
  13732. * @param asyncQueue - The queue to schedule the operation on.
  13733. * @param id - A Timer ID identifying the type of operation this is.
  13734. * @param delayMs - The delay (ms) before the operation should be scheduled.
  13735. * @param op - The operation to run.
  13736. * @param removalCallback - A callback to be called synchronously once the
  13737. * operation is executed or canceled, notifying the AsyncQueue to remove it
  13738. * from its delayedOperations list.
  13739. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  13740. * the DelayedOperation class public.
  13741. */ static createAndSchedule(t, e, n, s, i) {
  13742. const r = Date.now() + n, o = new ic(t, e, r, s, i);
  13743. return o.start(n), o;
  13744. }
  13745. /**
  13746. * Starts the timer. This is called immediately after construction by
  13747. * createAndSchedule().
  13748. */ start(t) {
  13749. this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);
  13750. }
  13751. /**
  13752. * Queues the operation to run immediately (if it hasn't already been run or
  13753. * canceled).
  13754. */ skipDelay() {
  13755. return this.handleDelayElapsed();
  13756. }
  13757. /**
  13758. * Cancels the operation if it hasn't already been executed or canceled. The
  13759. * promise will be rejected.
  13760. *
  13761. * As long as the operation has not yet been run, calling cancel() provides a
  13762. * guarantee that the operation will not be run.
  13763. */ cancel(t) {
  13764. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new q(L.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
  13765. }
  13766. handleDelayElapsed() {
  13767. this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(),
  13768. this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));
  13769. }
  13770. clearTimeout() {
  13771. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  13772. this.timerHandle = null);
  13773. }
  13774. }
  13775. /**
  13776. * Returns a FirestoreError that can be surfaced to the user if the provided
  13777. * error is an IndexedDbTransactionError. Re-throws the error otherwise.
  13778. */ function rc(t, e) {
  13779. if (N("AsyncQueue", `${e}: ${t}`), St(t)) return new q(L.UNAVAILABLE, `${e}: ${t}`);
  13780. throw t;
  13781. }
  13782. /**
  13783. * @license
  13784. * Copyright 2017 Google LLC
  13785. *
  13786. * Licensed under the Apache License, Version 2.0 (the "License");
  13787. * you may not use this file except in compliance with the License.
  13788. * You may obtain a copy of the License at
  13789. *
  13790. * http://www.apache.org/licenses/LICENSE-2.0
  13791. *
  13792. * Unless required by applicable law or agreed to in writing, software
  13793. * distributed under the License is distributed on an "AS IS" BASIS,
  13794. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13795. * See the License for the specific language governing permissions and
  13796. * limitations under the License.
  13797. */
  13798. /**
  13799. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  13800. * in order specified by the provided comparator. We always add a document key
  13801. * comparator on top of what is provided to guarantee document equality based on
  13802. * the key.
  13803. */ class oc {
  13804. /** The default ordering is by key if the comparator is omitted */
  13805. constructor(t) {
  13806. // We are adding document key comparator to the end as it's the only
  13807. // guaranteed unique property of a document.
  13808. this.comparator = t ? (e, n) => t(e, n) || at.comparator(e.key, n.key) : (t, e) => at.comparator(t.key, e.key),
  13809. this.keyedMap = gs(), this.sortedSet = new je(this.comparator);
  13810. }
  13811. /**
  13812. * Returns an empty copy of the existing DocumentSet, using the same
  13813. * comparator.
  13814. */ static emptySet(t) {
  13815. return new oc(t.comparator);
  13816. }
  13817. has(t) {
  13818. return null != this.keyedMap.get(t);
  13819. }
  13820. get(t) {
  13821. return this.keyedMap.get(t);
  13822. }
  13823. first() {
  13824. return this.sortedSet.minKey();
  13825. }
  13826. last() {
  13827. return this.sortedSet.maxKey();
  13828. }
  13829. isEmpty() {
  13830. return this.sortedSet.isEmpty();
  13831. }
  13832. /**
  13833. * Returns the index of the provided key in the document set, or -1 if the
  13834. * document key is not present in the set;
  13835. */ indexOf(t) {
  13836. const e = this.keyedMap.get(t);
  13837. return e ? this.sortedSet.indexOf(e) : -1;
  13838. }
  13839. get size() {
  13840. return this.sortedSet.size;
  13841. }
  13842. /** Iterates documents in order defined by "comparator" */ forEach(t) {
  13843. this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));
  13844. }
  13845. /** Inserts or updates a document with the same key */ add(t) {
  13846. // First remove the element if we have it.
  13847. const e = this.delete(t.key);
  13848. return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
  13849. }
  13850. /** Deletes a document with a given key */ delete(t) {
  13851. const e = this.get(t);
  13852. return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
  13853. }
  13854. isEqual(t) {
  13855. if (!(t instanceof oc)) return !1;
  13856. if (this.size !== t.size) return !1;
  13857. const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();
  13858. for (;e.hasNext(); ) {
  13859. const t = e.getNext().key, s = n.getNext().key;
  13860. if (!t.isEqual(s)) return !1;
  13861. }
  13862. return !0;
  13863. }
  13864. toString() {
  13865. const t = [];
  13866. return this.forEach((e => {
  13867. t.push(e.toString());
  13868. })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
  13869. }
  13870. copy(t, e) {
  13871. const n = new oc;
  13872. return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;
  13873. }
  13874. }
  13875. /**
  13876. * @license
  13877. * Copyright 2017 Google LLC
  13878. *
  13879. * Licensed under the Apache License, Version 2.0 (the "License");
  13880. * you may not use this file except in compliance with the License.
  13881. * You may obtain a copy of the License at
  13882. *
  13883. * http://www.apache.org/licenses/LICENSE-2.0
  13884. *
  13885. * Unless required by applicable law or agreed to in writing, software
  13886. * distributed under the License is distributed on an "AS IS" BASIS,
  13887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13888. * See the License for the specific language governing permissions and
  13889. * limitations under the License.
  13890. */
  13891. /**
  13892. * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
  13893. * duplicate events for the same doc.
  13894. */ class uc {
  13895. constructor() {
  13896. this.Tu = new je(at.comparator);
  13897. }
  13898. track(t) {
  13899. const e = t.doc.key, n = this.Tu.get(e);
  13900. n ?
  13901. // Merge the new change with the existing change.
  13902. 0 /* ChangeType.Added */ !== t.type && 3 /* ChangeType.Metadata */ === n.type ? this.Tu = this.Tu.insert(e, t) : 3 /* ChangeType.Metadata */ === t.type && 1 /* ChangeType.Removed */ !== n.type ? this.Tu = this.Tu.insert(e, {
  13903. type: n.type,
  13904. doc: t.doc
  13905. }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {
  13906. type: 2 /* ChangeType.Modified */ ,
  13907. doc: t.doc
  13908. }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.insert(e, {
  13909. type: 0 /* ChangeType.Added */ ,
  13910. doc: t.doc
  13911. }) : 1 /* ChangeType.Removed */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.remove(e) : 1 /* ChangeType.Removed */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {
  13912. type: 1 /* ChangeType.Removed */ ,
  13913. doc: n.doc
  13914. }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Tu = this.Tu.insert(e, {
  13915. type: 2 /* ChangeType.Modified */ ,
  13916. doc: t.doc
  13917. }) :
  13918. // This includes these cases, which don't make sense:
  13919. // Added->Added
  13920. // Removed->Removed
  13921. // Modified->Added
  13922. // Removed->Modified
  13923. // Metadata->Added
  13924. // Removed->Metadata
  13925. M() : this.Tu = this.Tu.insert(e, t);
  13926. }
  13927. Eu() {
  13928. const t = [];
  13929. return this.Tu.inorderTraversal(((e, n) => {
  13930. t.push(n);
  13931. })), t;
  13932. }
  13933. }
  13934. class cc {
  13935. constructor(t, e, n, s, i, r, o, u, c) {
  13936. this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i,
  13937. this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u,
  13938. this.hasCachedResults = c;
  13939. }
  13940. /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {
  13941. const r = [];
  13942. return e.forEach((t => {
  13943. r.push({
  13944. type: 0 /* ChangeType.Added */ ,
  13945. doc: t
  13946. });
  13947. })), new cc(t, e, oc.emptySet(e), r, n, s,
  13948. /* syncStateChanged= */ !0,
  13949. /* excludesMetadataChanges= */ !1, i);
  13950. }
  13951. get hasPendingWrites() {
  13952. return !this.mutatedKeys.isEmpty();
  13953. }
  13954. isEqual(t) {
  13955. if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && En(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
  13956. const e = this.docChanges, n = t.docChanges;
  13957. if (e.length !== n.length) return !1;
  13958. for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;
  13959. return !0;
  13960. }
  13961. }
  13962. /**
  13963. * @license
  13964. * Copyright 2017 Google LLC
  13965. *
  13966. * Licensed under the Apache License, Version 2.0 (the "License");
  13967. * you may not use this file except in compliance with the License.
  13968. * You may obtain a copy of the License at
  13969. *
  13970. * http://www.apache.org/licenses/LICENSE-2.0
  13971. *
  13972. * Unless required by applicable law or agreed to in writing, software
  13973. * distributed under the License is distributed on an "AS IS" BASIS,
  13974. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13975. * See the License for the specific language governing permissions and
  13976. * limitations under the License.
  13977. */
  13978. /**
  13979. * Holds the listeners and the last received ViewSnapshot for a query being
  13980. * tracked by EventManager.
  13981. */ class ac {
  13982. constructor() {
  13983. this.Au = void 0, this.listeners = [];
  13984. }
  13985. }
  13986. class hc {
  13987. constructor() {
  13988. this.queries = new ds((t => An(t)), En), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  13989. this.Ru = new Set;
  13990. }
  13991. }
  13992. async function lc(t, e) {
  13993. const n = B(t), s = e.query;
  13994. let i = !1, r = n.queries.get(s);
  13995. if (r || (i = !0, r = new ac), i) try {
  13996. r.Au = await n.onListen(s);
  13997. } catch (t) {
  13998. const n = rc(t, `Initialization of query '${Rn(e.query)}' failed`);
  13999. return void e.onError(n);
  14000. }
  14001. if (n.queries.set(s, r), r.listeners.push(e),
  14002. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14003. e.bu(n.onlineState), r.Au) {
  14004. e.Pu(r.Au) && wc(n);
  14005. }
  14006. }
  14007. async function fc(t, e) {
  14008. const n = B(t), s = e.query;
  14009. let i = !1;
  14010. const r = n.queries.get(s);
  14011. if (r) {
  14012. const t = r.listeners.indexOf(e);
  14013. t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);
  14014. }
  14015. if (i) return n.queries.delete(s), n.onUnlisten(s);
  14016. }
  14017. function dc(t, e) {
  14018. const n = B(t);
  14019. let s = !1;
  14020. for (const t of e) {
  14021. const e = t.query, i = n.queries.get(e);
  14022. if (i) {
  14023. for (const e of i.listeners) e.Pu(t) && (s = !0);
  14024. i.Au = t;
  14025. }
  14026. }
  14027. s && wc(n);
  14028. }
  14029. function _c(t, e, n) {
  14030. const s = B(t), i = s.queries.get(e);
  14031. if (i) for (const t of i.listeners) t.onError(n);
  14032. // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
  14033. // after an error.
  14034. s.queries.delete(e);
  14035. }
  14036. // Call all global snapshot listeners that have been set.
  14037. function wc(t) {
  14038. t.Ru.forEach((t => {
  14039. t.next();
  14040. }));
  14041. }
  14042. /**
  14043. * QueryListener takes a series of internal view snapshots and determines
  14044. * when to raise the event.
  14045. *
  14046. * It uses an Observer to dispatch events.
  14047. */ class mc {
  14048. constructor(t, e, n) {
  14049. this.query = t, this.vu = e,
  14050. /**
  14051. * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
  14052. * observer. This flag is set to true once we've actually raised an event.
  14053. */
  14054. this.Vu = !1, this.Su = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14055. this.options = n || {};
  14056. }
  14057. /**
  14058. * Applies the new ViewSnapshot to this listener, raising a user-facing event
  14059. * if applicable (depending on what changed, whether the user has opted into
  14060. * metadata-only changes, etc.). Returns true if a user-facing event was
  14061. * indeed raised.
  14062. */ Pu(t) {
  14063. if (!this.options.includeMetadataChanges) {
  14064. // Remove the metadata only changes.
  14065. const e = [];
  14066. for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);
  14067. t = new cc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged,
  14068. /* excludesMetadataChanges= */ !0, t.hasCachedResults);
  14069. }
  14070. let e = !1;
  14071. return this.Vu ? this.Du(t) && (this.vu.next(t), e = !0) : this.Cu(t, this.onlineState) && (this.xu(t),
  14072. e = !0), this.Su = t, e;
  14073. }
  14074. onError(t) {
  14075. this.vu.error(t);
  14076. }
  14077. /** Returns whether a snapshot was raised. */ bu(t) {
  14078. this.onlineState = t;
  14079. let e = !1;
  14080. return this.Su && !this.Vu && this.Cu(this.Su, t) && (this.xu(this.Su), e = !0),
  14081. e;
  14082. }
  14083. Cu(t, e) {
  14084. // Always raise the first event when we're synced
  14085. if (!t.fromCache) return !0;
  14086. // NOTE: We consider OnlineState.Unknown as online (it should become Offline
  14087. // or Online if we wait long enough).
  14088. const n = "Offline" /* OnlineState.Offline */ !== e;
  14089. // Don't raise the event if we're online, aren't synced yet (checked
  14090. // above) and are waiting for a sync.
  14091. return (!this.options.Nu || !n) && (!t.docs.isEmpty() || t.hasCachedResults || "Offline" /* OnlineState.Offline */ === e);
  14092. // Raise data from cache if we have any documents, have cached results before,
  14093. // or we are offline.
  14094. }
  14095. Du(t) {
  14096. // We don't need to handle includeDocumentMetadataChanges here because
  14097. // the Metadata only changes have already been stripped out if needed.
  14098. // At this point the only changes we will see are the ones we should
  14099. // propagate.
  14100. if (t.docChanges.length > 0) return !0;
  14101. const e = this.Su && this.Su.hasPendingWrites !== t.hasPendingWrites;
  14102. return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
  14103. // Generally we should have hit one of the cases above, but it's possible
  14104. // to get here if there were only metadata docChanges and they got
  14105. // stripped out.
  14106. }
  14107. xu(t) {
  14108. t = cc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults),
  14109. this.Vu = !0, this.vu.next(t);
  14110. }
  14111. }
  14112. /**
  14113. * @license
  14114. * Copyright 2020 Google LLC
  14115. *
  14116. * Licensed under the Apache License, Version 2.0 (the "License");
  14117. * you may not use this file except in compliance with the License.
  14118. * You may obtain a copy of the License at
  14119. *
  14120. * http://www.apache.org/licenses/LICENSE-2.0
  14121. *
  14122. * Unless required by applicable law or agreed to in writing, software
  14123. * distributed under the License is distributed on an "AS IS" BASIS,
  14124. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14125. * See the License for the specific language governing permissions and
  14126. * limitations under the License.
  14127. */
  14128. /**
  14129. * A complete element in the bundle stream, together with the byte length it
  14130. * occupies in the stream.
  14131. */ class gc {
  14132. constructor(t,
  14133. // How many bytes this element takes to store in the bundle.
  14134. e) {
  14135. this.ku = t, this.byteLength = e;
  14136. }
  14137. Ou() {
  14138. return "metadata" in this.ku;
  14139. }
  14140. }
  14141. /**
  14142. * @license
  14143. * Copyright 2020 Google LLC
  14144. *
  14145. * Licensed under the Apache License, Version 2.0 (the "License");
  14146. * you may not use this file except in compliance with the License.
  14147. * You may obtain a copy of the License at
  14148. *
  14149. * http://www.apache.org/licenses/LICENSE-2.0
  14150. *
  14151. * Unless required by applicable law or agreed to in writing, software
  14152. * distributed under the License is distributed on an "AS IS" BASIS,
  14153. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14154. * See the License for the specific language governing permissions and
  14155. * limitations under the License.
  14156. */
  14157. /**
  14158. * Helper to convert objects from bundles to model objects in the SDK.
  14159. */ class yc {
  14160. constructor(t) {
  14161. this.yt = t;
  14162. }
  14163. Ji(t) {
  14164. return Ws(this.yt, t);
  14165. }
  14166. /**
  14167. * Converts a BundleDocument to a MutableDocument.
  14168. */ Yi(t) {
  14169. return t.metadata.exists ? Zs(this.yt, t.document, !1) : en.newNoDocument(this.Ji(t.metadata.name), this.Xi(t.metadata.readTime));
  14170. }
  14171. Xi(t) {
  14172. return Ks(t);
  14173. }
  14174. }
  14175. /**
  14176. * A class to process the elements from a bundle, load them into local
  14177. * storage and provide progress update while loading.
  14178. */ class pc {
  14179. constructor(t, e, n) {
  14180. this.Mu = t, this.localStore = e, this.yt = n,
  14181. /** Batched queries to be saved into storage */
  14182. this.queries = [],
  14183. /** Batched documents to be saved into storage */
  14184. this.documents = [],
  14185. /** The collection groups affected by this bundle. */
  14186. this.collectionGroups = new Set, this.progress = Ic(t);
  14187. }
  14188. /**
  14189. * Adds an element from the bundle to the loader.
  14190. *
  14191. * Returns a new progress if adding the element leads to a new progress,
  14192. * otherwise returns null.
  14193. */ Fu(t) {
  14194. this.progress.bytesLoaded += t.byteLength;
  14195. let e = this.progress.documentsLoaded;
  14196. if (t.ku.namedQuery) this.queries.push(t.ku.namedQuery); else if (t.ku.documentMetadata) {
  14197. this.documents.push({
  14198. metadata: t.ku.documentMetadata
  14199. }), t.ku.documentMetadata.exists || ++e;
  14200. const n = ot.fromString(t.ku.documentMetadata.name);
  14201. this.collectionGroups.add(n.get(n.length - 2));
  14202. } else t.ku.document && (this.documents[this.documents.length - 1].document = t.ku.document,
  14203. ++e);
  14204. return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e,
  14205. Object.assign({}, this.progress)) : null;
  14206. }
  14207. $u(t) {
  14208. const e = new Map, n = new yc(this.yt);
  14209. for (const s of t) if (s.metadata.queries) {
  14210. const t = n.Ji(s.metadata.name);
  14211. for (const n of s.metadata.queries) {
  14212. const s = (e.get(n) || Rs()).add(t);
  14213. e.set(n, s);
  14214. }
  14215. }
  14216. return e;
  14217. }
  14218. /**
  14219. * Update the progress to 'Success' and return the updated progress.
  14220. */ async complete() {
  14221. const t = await nu(this.localStore, new yc(this.yt), this.documents, this.Mu.id), e = this.$u(this.documents);
  14222. for (const t of this.queries) await su(this.localStore, t, e.get(t.name));
  14223. return this.progress.taskState = "Success", {
  14224. progress: this.progress,
  14225. Bu: this.collectionGroups,
  14226. Lu: t
  14227. };
  14228. }
  14229. }
  14230. /**
  14231. * Returns a `LoadBundleTaskProgress` representing the initial progress of
  14232. * loading a bundle.
  14233. */ function Ic(t) {
  14234. return {
  14235. taskState: "Running",
  14236. documentsLoaded: 0,
  14237. bytesLoaded: 0,
  14238. totalDocuments: t.totalDocuments,
  14239. totalBytes: t.totalBytes
  14240. };
  14241. }
  14242. /**
  14243. * Returns a `LoadBundleTaskProgress` representing the progress that the loading
  14244. * has succeeded.
  14245. */
  14246. /**
  14247. * @license
  14248. * Copyright 2017 Google LLC
  14249. *
  14250. * Licensed under the Apache License, Version 2.0 (the "License");
  14251. * you may not use this file except in compliance with the License.
  14252. * You may obtain a copy of the License at
  14253. *
  14254. * http://www.apache.org/licenses/LICENSE-2.0
  14255. *
  14256. * Unless required by applicable law or agreed to in writing, software
  14257. * distributed under the License is distributed on an "AS IS" BASIS,
  14258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14259. * See the License for the specific language governing permissions and
  14260. * limitations under the License.
  14261. */
  14262. class Tc {
  14263. constructor(t) {
  14264. this.key = t;
  14265. }
  14266. }
  14267. class Ec {
  14268. constructor(t) {
  14269. this.key = t;
  14270. }
  14271. }
  14272. /**
  14273. * View is responsible for computing the final merged truth of what docs are in
  14274. * a query. It gets notified of local and remote changes to docs, and applies
  14275. * the query filters and limits to determine the most correct possible results.
  14276. */ class Ac {
  14277. constructor(t,
  14278. /** Documents included in the remote target */
  14279. e) {
  14280. this.query = t, this.qu = e, this.Uu = null, this.hasCachedResults = !1,
  14281. /**
  14282. * A flag whether the view is current with the backend. A view is considered
  14283. * current after it has seen the current flag from the backend and did not
  14284. * lose consistency within the watch stream (e.g. because of an existence
  14285. * filter mismatch).
  14286. */
  14287. this.current = !1,
  14288. /** Documents in the view but not in the remote target */
  14289. this.Ku = Rs(),
  14290. /** Document Keys that have local changes */
  14291. this.mutatedKeys = Rs(), this.Gu = vn(t), this.Qu = new oc(this.Gu);
  14292. }
  14293. /**
  14294. * The set of remote documents that the server has told us belongs to the target associated with
  14295. * this view.
  14296. */ get ju() {
  14297. return this.qu;
  14298. }
  14299. /**
  14300. * Iterates over a set of doc changes, applies the query limit, and computes
  14301. * what the new results should be, what the changes were, and whether we may
  14302. * need to go back to the local cache for more results. Does not make any
  14303. * changes to the view.
  14304. * @param docChanges - The doc changes to apply to this view.
  14305. * @param previousChanges - If this is being called with a refill, then start
  14306. * with this set of docs and changes instead of the current view.
  14307. * @returns a new set of docs, changes, and refill flag.
  14308. */ Wu(t, e) {
  14309. const n = e ? e.zu : new uc, s = e ? e.Qu : this.Qu;
  14310. let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;
  14311. // Track the last doc in a (full) limit. This is necessary, because some
  14312. // update (a delete, or an update moving a doc past the old limit) might
  14313. // mean there is some other document in the local cache that either should
  14314. // come (1) between the old last limit doc and the new last document, in the
  14315. // case of updates, or (2) after the new last document, in the case of
  14316. // deletes. So we keep this doc at the old limit to compare the updates to.
  14317. // Note that this should never get used in a refill (when previousChanges is
  14318. // set), because there will only be adds -- no deletes or updates.
  14319. const u = "F" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = "L" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;
  14320. // Drop documents out to meet limit/limitToLast requirement.
  14321. if (t.inorderTraversal(((t, e) => {
  14322. const a = s.get(t), h = bn(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations ||
  14323. // We only consider committed mutations for documents that were
  14324. // mutated during the lifetime of the view.
  14325. this.mutatedKeys.has(h.key) && h.hasCommittedMutations);
  14326. let d = !1;
  14327. // Calculate change
  14328. if (a && h) {
  14329. a.data.isEqual(h.data) ? l !== f && (n.track({
  14330. type: 3 /* ChangeType.Metadata */ ,
  14331. doc: h
  14332. }), d = !0) : this.Hu(a, h) || (n.track({
  14333. type: 2 /* ChangeType.Modified */ ,
  14334. doc: h
  14335. }), d = !0, (u && this.Gu(h, u) > 0 || c && this.Gu(h, c) < 0) && (
  14336. // This doc moved from inside the limit to outside the limit.
  14337. // That means there may be some other doc in the local cache
  14338. // that should be included instead.
  14339. o = !0));
  14340. } else !a && h ? (n.track({
  14341. type: 0 /* ChangeType.Added */ ,
  14342. doc: h
  14343. }), d = !0) : a && !h && (n.track({
  14344. type: 1 /* ChangeType.Removed */ ,
  14345. doc: a
  14346. }), d = !0, (u || c) && (
  14347. // A doc was removed from a full limit query. We'll need to
  14348. // requery from the local cache to see if we know about some other
  14349. // doc that should be in the results.
  14350. o = !0));
  14351. d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));
  14352. })), null !== this.query.limit) for (;r.size > this.query.limit; ) {
  14353. const t = "F" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();
  14354. r = r.delete(t.key), i = i.delete(t.key), n.track({
  14355. type: 1 /* ChangeType.Removed */ ,
  14356. doc: t
  14357. });
  14358. }
  14359. return {
  14360. Qu: r,
  14361. zu: n,
  14362. $i: o,
  14363. mutatedKeys: i
  14364. };
  14365. }
  14366. Hu(t, e) {
  14367. // We suppress the initial change event for documents that were modified as
  14368. // part of a write acknowledgment (e.g. when the value of a server transform
  14369. // is applied) as Watch will send us the same document again.
  14370. // By suppressing the event, we only raise two user visible events (one with
  14371. // `hasPendingWrites` and the final state of the document) instead of three
  14372. // (one with `hasPendingWrites`, the modified document with
  14373. // `hasPendingWrites` and the final state of the document).
  14374. return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
  14375. }
  14376. /**
  14377. * Updates the view with the given ViewDocumentChanges and optionally updates
  14378. * limbo docs and sync state from the provided target change.
  14379. * @param docChanges - The set of changes to make to the view's docs.
  14380. * @param updateLimboDocuments - Whether to update limbo documents based on
  14381. * this change.
  14382. * @param targetChange - A target change to apply for computing limbo docs and
  14383. * sync state.
  14384. * @returns A new ViewChange with the given docs, changes, and sync state.
  14385. */
  14386. // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  14387. applyChanges(t, e, n) {
  14388. const s = this.Qu;
  14389. this.Qu = t.Qu, this.mutatedKeys = t.mutatedKeys;
  14390. // Sort changes based on type and query comparator
  14391. const i = t.zu.Eu();
  14392. i.sort(((t, e) => function(t, e) {
  14393. const n = t => {
  14394. switch (t) {
  14395. case 0 /* ChangeType.Added */ :
  14396. return 1;
  14397. case 2 /* ChangeType.Modified */ :
  14398. case 3 /* ChangeType.Metadata */ :
  14399. // A metadata change is converted to a modified change at the public
  14400. // api layer. Since we sort by document key and then change type,
  14401. // metadata and modified changes must be sorted equivalently.
  14402. return 2;
  14403. case 1 /* ChangeType.Removed */ :
  14404. return 0;
  14405. default:
  14406. return M();
  14407. }
  14408. };
  14409. return n(t) - n(e);
  14410. }
  14411. /**
  14412. * @license
  14413. * Copyright 2020 Google LLC
  14414. *
  14415. * Licensed under the Apache License, Version 2.0 (the "License");
  14416. * you may not use this file except in compliance with the License.
  14417. * You may obtain a copy of the License at
  14418. *
  14419. * http://www.apache.org/licenses/LICENSE-2.0
  14420. *
  14421. * Unless required by applicable law or agreed to in writing, software
  14422. * distributed under the License is distributed on an "AS IS" BASIS,
  14423. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14424. * See the License for the specific language governing permissions and
  14425. * limitations under the License.
  14426. */ (t.type, e.type) || this.Gu(t.doc, e.doc))), this.Ju(n);
  14427. const r = e ? this.Yu() : [], o = 0 === this.Ku.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Uu;
  14428. if (this.Uu = o, 0 !== i.length || u) {
  14429. return {
  14430. snapshot: new cc(this.query, t.Qu, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u,
  14431. /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),
  14432. Xu: r
  14433. };
  14434. }
  14435. // no changes
  14436. return {
  14437. Xu: r
  14438. };
  14439. }
  14440. /**
  14441. * Applies an OnlineState change to the view, potentially generating a
  14442. * ViewChange if the view's syncState changes as a result.
  14443. */ bu(t) {
  14444. return this.current && "Offline" /* OnlineState.Offline */ === t ? (
  14445. // If we're offline, set `current` to false and then call applyChanges()
  14446. // to refresh our syncState and generate a ViewChange as appropriate. We
  14447. // are guaranteed to get a new TargetChange that sets `current` back to
  14448. // true once the client is back online.
  14449. this.current = !1, this.applyChanges({
  14450. Qu: this.Qu,
  14451. zu: new uc,
  14452. mutatedKeys: this.mutatedKeys,
  14453. $i: !1
  14454. },
  14455. /* updateLimboDocuments= */ !1)) : {
  14456. Xu: []
  14457. };
  14458. }
  14459. /**
  14460. * Returns whether the doc for the given key should be in limbo.
  14461. */ Zu(t) {
  14462. // If the remote end says it's part of this query, it's not in limbo.
  14463. return !this.qu.has(t) && (
  14464. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  14465. !!this.Qu.has(t) && !this.Qu.get(t).hasLocalMutations);
  14466. }
  14467. /**
  14468. * Updates syncedDocuments, current, and limbo docs based on the given change.
  14469. * Returns the list of changes to which docs are in limbo.
  14470. */ Ju(t) {
  14471. t && (t.addedDocuments.forEach((t => this.qu = this.qu.add(t))), t.modifiedDocuments.forEach((t => {})),
  14472. t.removedDocuments.forEach((t => this.qu = this.qu.delete(t))), this.current = t.current);
  14473. }
  14474. Yu() {
  14475. // We can only determine limbo documents when we're in-sync with the server.
  14476. if (!this.current) return [];
  14477. // TODO(klimt): Do this incrementally so that it's not quadratic when
  14478. // updating many documents.
  14479. const t = this.Ku;
  14480. this.Ku = Rs(), this.Qu.forEach((t => {
  14481. this.Zu(t.key) && (this.Ku = this.Ku.add(t.key));
  14482. }));
  14483. // Diff the new limbo docs with the old limbo docs.
  14484. const e = [];
  14485. return t.forEach((t => {
  14486. this.Ku.has(t) || e.push(new Ec(t));
  14487. })), this.Ku.forEach((n => {
  14488. t.has(n) || e.push(new Tc(n));
  14489. })), e;
  14490. }
  14491. /**
  14492. * Update the in-memory state of the current view with the state read from
  14493. * persistence.
  14494. *
  14495. * We update the query view whenever a client's primary status changes:
  14496. * - When a client transitions from primary to secondary, it can miss
  14497. * LocalStorage updates and its query views may temporarily not be
  14498. * synchronized with the state on disk.
  14499. * - For secondary to primary transitions, the client needs to update the list
  14500. * of `syncedDocuments` since secondary clients update their query views
  14501. * based purely on synthesized RemoteEvents.
  14502. *
  14503. * @param queryResult.documents - The documents that match the query according
  14504. * to the LocalStore.
  14505. * @param queryResult.remoteKeys - The keys of the documents that match the
  14506. * query according to the backend.
  14507. *
  14508. * @returns The ViewChange that resulted from this synchronization.
  14509. */
  14510. // PORTING NOTE: Multi-tab only.
  14511. tc(t) {
  14512. this.qu = t.Hi, this.Ku = Rs();
  14513. const e = this.Wu(t.documents);
  14514. return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
  14515. }
  14516. /**
  14517. * Returns a view snapshot as if this query was just listened to. Contains
  14518. * a document add for every existing document and the `fromCache` and
  14519. * `hasPendingWrites` status of the already established view.
  14520. */
  14521. // PORTING NOTE: Multi-tab only.
  14522. ec() {
  14523. return cc.fromInitialDocuments(this.query, this.Qu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Uu, this.hasCachedResults);
  14524. }
  14525. }
  14526. /**
  14527. * QueryView contains all of the data that SyncEngine needs to keep track of for
  14528. * a particular query.
  14529. */
  14530. class Rc {
  14531. constructor(
  14532. /**
  14533. * The query itself.
  14534. */
  14535. t,
  14536. /**
  14537. * The target number created by the client that is used in the watch
  14538. * stream to identify this query.
  14539. */
  14540. e,
  14541. /**
  14542. * The view is responsible for computing the final merged truth of what
  14543. * docs are in the query. It gets notified of local and remote changes,
  14544. * and applies the query filters and limits to determine the most correct
  14545. * possible results.
  14546. */
  14547. n) {
  14548. this.query = t, this.targetId = e, this.view = n;
  14549. }
  14550. }
  14551. /** Tracks a limbo resolution. */ class bc {
  14552. constructor(t) {
  14553. this.key = t,
  14554. /**
  14555. * Set to true once we've received a document. This is used in
  14556. * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
  14557. * decide whether it needs to manufacture a delete event for the target once
  14558. * the target is CURRENT.
  14559. */
  14560. this.nc = !1;
  14561. }
  14562. }
  14563. /**
  14564. * An implementation of `SyncEngine` coordinating with other parts of SDK.
  14565. *
  14566. * The parts of SyncEngine that act as a callback to RemoteStore need to be
  14567. * registered individually. This is done in `syncEngineWrite()` and
  14568. * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
  14569. * serve as entry points to RemoteStore's functionality.
  14570. *
  14571. * Note: some field defined in this class might have public access level, but
  14572. * the class is not exported so they are only accessible from this module.
  14573. * This is useful to implement optional features (like bundles) in free
  14574. * functions, such that they are tree-shakeable.
  14575. */ class Pc {
  14576. constructor(t, e, n,
  14577. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  14578. s, i, r) {
  14579. this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s,
  14580. this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.sc = {}, this.ic = new ds((t => An(t)), En),
  14581. this.rc = new Map,
  14582. /**
  14583. * The keys of documents that are in limbo for which we haven't yet started a
  14584. * limbo resolution query. The strings in this set are the result of calling
  14585. * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
  14586. *
  14587. * The `Set` type was chosen because it provides efficient lookup and removal
  14588. * of arbitrary elements and it also maintains insertion order, providing the
  14589. * desired queue-like FIFO semantics.
  14590. */
  14591. this.oc = new Set,
  14592. /**
  14593. * Keeps track of the target ID for each document that is in limbo with an
  14594. * active target.
  14595. */
  14596. this.uc = new je(at.comparator),
  14597. /**
  14598. * Keeps track of the information about an active limbo resolution for each
  14599. * active target ID that was started for the purpose of limbo resolution.
  14600. */
  14601. this.cc = new Map, this.ac = new Ro,
  14602. /** Stores user completion handlers, indexed by User and BatchId. */
  14603. this.hc = {},
  14604. /** Stores user callbacks waiting for all pending writes to be acknowledged. */
  14605. this.lc = new Map, this.fc = Zr.vn(), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14606. // The primary state is set to `true` or `false` immediately after Firestore
  14607. // startup. In the interim, a client should only be considered primary if
  14608. // `isPrimary` is true.
  14609. this.dc = void 0;
  14610. }
  14611. get isPrimaryClient() {
  14612. return !0 === this.dc;
  14613. }
  14614. }
  14615. /**
  14616. * Initiates the new listen, resolves promise when listen enqueued to the
  14617. * server. All the subsequent view snapshots or errors are sent to the
  14618. * subscribed handlers. Returns the initial snapshot.
  14619. */
  14620. async function vc(t, e) {
  14621. const n = na(t);
  14622. let s, i;
  14623. const r = n.ic.get(e);
  14624. if (r)
  14625. // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
  14626. // already exists when EventManager calls us for the first time. This
  14627. // happens when the primary tab is already listening to this query on
  14628. // behalf of another tab and the user of the primary also starts listening
  14629. // to the query. EventManager will not have an assigned target ID in this
  14630. // case and calls `listen` to obtain this ID.
  14631. s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.ec(); else {
  14632. const t = await Jo(n.localStore, pn(e));
  14633. n.isPrimaryClient && xu(n.remoteStore, t);
  14634. const r = n.sharedClientState.addLocalQueryTarget(t.targetId);
  14635. s = t.targetId, i = await Vc(n, e, s, "current" === r, t.resumeToken);
  14636. }
  14637. return i;
  14638. }
  14639. /**
  14640. * Registers a view for a previously unknown query and computes its initial
  14641. * snapshot.
  14642. */ async function Vc(t, e, n, s, i) {
  14643. // PORTING NOTE: On Web only, we inject the code that registers new Limbo
  14644. // targets based on view changes. This allows us to only depend on Limbo
  14645. // changes when user code includes queries.
  14646. t._c = (e, n, s) => async function(t, e, n, s) {
  14647. let i = e.view.Wu(n);
  14648. i.$i && (
  14649. // The query has a limit and some docs were removed, so we need
  14650. // to re-run the query against the local store to make sure we
  14651. // didn't lose any good docs that had been past the limit.
  14652. i = await Xo(t.localStore, e.query,
  14653. /* usePreviousResults= */ !1).then((({documents: t}) => e.view.Wu(t, i))));
  14654. const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i,
  14655. /* updateLimboDocuments= */ t.isPrimaryClient, r);
  14656. return qc(t, e.targetId, o.Xu), o.snapshot;
  14657. }(t, e, n, s);
  14658. const r = await Xo(t.localStore, e,
  14659. /* usePreviousResults= */ !0), o = new Ac(e, r.Hi), u = o.Wu(r.documents), c = Vs.createSynthesizedTargetChangeForCurrentChange(n, s && "Offline" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u,
  14660. /* updateLimboDocuments= */ t.isPrimaryClient, c);
  14661. qc(t, n, a.Xu);
  14662. const h = new Rc(e, n, o);
  14663. return t.ic.set(e, h), t.rc.has(n) ? t.rc.get(n).push(e) : t.rc.set(n, [ e ]), a.snapshot;
  14664. }
  14665. /** Stops listening to the query. */ async function Sc(t, e) {
  14666. const n = B(t), s = n.ic.get(e), i = n.rc.get(s.targetId);
  14667. if (i.length > 1) return n.rc.set(s.targetId, i.filter((t => !En(t, e)))), void n.ic.delete(e);
  14668. // No other queries are mapped to the target, clean up the query and the target.
  14669. if (n.isPrimaryClient) {
  14670. // We need to remove the local query target first to allow us to verify
  14671. // whether any other client is still interested in this target.
  14672. n.sharedClientState.removeLocalQueryTarget(s.targetId);
  14673. n.sharedClientState.isActiveQueryTarget(s.targetId) || await Yo(n.localStore, s.targetId,
  14674. /*keepPersistedTargetData=*/ !1).then((() => {
  14675. n.sharedClientState.clearQueryState(s.targetId), Nu(n.remoteStore, s.targetId),
  14676. Bc(n, s.targetId);
  14677. })).catch(At);
  14678. } else Bc(n, s.targetId), await Yo(n.localStore, s.targetId,
  14679. /*keepPersistedTargetData=*/ !0);
  14680. }
  14681. /**
  14682. * Initiates the write of local mutation batch which involves adding the
  14683. * writes to the mutation queue, notifying the remote store about new
  14684. * mutations and raising events for any changes this write caused.
  14685. *
  14686. * The promise returned by this call is resolved when the above steps
  14687. * have completed, *not* when the write was acked by the backend. The
  14688. * userCallback is resolved once the write was acked/rejected by the
  14689. * backend (or failed locally for any other reason).
  14690. */ async function Dc(t, e, n) {
  14691. const s = sa(t);
  14692. try {
  14693. const t = await function(t, e) {
  14694. const n = B(t), s = st.now(), i = e.reduce(((t, e) => t.add(e.key)), Rs());
  14695. let r, o;
  14696. return n.persistence.runTransaction("Locally write mutations", "readwrite", (t => {
  14697. // Figure out which keys do not have a remote version in the cache, this
  14698. // is needed to create the right overlay mutation: if no remote version
  14699. // presents, we do not need to create overlays as patch mutations.
  14700. // TODO(Overlay): Is there a better way to determine this? Using the
  14701. // document version does not work because local mutations set them back
  14702. // to 0.
  14703. let u = ws(), c = Rs();
  14704. return n.Gi.getEntries(t, i).next((t => {
  14705. u = t, u.forEach(((t, e) => {
  14706. e.isValidDocument() || (c = c.add(t));
  14707. }));
  14708. })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {
  14709. r = i;
  14710. // For non-idempotent mutations (such as `FieldValue.increment()`),
  14711. // we record the base state in a separate patch mutation. This is
  14712. // later used to guarantee consistent values and prevents flicker
  14713. // even if the backend sends us an update that already includes our
  14714. // transform.
  14715. const o = [];
  14716. for (const t of e) {
  14717. const e = Zn(t, r.get(t.key).overlayedDocument);
  14718. null != e &&
  14719. // NOTE: The base state should only be applied if there's some
  14720. // existing document to override, so use a Precondition of
  14721. // exists=true
  14722. o.push(new ns(t.key, e, tn(e.value.mapValue), Wn.exists(!0)));
  14723. }
  14724. return n.mutationQueue.addMutationBatch(t, s, o, e);
  14725. })).next((e => {
  14726. o = e;
  14727. const s = e.applyToLocalDocumentSet(r, c);
  14728. return n.documentOverlayCache.saveOverlays(t, e.batchId, s);
  14729. }));
  14730. })).then((() => ({
  14731. batchId: o.batchId,
  14732. changes: ys(r)
  14733. })));
  14734. }(s.localStore, e);
  14735. s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {
  14736. let s = t.hc[t.currentUser.toKey()];
  14737. s || (s = new je(tt));
  14738. s = s.insert(e, n), t.hc[t.currentUser.toKey()] = s;
  14739. }
  14740. /**
  14741. * Resolves or rejects the user callback for the given batch and then discards
  14742. * it.
  14743. */ (s, t.batchId, n), await Gc(s, t.changes), await Qu(s.remoteStore);
  14744. } catch (t) {
  14745. // If we can't persist the mutation, we reject the user callback and
  14746. // don't send the mutation. The user can then retry the write.
  14747. const e = rc(t, "Failed to persist write");
  14748. n.reject(e);
  14749. }
  14750. }
  14751. /**
  14752. * Applies one remote event to the sync engine, notifying any views of the
  14753. * changes, and releasing any pending mutation batches that would become
  14754. * visible because of the snapshot version the remote event contains.
  14755. */ async function Cc(t, e) {
  14756. const n = B(t);
  14757. try {
  14758. const t = await Wo(n.localStore, e);
  14759. // Update `receivedDocument` as appropriate for any limbo targets.
  14760. e.targetChanges.forEach(((t, e) => {
  14761. const s = n.cc.get(e);
  14762. s && (
  14763. // Since this is a limbo resolution lookup, it's for a single document
  14764. // and it could be added, modified, or removed, but not a combination.
  14765. F(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1),
  14766. t.addedDocuments.size > 0 ? s.nc = !0 : t.modifiedDocuments.size > 0 ? F(s.nc) : t.removedDocuments.size > 0 && (F(s.nc),
  14767. s.nc = !1));
  14768. })), await Gc(n, t, e);
  14769. } catch (t) {
  14770. await At(t);
  14771. }
  14772. }
  14773. /**
  14774. * Applies an OnlineState change to the sync engine and notifies any views of
  14775. * the change.
  14776. */ function xc(t, e, n) {
  14777. const s = B(t);
  14778. // If we are the secondary client, we explicitly ignore the remote store's
  14779. // online state (the local client may go offline, even though the primary
  14780. // tab remains online) and only apply the primary tab's online state from
  14781. // SharedClientState.
  14782. if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
  14783. const t = [];
  14784. s.ic.forEach(((n, s) => {
  14785. const i = s.view.bu(e);
  14786. i.snapshot && t.push(i.snapshot);
  14787. })), function(t, e) {
  14788. const n = B(t);
  14789. n.onlineState = e;
  14790. let s = !1;
  14791. n.queries.forEach(((t, n) => {
  14792. for (const t of n.listeners)
  14793. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14794. t.bu(e) && (s = !0);
  14795. })), s && wc(n);
  14796. }(s.eventManager, e), t.length && s.sc.Wo(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);
  14797. }
  14798. }
  14799. /**
  14800. * Rejects the listen for the given targetID. This can be triggered by the
  14801. * backend for any active target.
  14802. *
  14803. * @param syncEngine - The sync engine implementation.
  14804. * @param targetId - The targetID corresponds to one previously initiated by the
  14805. * user as part of TargetData passed to listen() on RemoteStore.
  14806. * @param err - A description of the condition that has forced the rejection.
  14807. * Nearly always this will be an indication that the user is no longer
  14808. * authorized to see the data matching the target.
  14809. */ async function Nc(t, e, n) {
  14810. const s = B(t);
  14811. // PORTING NOTE: Multi-tab only.
  14812. s.sharedClientState.updateQueryState(e, "rejected", n);
  14813. const i = s.cc.get(e), r = i && i.key;
  14814. if (r) {
  14815. // TODO(klimt): We really only should do the following on permission
  14816. // denied errors, but we don't have the cause code here.
  14817. // It's a limbo doc. Create a synthetic event saying it was deleted.
  14818. // This is kind of a hack. Ideally, we would have a method in the local
  14819. // store to purge a document. However, it would be tricky to keep all of
  14820. // the local store's invariants with another method.
  14821. let t = new je(at.comparator);
  14822. // TODO(b/217189216): This limbo document should ideally have a read time,
  14823. // so that it is picked up by any read-time based scans. The backend,
  14824. // however, does not send a read time for target removals.
  14825. t = t.insert(r, en.newNoDocument(r, it.min()));
  14826. const n = Rs().add(r), i = new vs(it.min(),
  14827. /* targetChanges= */ new Map,
  14828. /* targetMismatches= */ new He(tt), t, n);
  14829. await Cc(s, i),
  14830. // Since this query failed, we won't want to manually unlisten to it.
  14831. // We only remove it from bookkeeping after we successfully applied the
  14832. // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
  14833. // this query when the RemoteStore restarts the Watch stream, which should
  14834. // re-trigger the target failure.
  14835. s.uc = s.uc.remove(r), s.cc.delete(e), Kc(s);
  14836. } else await Yo(s.localStore, e,
  14837. /* keepPersistedTargetData */ !1).then((() => Bc(s, e, n))).catch(At);
  14838. }
  14839. async function kc(t, e) {
  14840. const n = B(t), s = e.batch.batchId;
  14841. try {
  14842. const t = await Qo(n.localStore, e);
  14843. // The local store may or may not be able to apply the write result and
  14844. // raise events immediately (depending on whether the watcher is caught
  14845. // up), so we raise user callbacks first so that they consistently happen
  14846. // before listen events.
  14847. $c(n, s, /*error=*/ null), Fc(n, s), n.sharedClientState.updateMutationState(s, "acknowledged"),
  14848. await Gc(n, t);
  14849. } catch (t) {
  14850. await At(t);
  14851. }
  14852. }
  14853. async function Oc(t, e, n) {
  14854. const s = B(t);
  14855. try {
  14856. const t = await function(t, e) {
  14857. const n = B(t);
  14858. return n.persistence.runTransaction("Reject batch", "readwrite-primary", (t => {
  14859. let s;
  14860. return n.mutationQueue.lookupMutationBatch(t, e).next((e => (F(null !== e), s = e.keys(),
  14861. n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));
  14862. }));
  14863. }
  14864. /**
  14865. * Returns the largest (latest) batch id in mutation queue that is pending
  14866. * server response.
  14867. *
  14868. * Returns `BATCHID_UNKNOWN` if the queue is empty.
  14869. */ (s.localStore, e);
  14870. // The local store may or may not be able to apply the write result and
  14871. // raise events immediately (depending on whether the watcher is caught up),
  14872. // so we raise user callbacks first so that they consistently happen before
  14873. // listen events.
  14874. $c(s, e, n), Fc(s, e), s.sharedClientState.updateMutationState(e, "rejected", n),
  14875. await Gc(s, t);
  14876. } catch (n) {
  14877. await At(n);
  14878. }
  14879. }
  14880. /**
  14881. * Registers a user callback that resolves when all pending mutations at the moment of calling
  14882. * are acknowledged .
  14883. */ async function Mc(t, e) {
  14884. const n = B(t);
  14885. $u(n.remoteStore) || x("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
  14886. try {
  14887. const t = await function(t) {
  14888. const e = B(t);
  14889. return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));
  14890. }(n.localStore);
  14891. if (-1 === t)
  14892. // Trigger the callback right away if there is no pending writes at the moment.
  14893. return void e.resolve();
  14894. const s = n.lc.get(t) || [];
  14895. s.push(e), n.lc.set(t, s);
  14896. } catch (t) {
  14897. const n = rc(t, "Initialization of waitForPendingWrites() operation failed");
  14898. e.reject(n);
  14899. }
  14900. }
  14901. /**
  14902. * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
  14903. * if there are any.
  14904. */ function Fc(t, e) {
  14905. (t.lc.get(e) || []).forEach((t => {
  14906. t.resolve();
  14907. })), t.lc.delete(e);
  14908. }
  14909. /** Reject all outstanding callbacks waiting for pending writes to complete. */ function $c(t, e, n) {
  14910. const s = B(t);
  14911. let i = s.hc[s.currentUser.toKey()];
  14912. // NOTE: Mutations restored from persistence won't have callbacks, so it's
  14913. // okay for there to be no callback for this ID.
  14914. if (i) {
  14915. const t = i.get(e);
  14916. t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.hc[s.currentUser.toKey()] = i;
  14917. }
  14918. }
  14919. function Bc(t, e, n = null) {
  14920. t.sharedClientState.removeLocalQueryTarget(e);
  14921. for (const s of t.rc.get(e)) t.ic.delete(s), n && t.sc.wc(s, n);
  14922. if (t.rc.delete(e), t.isPrimaryClient) {
  14923. t.ac.ls(e).forEach((e => {
  14924. t.ac.containsKey(e) ||
  14925. // We removed the last reference for this key
  14926. Lc(t, e);
  14927. }));
  14928. }
  14929. }
  14930. function Lc(t, e) {
  14931. t.oc.delete(e.path.canonicalString());
  14932. // It's possible that the target already got removed because the query failed. In that case,
  14933. // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
  14934. const n = t.uc.get(e);
  14935. null !== n && (Nu(t.remoteStore, n), t.uc = t.uc.remove(e), t.cc.delete(n), Kc(t));
  14936. }
  14937. function qc(t, e, n) {
  14938. for (const s of n) if (s instanceof Tc) t.ac.addReference(s.key, e), Uc(t, s); else if (s instanceof Ec) {
  14939. x("SyncEngine", "Document no longer in limbo: " + s.key), t.ac.removeReference(s.key, e);
  14940. t.ac.containsKey(s.key) ||
  14941. // We removed the last reference for this key
  14942. Lc(t, s.key);
  14943. } else M();
  14944. }
  14945. function Uc(t, e) {
  14946. const n = e.key, s = n.path.canonicalString();
  14947. t.uc.get(n) || t.oc.has(s) || (x("SyncEngine", "New document in limbo: " + n), t.oc.add(s),
  14948. Kc(t));
  14949. }
  14950. /**
  14951. * Starts listens for documents in limbo that are enqueued for resolution,
  14952. * subject to a maximum number of concurrent resolutions.
  14953. *
  14954. * Without bounding the number of concurrent resolutions, the server can fail
  14955. * with "resource exhausted" errors which can lead to pathological client
  14956. * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
  14957. */ function Kc(t) {
  14958. for (;t.oc.size > 0 && t.uc.size < t.maxConcurrentLimboResolutions; ) {
  14959. const e = t.oc.values().next().value;
  14960. t.oc.delete(e);
  14961. const n = new at(ot.fromString(e)), s = t.fc.next();
  14962. t.cc.set(s, new bc(n)), t.uc = t.uc.insert(n, s), xu(t.remoteStore, new Ji(pn(dn(n.path)), s, 2 /* TargetPurpose.LimboResolution */ , Mt.at));
  14963. }
  14964. }
  14965. async function Gc(t, e, n) {
  14966. const s = B(t), i = [], r = [], o = [];
  14967. s.ic.isEmpty() || (s.ic.forEach(((t, u) => {
  14968. o.push(s._c(u, e, n).then((t => {
  14969. // Update views if there are actual changes.
  14970. if (
  14971. // If there are changes, or we are handling a global snapshot, notify
  14972. // secondary clients to update query state.
  14973. (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? "not-current" : "current"),
  14974. t) {
  14975. i.push(t);
  14976. const e = Lo.Ci(u.targetId, t);
  14977. r.push(e);
  14978. }
  14979. })));
  14980. })), await Promise.all(o), s.sc.Wo(i), await async function(t, e) {
  14981. const n = B(t);
  14982. try {
  14983. await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (t => Rt.forEach(e, (e => Rt.forEach(e.Si, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => Rt.forEach(e.Di, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));
  14984. } catch (t) {
  14985. if (!St(t)) throw t;
  14986. // If `notifyLocalViewChanges` fails, we did not advance the sequence
  14987. // number for the documents that were included in this transaction.
  14988. // This might trigger them to be deleted earlier than they otherwise
  14989. // would have, but it should not invalidate the integrity of the data.
  14990. x("LocalStore", "Failed to update sequence numbers: " + t);
  14991. }
  14992. for (const t of e) {
  14993. const e = t.targetId;
  14994. if (!t.fromCache) {
  14995. const t = n.qi.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);
  14996. // Advance the last limbo free snapshot version
  14997. n.qi = n.qi.insert(e, i);
  14998. }
  14999. }
  15000. }(s.localStore, r));
  15001. }
  15002. async function Qc(t, e) {
  15003. const n = B(t);
  15004. if (!n.currentUser.isEqual(e)) {
  15005. x("SyncEngine", "User change. New user:", e.toKey());
  15006. const t = await Go(n.localStore, e);
  15007. n.currentUser = e,
  15008. // Fails tasks waiting for pending writes requested by previous user.
  15009. function(t, e) {
  15010. t.lc.forEach((t => {
  15011. t.forEach((t => {
  15012. t.reject(new q(L.CANCELLED, e));
  15013. }));
  15014. })), t.lc.clear();
  15015. }(n, "'waitForPendingWrites' promise is rejected due to a user change."),
  15016. // TODO(b/114226417): Consider calling this only in the primary tab.
  15017. n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await Gc(n, t.ji);
  15018. }
  15019. }
  15020. function jc(t, e) {
  15021. const n = B(t), s = n.cc.get(e);
  15022. if (s && s.nc) return Rs().add(s.key);
  15023. {
  15024. let t = Rs();
  15025. const s = n.rc.get(e);
  15026. if (!s) return t;
  15027. for (const e of s) {
  15028. const s = n.ic.get(e);
  15029. t = t.unionWith(s.view.ju);
  15030. }
  15031. return t;
  15032. }
  15033. }
  15034. /**
  15035. * Reconcile the list of synced documents in an existing view with those
  15036. * from persistence.
  15037. */ async function Wc(t, e) {
  15038. const n = B(t), s = await Xo(n.localStore, e.query,
  15039. /* usePreviousResults= */ !0), i = e.view.tc(s);
  15040. return n.isPrimaryClient && qc(n, e.targetId, i.Xu), i;
  15041. }
  15042. /**
  15043. * Retrieves newly changed documents from remote document cache and raises
  15044. * snapshots if needed.
  15045. */
  15046. // PORTING NOTE: Multi-Tab only.
  15047. async function zc(t, e) {
  15048. const n = B(t);
  15049. return tu(n.localStore, e).then((t => Gc(n, t)));
  15050. }
  15051. /** Applies a mutation state to an existing batch. */
  15052. // PORTING NOTE: Multi-Tab only.
  15053. async function Hc(t, e, n, s) {
  15054. const i = B(t), r = await function(t, e) {
  15055. const n = B(t), s = B(n.mutationQueue);
  15056. return n.persistence.runTransaction("Lookup mutation documents", "readonly", (t => s.Tn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : Rt.resolve(null)))));
  15057. }
  15058. // PORTING NOTE: Multi-Tab only.
  15059. (i.localStore, e);
  15060. null !== r ? ("pending" === n ?
  15061. // If we are the primary client, we need to send this write to the
  15062. // backend. Secondary clients will ignore these writes since their remote
  15063. // connection is disabled.
  15064. await Qu(i.remoteStore) : "acknowledged" === n || "rejected" === n ? (
  15065. // NOTE: Both these methods are no-ops for batches that originated from
  15066. // other clients.
  15067. $c(i, e, s || null), Fc(i, e), function(t, e) {
  15068. B(B(t).mutationQueue).An(e);
  15069. }
  15070. // PORTING NOTE: Multi-Tab only.
  15071. (i.localStore, e)) : M(), await Gc(i, r)) :
  15072. // A throttled tab may not have seen the mutation before it was completed
  15073. // and removed from the mutation queue, in which case we won't have cached
  15074. // the affected documents. In this case we can safely ignore the update
  15075. // since that means we didn't apply the mutation locally at all (if we
  15076. // had, we would have cached the affected documents), and so we will just
  15077. // see any resulting document changes via normal remote document updates
  15078. // as applicable.
  15079. x("SyncEngine", "Cannot apply mutation batch with id: " + e);
  15080. }
  15081. /** Applies a query target change from a different tab. */
  15082. // PORTING NOTE: Multi-Tab only.
  15083. async function Jc(t, e) {
  15084. const n = B(t);
  15085. if (na(n), sa(n), !0 === e && !0 !== n.dc) {
  15086. // Secondary tabs only maintain Views for their local listeners and the
  15087. // Views internal state may not be 100% populated (in particular
  15088. // secondary tabs don't track syncedDocuments, the set of documents the
  15089. // server considers to be in the target). So when a secondary becomes
  15090. // primary, we need to need to make sure that all views for all targets
  15091. // match the state on disk.
  15092. const t = n.sharedClientState.getAllActiveQueryTargets(), e = await Yc(n, t.toArray());
  15093. n.dc = !0, await ec(n.remoteStore, !0);
  15094. for (const t of e) xu(n.remoteStore, t);
  15095. } else if (!1 === e && !1 !== n.dc) {
  15096. const t = [];
  15097. let e = Promise.resolve();
  15098. n.rc.forEach(((s, i) => {
  15099. n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (Bc(n, i),
  15100. Yo(n.localStore, i,
  15101. /*keepPersistedTargetData=*/ !0)))), Nu(n.remoteStore, i);
  15102. })), await e, await Yc(n, t),
  15103. // PORTING NOTE: Multi-Tab only.
  15104. function(t) {
  15105. const e = B(t);
  15106. e.cc.forEach(((t, n) => {
  15107. Nu(e.remoteStore, n);
  15108. })), e.ac.fs(), e.cc = new Map, e.uc = new je(at.comparator);
  15109. }
  15110. /**
  15111. * Reconcile the query views of the provided query targets with the state from
  15112. * persistence. Raises snapshots for any changes that affect the local
  15113. * client and returns the updated state of all target's query data.
  15114. *
  15115. * @param syncEngine - The sync engine implementation
  15116. * @param targets - the list of targets with views that need to be recomputed
  15117. * @param transitionToPrimary - `true` iff the tab transitions from a secondary
  15118. * tab to a primary tab
  15119. */
  15120. // PORTING NOTE: Multi-Tab only.
  15121. (n), n.dc = !1, await ec(n.remoteStore, !1);
  15122. }
  15123. }
  15124. async function Yc(t, e, n) {
  15125. const s = B(t), i = [], r = [];
  15126. for (const t of e) {
  15127. let e;
  15128. const n = s.rc.get(t);
  15129. if (n && 0 !== n.length) {
  15130. // For queries that have a local View, we fetch their current state
  15131. // from LocalStore (as the resume token and the snapshot version
  15132. // might have changed) and reconcile their views with the persisted
  15133. // state (the list of syncedDocuments may have gotten out of sync).
  15134. e = await Jo(s.localStore, pn(n[0]));
  15135. for (const t of n) {
  15136. const e = s.ic.get(t), n = await Wc(s, e);
  15137. n.snapshot && r.push(n.snapshot);
  15138. }
  15139. } else {
  15140. // For queries that never executed on this client, we need to
  15141. // allocate the target in LocalStore and initialize a new View.
  15142. const n = await Zo(s.localStore, t);
  15143. e = await Jo(s.localStore, n), await Vc(s, Xc(n), t,
  15144. /*current=*/ !1, e.resumeToken);
  15145. }
  15146. i.push(e);
  15147. }
  15148. return s.sc.Wo(r), i;
  15149. }
  15150. /**
  15151. * Creates a `Query` object from the specified `Target`. There is no way to
  15152. * obtain the original `Query`, so we synthesize a `Query` from the `Target`
  15153. * object.
  15154. *
  15155. * The synthesized result might be different from the original `Query`, but
  15156. * since the synthesized `Query` should return the same results as the
  15157. * original one (only the presentation of results might differ), the potential
  15158. * difference will not cause issues.
  15159. */
  15160. // PORTING NOTE: Multi-Tab only.
  15161. function Xc(t) {
  15162. return fn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* LimitType.First */ , t.startAt, t.endAt);
  15163. }
  15164. /** Returns the IDs of the clients that are currently active. */
  15165. // PORTING NOTE: Multi-Tab only.
  15166. function Zc(t) {
  15167. const e = B(t);
  15168. return B(B(e.localStore).persistence).vi();
  15169. }
  15170. /** Applies a query target change from a different tab. */
  15171. // PORTING NOTE: Multi-Tab only.
  15172. async function ta(t, e, n, s) {
  15173. const i = B(t);
  15174. if (i.dc)
  15175. // If we receive a target state notification via WebStorage, we are
  15176. // either already secondary or another tab has taken the primary lease.
  15177. return void x("SyncEngine", "Ignoring unexpected query state notification.");
  15178. const r = i.rc.get(e);
  15179. if (r && r.length > 0) switch (n) {
  15180. case "current":
  15181. case "not-current":
  15182. {
  15183. const t = await tu(i.localStore, Pn(r[0])), s = vs.createSynthesizedRemoteEventForCurrentChange(e, "current" === n, Wt.EMPTY_BYTE_STRING);
  15184. await Gc(i, t, s);
  15185. break;
  15186. }
  15187. case "rejected":
  15188. await Yo(i.localStore, e,
  15189. /* keepPersistedTargetData */ !0), Bc(i, e, s);
  15190. break;
  15191. default:
  15192. M();
  15193. }
  15194. }
  15195. /** Adds or removes Watch targets for queries from different tabs. */ async function ea(t, e, n) {
  15196. const s = na(t);
  15197. if (s.dc) {
  15198. for (const t of e) {
  15199. if (s.rc.has(t)) {
  15200. // A target might have been added in a previous attempt
  15201. x("SyncEngine", "Adding an already active target " + t);
  15202. continue;
  15203. }
  15204. const e = await Zo(s.localStore, t), n = await Jo(s.localStore, e);
  15205. await Vc(s, Xc(e), n.targetId,
  15206. /*current=*/ !1, n.resumeToken), xu(s.remoteStore, n);
  15207. }
  15208. for (const t of n)
  15209. // Check that the target is still active since the target might have been
  15210. // removed if it has been rejected by the backend.
  15211. s.rc.has(t) &&
  15212. // Release queries that are still active.
  15213. await Yo(s.localStore, t,
  15214. /* keepPersistedTargetData */ !1).then((() => {
  15215. Nu(s.remoteStore, t), Bc(s, t);
  15216. })).catch(At);
  15217. }
  15218. }
  15219. function na(t) {
  15220. const e = B(t);
  15221. return e.remoteStore.remoteSyncer.applyRemoteEvent = Cc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = jc.bind(null, e),
  15222. e.remoteStore.remoteSyncer.rejectListen = Nc.bind(null, e), e.sc.Wo = dc.bind(null, e.eventManager),
  15223. e.sc.wc = _c.bind(null, e.eventManager), e;
  15224. }
  15225. function sa(t) {
  15226. const e = B(t);
  15227. return e.remoteStore.remoteSyncer.applySuccessfulWrite = kc.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Oc.bind(null, e),
  15228. e;
  15229. }
  15230. /**
  15231. * Loads a Firestore bundle into the SDK. The returned promise resolves when
  15232. * the bundle finished loading.
  15233. *
  15234. * @param syncEngine - SyncEngine to use.
  15235. * @param bundleReader - Bundle to load into the SDK.
  15236. * @param task - LoadBundleTask used to update the loading progress to public API.
  15237. */ function ia(t, e, n) {
  15238. const s = B(t);
  15239. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  15240. (
  15241. /** Loads a bundle and returns the list of affected collection groups. */
  15242. async function(t, e, n) {
  15243. try {
  15244. const s = await e.getMetadata();
  15245. if (await function(t, e) {
  15246. const n = B(t), s = Ks(e.createTime);
  15247. return n.persistence.runTransaction("hasNewerBundle", "readonly", (t => n.Ns.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));
  15248. }
  15249. /**
  15250. * Saves the given `BundleMetadata` to local persistence.
  15251. */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {
  15252. return {
  15253. taskState: "Success",
  15254. documentsLoaded: t.totalDocuments,
  15255. bytesLoaded: t.totalBytes,
  15256. totalDocuments: t.totalDocuments,
  15257. totalBytes: t.totalBytes
  15258. };
  15259. }(s)), Promise.resolve(new Set);
  15260. n._updateProgress(Ic(s));
  15261. const i = new pc(s, t.localStore, e.yt);
  15262. let r = await e.mc();
  15263. for (;r; ) {
  15264. const t = await i.Fu(r);
  15265. t && n._updateProgress(t), r = await e.mc();
  15266. }
  15267. const o = await i.complete();
  15268. return await Gc(t, o.Lu,
  15269. /* remoteEvent */ void 0),
  15270. // Save metadata, so loading the same bundle will skip.
  15271. await function(t, e) {
  15272. const n = B(t);
  15273. return n.persistence.runTransaction("Save bundle", "readwrite", (t => n.Ns.saveBundleMetadata(t, e)));
  15274. }
  15275. /**
  15276. * Returns a promise of a `NamedQuery` associated with given query name. Promise
  15277. * resolves to undefined if no persisted data can be found.
  15278. */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Bu);
  15279. } catch (t) {
  15280. return k("SyncEngine", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);
  15281. }
  15282. }
  15283. /**
  15284. * @license
  15285. * Copyright 2020 Google LLC
  15286. *
  15287. * Licensed under the Apache License, Version 2.0 (the "License");
  15288. * you may not use this file except in compliance with the License.
  15289. * You may obtain a copy of the License at
  15290. *
  15291. * http://www.apache.org/licenses/LICENSE-2.0
  15292. *
  15293. * Unless required by applicable law or agreed to in writing, software
  15294. * distributed under the License is distributed on an "AS IS" BASIS,
  15295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15296. * See the License for the specific language governing permissions and
  15297. * limitations under the License.
  15298. */
  15299. /**
  15300. * Provides all components needed for Firestore with in-memory persistence.
  15301. * Uses EagerGC garbage collection.
  15302. */)(s, e, n).then((t => {
  15303. s.sharedClientState.notifyBundleLoaded(t);
  15304. }));
  15305. }
  15306. class ra {
  15307. constructor() {
  15308. this.synchronizeTabs = !1;
  15309. }
  15310. async initialize(t) {
  15311. this.yt = Tu(t.databaseInfo.databaseId), this.sharedClientState = this.gc(t), this.persistence = this.yc(t),
  15312. await this.persistence.start(), this.localStore = this.Ic(t), this.gcScheduler = this.Tc(t, this.localStore),
  15313. this.indexBackfillerScheduler = this.Ec(t, this.localStore);
  15314. }
  15315. Tc(t, e) {
  15316. return null;
  15317. }
  15318. Ec(t, e) {
  15319. return null;
  15320. }
  15321. Ic(t) {
  15322. return Ko(this.persistence, new qo, t.initialUser, this.yt);
  15323. }
  15324. yc(t) {
  15325. return new Do(xo.Bs, this.yt);
  15326. }
  15327. gc(t) {
  15328. return new du;
  15329. }
  15330. async terminate() {
  15331. this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(),
  15332. await this.persistence.shutdown();
  15333. }
  15334. }
  15335. /**
  15336. * Provides all components needed for Firestore with IndexedDB persistence.
  15337. */ class oa extends ra {
  15338. constructor(t, e, n) {
  15339. super(), this.Ac = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;
  15340. }
  15341. async initialize(t) {
  15342. await super.initialize(t), await this.Ac.initialize(this, t),
  15343. // Enqueue writes from a previous session
  15344. await sa(this.Ac.syncEngine), await Qu(this.Ac.remoteStore),
  15345. // NOTE: This will immediately call the listener, so we make sure to
  15346. // set it after localStore / remoteStore are started.
  15347. await this.persistence.li((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(),
  15348. this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(),
  15349. Promise.resolve())));
  15350. }
  15351. Ic(t) {
  15352. return Ko(this.persistence, new qo, t.initialUser, this.yt);
  15353. }
  15354. Tc(t, e) {
  15355. const n = this.persistence.referenceDelegate.garbageCollector;
  15356. return new oo(n, t.asyncQueue, e);
  15357. }
  15358. Ec(t, e) {
  15359. const n = new Ot(e, this.persistence);
  15360. return new kt(t.asyncQueue, n);
  15361. }
  15362. yc(t) {
  15363. const e = Bo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? Qr.withCacheSize(this.cacheSizeBytes) : Qr.DEFAULT;
  15364. return new Mo(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, pu(), Iu(), this.yt, this.sharedClientState, !!this.forceOwnership);
  15365. }
  15366. gc(t) {
  15367. return new du;
  15368. }
  15369. }
  15370. /**
  15371. * Provides all components needed for Firestore with multi-tab IndexedDB
  15372. * persistence.
  15373. *
  15374. * In the legacy client, this provider is used to provide both multi-tab and
  15375. * non-multi-tab persistence since we cannot tell at build time whether
  15376. * `synchronizeTabs` will be enabled.
  15377. */ class ua extends oa {
  15378. constructor(t, e) {
  15379. super(t, e, /* forceOwnership= */ !1), this.Ac = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;
  15380. }
  15381. async initialize(t) {
  15382. await super.initialize(t);
  15383. const e = this.Ac.syncEngine;
  15384. this.sharedClientState instanceof fu && (this.sharedClientState.syncEngine = {
  15385. Fr: Hc.bind(null, e),
  15386. $r: ta.bind(null, e),
  15387. Br: ea.bind(null, e),
  15388. vi: Zc.bind(null, e),
  15389. Mr: zc.bind(null, e)
  15390. }, await this.sharedClientState.start()),
  15391. // NOTE: This will immediately call the listener, so we make sure to
  15392. // set it after localStore / remoteStore are started.
  15393. await this.persistence.li((async t => {
  15394. await Jc(this.Ac.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()),
  15395. this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());
  15396. }));
  15397. }
  15398. gc(t) {
  15399. const e = pu();
  15400. if (!fu.C(e)) throw new q(L.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
  15401. const n = Bo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);
  15402. return new fu(e, t.asyncQueue, n, t.clientId, t.initialUser);
  15403. }
  15404. }
  15405. /**
  15406. * Initializes and wires the components that are needed to interface with the
  15407. * network.
  15408. */ class ca {
  15409. async initialize(t, e) {
  15410. this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState,
  15411. this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e),
  15412. this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e,
  15413. /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => xc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */),
  15414. this.remoteStore.remoteSyncer.handleCredentialChange = Qc.bind(null, this.syncEngine),
  15415. await ec(this.remoteStore, this.syncEngine.isPrimaryClient));
  15416. }
  15417. createEventManager(t) {
  15418. return new hc;
  15419. }
  15420. createDatastore(t) {
  15421. const e = Tu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new yu(s));
  15422. var s;
  15423. /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {
  15424. return new Pu(t, e, n, s);
  15425. }(t.authCredentials, t.appCheckCredentials, n, e);
  15426. }
  15427. createRemoteStore(t) {
  15428. return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => xc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */),
  15429. r = wu.C() ? new wu : new _u, new Su(e, n, s, i, r);
  15430. var e, n, s, i, r;
  15431. /** Re-enables the network. Idempotent. */ }
  15432. createSyncEngine(t, e) {
  15433. return function(t, e, n,
  15434. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15435. s, i, r, o) {
  15436. const u = new Pc(t, e, n, s, i, r);
  15437. return o && (u.dc = !0), u;
  15438. }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
  15439. }
  15440. terminate() {
  15441. return async function(t) {
  15442. const e = B(t);
  15443. x("RemoteStore", "RemoteStore shutting down."), e._u.add(5 /* OfflineCause.Shutdown */),
  15444. await Cu(e), e.mu.shutdown(),
  15445. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
  15446. // triggering spurious listener events with cached data, etc.
  15447. e.gu.set("Unknown" /* OnlineState.Unknown */);
  15448. }(this.remoteStore);
  15449. }
  15450. }
  15451. /**
  15452. * @license
  15453. * Copyright 2017 Google LLC
  15454. *
  15455. * Licensed under the Apache License, Version 2.0 (the "License");
  15456. * you may not use this file except in compliance with the License.
  15457. * You may obtain a copy of the License at
  15458. *
  15459. * http://www.apache.org/licenses/LICENSE-2.0
  15460. *
  15461. * Unless required by applicable law or agreed to in writing, software
  15462. * distributed under the License is distributed on an "AS IS" BASIS,
  15463. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15464. * See the License for the specific language governing permissions and
  15465. * limitations under the License.
  15466. */ function aa(t, e, n) {
  15467. if (!n) throw new q(L.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);
  15468. }
  15469. /**
  15470. * Validates that two boolean options are not set at the same time.
  15471. * @internal
  15472. */ function ha(t, e, n, s) {
  15473. if (!0 === e && !0 === s) throw new q(L.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);
  15474. }
  15475. /**
  15476. * Validates that `path` refers to a document (indicated by the fact it contains
  15477. * an even numbers of segments).
  15478. */ function la(t) {
  15479. if (!at.isDocumentKey(t)) throw new q(L.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
  15480. }
  15481. /**
  15482. * Validates that `path` refers to a collection (indicated by the fact it
  15483. * contains an odd numbers of segments).
  15484. */ function fa(t) {
  15485. if (at.isDocumentKey(t)) throw new q(L.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
  15486. }
  15487. /**
  15488. * Returns true if it's a non-null object without a custom prototype
  15489. * (i.e. excludes Array, Date, etc.).
  15490. */
  15491. /** Returns a string describing the type / value of the provided input. */
  15492. function da(t) {
  15493. if (void 0 === t) return "undefined";
  15494. if (null === t) return "null";
  15495. if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`),
  15496. JSON.stringify(t);
  15497. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  15498. if ("object" == typeof t) {
  15499. if (t instanceof Array) return "an array";
  15500. {
  15501. const e =
  15502. /** try to get the constructor name for an object. */
  15503. function(t) {
  15504. if (t.constructor) return t.constructor.name;
  15505. return null;
  15506. }
  15507. /**
  15508. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  15509. * underlying instance. Throws if `obj` is not an instance of `T`.
  15510. *
  15511. * This cast is used in the Lite and Full SDK to verify instance types for
  15512. * arguments passed to the public API.
  15513. * @internal
  15514. */ (t);
  15515. return e ? `a custom ${e} object` : "an object";
  15516. }
  15517. }
  15518. return "function" == typeof t ? "a function" : M();
  15519. }
  15520. function _a(t,
  15521. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15522. e) {
  15523. if ("_delegate" in t && (
  15524. // Unwrap Compat types
  15525. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15526. t = t._delegate), !(t instanceof e)) {
  15527. if (e.name === t.constructor.name) throw new q(L.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  15528. {
  15529. const n = da(t);
  15530. throw new q(L.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);
  15531. }
  15532. }
  15533. return t;
  15534. }
  15535. function wa(t, e) {
  15536. if (e <= 0) throw new q(L.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);
  15537. }
  15538. /**
  15539. * @license
  15540. * Copyright 2020 Google LLC
  15541. *
  15542. * Licensed under the Apache License, Version 2.0 (the "License");
  15543. * you may not use this file except in compliance with the License.
  15544. * You may obtain a copy of the License at
  15545. *
  15546. * http://www.apache.org/licenses/LICENSE-2.0
  15547. *
  15548. * Unless required by applicable law or agreed to in writing, software
  15549. * distributed under the License is distributed on an "AS IS" BASIS,
  15550. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15551. * See the License for the specific language governing permissions and
  15552. * limitations under the License.
  15553. */ const ma = new Map;
  15554. /**
  15555. * An instance map that ensures only one Datastore exists per Firestore
  15556. * instance.
  15557. */
  15558. /**
  15559. * A concrete type describing all the values that can be applied via a
  15560. * user-supplied `FirestoreSettings` object. This is a separate type so that
  15561. * defaults can be supplied and the value can be checked for equality.
  15562. */
  15563. class ga {
  15564. constructor(t) {
  15565. var e;
  15566. if (void 0 === t.host) {
  15567. if (void 0 !== t.ssl) throw new q(L.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  15568. this.host = "firestore.googleapis.com", this.ssl = true;
  15569. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  15570. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  15571. void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  15572. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new q(L.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  15573. this.cacheSizeBytes = t.cacheSizeBytes;
  15574. }
  15575. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  15576. this.useFetchStreams = !!t.useFetchStreams, ha("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling);
  15577. }
  15578. isEqual(t) {
  15579. return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  15580. }
  15581. }
  15582. /**
  15583. * @license
  15584. * Copyright 2020 Google LLC
  15585. *
  15586. * Licensed under the Apache License, Version 2.0 (the "License");
  15587. * you may not use this file except in compliance with the License.
  15588. * You may obtain a copy of the License at
  15589. *
  15590. * http://www.apache.org/licenses/LICENSE-2.0
  15591. *
  15592. * Unless required by applicable law or agreed to in writing, software
  15593. * distributed under the License is distributed on an "AS IS" BASIS,
  15594. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15595. * See the License for the specific language governing permissions and
  15596. * limitations under the License.
  15597. */
  15598. /**
  15599. * The Cloud Firestore service interface.
  15600. *
  15601. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  15602. */ class ya {
  15603. /** @hideconstructor */
  15604. constructor(t, e, n, s) {
  15605. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  15606. this._app = s,
  15607. /**
  15608. * Whether it's a Firestore or Firestore Lite instance.
  15609. */
  15610. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new ga({}),
  15611. this._settingsFrozen = !1;
  15612. }
  15613. /**
  15614. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  15615. * instance.
  15616. */ get app() {
  15617. if (!this._app) throw new q(L.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  15618. return this._app;
  15619. }
  15620. get _initialized() {
  15621. return this._settingsFrozen;
  15622. }
  15623. get _terminated() {
  15624. return void 0 !== this._terminateTask;
  15625. }
  15626. _setSettings(t) {
  15627. if (this._settingsFrozen) throw new q(L.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
  15628. this._settings = new ga(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  15629. if (!t) return new G;
  15630. switch (t.type) {
  15631. case "gapi":
  15632. const e = t.client;
  15633. return new z(e, t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  15634. case "provider":
  15635. return t.client;
  15636. default:
  15637. throw new q(L.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
  15638. }
  15639. }(t.credentials));
  15640. }
  15641. _getSettings() {
  15642. return this._settings;
  15643. }
  15644. _freezeSettings() {
  15645. return this._settingsFrozen = !0, this._settings;
  15646. }
  15647. _delete() {
  15648. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  15649. }
  15650. /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
  15651. return {
  15652. app: this._app,
  15653. databaseId: this._databaseId,
  15654. settings: this._settings
  15655. };
  15656. }
  15657. /**
  15658. * Terminates all components used by this client. Subclasses can override
  15659. * this method to clean up their own dependencies, but must also call this
  15660. * method.
  15661. *
  15662. * Only ever called once.
  15663. */ _terminate() {
  15664. /**
  15665. * Removes all components associated with the provided instance. Must be called
  15666. * when the `Firestore` instance is terminated.
  15667. */
  15668. return function(t) {
  15669. const e = ma.get(t);
  15670. e && (x("ComponentProvider", "Removing Datastore"), ma.delete(t), e.terminate());
  15671. }(this), Promise.resolve();
  15672. }
  15673. }
  15674. /**
  15675. * Modify this instance to communicate with the Cloud Firestore emulator.
  15676. *
  15677. * Note: This must be called before this instance has been used to do any
  15678. * operations.
  15679. *
  15680. * @param firestore - The `Firestore` instance to configure to connect to the
  15681. * emulator.
  15682. * @param host - the emulator host (ex: localhost).
  15683. * @param port - the emulator port (ex: 9000).
  15684. * @param options.mockUserToken - the mock auth token to use for unit testing
  15685. * Security Rules.
  15686. */ function pa(t, e, n, s = {}) {
  15687. var i;
  15688. const r = (t = _a(t, ya))._getSettings();
  15689. if ("firestore.googleapis.com" !== r.host && r.host !== e && k("Host has been set in both settings() and useEmulator(), emulator host will be used"),
  15690. t._setSettings(Object.assign(Object.assign({}, r), {
  15691. host: `${e}:${n}`,
  15692. ssl: !1
  15693. })), s.mockUserToken) {
  15694. let e, n;
  15695. if ("string" == typeof s.mockUserToken) e = s.mockUserToken, n = v.MOCK_USER; else {
  15696. // Let createMockUserToken validate first (catches common mistakes like
  15697. // invalid field "uid" and missing field "sub" / "user_id".)
  15698. e = d(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);
  15699. const r = s.mockUserToken.sub || s.mockUserToken.user_id;
  15700. if (!r) throw new q(L.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  15701. n = new v(r);
  15702. }
  15703. t._authCredentials = new Q(new K(e, n));
  15704. }
  15705. }
  15706. /**
  15707. * @license
  15708. * Copyright 2020 Google LLC
  15709. *
  15710. * Licensed under the Apache License, Version 2.0 (the "License");
  15711. * you may not use this file except in compliance with the License.
  15712. * You may obtain a copy of the License at
  15713. *
  15714. * http://www.apache.org/licenses/LICENSE-2.0
  15715. *
  15716. * Unless required by applicable law or agreed to in writing, software
  15717. * distributed under the License is distributed on an "AS IS" BASIS,
  15718. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15719. * See the License for the specific language governing permissions and
  15720. * limitations under the License.
  15721. */
  15722. /**
  15723. * A `DocumentReference` refers to a document location in a Firestore database
  15724. * and can be used to write, read, or listen to the location. The document at
  15725. * the referenced location may or may not exist.
  15726. */ class Ia {
  15727. /** @hideconstructor */
  15728. constructor(t,
  15729. /**
  15730. * If provided, the `FirestoreDataConverter` associated with this instance.
  15731. */
  15732. e, n) {
  15733. this.converter = e, this._key = n,
  15734. /** The type of this Firestore reference. */
  15735. this.type = "document", this.firestore = t;
  15736. }
  15737. get _path() {
  15738. return this._key.path;
  15739. }
  15740. /**
  15741. * The document's identifier within its collection.
  15742. */ get id() {
  15743. return this._key.path.lastSegment();
  15744. }
  15745. /**
  15746. * A string representing the path of the referenced document (relative
  15747. * to the root of the database).
  15748. */ get path() {
  15749. return this._key.path.canonicalString();
  15750. }
  15751. /**
  15752. * The collection this `DocumentReference` belongs to.
  15753. */ get parent() {
  15754. return new Ea(this.firestore, this.converter, this._key.path.popLast());
  15755. }
  15756. withConverter(t) {
  15757. return new Ia(this.firestore, t, this._key);
  15758. }
  15759. }
  15760. /**
  15761. * A `Query` refers to a query which you can read or listen to. You can also
  15762. * construct refined `Query` objects by adding filters and ordering.
  15763. */ class Ta {
  15764. // This is the lite version of the Query class in the main SDK.
  15765. /** @hideconstructor protected */
  15766. constructor(t,
  15767. /**
  15768. * If provided, the `FirestoreDataConverter` associated with this instance.
  15769. */
  15770. e, n) {
  15771. this.converter = e, this._query = n,
  15772. /** The type of this Firestore reference. */
  15773. this.type = "query", this.firestore = t;
  15774. }
  15775. withConverter(t) {
  15776. return new Ta(this.firestore, t, this._query);
  15777. }
  15778. }
  15779. /**
  15780. * A `CollectionReference` object can be used for adding documents, getting
  15781. * document references, and querying for documents (using {@link query}).
  15782. */ class Ea extends Ta {
  15783. /** @hideconstructor */
  15784. constructor(t, e, n) {
  15785. super(t, e, dn(n)), this._path = n,
  15786. /** The type of this Firestore reference. */
  15787. this.type = "collection";
  15788. }
  15789. /** The collection's identifier. */ get id() {
  15790. return this._query.path.lastSegment();
  15791. }
  15792. /**
  15793. * A string representing the path of the referenced collection (relative
  15794. * to the root of the database).
  15795. */ get path() {
  15796. return this._query.path.canonicalString();
  15797. }
  15798. /**
  15799. * A reference to the containing `DocumentReference` if this is a
  15800. * subcollection. If this isn't a subcollection, the reference is null.
  15801. */ get parent() {
  15802. const t = this._path.popLast();
  15803. return t.isEmpty() ? null : new Ia(this.firestore,
  15804. /* converter= */ null, new at(t));
  15805. }
  15806. withConverter(t) {
  15807. return new Ea(this.firestore, t, this._path);
  15808. }
  15809. }
  15810. function Aa(t, e, ...n) {
  15811. if (t = _(t), aa("collection", "path", e), t instanceof ya) {
  15812. const s = ot.fromString(e, ...n);
  15813. return fa(s), new Ea(t, /* converter= */ null, s);
  15814. }
  15815. {
  15816. if (!(t instanceof Ia || t instanceof Ea)) throw new q(L.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  15817. const s = t._path.child(ot.fromString(e, ...n));
  15818. return fa(s), new Ea(t.firestore,
  15819. /* converter= */ null, s);
  15820. }
  15821. }
  15822. // TODO(firestorelite): Consider using ErrorFactory -
  15823. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  15824. /**
  15825. * Creates and returns a new `Query` instance that includes all documents in the
  15826. * database that are contained in a collection or subcollection with the
  15827. * given `collectionId`.
  15828. *
  15829. * @param firestore - A reference to the root `Firestore` instance.
  15830. * @param collectionId - Identifies the collections to query over. Every
  15831. * collection or subcollection with this ID as the last segment of its path
  15832. * will be included. Cannot contain a slash.
  15833. * @returns The created `Query`.
  15834. */ function Ra(t, e) {
  15835. if (t = _a(t, ya), aa("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new q(L.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  15836. return new Ta(t,
  15837. /* converter= */ null, function(t) {
  15838. return new ln(ot.emptyPath(), t);
  15839. }(e));
  15840. }
  15841. function ba(t, e, ...n) {
  15842. if (t = _(t),
  15843. // We allow omission of 'pathString' but explicitly prohibit passing in both
  15844. // 'undefined' and 'null'.
  15845. 1 === arguments.length && (e = Z.R()), aa("doc", "path", e), t instanceof ya) {
  15846. const s = ot.fromString(e, ...n);
  15847. return la(s), new Ia(t,
  15848. /* converter= */ null, new at(s));
  15849. }
  15850. {
  15851. if (!(t instanceof Ia || t instanceof Ea)) throw new q(L.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  15852. const s = t._path.child(ot.fromString(e, ...n));
  15853. return la(s), new Ia(t.firestore, t instanceof Ea ? t.converter : null, new at(s));
  15854. }
  15855. }
  15856. /**
  15857. * Returns true if the provided references are equal.
  15858. *
  15859. * @param left - A reference to compare.
  15860. * @param right - A reference to compare.
  15861. * @returns true if the references point to the same location in the same
  15862. * Firestore database.
  15863. */ function Pa(t, e) {
  15864. return t = _(t), e = _(e), (t instanceof Ia || t instanceof Ea) && (e instanceof Ia || e instanceof Ea) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);
  15865. }
  15866. /**
  15867. * Returns true if the provided queries point to the same collection and apply
  15868. * the same constraints.
  15869. *
  15870. * @param left - A `Query` to compare.
  15871. * @param right - A `Query` to compare.
  15872. * @returns true if the references point to the same location in the same
  15873. * Firestore database.
  15874. */ function va(t, e) {
  15875. return t = _(t), e = _(e), t instanceof Ta && e instanceof Ta && (t.firestore === e.firestore && En(t._query, e._query) && t.converter === e.converter);
  15876. }
  15877. /**
  15878. * @license
  15879. * Copyright 2020 Google LLC
  15880. *
  15881. * Licensed under the Apache License, Version 2.0 (the "License");
  15882. * you may not use this file except in compliance with the License.
  15883. * You may obtain a copy of the License at
  15884. *
  15885. * http://www.apache.org/licenses/LICENSE-2.0
  15886. *
  15887. * Unless required by applicable law or agreed to in writing, software
  15888. * distributed under the License is distributed on an "AS IS" BASIS,
  15889. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15890. * See the License for the specific language governing permissions and
  15891. * limitations under the License.
  15892. */
  15893. /**
  15894. * How many bytes to read each time when `ReadableStreamReader.read()` is
  15895. * called. Only applicable for byte streams that we control (e.g. those backed
  15896. * by an UInt8Array).
  15897. */
  15898. /**
  15899. * Builds a `ByteStreamReader` from a UInt8Array.
  15900. * @param source - The data source to use.
  15901. * @param bytesPerRead - How many bytes each `read()` from the returned reader
  15902. * will read.
  15903. */
  15904. function Va(t, e = 10240) {
  15905. let n = 0;
  15906. // The TypeScript definition for ReadableStreamReader changed. We use
  15907. // `any` here to allow this code to compile with different versions.
  15908. // See https://github.com/microsoft/TypeScript/issues/42970
  15909. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15910. return {
  15911. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15912. async read() {
  15913. if (n < t.byteLength) {
  15914. const s = {
  15915. value: t.slice(n, n + e),
  15916. done: !1
  15917. };
  15918. return n += e, s;
  15919. }
  15920. return {
  15921. done: !0
  15922. };
  15923. },
  15924. async cancel() {},
  15925. releaseLock() {},
  15926. closed: Promise.reject("unimplemented")
  15927. };
  15928. }
  15929. /**
  15930. * @license
  15931. * Copyright 2020 Google LLC
  15932. *
  15933. * Licensed under the Apache License, Version 2.0 (the "License");
  15934. * you may not use this file except in compliance with the License.
  15935. * You may obtain a copy of the License at
  15936. *
  15937. * http://www.apache.org/licenses/LICENSE-2.0
  15938. *
  15939. * Unless required by applicable law or agreed to in writing, software
  15940. * distributed under the License is distributed on an "AS IS" BASIS,
  15941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15942. * See the License for the specific language governing permissions and
  15943. * limitations under the License.
  15944. */
  15945. /**
  15946. * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
  15947. */
  15948. /**
  15949. * @license
  15950. * Copyright 2017 Google LLC
  15951. *
  15952. * Licensed under the Apache License, Version 2.0 (the "License");
  15953. * you may not use this file except in compliance with the License.
  15954. * You may obtain a copy of the License at
  15955. *
  15956. * http://www.apache.org/licenses/LICENSE-2.0
  15957. *
  15958. * Unless required by applicable law or agreed to in writing, software
  15959. * distributed under the License is distributed on an "AS IS" BASIS,
  15960. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15961. * See the License for the specific language governing permissions and
  15962. * limitations under the License.
  15963. */
  15964. /*
  15965. * A wrapper implementation of Observer<T> that will dispatch events
  15966. * asynchronously. To allow immediate silencing, a mute call is added which
  15967. * causes events scheduled to no longer be raised.
  15968. */
  15969. class Sa {
  15970. constructor(t) {
  15971. this.observer = t,
  15972. /**
  15973. * When set to true, will not raise future events. Necessary to deal with
  15974. * async detachment of listener.
  15975. */
  15976. this.muted = !1;
  15977. }
  15978. next(t) {
  15979. this.observer.next && this.Rc(this.observer.next, t);
  15980. }
  15981. error(t) {
  15982. this.observer.error ? this.Rc(this.observer.error, t) : N("Uncaught Error in snapshot listener:", t.toString());
  15983. }
  15984. bc() {
  15985. this.muted = !0;
  15986. }
  15987. Rc(t, e) {
  15988. this.muted || setTimeout((() => {
  15989. this.muted || t(e);
  15990. }), 0);
  15991. }
  15992. }
  15993. /**
  15994. * @license
  15995. * Copyright 2020 Google LLC
  15996. *
  15997. * Licensed under the Apache License, Version 2.0 (the "License");
  15998. * you may not use this file except in compliance with the License.
  15999. * You may obtain a copy of the License at
  16000. *
  16001. * http://www.apache.org/licenses/LICENSE-2.0
  16002. *
  16003. * Unless required by applicable law or agreed to in writing, software
  16004. * distributed under the License is distributed on an "AS IS" BASIS,
  16005. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16006. * See the License for the specific language governing permissions and
  16007. * limitations under the License.
  16008. */
  16009. /**
  16010. * A class representing a bundle.
  16011. *
  16012. * Takes a bundle stream or buffer, and presents abstractions to read bundled
  16013. * elements out of the underlying content.
  16014. */ class Da {
  16015. constructor(
  16016. /** The reader to read from underlying binary bundle data source. */
  16017. t, e) {
  16018. this.Pc = t, this.yt = e,
  16019. /** Cached bundle metadata. */
  16020. this.metadata = new U,
  16021. /**
  16022. * Internal buffer to hold bundle content, accumulating incomplete element
  16023. * content.
  16024. */
  16025. this.buffer = new Uint8Array, this.vc = new TextDecoder("utf-8"),
  16026. // Read the metadata (which is the first element).
  16027. this.Vc().then((t => {
  16028. t && t.Ou() ? this.metadata.resolve(t.ku.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null == t ? void 0 : t.ku)}`));
  16029. }), (t => this.metadata.reject(t)));
  16030. }
  16031. close() {
  16032. return this.Pc.cancel();
  16033. }
  16034. async getMetadata() {
  16035. return this.metadata.promise;
  16036. }
  16037. async mc() {
  16038. // Makes sure metadata is read before proceeding.
  16039. return await this.getMetadata(), this.Vc();
  16040. }
  16041. /**
  16042. * Reads from the head of internal buffer, and pulling more data from
  16043. * underlying stream if a complete element cannot be found, until an
  16044. * element(including the prefixed length and the JSON string) is found.
  16045. *
  16046. * Once a complete element is read, it is dropped from internal buffer.
  16047. *
  16048. * Returns either the bundled element, or null if we have reached the end of
  16049. * the stream.
  16050. */ async Vc() {
  16051. const t = await this.Sc();
  16052. if (null === t) return null;
  16053. const e = this.vc.decode(t), n = Number(e);
  16054. isNaN(n) && this.Dc(`length string (${e}) is not valid number`);
  16055. const s = await this.Cc(n);
  16056. return new gc(JSON.parse(s), t.length + n);
  16057. }
  16058. /** First index of '{' from the underlying buffer. */ xc() {
  16059. return this.buffer.findIndex((t => t === "{".charCodeAt(0)));
  16060. }
  16061. /**
  16062. * Reads from the beginning of the internal buffer, until the first '{', and
  16063. * return the content.
  16064. *
  16065. * If reached end of the stream, returns a null.
  16066. */ async Sc() {
  16067. for (;this.xc() < 0; ) {
  16068. if (await this.Nc()) break;
  16069. }
  16070. // Broke out of the loop because underlying stream is closed, and there
  16071. // happens to be no more data to process.
  16072. if (0 === this.buffer.length) return null;
  16073. const t = this.xc();
  16074. // Broke out of the loop because underlying stream is closed, but still
  16075. // cannot find an open bracket.
  16076. t < 0 && this.Dc("Reached the end of bundle when a length string is expected.");
  16077. const e = this.buffer.slice(0, t);
  16078. // Update the internal buffer to drop the read length.
  16079. return this.buffer = this.buffer.slice(t), e;
  16080. }
  16081. /**
  16082. * Reads from a specified position from the internal buffer, for a specified
  16083. * number of bytes, pulling more data from the underlying stream if needed.
  16084. *
  16085. * Returns a string decoded from the read bytes.
  16086. */ async Cc(t) {
  16087. for (;this.buffer.length < t; ) {
  16088. await this.Nc() && this.Dc("Reached the end of bundle when more is expected.");
  16089. }
  16090. const e = this.vc.decode(this.buffer.slice(0, t));
  16091. // Update the internal buffer to drop the read json string.
  16092. return this.buffer = this.buffer.slice(t), e;
  16093. }
  16094. Dc(t) {
  16095. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16096. throw this.Pc.cancel(), new Error(`Invalid bundle format: ${t}`);
  16097. }
  16098. /**
  16099. * Pulls more data from underlying stream to internal buffer.
  16100. * Returns a boolean indicating whether the stream is finished.
  16101. */ async Nc() {
  16102. const t = await this.Pc.read();
  16103. if (!t.done) {
  16104. const e = new Uint8Array(this.buffer.length + t.value.length);
  16105. e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;
  16106. }
  16107. return t.done;
  16108. }
  16109. }
  16110. /**
  16111. * @license
  16112. * Copyright 2022 Google LLC
  16113. *
  16114. * Licensed under the Apache License, Version 2.0 (the "License");
  16115. * you may not use this file except in compliance with the License.
  16116. * You may obtain a copy of the License at
  16117. *
  16118. * http://www.apache.org/licenses/LICENSE-2.0
  16119. *
  16120. * Unless required by applicable law or agreed to in writing, software
  16121. * distributed under the License is distributed on an "AS IS" BASIS,
  16122. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16123. * See the License for the specific language governing permissions and
  16124. * limitations under the License.
  16125. */
  16126. /**
  16127. * Represents an aggregation that can be performed by Firestore.
  16128. */
  16129. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  16130. class Ca {
  16131. constructor() {
  16132. /** A type string to uniquely identify instances of this class. */
  16133. this.type = "AggregateField";
  16134. }
  16135. }
  16136. /**
  16137. * The results of executing an aggregation query.
  16138. */ class xa {
  16139. /** @hideconstructor */
  16140. constructor(t, e) {
  16141. this._data = e,
  16142. /** A type string to uniquely identify instances of this class. */
  16143. this.type = "AggregateQuerySnapshot", this.query = t;
  16144. }
  16145. /**
  16146. * Returns the results of the aggregations performed over the underlying
  16147. * query.
  16148. *
  16149. * The keys of the returned object will be the same as those of the
  16150. * `AggregateSpec` object specified to the aggregation method, and the values
  16151. * will be the corresponding aggregation result.
  16152. *
  16153. * @returns The results of the aggregations performed over the underlying
  16154. * query.
  16155. */ data() {
  16156. return this._data;
  16157. }
  16158. }
  16159. /**
  16160. * @license
  16161. * Copyright 2022 Google LLC
  16162. *
  16163. * Licensed under the Apache License, Version 2.0 (the "License");
  16164. * you may not use this file except in compliance with the License.
  16165. * You may obtain a copy of the License at
  16166. *
  16167. * http://www.apache.org/licenses/LICENSE-2.0
  16168. *
  16169. * Unless required by applicable law or agreed to in writing, software
  16170. * distributed under the License is distributed on an "AS IS" BASIS,
  16171. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16172. * See the License for the specific language governing permissions and
  16173. * limitations under the License.
  16174. */
  16175. /**
  16176. * CountQueryRunner encapsulates the logic needed to run the count aggregation
  16177. * queries.
  16178. */ class Na {
  16179. constructor(t, e, n) {
  16180. this.query = t, this.datastore = e, this.userDataWriter = n;
  16181. }
  16182. run() {
  16183. return vu(this.datastore, this.query._query).then((t => {
  16184. F(void 0 !== t[0]);
  16185. const e = Object.entries(t[0]).filter((([t, e]) => "count_alias" === t)).map((([t, e]) => this.userDataWriter.convertValue(e)))[0];
  16186. return F("number" == typeof e), Promise.resolve(new xa(this.query, {
  16187. count: e
  16188. }));
  16189. }));
  16190. }
  16191. }
  16192. /**
  16193. * @license
  16194. * Copyright 2017 Google LLC
  16195. *
  16196. * Licensed under the Apache License, Version 2.0 (the "License");
  16197. * you may not use this file except in compliance with the License.
  16198. * You may obtain a copy of the License at
  16199. *
  16200. * http://www.apache.org/licenses/LICENSE-2.0
  16201. *
  16202. * Unless required by applicable law or agreed to in writing, software
  16203. * distributed under the License is distributed on an "AS IS" BASIS,
  16204. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16205. * See the License for the specific language governing permissions and
  16206. * limitations under the License.
  16207. */
  16208. /**
  16209. * Internal transaction object responsible for accumulating the mutations to
  16210. * perform and the base versions for any documents read.
  16211. */ class ka {
  16212. constructor(t) {
  16213. this.datastore = t,
  16214. // The version of each document that was read during this transaction.
  16215. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  16216. /**
  16217. * A deferred usage error that occurred previously in this transaction that
  16218. * will cause the transaction to fail once it actually commits.
  16219. */
  16220. this.lastWriteError = null,
  16221. /**
  16222. * Set of documents that have been written in the transaction.
  16223. *
  16224. * When there's more than one write to the same key in a transaction, any
  16225. * writes after the first are handled differently.
  16226. */
  16227. this.writtenDocs = new Set;
  16228. }
  16229. async lookup(t) {
  16230. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new q(L.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
  16231. const e = await async function(t, e) {
  16232. const n = B(t), s = Js(n.yt) + "/documents", i = {
  16233. documents: e.map((t => js(n.yt, t)))
  16234. }, r = await n._o("BatchGetDocuments", s, i, e.length), o = new Map;
  16235. r.forEach((t => {
  16236. const e = ti(n.yt, t);
  16237. o.set(e.key.toString(), e);
  16238. }));
  16239. const u = [];
  16240. return e.forEach((t => {
  16241. const e = o.get(t.toString());
  16242. F(!!e), u.push(e);
  16243. })), u;
  16244. }(this.datastore, t);
  16245. return e.forEach((t => this.recordVersion(t))), e;
  16246. }
  16247. set(t, e) {
  16248. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16249. }
  16250. update(t, e) {
  16251. try {
  16252. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  16253. } catch (t) {
  16254. this.lastWriteError = t;
  16255. }
  16256. this.writtenDocs.add(t.toString());
  16257. }
  16258. delete(t) {
  16259. this.write(new os(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16260. }
  16261. async commit() {
  16262. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  16263. const t = this.readVersions;
  16264. // For each mutation, note that the doc was written.
  16265. this.mutations.forEach((e => {
  16266. t.delete(e.key.toString());
  16267. })),
  16268. // For each document that was read but not written to, we want to perform
  16269. // a `verify` operation.
  16270. t.forEach(((t, e) => {
  16271. const n = at.fromPath(e);
  16272. this.mutations.push(new us(n, this.precondition(n)));
  16273. })), await async function(t, e) {
  16274. const n = B(t), s = Js(n.yt) + "/documents", i = {
  16275. writes: e.map((t => ni(n.yt, t)))
  16276. };
  16277. await n.ao("Commit", s, i);
  16278. }(this.datastore, this.mutations), this.committed = !0;
  16279. }
  16280. recordVersion(t) {
  16281. let e;
  16282. if (t.isFoundDocument()) e = t.version; else {
  16283. if (!t.isNoDocument()) throw M();
  16284. // Represent a deleted doc using SnapshotVersion.min().
  16285. e = it.min();
  16286. }
  16287. const n = this.readVersions.get(t.key.toString());
  16288. if (n) {
  16289. if (!e.isEqual(n))
  16290. // This transaction will fail no matter what.
  16291. throw new q(L.ABORTED, "Document version changed between two reads.");
  16292. } else this.readVersions.set(t.key.toString(), e);
  16293. }
  16294. /**
  16295. * Returns the version of this document when it was read in this transaction,
  16296. * as a precondition, or no precondition if it was not read.
  16297. */ precondition(t) {
  16298. const e = this.readVersions.get(t.toString());
  16299. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(it.min()) ? Wn.exists(!1) : Wn.updateTime(e) : Wn.none();
  16300. }
  16301. /**
  16302. * Returns the precondition for a document if the operation is an update.
  16303. */ preconditionForUpdate(t) {
  16304. const e = this.readVersions.get(t.toString());
  16305. // The first time a document is written, we want to take into account the
  16306. // read time and existence
  16307. if (!this.writtenDocs.has(t.toString()) && e) {
  16308. if (e.isEqual(it.min()))
  16309. // The document doesn't exist, so fail the transaction.
  16310. // This has to be validated locally because you can't send a
  16311. // precondition that a document does not exist without changing the
  16312. // semantics of the backend write to be an insert. This is the reverse
  16313. // of what we want, since we want to assert that the document doesn't
  16314. // exist but then send the update and have it fail. Since we can't
  16315. // express that to the backend, we have to validate locally.
  16316. // Note: this can change once we can send separate verify writes in the
  16317. // transaction.
  16318. throw new q(L.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  16319. // Document exists, base precondition on document update time.
  16320. return Wn.updateTime(e);
  16321. }
  16322. // Document was not read, so we just use the preconditions for a blind
  16323. // update.
  16324. return Wn.exists(!0);
  16325. }
  16326. write(t) {
  16327. this.ensureCommitNotCalled(), this.mutations.push(t);
  16328. }
  16329. ensureCommitNotCalled() {}
  16330. }
  16331. /**
  16332. * @license
  16333. * Copyright 2019 Google LLC
  16334. *
  16335. * Licensed under the Apache License, Version 2.0 (the "License");
  16336. * you may not use this file except in compliance with the License.
  16337. * You may obtain a copy of the License at
  16338. *
  16339. * http://www.apache.org/licenses/LICENSE-2.0
  16340. *
  16341. * Unless required by applicable law or agreed to in writing, software
  16342. * distributed under the License is distributed on an "AS IS" BASIS,
  16343. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16344. * See the License for the specific language governing permissions and
  16345. * limitations under the License.
  16346. */
  16347. /**
  16348. * TransactionRunner encapsulates the logic needed to run and retry transactions
  16349. * with backoff.
  16350. */ class Oa {
  16351. constructor(t, e, n, s, i) {
  16352. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s,
  16353. this.deferred = i, this.kc = n.maxAttempts, this.xo = new Eu(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  16354. }
  16355. /** Runs the transaction and sets the result on deferred. */ run() {
  16356. this.kc -= 1, this.Oc();
  16357. }
  16358. Oc() {
  16359. this.xo.Ro((async () => {
  16360. const t = new ka(this.datastore), e = this.Mc(t);
  16361. e && e.then((e => {
  16362. this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {
  16363. this.deferred.resolve(e);
  16364. })).catch((t => {
  16365. this.Fc(t);
  16366. }))));
  16367. })).catch((t => {
  16368. this.Fc(t);
  16369. }));
  16370. }));
  16371. }
  16372. Mc(t) {
  16373. try {
  16374. const e = this.updateFunction(t);
  16375. return !Ut(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  16376. null);
  16377. } catch (t) {
  16378. // Do not retry errors thrown by user provided updateFunction.
  16379. return this.deferred.reject(t), null;
  16380. }
  16381. }
  16382. Fc(t) {
  16383. this.kc > 0 && this.$c(t) ? (this.kc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Oc(),
  16384. Promise.resolve())))) : this.deferred.reject(t);
  16385. }
  16386. $c(t) {
  16387. if ("FirebaseError" === t.name) {
  16388. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  16389. // non-matching document versions with ABORTED. These errors should be retried.
  16390. const e = t.code;
  16391. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !ls(e);
  16392. }
  16393. return !1;
  16394. }
  16395. }
  16396. /**
  16397. * @license
  16398. * Copyright 2017 Google LLC
  16399. *
  16400. * Licensed under the Apache License, Version 2.0 (the "License");
  16401. * you may not use this file except in compliance with the License.
  16402. * You may obtain a copy of the License at
  16403. *
  16404. * http://www.apache.org/licenses/LICENSE-2.0
  16405. *
  16406. * Unless required by applicable law or agreed to in writing, software
  16407. * distributed under the License is distributed on an "AS IS" BASIS,
  16408. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16409. * See the License for the specific language governing permissions and
  16410. * limitations under the License.
  16411. */
  16412. /**
  16413. * FirestoreClient is a top-level class that constructs and owns all of the
  16414. * pieces of the client SDK architecture. It is responsible for creating the
  16415. * async queue that is shared by all of the other components in the system.
  16416. */
  16417. class Ma {
  16418. constructor(t, e,
  16419. /**
  16420. * Asynchronous queue responsible for all of our internal processing. When
  16421. * we get incoming work from the user (via public API) or the network
  16422. * (incoming GRPC messages), we should always schedule onto this queue.
  16423. * This ensures all of our work is properly serialized (e.g. we don't
  16424. * start processing a new operation while the previous one is waiting for
  16425. * an async I/O to complete).
  16426. */
  16427. n, s) {
  16428. this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s,
  16429. this.user = v.UNAUTHENTICATED, this.clientId = Z.R(), this.authCredentialListener = () => Promise.resolve(),
  16430. this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {
  16431. x("FirestoreClient", "Received user=", t.uid), await this.authCredentialListener(t),
  16432. this.user = t;
  16433. })), this.appCheckCredentials.start(n, (t => (x("FirestoreClient", "Received new app check token=", t),
  16434. this.appCheckCredentialListener(t, this.user))));
  16435. }
  16436. async getConfiguration() {
  16437. return {
  16438. asyncQueue: this.asyncQueue,
  16439. databaseInfo: this.databaseInfo,
  16440. clientId: this.clientId,
  16441. authCredentials: this.authCredentials,
  16442. appCheckCredentials: this.appCheckCredentials,
  16443. initialUser: this.user,
  16444. maxConcurrentLimboResolutions: 100
  16445. };
  16446. }
  16447. setCredentialChangeListener(t) {
  16448. this.authCredentialListener = t;
  16449. }
  16450. setAppCheckTokenChangeListener(t) {
  16451. this.appCheckCredentialListener = t;
  16452. }
  16453. /**
  16454. * Checks that the client has not been terminated. Ensures that other methods on
  16455. * this class cannot be called after the client is terminated.
  16456. */ verifyNotTerminated() {
  16457. if (this.asyncQueue.isShuttingDown) throw new q(L.FAILED_PRECONDITION, "The client has already been terminated.");
  16458. }
  16459. terminate() {
  16460. this.asyncQueue.enterRestrictedMode();
  16461. const t = new U;
  16462. return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {
  16463. try {
  16464. this.onlineComponents && await this.onlineComponents.terminate(), this.offlineComponents && await this.offlineComponents.terminate(),
  16465. // The credentials provider must be terminated after shutting down the
  16466. // RemoteStore as it will prevent the RemoteStore from retrieving auth
  16467. // tokens.
  16468. this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();
  16469. } catch (e) {
  16470. const n = rc(e, "Failed to shutdown persistence");
  16471. t.reject(n);
  16472. }
  16473. })), t.promise;
  16474. }
  16475. }
  16476. async function Fa(t, e) {
  16477. t.asyncQueue.verifyOperationInProgress(), x("FirestoreClient", "Initializing OfflineComponentProvider");
  16478. const n = await t.getConfiguration();
  16479. await e.initialize(n);
  16480. let s = n.initialUser;
  16481. t.setCredentialChangeListener((async t => {
  16482. s.isEqual(t) || (await Go(e.localStore, t), s = t);
  16483. })),
  16484. // When a user calls clearPersistence() in one client, all other clients
  16485. // need to be terminated to allow the delete to succeed.
  16486. e.persistence.setDatabaseDeletedListener((() => t.terminate())), t.offlineComponents = e;
  16487. }
  16488. async function $a(t, e) {
  16489. t.asyncQueue.verifyOperationInProgress();
  16490. const n = await Ba(t);
  16491. x("FirestoreClient", "Initializing OnlineComponentProvider");
  16492. const s = await t.getConfiguration();
  16493. await e.initialize(n, s),
  16494. // The CredentialChangeListener of the online component provider takes
  16495. // precedence over the offline component provider.
  16496. t.setCredentialChangeListener((t => tc(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => tc(e.remoteStore, n))),
  16497. t.onlineComponents = e;
  16498. }
  16499. async function Ba(t) {
  16500. return t.offlineComponents || (x("FirestoreClient", "Using default OfflineComponentProvider"),
  16501. await Fa(t, new ra)), t.offlineComponents;
  16502. }
  16503. async function La(t) {
  16504. return t.onlineComponents || (x("FirestoreClient", "Using default OnlineComponentProvider"),
  16505. await $a(t, new ca)), t.onlineComponents;
  16506. }
  16507. function qa(t) {
  16508. return Ba(t).then((t => t.persistence));
  16509. }
  16510. function Ua(t) {
  16511. return Ba(t).then((t => t.localStore));
  16512. }
  16513. function Ka(t) {
  16514. return La(t).then((t => t.remoteStore));
  16515. }
  16516. function Ga(t) {
  16517. return La(t).then((t => t.syncEngine));
  16518. }
  16519. function Qa(t) {
  16520. return La(t).then((t => t.datastore));
  16521. }
  16522. async function ja(t) {
  16523. const e = await La(t), n = e.eventManager;
  16524. return n.onListen = vc.bind(null, e.syncEngine), n.onUnlisten = Sc.bind(null, e.syncEngine),
  16525. n;
  16526. }
  16527. /** Enables the network connection and re-enqueues all pending operations. */ function Wa(t) {
  16528. return t.asyncQueue.enqueue((async () => {
  16529. const e = await qa(t), n = await Ka(t);
  16530. return e.setNetworkEnabled(!0), function(t) {
  16531. const e = B(t);
  16532. return e._u.delete(0 /* OfflineCause.UserDisabled */), Du(e);
  16533. }(n);
  16534. }));
  16535. }
  16536. /** Disables the network connection. Pending operations will not complete. */ function za(t) {
  16537. return t.asyncQueue.enqueue((async () => {
  16538. const e = await qa(t), n = await Ka(t);
  16539. return e.setNetworkEnabled(!1), async function(t) {
  16540. const e = B(t);
  16541. e._u.add(0 /* OfflineCause.UserDisabled */), await Cu(e),
  16542. // Set the OnlineState to Offline so get()s return from cache, etc.
  16543. e.gu.set("Offline" /* OnlineState.Offline */);
  16544. }(n);
  16545. }));
  16546. }
  16547. /**
  16548. * Returns a Promise that resolves when all writes that were pending at the time
  16549. * this method was called received server acknowledgement. An acknowledgement
  16550. * can be either acceptance or rejection.
  16551. */ function Ha(t, e) {
  16552. const n = new U;
  16553. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16554. try {
  16555. const s = await function(t, e) {
  16556. const n = B(t);
  16557. return n.persistence.runTransaction("read document", "readonly", (t => n.localDocuments.getDocument(t, e)));
  16558. }(t, e);
  16559. s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new q(L.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"));
  16560. } catch (t) {
  16561. const s = rc(t, `Failed to get document '${e} from cache`);
  16562. n.reject(s);
  16563. }
  16564. }
  16565. /**
  16566. * Retrieves a latency-compensated document from the backend via a
  16567. * SnapshotListener.
  16568. */ (await Ua(t), e, n))), n.promise;
  16569. }
  16570. function Ja(t, e, n = {}) {
  16571. const s = new U;
  16572. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16573. const r = new Sa({
  16574. next: r => {
  16575. // Remove query first before passing event to user to avoid
  16576. // user actions affecting the now stale query.
  16577. e.enqueueAndForget((() => fc(t, o)));
  16578. const u = r.docs.has(n);
  16579. !u && r.fromCache ?
  16580. // TODO(dimond): If we're online and the document doesn't
  16581. // exist then we resolve with a doc.exists set to false. If
  16582. // we're offline however, we reject the Promise in this
  16583. // case. Two options: 1) Cache the negative response from
  16584. // the server so we can deliver that even when you're
  16585. // offline 2) Actually reject the Promise in the online case
  16586. // if the document doesn't exist.
  16587. i.reject(new q(L.UNAVAILABLE, "Failed to get document because the client is offline.")) : u && r.fromCache && s && "server" === s.source ? i.reject(new q(L.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(r);
  16588. },
  16589. error: t => i.reject(t)
  16590. }), o = new mc(dn(n.path), r, {
  16591. includeMetadataChanges: !0,
  16592. Nu: !0
  16593. });
  16594. return lc(t, o);
  16595. }(await ja(t), t.asyncQueue, e, n, s))), s.promise;
  16596. }
  16597. function Ya(t, e) {
  16598. const n = new U;
  16599. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16600. try {
  16601. const s = await Xo(t, e,
  16602. /* usePreviousResults= */ !0), i = new Ac(e, s.Hi), r = i.Wu(s.documents), o = i.applyChanges(r,
  16603. /* updateLimboDocuments= */ !1);
  16604. n.resolve(o.snapshot);
  16605. } catch (t) {
  16606. const s = rc(t, `Failed to execute query '${e} against cache`);
  16607. n.reject(s);
  16608. }
  16609. }
  16610. /**
  16611. * Retrieves a latency-compensated query snapshot from the backend via a
  16612. * SnapshotListener.
  16613. */ (await Ua(t), e, n))), n.promise;
  16614. }
  16615. function Xa(t, e, n = {}) {
  16616. const s = new U;
  16617. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16618. const r = new Sa({
  16619. next: n => {
  16620. // Remove query first before passing event to user to avoid
  16621. // user actions affecting the now stale query.
  16622. e.enqueueAndForget((() => fc(t, o))), n.fromCache && "server" === s.source ? i.reject(new q(L.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n);
  16623. },
  16624. error: t => i.reject(t)
  16625. }), o = new mc(n, r, {
  16626. includeMetadataChanges: !0,
  16627. Nu: !0
  16628. });
  16629. return lc(t, o);
  16630. }(await ja(t), t.asyncQueue, e, n, s))), s.promise;
  16631. }
  16632. function Za(t, e) {
  16633. const n = new Sa(e);
  16634. return t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16635. B(t).Ru.add(e),
  16636. // Immediately fire an initial event, indicating all existing listeners
  16637. // are in-sync.
  16638. e.next();
  16639. }(await ja(t), n))), () => {
  16640. n.bc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16641. B(t).Ru.delete(e);
  16642. }(await ja(t), n)));
  16643. };
  16644. }
  16645. /**
  16646. * Takes an updateFunction in which a set of reads and writes can be performed
  16647. * atomically. In the updateFunction, the client can read and write values
  16648. * using the supplied transaction object. After the updateFunction, all
  16649. * changes will be committed. If a retryable error occurs (ex: some other
  16650. * client has changed any of the data referenced), then the updateFunction
  16651. * will be called again after a backoff. If the updateFunction still fails
  16652. * after all retries, then the transaction will be rejected.
  16653. *
  16654. * The transaction object passed to the updateFunction contains methods for
  16655. * accessing documents and collections. Unlike other datastore access, data
  16656. * accessed with the transaction will not reflect local changes that have not
  16657. * been committed. For this reason, it is required that all reads are
  16658. * performed before any writes. Transactions must be performed while online.
  16659. */ function th(t, e, n, s) {
  16660. const i = function(t, e) {
  16661. let n;
  16662. n = "string" == typeof t ? (new TextEncoder).encode(t) : t;
  16663. return function(t, e) {
  16664. return new Da(t, e);
  16665. }(function(t, e) {
  16666. if (t instanceof Uint8Array) return Va(t, e);
  16667. if (t instanceof ArrayBuffer) return Va(new Uint8Array(t), e);
  16668. if (t instanceof ReadableStream) return t.getReader();
  16669. throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
  16670. }(n), e);
  16671. }
  16672. /**
  16673. * @license
  16674. * Copyright 2020 Google LLC
  16675. *
  16676. * Licensed under the Apache License, Version 2.0 (the "License");
  16677. * you may not use this file except in compliance with the License.
  16678. * You may obtain a copy of the License at
  16679. *
  16680. * http://www.apache.org/licenses/LICENSE-2.0
  16681. *
  16682. * Unless required by applicable law or agreed to in writing, software
  16683. * distributed under the License is distributed on an "AS IS" BASIS,
  16684. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16685. * See the License for the specific language governing permissions and
  16686. * limitations under the License.
  16687. */ (n, Tu(e));
  16688. t.asyncQueue.enqueueAndForget((async () => {
  16689. ia(await Ga(t), i, s);
  16690. }));
  16691. }
  16692. function eh(t, e) {
  16693. return t.asyncQueue.enqueue((async () => function(t, e) {
  16694. const n = B(t);
  16695. return n.persistence.runTransaction("Get named query", "readonly", (t => n.Ns.getNamedQuery(t, e)));
  16696. }(await Ua(t), e)));
  16697. }
  16698. class nh {
  16699. constructor() {
  16700. // The last promise in the queue.
  16701. this.Bc = Promise.resolve(),
  16702. // A list of retryable operations. Retryable operations are run in order and
  16703. // retried with backoff.
  16704. this.Lc = [],
  16705. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  16706. // be changed again.
  16707. this.qc = !1,
  16708. // Operations scheduled to be queued in the future. Operations are
  16709. // automatically removed after they are run or canceled.
  16710. this.Uc = [],
  16711. // visible for testing
  16712. this.Kc = null,
  16713. // Flag set while there's an outstanding AsyncQueue operation, used for
  16714. // assertion sanity-checks.
  16715. this.Gc = !1,
  16716. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  16717. this.Qc = !1,
  16718. // List of TimerIds to fast-forward delays for.
  16719. this.jc = [],
  16720. // Backoff timer used to schedule retries for retryable operations
  16721. this.xo = new Eu(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  16722. // Visibility handler that triggers an immediate retry of all retryable
  16723. // operations. Meant to speed up recovery when we regain file system access
  16724. // after page comes into foreground.
  16725. this.Wc = () => {
  16726. const t = Iu();
  16727. t && x("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.xo.Po();
  16728. };
  16729. const t = Iu();
  16730. t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Wc);
  16731. }
  16732. get isShuttingDown() {
  16733. return this.qc;
  16734. }
  16735. /**
  16736. * Adds a new operation to the queue without waiting for it to complete (i.e.
  16737. * we ignore the Promise result).
  16738. */ enqueueAndForget(t) {
  16739. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16740. this.enqueue(t);
  16741. }
  16742. enqueueAndForgetEvenWhileRestricted(t) {
  16743. this.zc(),
  16744. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16745. this.Hc(t);
  16746. }
  16747. enterRestrictedMode(t) {
  16748. if (!this.qc) {
  16749. this.qc = !0, this.Qc = t || !1;
  16750. const e = Iu();
  16751. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Wc);
  16752. }
  16753. }
  16754. enqueue(t) {
  16755. if (this.zc(), this.qc)
  16756. // Return a Promise which never resolves.
  16757. return new Promise((() => {}));
  16758. // Create a deferred Promise that we can return to the callee. This
  16759. // allows us to return a "hanging Promise" only to the callee and still
  16760. // advance the queue even when the operation is not run.
  16761. const e = new U;
  16762. return this.Hc((() => this.qc && this.Qc ? Promise.resolve() : (t().then(e.resolve, e.reject),
  16763. e.promise))).then((() => e.promise));
  16764. }
  16765. enqueueRetryable(t) {
  16766. this.enqueueAndForget((() => (this.Lc.push(t), this.Jc())));
  16767. }
  16768. /**
  16769. * Runs the next operation from the retryable queue. If the operation fails,
  16770. * reschedules with backoff.
  16771. */ async Jc() {
  16772. if (0 !== this.Lc.length) {
  16773. try {
  16774. await this.Lc[0](), this.Lc.shift(), this.xo.reset();
  16775. } catch (t) {
  16776. if (!St(t)) throw t;
  16777. // Failure will be handled by AsyncQueue
  16778. x("AsyncQueue", "Operation failed with retryable error: " + t);
  16779. }
  16780. this.Lc.length > 0 &&
  16781. // If there are additional operations, we re-schedule `retryNextOp()`.
  16782. // This is necessary to run retryable operations that failed during
  16783. // their initial attempt since we don't know whether they are already
  16784. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  16785. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  16786. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  16787. // call scheduled here.
  16788. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  16789. // new backoff on every call, there is only ever a single additional
  16790. // operation in the queue.
  16791. this.xo.Ro((() => this.Jc()));
  16792. }
  16793. }
  16794. Hc(t) {
  16795. const e = this.Bc.then((() => (this.Gc = !0, t().catch((t => {
  16796. this.Kc = t, this.Gc = !1;
  16797. const e =
  16798. /**
  16799. * Chrome includes Error.message in Error.stack. Other browsers do not.
  16800. * This returns expected output of message + stack when available.
  16801. * @param error - Error or FirestoreError
  16802. */
  16803. function(t) {
  16804. let e = t.message || "";
  16805. t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
  16806. return e;
  16807. }
  16808. /**
  16809. * @license
  16810. * Copyright 2017 Google LLC
  16811. *
  16812. * Licensed under the Apache License, Version 2.0 (the "License");
  16813. * you may not use this file except in compliance with the License.
  16814. * You may obtain a copy of the License at
  16815. *
  16816. * http://www.apache.org/licenses/LICENSE-2.0
  16817. *
  16818. * Unless required by applicable law or agreed to in writing, software
  16819. * distributed under the License is distributed on an "AS IS" BASIS,
  16820. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16821. * See the License for the specific language governing permissions and
  16822. * limitations under the License.
  16823. */ (t);
  16824. // Re-throw the error so that this.tail becomes a rejected Promise and
  16825. // all further attempts to chain (via .then) will just short-circuit
  16826. // and return the rejected Promise.
  16827. throw N("INTERNAL UNHANDLED ERROR: ", e), t;
  16828. })).then((t => (this.Gc = !1, t))))));
  16829. return this.Bc = e, e;
  16830. }
  16831. enqueueAfterDelay(t, e, n) {
  16832. this.zc(),
  16833. // Fast-forward delays for timerIds that have been overriden.
  16834. this.jc.indexOf(t) > -1 && (e = 0);
  16835. const s = ic.createAndSchedule(this, t, e, n, (t => this.Yc(t)));
  16836. return this.Uc.push(s), s;
  16837. }
  16838. zc() {
  16839. this.Kc && M();
  16840. }
  16841. verifyOperationInProgress() {}
  16842. /**
  16843. * Waits until all currently queued tasks are finished executing. Delayed
  16844. * operations are not run.
  16845. */ async Xc() {
  16846. // Operations in the queue prior to draining may have enqueued additional
  16847. // operations. Keep draining the queue until the tail is no longer advanced,
  16848. // which indicates that no more new operations were enqueued and that all
  16849. // operations were executed.
  16850. let t;
  16851. do {
  16852. t = this.Bc, await t;
  16853. } while (t !== this.Bc);
  16854. }
  16855. /**
  16856. * For Tests: Determine if a delayed operation with a particular TimerId
  16857. * exists.
  16858. */ Zc(t) {
  16859. for (const e of this.Uc) if (e.timerId === t) return !0;
  16860. return !1;
  16861. }
  16862. /**
  16863. * For Tests: Runs some or all delayed operations early.
  16864. *
  16865. * @param lastTimerId - Delayed operations up to and including this TimerId
  16866. * will be drained. Pass TimerId.All to run all delayed operations.
  16867. * @returns a Promise that resolves once all operations have been run.
  16868. */ ta(t) {
  16869. // Note that draining may generate more delayed ops, so we do that first.
  16870. return this.Xc().then((() => {
  16871. // Run ops in the same order they'd run if they ran naturally.
  16872. this.Uc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));
  16873. for (const e of this.Uc) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break;
  16874. return this.Xc();
  16875. }));
  16876. }
  16877. /**
  16878. * For Tests: Skip all subsequent delays for a timer id.
  16879. */ ea(t) {
  16880. this.jc.push(t);
  16881. }
  16882. /** Called once a DelayedOperation is run or canceled. */ Yc(t) {
  16883. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  16884. const e = this.Uc.indexOf(t);
  16885. this.Uc.splice(e, 1);
  16886. }
  16887. }
  16888. function sh(t) {
  16889. /**
  16890. * Returns true if obj is an object and contains at least one of the specified
  16891. * methods.
  16892. */
  16893. return function(t, e) {
  16894. if ("object" != typeof t || null === t) return !1;
  16895. const n = t;
  16896. for (const t of e) if (t in n && "function" == typeof n[t]) return !0;
  16897. return !1;
  16898. }
  16899. /**
  16900. * @license
  16901. * Copyright 2020 Google LLC
  16902. *
  16903. * Licensed under the Apache License, Version 2.0 (the "License");
  16904. * you may not use this file except in compliance with the License.
  16905. * You may obtain a copy of the License at
  16906. *
  16907. * http://www.apache.org/licenses/LICENSE-2.0
  16908. *
  16909. * Unless required by applicable law or agreed to in writing, software
  16910. * distributed under the License is distributed on an "AS IS" BASIS,
  16911. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16912. * See the License for the specific language governing permissions and
  16913. * limitations under the License.
  16914. */
  16915. /**
  16916. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  16917. * loading, as well as task completion and error events.
  16918. *
  16919. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  16920. */ (t, [ "next", "error", "complete" ]);
  16921. }
  16922. class ih {
  16923. constructor() {
  16924. this._progressObserver = {}, this._taskCompletionResolver = new U, this._lastProgress = {
  16925. taskState: "Running",
  16926. totalBytes: 0,
  16927. totalDocuments: 0,
  16928. bytesLoaded: 0,
  16929. documentsLoaded: 0
  16930. };
  16931. }
  16932. /**
  16933. * Registers functions to listen to bundle loading progress events.
  16934. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  16935. * each time a Firestore document is loaded from the bundle.
  16936. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  16937. * error, and there should be no more updates after this.
  16938. * @param complete - Called when the loading task is complete.
  16939. */ onProgress(t, e, n) {
  16940. this._progressObserver = {
  16941. next: t,
  16942. error: e,
  16943. complete: n
  16944. };
  16945. }
  16946. /**
  16947. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  16948. *
  16949. * @param onRejected - Called when an error occurs during bundle loading.
  16950. */ catch(t) {
  16951. return this._taskCompletionResolver.promise.catch(t);
  16952. }
  16953. /**
  16954. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  16955. *
  16956. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  16957. * The update will always have its `taskState` set to `"Success"`.
  16958. * @param onRejected - Called when an error occurs during bundle loading.
  16959. */ then(t, e) {
  16960. return this._taskCompletionResolver.promise.then(t, e);
  16961. }
  16962. /**
  16963. * Notifies all observers that bundle loading has completed, with a provided
  16964. * `LoadBundleTaskProgress` object.
  16965. *
  16966. * @private
  16967. */ _completeWith(t) {
  16968. this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(),
  16969. this._taskCompletionResolver.resolve(t);
  16970. }
  16971. /**
  16972. * Notifies all observers that bundle loading has failed, with a provided
  16973. * `Error` as the reason.
  16974. *
  16975. * @private
  16976. */ _failWith(t) {
  16977. this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress),
  16978. this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);
  16979. }
  16980. /**
  16981. * Notifies a progress update of loading a bundle.
  16982. * @param progress - The new progress.
  16983. *
  16984. * @private
  16985. */ _updateProgress(t) {
  16986. this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);
  16987. }
  16988. }
  16989. /**
  16990. * @license
  16991. * Copyright 2020 Google LLC
  16992. *
  16993. * Licensed under the Apache License, Version 2.0 (the "License");
  16994. * you may not use this file except in compliance with the License.
  16995. * You may obtain a copy of the License at
  16996. *
  16997. * http://www.apache.org/licenses/LICENSE-2.0
  16998. *
  16999. * Unless required by applicable law or agreed to in writing, software
  17000. * distributed under the License is distributed on an "AS IS" BASIS,
  17001. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17002. * See the License for the specific language governing permissions and
  17003. * limitations under the License.
  17004. */
  17005. /** DOMException error code constants. */ const rh = -1;
  17006. /**
  17007. * The Cloud Firestore service interface.
  17008. *
  17009. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  17010. */
  17011. class oh extends ya {
  17012. /** @hideconstructor */
  17013. constructor(t, e, n, s) {
  17014. super(t, e, n, s),
  17015. /**
  17016. * Whether it's a {@link Firestore} or Firestore Lite instance.
  17017. */
  17018. this.type = "firestore", this._queue = new nh, this._persistenceKey = (null == s ? void 0 : s.name) || "[DEFAULT]";
  17019. }
  17020. _terminate() {
  17021. return this._firestoreClient ||
  17022. // The client must be initialized to ensure that all subsequent API
  17023. // usage throws an exception.
  17024. hh(this), this._firestoreClient.terminate();
  17025. }
  17026. }
  17027. /**
  17028. * Initializes a new instance of {@link Firestore} with the provided settings.
  17029. * Can only be called before any other function, including
  17030. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  17031. * equivalent to calling {@link (getFirestore:1)}.
  17032. *
  17033. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  17034. * be associated.
  17035. * @param settings - A settings object to configure the {@link Firestore} instance.
  17036. * @param databaseId - The name of database.
  17037. * @returns A newly initialized {@link Firestore} instance.
  17038. */ function uh(t, e, n) {
  17039. n || (n = "(default)");
  17040. const s = _getProvider(t, "firestore");
  17041. if (s.isInitialized(n)) {
  17042. const t = s.getImmediate({
  17043. identifier: n
  17044. }), i = s.getOptions(n);
  17045. if (w(i, e)) return t;
  17046. throw new q(L.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.");
  17047. }
  17048. if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new q(L.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17049. return s.initialize({
  17050. options: e,
  17051. instanceIdentifier: n
  17052. });
  17053. }
  17054. function ch(e, n) {
  17055. const s = "object" == typeof e ? e : t(), i = "string" == typeof e ? e : n || "(default)", r = _getProvider(s, "firestore").getImmediate({
  17056. identifier: i
  17057. });
  17058. if (!r._initialized) {
  17059. const t = m("firestore");
  17060. t && pa(r, ...t);
  17061. }
  17062. return r;
  17063. }
  17064. /**
  17065. * @internal
  17066. */ function ah(t) {
  17067. return t._firestoreClient || hh(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;
  17068. }
  17069. function hh(t) {
  17070. var e;
  17071. const n = t._freezeSettings(), s = function(t, e, n, s) {
  17072. return new Ft(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, s.useFetchStreams);
  17073. }
  17074. /**
  17075. * @license
  17076. * Copyright 2020 Google LLC
  17077. *
  17078. * Licensed under the Apache License, Version 2.0 (the "License");
  17079. * you may not use this file except in compliance with the License.
  17080. * You may obtain a copy of the License at
  17081. *
  17082. * http://www.apache.org/licenses/LICENSE-2.0
  17083. *
  17084. * Unless required by applicable law or agreed to in writing, software
  17085. * distributed under the License is distributed on an "AS IS" BASIS,
  17086. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17087. * See the License for the specific language governing permissions and
  17088. * limitations under the License.
  17089. */
  17090. // settings() defaults:
  17091. (t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, n);
  17092. t._firestoreClient = new Ma(t._authCredentials, t._appCheckCredentials, t._queue, s);
  17093. }
  17094. /**
  17095. * Attempts to enable persistent storage, if possible.
  17096. *
  17097. * Must be called before any other functions (other than
  17098. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  17099. * {@link clearIndexedDbPersistence}.
  17100. *
  17101. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  17102. * returns. Note that even after this failure, the {@link Firestore} instance will
  17103. * remain usable, however offline persistence will be disabled.
  17104. *
  17105. * There are several reasons why this can fail, which can be identified by
  17106. * the `code` on the error.
  17107. *
  17108. * * failed-precondition: The app is already open in another browser tab.
  17109. * * unimplemented: The browser is incompatible with the offline
  17110. * persistence implementation.
  17111. *
  17112. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17113. * @param persistenceSettings - Optional settings object to configure
  17114. * persistence.
  17115. * @returns A `Promise` that represents successfully enabling persistent storage.
  17116. */ function lh(t, e) {
  17117. Th(t = _a(t, oh));
  17118. const n = ah(t), s = t._freezeSettings(), i = new ca;
  17119. return dh(n, i, new oa(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
  17120. }
  17121. /**
  17122. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  17123. * across all tabs, all operations share access to local persistence, including
  17124. * shared execution of queries and latency-compensated local document updates
  17125. * across all connected instances.
  17126. *
  17127. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  17128. * it returns. Note that even after this failure, the {@link Firestore} instance will
  17129. * remain usable, however offline persistence will be disabled.
  17130. *
  17131. * There are several reasons why this can fail, which can be identified by
  17132. * the `code` on the error.
  17133. *
  17134. * * failed-precondition: The app is already open in another browser tab and
  17135. * multi-tab is not enabled.
  17136. * * unimplemented: The browser is incompatible with the offline
  17137. * persistence implementation.
  17138. *
  17139. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17140. * @returns A `Promise` that represents successfully enabling persistent
  17141. * storage.
  17142. */ function fh(t) {
  17143. Th(t = _a(t, oh));
  17144. const e = ah(t), n = t._freezeSettings(), s = new ca;
  17145. return dh(e, s, new ua(s, n.cacheSizeBytes));
  17146. }
  17147. /**
  17148. * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
  17149. * If the operation fails with a recoverable error (see
  17150. * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
  17151. * but the client remains usable.
  17152. */ function dh(t, e, n) {
  17153. const s = new U;
  17154. return t.asyncQueue.enqueue((async () => {
  17155. try {
  17156. await Fa(t, n), await $a(t, e), s.resolve();
  17157. } catch (t) {
  17158. const e = t;
  17159. if (!
  17160. /**
  17161. * Decides whether the provided error allows us to gracefully disable
  17162. * persistence (as opposed to crashing the client).
  17163. */
  17164. function(t) {
  17165. if ("FirebaseError" === t.name) return t.code === L.FAILED_PRECONDITION || t.code === L.UNIMPLEMENTED;
  17166. if ("undefined" != typeof DOMException && t instanceof DOMException)
  17167. // There are a few known circumstances where we can open IndexedDb but
  17168. // trying to read/write will fail (e.g. quota exceeded). For
  17169. // well-understood cases, we attempt to detect these and then gracefully
  17170. // fall back to memory persistence.
  17171. // NOTE: Rather than continue to add to this list, we could decide to
  17172. // always fall back, with the risk that we might accidentally hide errors
  17173. // representing actual SDK bugs.
  17174. // When the browser is out of quota we could get either quota exceeded
  17175. // or an aborted error depending on whether the error happened during
  17176. // schema migration.
  17177. return 22 === t.code || 20 === t.code ||
  17178. // Firefox Private Browsing mode disables IndexedDb and returns
  17179. // INVALID_STATE for any usage.
  17180. 11 === t.code;
  17181. return !0;
  17182. }
  17183. /**
  17184. * Clears the persistent storage. This includes pending writes and cached
  17185. * documents.
  17186. *
  17187. * Must be called while the {@link Firestore} instance is not started (after the app is
  17188. * terminated or when the app is first initialized). On startup, this function
  17189. * must be called before other functions (other than {@link
  17190. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  17191. * instance is still running, the promise will be rejected with the error code
  17192. * of `failed-precondition`.
  17193. *
  17194. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  17195. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  17196. * dropping existing data but does not attempt to securely overwrite or
  17197. * otherwise make cached data unrecoverable. For applications that are sensitive
  17198. * to the disclosure of cached data in between user sessions, we strongly
  17199. * recommend not enabling persistence at all.
  17200. *
  17201. * @param firestore - The {@link Firestore} instance to clear persistence for.
  17202. * @returns A `Promise` that is resolved when the persistent storage is
  17203. * cleared. Otherwise, the promise is rejected with an error.
  17204. */ (e)) throw e;
  17205. k("Error enabling offline persistence. Falling back to persistence disabled: " + e),
  17206. s.reject(e);
  17207. }
  17208. })).then((() => s.promise));
  17209. }
  17210. function _h(t) {
  17211. if (t._initialized && !t._terminated) throw new q(L.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  17212. const e = new U;
  17213. return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {
  17214. try {
  17215. await async function(t) {
  17216. if (!Pt.C()) return Promise.resolve();
  17217. const e = t + "main";
  17218. await Pt.delete(e);
  17219. }
  17220. /**
  17221. * @license
  17222. * Copyright 2017 Google LLC
  17223. *
  17224. * Licensed under the Apache License, Version 2.0 (the "License");
  17225. * you may not use this file except in compliance with the License.
  17226. * You may obtain a copy of the License at
  17227. *
  17228. * http://www.apache.org/licenses/LICENSE-2.0
  17229. *
  17230. * Unless required by applicable law or agreed to in writing, software
  17231. * distributed under the License is distributed on an "AS IS" BASIS,
  17232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17233. * See the License for the specific language governing permissions and
  17234. * limitations under the License.
  17235. */
  17236. /**
  17237. * Compares two array for equality using comparator. The method computes the
  17238. * intersection and invokes `onAdd` for every element that is in `after` but not
  17239. * `before`. `onRemove` is invoked for every element in `before` but missing
  17240. * from `after`.
  17241. *
  17242. * The method creates a copy of both `before` and `after` and runs in O(n log
  17243. * n), where n is the size of the two lists.
  17244. *
  17245. * @param before - The elements that exist in the original array.
  17246. * @param after - The elements to diff against the original array.
  17247. * @param comparator - The comparator for the elements in before and after.
  17248. * @param onAdd - A function to invoke for every element that is part of `
  17249. * after` but not `before`.
  17250. * @param onRemove - A function to invoke for every element that is part of
  17251. * `before` but not `after`.
  17252. */ (Bo(t._databaseId, t._persistenceKey)), e.resolve();
  17253. } catch (t) {
  17254. e.reject(t);
  17255. }
  17256. })), e.promise;
  17257. }
  17258. /**
  17259. * Waits until all currently pending writes for the active user have been
  17260. * acknowledged by the backend.
  17261. *
  17262. * The returned promise resolves immediately if there are no outstanding writes.
  17263. * Otherwise, the promise waits for all previously issued writes (including
  17264. * those written in a previous app session), but it does not wait for writes
  17265. * that were added after the function is called. If you want to wait for
  17266. * additional writes, call `waitForPendingWrites()` again.
  17267. *
  17268. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  17269. * changes.
  17270. *
  17271. * @returns A `Promise` which resolves when all currently pending writes have been
  17272. * acknowledged by the backend.
  17273. */ function wh(t) {
  17274. return function(t) {
  17275. const e = new U;
  17276. return t.asyncQueue.enqueueAndForget((async () => Mc(await Ga(t), e))), e.promise;
  17277. }(ah(t = _a(t, oh)));
  17278. }
  17279. /**
  17280. * Re-enables use of the network for this {@link Firestore} instance after a prior
  17281. * call to {@link disableNetwork}.
  17282. *
  17283. * @returns A `Promise` that is resolved once the network has been enabled.
  17284. */ function mh(t) {
  17285. return Wa(ah(t = _a(t, oh)));
  17286. }
  17287. /**
  17288. * Disables network usage for this instance. It can be re-enabled via {@link
  17289. * enableNetwork}. While the network is disabled, any snapshot listeners,
  17290. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  17291. * operations will be queued until the network is restored.
  17292. *
  17293. * @returns A `Promise` that is resolved once the network has been disabled.
  17294. */ function gh(t) {
  17295. return za(ah(t = _a(t, oh)));
  17296. }
  17297. /**
  17298. * Terminates the provided {@link Firestore} instance.
  17299. *
  17300. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  17301. * may be used. Any other function will throw a `FirestoreError`.
  17302. *
  17303. * To restart after termination, create a new instance of FirebaseFirestore with
  17304. * {@link (getFirestore:1)}.
  17305. *
  17306. * Termination does not cancel any pending writes, and any promises that are
  17307. * awaiting a response from the server will not be resolved. If you have
  17308. * persistence enabled, the next time you start this instance, it will resume
  17309. * sending these writes to the server.
  17310. *
  17311. * Note: Under normal circumstances, calling `terminate()` is not required. This
  17312. * function is useful only when you want to force this instance to release all
  17313. * of its resources or in combination with `clearIndexedDbPersistence()` to
  17314. * ensure that all local state is destroyed between test runs.
  17315. *
  17316. * @returns A `Promise` that is resolved when the instance has been successfully
  17317. * terminated.
  17318. */ function yh(t) {
  17319. return e(t.app, "firestore", t._databaseId.database), t._delete();
  17320. }
  17321. /**
  17322. * Loads a Firestore bundle into the local cache.
  17323. *
  17324. * @param firestore - The {@link Firestore} instance to load bundles for.
  17325. * @param bundleData - An object representing the bundle to be loaded. Valid
  17326. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  17327. *
  17328. * @returns A `LoadBundleTask` object, which notifies callers with progress
  17329. * updates, and completion or error events. It can be used as a
  17330. * `Promise<LoadBundleTaskProgress>`.
  17331. */ function ph(t, e) {
  17332. const n = ah(t = _a(t, oh)), s = new ih;
  17333. return th(n, t._databaseId, e, s), s;
  17334. }
  17335. /**
  17336. * Reads a Firestore {@link Query} from local cache, identified by the given
  17337. * name.
  17338. *
  17339. * The named queries are packaged into bundles on the server side (along
  17340. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  17341. * in local cache, use this method to extract a {@link Query} by name.
  17342. *
  17343. * @param firestore - The {@link Firestore} instance to read the query from.
  17344. * @param name - The name of the query.
  17345. * @returns A `Promise` that is resolved with the Query or `null`.
  17346. */ function Ih(t, e) {
  17347. return eh(ah(t = _a(t, oh)), e).then((e => e ? new Ta(t, null, e.query) : null));
  17348. }
  17349. function Th(t) {
  17350. if (t._initialized || t._terminated) throw new q(L.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");
  17351. }
  17352. /**
  17353. * @license
  17354. * Copyright 2020 Google LLC
  17355. *
  17356. * Licensed under the Apache License, Version 2.0 (the "License");
  17357. * you may not use this file except in compliance with the License.
  17358. * You may obtain a copy of the License at
  17359. *
  17360. * http://www.apache.org/licenses/LICENSE-2.0
  17361. *
  17362. * Unless required by applicable law or agreed to in writing, software
  17363. * distributed under the License is distributed on an "AS IS" BASIS,
  17364. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17365. * See the License for the specific language governing permissions and
  17366. * limitations under the License.
  17367. */
  17368. /**
  17369. * @license
  17370. * Copyright 2020 Google LLC
  17371. *
  17372. * Licensed under the Apache License, Version 2.0 (the "License");
  17373. * you may not use this file except in compliance with the License.
  17374. * You may obtain a copy of the License at
  17375. *
  17376. * http://www.apache.org/licenses/LICENSE-2.0
  17377. *
  17378. * Unless required by applicable law or agreed to in writing, software
  17379. * distributed under the License is distributed on an "AS IS" BASIS,
  17380. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17381. * See the License for the specific language governing permissions and
  17382. * limitations under the License.
  17383. */
  17384. /**
  17385. * An immutable object representing an array of bytes.
  17386. */
  17387. class Eh {
  17388. /** @hideconstructor */
  17389. constructor(t) {
  17390. this._byteString = t;
  17391. }
  17392. /**
  17393. * Creates a new `Bytes` object from the given Base64 string, converting it to
  17394. * bytes.
  17395. *
  17396. * @param base64 - The Base64 string used to create the `Bytes` object.
  17397. */ static fromBase64String(t) {
  17398. try {
  17399. return new Eh(Wt.fromBase64String(t));
  17400. } catch (t) {
  17401. throw new q(L.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + t);
  17402. }
  17403. }
  17404. /**
  17405. * Creates a new `Bytes` object from the given Uint8Array.
  17406. *
  17407. * @param array - The Uint8Array used to create the `Bytes` object.
  17408. */ static fromUint8Array(t) {
  17409. return new Eh(Wt.fromUint8Array(t));
  17410. }
  17411. /**
  17412. * Returns the underlying bytes as a Base64-encoded string.
  17413. *
  17414. * @returns The Base64-encoded string created from the `Bytes` object.
  17415. */ toBase64() {
  17416. return this._byteString.toBase64();
  17417. }
  17418. /**
  17419. * Returns the underlying bytes in a new `Uint8Array`.
  17420. *
  17421. * @returns The Uint8Array created from the `Bytes` object.
  17422. */ toUint8Array() {
  17423. return this._byteString.toUint8Array();
  17424. }
  17425. /**
  17426. * Returns a string representation of the `Bytes` object.
  17427. *
  17428. * @returns A string representation of the `Bytes` object.
  17429. */ toString() {
  17430. return "Bytes(base64: " + this.toBase64() + ")";
  17431. }
  17432. /**
  17433. * Returns true if this `Bytes` object is equal to the provided one.
  17434. *
  17435. * @param other - The `Bytes` object to compare against.
  17436. * @returns true if this `Bytes` object is equal to the provided one.
  17437. */ isEqual(t) {
  17438. return this._byteString.isEqual(t._byteString);
  17439. }
  17440. }
  17441. /**
  17442. * @license
  17443. * Copyright 2020 Google LLC
  17444. *
  17445. * Licensed under the Apache License, Version 2.0 (the "License");
  17446. * you may not use this file except in compliance with the License.
  17447. * You may obtain a copy of the License at
  17448. *
  17449. * http://www.apache.org/licenses/LICENSE-2.0
  17450. *
  17451. * Unless required by applicable law or agreed to in writing, software
  17452. * distributed under the License is distributed on an "AS IS" BASIS,
  17453. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17454. * See the License for the specific language governing permissions and
  17455. * limitations under the License.
  17456. */
  17457. /**
  17458. * A `FieldPath` refers to a field in a document. The path may consist of a
  17459. * single field name (referring to a top-level field in the document), or a
  17460. * list of field names (referring to a nested field in the document).
  17461. *
  17462. * Create a `FieldPath` by providing field names. If more than one field
  17463. * name is provided, the path will point to a nested field in a document.
  17464. */ class Ah {
  17465. /**
  17466. * Creates a `FieldPath` from the provided field names. If more than one field
  17467. * name is provided, the path will point to a nested field in a document.
  17468. *
  17469. * @param fieldNames - A list of field names.
  17470. */
  17471. constructor(...t) {
  17472. for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new q(L.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  17473. this._internalPath = new ct(t);
  17474. }
  17475. /**
  17476. * Returns true if this `FieldPath` is equal to the provided one.
  17477. *
  17478. * @param other - The `FieldPath` to compare against.
  17479. * @returns true if this `FieldPath` is equal to the provided one.
  17480. */ isEqual(t) {
  17481. return this._internalPath.isEqual(t._internalPath);
  17482. }
  17483. }
  17484. /**
  17485. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  17486. * It can be used in queries to sort or filter by the document ID.
  17487. */ function Rh() {
  17488. return new Ah("__name__");
  17489. }
  17490. /**
  17491. * @license
  17492. * Copyright 2020 Google LLC
  17493. *
  17494. * Licensed under the Apache License, Version 2.0 (the "License");
  17495. * you may not use this file except in compliance with the License.
  17496. * You may obtain a copy of the License at
  17497. *
  17498. * http://www.apache.org/licenses/LICENSE-2.0
  17499. *
  17500. * Unless required by applicable law or agreed to in writing, software
  17501. * distributed under the License is distributed on an "AS IS" BASIS,
  17502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17503. * See the License for the specific language governing permissions and
  17504. * limitations under the License.
  17505. */
  17506. /**
  17507. * Sentinel values that can be used when writing document fields with `set()`
  17508. * or `update()`.
  17509. */ class bh {
  17510. /**
  17511. * @param _methodName - The public API endpoint that returns this class.
  17512. * @hideconstructor
  17513. */
  17514. constructor(t) {
  17515. this._methodName = t;
  17516. }
  17517. }
  17518. /**
  17519. * @license
  17520. * Copyright 2017 Google LLC
  17521. *
  17522. * Licensed under the Apache License, Version 2.0 (the "License");
  17523. * you may not use this file except in compliance with the License.
  17524. * You may obtain a copy of the License at
  17525. *
  17526. * http://www.apache.org/licenses/LICENSE-2.0
  17527. *
  17528. * Unless required by applicable law or agreed to in writing, software
  17529. * distributed under the License is distributed on an "AS IS" BASIS,
  17530. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17531. * See the License for the specific language governing permissions and
  17532. * limitations under the License.
  17533. */
  17534. /**
  17535. * An immutable object representing a geographic location in Firestore. The
  17536. * location is represented as latitude/longitude pair.
  17537. *
  17538. * Latitude values are in the range of [-90, 90].
  17539. * Longitude values are in the range of [-180, 180].
  17540. */ class Ph {
  17541. /**
  17542. * Creates a new immutable `GeoPoint` object with the provided latitude and
  17543. * longitude values.
  17544. * @param latitude - The latitude as number between -90 and 90.
  17545. * @param longitude - The longitude as number between -180 and 180.
  17546. */
  17547. constructor(t, e) {
  17548. if (!isFinite(t) || t < -90 || t > 90) throw new q(L.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
  17549. if (!isFinite(e) || e < -180 || e > 180) throw new q(L.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
  17550. this._lat = t, this._long = e;
  17551. }
  17552. /**
  17553. * The latitude of this `GeoPoint` instance.
  17554. */ get latitude() {
  17555. return this._lat;
  17556. }
  17557. /**
  17558. * The longitude of this `GeoPoint` instance.
  17559. */ get longitude() {
  17560. return this._long;
  17561. }
  17562. /**
  17563. * Returns true if this `GeoPoint` is equal to the provided one.
  17564. *
  17565. * @param other - The `GeoPoint` to compare against.
  17566. * @returns true if this `GeoPoint` is equal to the provided one.
  17567. */ isEqual(t) {
  17568. return this._lat === t._lat && this._long === t._long;
  17569. }
  17570. /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
  17571. return {
  17572. latitude: this._lat,
  17573. longitude: this._long
  17574. };
  17575. }
  17576. /**
  17577. * Actually private to JS consumers of our API, so this function is prefixed
  17578. * with an underscore.
  17579. */ _compareTo(t) {
  17580. return tt(this._lat, t._lat) || tt(this._long, t._long);
  17581. }
  17582. }
  17583. /**
  17584. * @license
  17585. * Copyright 2017 Google LLC
  17586. *
  17587. * Licensed under the Apache License, Version 2.0 (the "License");
  17588. * you may not use this file except in compliance with the License.
  17589. * You may obtain a copy of the License at
  17590. *
  17591. * http://www.apache.org/licenses/LICENSE-2.0
  17592. *
  17593. * Unless required by applicable law or agreed to in writing, software
  17594. * distributed under the License is distributed on an "AS IS" BASIS,
  17595. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17596. * See the License for the specific language governing permissions and
  17597. * limitations under the License.
  17598. */ const vh = /^__.*__$/;
  17599. /** The result of parsing document data (e.g. for a setData call). */ class Vh {
  17600. constructor(t, e, n) {
  17601. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  17602. }
  17603. toMutation(t, e) {
  17604. return null !== this.fieldMask ? new ns(t, this.data, this.fieldMask, e, this.fieldTransforms) : new es(t, this.data, e, this.fieldTransforms);
  17605. }
  17606. }
  17607. /** The result of parsing "update" data (i.e. for an updateData call). */ class Sh {
  17608. constructor(t,
  17609. // The fieldMask does not include document transforms.
  17610. e, n) {
  17611. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  17612. }
  17613. toMutation(t, e) {
  17614. return new ns(t, this.data, this.fieldMask, e, this.fieldTransforms);
  17615. }
  17616. }
  17617. function Dh(t) {
  17618. switch (t) {
  17619. case 0 /* UserDataSource.Set */ :
  17620. // fall through
  17621. case 2 /* UserDataSource.MergeSet */ :
  17622. // fall through
  17623. case 1 /* UserDataSource.Update */ :
  17624. return !0;
  17625. case 3 /* UserDataSource.Argument */ :
  17626. case 4 /* UserDataSource.ArrayArgument */ :
  17627. return !1;
  17628. default:
  17629. throw M();
  17630. }
  17631. }
  17632. /** A "context" object passed around while parsing user data. */ class Ch {
  17633. /**
  17634. * Initializes a ParseContext with the given source and path.
  17635. *
  17636. * @param settings - The settings for the parser.
  17637. * @param databaseId - The database ID of the Firestore instance.
  17638. * @param serializer - The serializer to use to generate the Value proto.
  17639. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  17640. * rather than throw.
  17641. * @param fieldTransforms - A mutable list of field transforms encountered
  17642. * while parsing the data.
  17643. * @param fieldMask - A mutable list of field paths encountered while parsing
  17644. * the data.
  17645. *
  17646. * TODO(b/34871131): We don't support array paths right now, so path can be
  17647. * null to indicate the context represents any location within an array (in
  17648. * which case certain features will not work and errors will be somewhat
  17649. * compromised).
  17650. */
  17651. constructor(t, e, n, s, i, r) {
  17652. this.settings = t, this.databaseId = e, this.yt = n, this.ignoreUndefinedProperties = s,
  17653. // Minor hack: If fieldTransforms is undefined, we assume this is an
  17654. // external call and we need to validate the entire path.
  17655. void 0 === i && this.na(), this.fieldTransforms = i || [], this.fieldMask = r || [];
  17656. }
  17657. get path() {
  17658. return this.settings.path;
  17659. }
  17660. get sa() {
  17661. return this.settings.sa;
  17662. }
  17663. /** Returns a new context with the specified settings overwritten. */ ia(t) {
  17664. return new Ch(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.yt, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  17665. }
  17666. ra(t) {
  17667. var e;
  17668. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({
  17669. path: n,
  17670. oa: !1
  17671. });
  17672. return s.ua(t), s;
  17673. }
  17674. ca(t) {
  17675. var e;
  17676. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({
  17677. path: n,
  17678. oa: !1
  17679. });
  17680. return s.na(), s;
  17681. }
  17682. aa(t) {
  17683. // TODO(b/34871131): We don't support array paths right now; so make path
  17684. // undefined.
  17685. return this.ia({
  17686. path: void 0,
  17687. oa: !0
  17688. });
  17689. }
  17690. ha(t) {
  17691. return Yh(t, this.settings.methodName, this.settings.la || !1, this.path, this.settings.fa);
  17692. }
  17693. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {
  17694. return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));
  17695. }
  17696. na() {
  17697. // TODO(b/34871131): Remove null check once we have proper paths for fields
  17698. // within arrays.
  17699. if (this.path) for (let t = 0; t < this.path.length; t++) this.ua(this.path.get(t));
  17700. }
  17701. ua(t) {
  17702. if (0 === t.length) throw this.ha("Document fields must not be empty");
  17703. if (Dh(this.sa) && vh.test(t)) throw this.ha('Document fields cannot begin and end with "__"');
  17704. }
  17705. }
  17706. /**
  17707. * Helper for parsing raw user input (provided via the API) into internal model
  17708. * classes.
  17709. */ class xh {
  17710. constructor(t, e, n) {
  17711. this.databaseId = t, this.ignoreUndefinedProperties = e, this.yt = n || Tu(t);
  17712. }
  17713. /** Creates a new top-level parse context. */ da(t, e, n, s = !1) {
  17714. return new Ch({
  17715. sa: t,
  17716. methodName: e,
  17717. fa: n,
  17718. path: ct.emptyPath(),
  17719. oa: !1,
  17720. la: s
  17721. }, this.databaseId, this.yt, this.ignoreUndefinedProperties);
  17722. }
  17723. }
  17724. function Nh(t) {
  17725. const e = t._freezeSettings(), n = Tu(t._databaseId);
  17726. return new xh(t._databaseId, !!e.ignoreUndefinedProperties, n);
  17727. }
  17728. /** Parse document data from a set() call. */ function kh(t, e, n, s, i, r = {}) {
  17729. const o = t.da(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);
  17730. Wh("Data must be an object, but it was:", o, s);
  17731. const u = Qh(s, o);
  17732. let c, a;
  17733. if (r.merge) c = new Xe(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {
  17734. const t = [];
  17735. for (const s of r.mergeFields) {
  17736. const i = zh(e, s, n);
  17737. if (!o.contains(i)) throw new q(L.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);
  17738. Xh(t, i) || t.push(i);
  17739. }
  17740. c = new Xe(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));
  17741. } else c = null, a = o.fieldTransforms;
  17742. return new Vh(new Ze(u), c, a);
  17743. }
  17744. class Oh extends bh {
  17745. _toFieldTransform(t) {
  17746. if (2 /* UserDataSource.MergeSet */ !== t.sa) throw 1 /* UserDataSource.Update */ === t.sa ? t.ha(`${this._methodName}() can only appear at the top level of your update data`) : t.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
  17747. // No transform to add for a delete, but we need to add it to our
  17748. // fieldMask so it gets deleted.
  17749. return t.fieldMask.push(t.path), null;
  17750. }
  17751. isEqual(t) {
  17752. return t instanceof Oh;
  17753. }
  17754. }
  17755. /**
  17756. * Creates a child context for parsing SerializableFieldValues.
  17757. *
  17758. * This is different than calling `ParseContext.contextWith` because it keeps
  17759. * the fieldTransforms and fieldMask separate.
  17760. *
  17761. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  17762. * Although these values are used with writes, any elements in these FieldValues
  17763. * are not considered writes since they cannot contain any FieldValue sentinels,
  17764. * etc.
  17765. *
  17766. * @param fieldValue - The sentinel FieldValue for which to create a child
  17767. * context.
  17768. * @param context - The parent context.
  17769. * @param arrayElement - Whether or not the FieldValue has an array.
  17770. */ function Mh(t, e, n) {
  17771. return new Ch({
  17772. sa: 3 /* UserDataSource.Argument */ ,
  17773. fa: e.settings.fa,
  17774. methodName: t._methodName,
  17775. oa: n
  17776. }, e.databaseId, e.yt, e.ignoreUndefinedProperties);
  17777. }
  17778. class Fh extends bh {
  17779. _toFieldTransform(t) {
  17780. return new Gn(t.path, new Mn);
  17781. }
  17782. isEqual(t) {
  17783. return t instanceof Fh;
  17784. }
  17785. }
  17786. class $h extends bh {
  17787. constructor(t, e) {
  17788. super(t), this._a = e;
  17789. }
  17790. _toFieldTransform(t) {
  17791. const e = Mh(this, t,
  17792. /*array=*/ !0), n = this._a.map((t => Gh(t, e))), s = new Fn(n);
  17793. return new Gn(t.path, s);
  17794. }
  17795. isEqual(t) {
  17796. // TODO(mrschmidt): Implement isEquals
  17797. return this === t;
  17798. }
  17799. }
  17800. class Bh extends bh {
  17801. constructor(t, e) {
  17802. super(t), this._a = e;
  17803. }
  17804. _toFieldTransform(t) {
  17805. const e = Mh(this, t,
  17806. /*array=*/ !0), n = this._a.map((t => Gh(t, e))), s = new Bn(n);
  17807. return new Gn(t.path, s);
  17808. }
  17809. isEqual(t) {
  17810. // TODO(mrschmidt): Implement isEquals
  17811. return this === t;
  17812. }
  17813. }
  17814. class Lh extends bh {
  17815. constructor(t, e) {
  17816. super(t), this.wa = e;
  17817. }
  17818. _toFieldTransform(t) {
  17819. const e = new qn(t.yt, Cn(t.yt, this.wa));
  17820. return new Gn(t.path, e);
  17821. }
  17822. isEqual(t) {
  17823. // TODO(mrschmidt): Implement isEquals
  17824. return this === t;
  17825. }
  17826. }
  17827. /** Parse update data from an update() call. */ function qh(t, e, n, s) {
  17828. const i = t.da(1 /* UserDataSource.Update */ , e, n);
  17829. Wh("Data must be an object, but it was:", i, s);
  17830. const r = [], o = Ze.empty();
  17831. Lt(s, ((t, s) => {
  17832. const u = Jh(e, t, n);
  17833. // For Compat types, we have to "extract" the underlying types before
  17834. // performing validation.
  17835. s = _(s);
  17836. const c = i.ca(u);
  17837. if (s instanceof Oh)
  17838. // Add it to the field mask, but don't add anything to updateData.
  17839. r.push(u); else {
  17840. const t = Gh(s, c);
  17841. null != t && (r.push(u), o.set(u, t));
  17842. }
  17843. }));
  17844. const u = new Xe(r);
  17845. return new Sh(o, u, i.fieldTransforms);
  17846. }
  17847. /** Parse update data from a list of field/value arguments. */ function Uh(t, e, n, s, i, r) {
  17848. const o = t.da(1 /* UserDataSource.Update */ , e, n), u = [ zh(e, s, n) ], c = [ i ];
  17849. if (r.length % 2 != 0) throw new q(L.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
  17850. for (let t = 0; t < r.length; t += 2) u.push(zh(e, r[t])), c.push(r[t + 1]);
  17851. const a = [], h = Ze.empty();
  17852. // We iterate in reverse order to pick the last value for a field if the
  17853. // user specified the field multiple times.
  17854. for (let t = u.length - 1; t >= 0; --t) if (!Xh(a, u[t])) {
  17855. const e = u[t];
  17856. let n = c[t];
  17857. // For Compat types, we have to "extract" the underlying types before
  17858. // performing validation.
  17859. n = _(n);
  17860. const s = o.ca(e);
  17861. if (n instanceof Oh)
  17862. // Add it to the field mask, but don't add anything to updateData.
  17863. a.push(e); else {
  17864. const t = Gh(n, s);
  17865. null != t && (a.push(e), h.set(e, t));
  17866. }
  17867. }
  17868. const l = new Xe(a);
  17869. return new Sh(h, l, o.fieldTransforms);
  17870. }
  17871. /**
  17872. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  17873. * bound).
  17874. *
  17875. * @param allowArrays - Whether the query value is an array that may directly
  17876. * contain additional arrays (e.g. the operand of an `in` query).
  17877. */ function Kh(t, e, n, s = !1) {
  17878. return Gh(n, t.da(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  17879. }
  17880. /**
  17881. * Parses user data to Protobuf Values.
  17882. *
  17883. * @param input - Data to be parsed.
  17884. * @param context - A context object representing the current path being parsed,
  17885. * the source of the data being parsed, etc.
  17886. * @returns The parsed value, or null if the value was a FieldValue sentinel
  17887. * that should not be included in the resulting parsed data.
  17888. */ function Gh(t, e) {
  17889. if (jh(
  17890. // Unwrap the API type from the Compat SDK. This will return the API type
  17891. // from firestore-exp.
  17892. t = _(t))) return Wh("Unsupported field value:", e, t), Qh(t, e);
  17893. if (t instanceof bh)
  17894. // FieldValues usually parse into transforms (except deleteField())
  17895. // in which case we do not want to include this field in our parsed data
  17896. // (as doing so will overwrite the field directly prior to the transform
  17897. // trying to transform it). So we don't add this location to
  17898. // context.fieldMask and we return null as our parsing result.
  17899. /**
  17900. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  17901. * context.fieldTransforms.
  17902. */
  17903. return function(t, e) {
  17904. // Sentinels are only supported with writes, and not within arrays.
  17905. if (!Dh(e.sa)) throw e.ha(`${t._methodName}() can only be used with update() and set()`);
  17906. if (!e.path) throw e.ha(`${t._methodName}() is not currently supported inside arrays`);
  17907. const n = t._toFieldTransform(e);
  17908. n && e.fieldTransforms.push(n);
  17909. }
  17910. /**
  17911. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  17912. *
  17913. * @returns The parsed value
  17914. */ (t, e), null;
  17915. if (void 0 === t && e.ignoreUndefinedProperties)
  17916. // If the input is undefined it can never participate in the fieldMask, so
  17917. // don't handle this below. If `ignoreUndefinedProperties` is false,
  17918. // `parseScalarValue` will reject an undefined value.
  17919. return null;
  17920. if (
  17921. // If context.path is null we are inside an array and we don't support
  17922. // field mask paths more granular than the top-level array.
  17923. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  17924. // TODO(b/34871131): Include the path containing the array in the error
  17925. // message.
  17926. // In the case of IN queries, the parsed data is an array (representing
  17927. // the set of values to be included for the IN query) that may directly
  17928. // contain additional arrays (each representing an individual field
  17929. // value), so we disable this validation.
  17930. if (e.settings.oa && 4 /* UserDataSource.ArrayArgument */ !== e.sa) throw e.ha("Nested arrays are not supported");
  17931. return function(t, e) {
  17932. const n = [];
  17933. let s = 0;
  17934. for (const i of t) {
  17935. let t = Gh(i, e.aa(s));
  17936. null == t && (
  17937. // Just include nulls in the array for fields being replaced with a
  17938. // sentinel.
  17939. t = {
  17940. nullValue: "NULL_VALUE"
  17941. }), n.push(t), s++;
  17942. }
  17943. return {
  17944. arrayValue: {
  17945. values: n
  17946. }
  17947. };
  17948. }(t, e);
  17949. }
  17950. return function(t, e) {
  17951. if (null === (t = _(t))) return {
  17952. nullValue: "NULL_VALUE"
  17953. };
  17954. if ("number" == typeof t) return Cn(e.yt, t);
  17955. if ("boolean" == typeof t) return {
  17956. booleanValue: t
  17957. };
  17958. if ("string" == typeof t) return {
  17959. stringValue: t
  17960. };
  17961. if (t instanceof Date) {
  17962. const n = st.fromDate(t);
  17963. return {
  17964. timestampValue: Ls(e.yt, n)
  17965. };
  17966. }
  17967. if (t instanceof st) {
  17968. // Firestore backend truncates precision down to microseconds. To ensure
  17969. // offline mode works the same with regards to truncation, perform the
  17970. // truncation immediately without waiting for the backend to do that.
  17971. const n = new st(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  17972. return {
  17973. timestampValue: Ls(e.yt, n)
  17974. };
  17975. }
  17976. if (t instanceof Ph) return {
  17977. geoPointValue: {
  17978. latitude: t.latitude,
  17979. longitude: t.longitude
  17980. }
  17981. };
  17982. if (t instanceof Eh) return {
  17983. bytesValue: qs(e.yt, t._byteString)
  17984. };
  17985. if (t instanceof Ia) {
  17986. const n = e.databaseId, s = t.firestore._databaseId;
  17987. if (!s.isEqual(n)) throw e.ha(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);
  17988. return {
  17989. referenceValue: Gs(t.firestore._databaseId || e.databaseId, t._key.path)
  17990. };
  17991. }
  17992. throw e.ha(`Unsupported field value: ${da(t)}`);
  17993. }
  17994. /**
  17995. * Checks whether an object looks like a JSON object that should be converted
  17996. * into a struct. Normal class/prototype instances are considered to look like
  17997. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  17998. * GeoPoints, etc. are not considered to look like JSON objects since they map
  17999. * to specific FieldValue types other than ObjectValue.
  18000. */ (t, e);
  18001. }
  18002. function Qh(t, e) {
  18003. const n = {};
  18004. return qt(t) ?
  18005. // If we encounter an empty object, we explicitly add it to the update
  18006. // mask to ensure that the server creates a map entry.
  18007. e.path && e.path.length > 0 && e.fieldMask.push(e.path) : Lt(t, ((t, s) => {
  18008. const i = Gh(s, e.ra(t));
  18009. null != i && (n[t] = i);
  18010. })), {
  18011. mapValue: {
  18012. fields: n
  18013. }
  18014. };
  18015. }
  18016. function jh(t) {
  18017. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof st || t instanceof Ph || t instanceof Eh || t instanceof Ia || t instanceof bh);
  18018. }
  18019. function Wh(t, e, n) {
  18020. if (!jh(n) || !function(t) {
  18021. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  18022. }(n)) {
  18023. const s = da(n);
  18024. throw "an object" === s ? e.ha(t + " a custom object") : e.ha(t + " " + s);
  18025. }
  18026. }
  18027. /**
  18028. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  18029. */ function zh(t, e, n) {
  18030. if ((
  18031. // If required, replace the FieldPath Compat class with with the firestore-exp
  18032. // FieldPath.
  18033. e = _(e)) instanceof Ah) return e._internalPath;
  18034. if ("string" == typeof e) return Jh(t, e);
  18035. throw Yh("Field path arguments must be of type string or ", t,
  18036. /* hasConverter= */ !1,
  18037. /* path= */ void 0, n);
  18038. }
  18039. /**
  18040. * Matches any characters in a field path string that are reserved.
  18041. */ const Hh = new RegExp("[~\\*/\\[\\]]");
  18042. /**
  18043. * Wraps fromDotSeparatedString with an error message about the method that
  18044. * was thrown.
  18045. * @param methodName - The publicly visible method name
  18046. * @param path - The dot-separated string form of a field path which will be
  18047. * split on dots.
  18048. * @param targetDoc - The document against which the field path will be
  18049. * evaluated.
  18050. */ function Jh(t, e, n) {
  18051. if (e.search(Hh) >= 0) throw Yh(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t,
  18052. /* hasConverter= */ !1,
  18053. /* path= */ void 0, n);
  18054. try {
  18055. return new Ah(...e.split("."))._internalPath;
  18056. } catch (s) {
  18057. throw Yh(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t,
  18058. /* hasConverter= */ !1,
  18059. /* path= */ void 0, n);
  18060. }
  18061. }
  18062. function Yh(t, e, n, s, i) {
  18063. const r = s && !s.isEmpty(), o = void 0 !== i;
  18064. let u = `Function ${e}() called with invalid data`;
  18065. n && (u += " (via `toFirestore()`)"), u += ". ";
  18066. let c = "";
  18067. return (r || o) && (c += " (found", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`),
  18068. c += ")"), new q(L.INVALID_ARGUMENT, u + t + c);
  18069. }
  18070. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Xh(t, e) {
  18071. return t.some((t => t.isEqual(e)));
  18072. }
  18073. /**
  18074. * @license
  18075. * Copyright 2020 Google LLC
  18076. *
  18077. * Licensed under the Apache License, Version 2.0 (the "License");
  18078. * you may not use this file except in compliance with the License.
  18079. * You may obtain a copy of the License at
  18080. *
  18081. * http://www.apache.org/licenses/LICENSE-2.0
  18082. *
  18083. * Unless required by applicable law or agreed to in writing, software
  18084. * distributed under the License is distributed on an "AS IS" BASIS,
  18085. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18086. * See the License for the specific language governing permissions and
  18087. * limitations under the License.
  18088. */
  18089. /**
  18090. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18091. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18092. * get a specific field.
  18093. *
  18094. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18095. * access will return 'undefined'. You can use the `exists()` method to
  18096. * explicitly verify a document's existence.
  18097. */ class Zh {
  18098. // Note: This class is stripped down version of the DocumentSnapshot in
  18099. // the legacy SDK. The changes are:
  18100. // - No support for SnapshotMetadata.
  18101. // - No support for SnapshotOptions.
  18102. /** @hideconstructor protected */
  18103. constructor(t, e, n, s, i) {
  18104. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s,
  18105. this._converter = i;
  18106. }
  18107. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
  18108. return this._key.path.lastSegment();
  18109. }
  18110. /**
  18111. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  18112. */ get ref() {
  18113. return new Ia(this._firestore, this._converter, this._key);
  18114. }
  18115. /**
  18116. * Signals whether or not the document at the snapshot's location exists.
  18117. *
  18118. * @returns true if the document exists.
  18119. */ exists() {
  18120. return null !== this._document;
  18121. }
  18122. /**
  18123. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18124. * the document doesn't exist.
  18125. *
  18126. * @returns An `Object` containing all fields in the document or `undefined`
  18127. * if the document doesn't exist.
  18128. */ data() {
  18129. if (this._document) {
  18130. if (this._converter) {
  18131. // We only want to use the converter and create a new DocumentSnapshot
  18132. // if a converter has been provided.
  18133. const t = new tl(this._firestore, this._userDataWriter, this._key, this._document,
  18134. /* converter= */ null);
  18135. return this._converter.fromFirestore(t);
  18136. }
  18137. return this._userDataWriter.convertValue(this._document.data.value);
  18138. }
  18139. }
  18140. /**
  18141. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18142. * document or field doesn't exist.
  18143. *
  18144. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18145. * field.
  18146. * @returns The data at the specified field location or undefined if no such
  18147. * field exists in the document.
  18148. */
  18149. // We are using `any` here to avoid an explicit cast by our users.
  18150. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18151. get(t) {
  18152. if (this._document) {
  18153. const e = this._document.data.field(el("DocumentSnapshot.get", t));
  18154. if (null !== e) return this._userDataWriter.convertValue(e);
  18155. }
  18156. }
  18157. }
  18158. /**
  18159. * A `QueryDocumentSnapshot` contains data read from a document in your
  18160. * Firestore database as part of a query. The document is guaranteed to exist
  18161. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18162. * specific field.
  18163. *
  18164. * A `QueryDocumentSnapshot` offers the same API surface as a
  18165. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18166. * `exists` property will always be true and `data()` will never return
  18167. * 'undefined'.
  18168. */ class tl extends Zh {
  18169. /**
  18170. * Retrieves all fields in the document as an `Object`.
  18171. *
  18172. * @override
  18173. * @returns An `Object` containing all fields in the document.
  18174. */
  18175. data() {
  18176. return super.data();
  18177. }
  18178. }
  18179. /**
  18180. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  18181. */ function el(t, e) {
  18182. return "string" == typeof e ? Jh(t, e) : e instanceof Ah ? e._internalPath : e._delegate._internalPath;
  18183. }
  18184. /**
  18185. * @license
  18186. * Copyright 2020 Google LLC
  18187. *
  18188. * Licensed under the Apache License, Version 2.0 (the "License");
  18189. * you may not use this file except in compliance with the License.
  18190. * You may obtain a copy of the License at
  18191. *
  18192. * http://www.apache.org/licenses/LICENSE-2.0
  18193. *
  18194. * Unless required by applicable law or agreed to in writing, software
  18195. * distributed under the License is distributed on an "AS IS" BASIS,
  18196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18197. * See the License for the specific language governing permissions and
  18198. * limitations under the License.
  18199. */ function nl(t) {
  18200. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new q(L.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
  18201. }
  18202. /**
  18203. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  18204. * to a Firestore query.
  18205. */ class sl {}
  18206. /**
  18207. * A `QueryConstraint` is used to narrow the set of documents returned by a
  18208. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  18209. * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
  18210. * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
  18211. * can then be passed to {@link query} to create a new query instance that
  18212. * also contains this `QueryConstraint`.
  18213. */ class il extends sl {}
  18214. function rl(t, e, ...n) {
  18215. let s = [];
  18216. e instanceof sl && s.push(e), s = s.concat(n), function(t) {
  18217. const e = t.filter((t => t instanceof cl)).length, n = t.filter((t => t instanceof ol)).length;
  18218. if (e > 1 || e > 0 && n > 0) throw new q(L.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");
  18219. }
  18220. /**
  18221. * @license
  18222. * Copyright 2020 Google LLC
  18223. *
  18224. * Licensed under the Apache License, Version 2.0 (the "License");
  18225. * you may not use this file except in compliance with the License.
  18226. * You may obtain a copy of the License at
  18227. *
  18228. * http://www.apache.org/licenses/LICENSE-2.0
  18229. *
  18230. * Unless required by applicable law or agreed to in writing, software
  18231. * distributed under the License is distributed on an "AS IS" BASIS,
  18232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18233. * See the License for the specific language governing permissions and
  18234. * limitations under the License.
  18235. */
  18236. /**
  18237. * Converts Firestore's internal types to the JavaScript types that we expose
  18238. * to the user.
  18239. *
  18240. * @internal
  18241. */ (s);
  18242. for (const e of s) t = e._apply(t);
  18243. return t;
  18244. }
  18245. /**
  18246. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  18247. * a Firestore query by filtering on one or more document fields.
  18248. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  18249. * be passed to {@link query} to create a new query instance that also contains
  18250. * this `QueryFieldFilterConstraint`.
  18251. */ class ol extends il {
  18252. /**
  18253. * @internal
  18254. */
  18255. constructor(t, e, n) {
  18256. super(), this._field = t, this._op = e, this._value = n,
  18257. /** The type of this query constraint */
  18258. this.type = "where";
  18259. }
  18260. static _create(t, e, n) {
  18261. return new ol(t, e, n);
  18262. }
  18263. _apply(t) {
  18264. const e = this._parse(t);
  18265. return bl(t._query, e), new Ta(t.firestore, t.converter, In(t._query, e));
  18266. }
  18267. _parse(t) {
  18268. const e = Nh(t.firestore), n = function(t, e, n, s, i, r, o) {
  18269. let u;
  18270. if (i.isKeyField()) {
  18271. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === r || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new q(L.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);
  18272. if ("in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r) {
  18273. Rl(o, r);
  18274. const e = [];
  18275. for (const n of o) e.push(Al(s, t, n));
  18276. u = {
  18277. arrayValue: {
  18278. values: e
  18279. }
  18280. };
  18281. } else u = Al(s, t, o);
  18282. } else "in" /* Operator.IN */ !== r && "not-in" /* Operator.NOT_IN */ !== r && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== r || Rl(o, r),
  18283. u = Kh(n, e, o,
  18284. /* allowArrays= */ "in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r);
  18285. return Pe.create(i, r, u);
  18286. }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value);
  18287. return n;
  18288. }
  18289. }
  18290. /**
  18291. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  18292. * must contain the specified field and that the value should satisfy the
  18293. * relation constraint provided.
  18294. *
  18295. * @param fieldPath - The path to compare
  18296. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  18297. * "&lt;=", "!=").
  18298. * @param value - The value for comparison
  18299. * @returns The created {@link QueryFieldFilterConstraint}.
  18300. */ function ul(t, e, n) {
  18301. const s = e, i = el("where", t);
  18302. return ol._create(i, s, n);
  18303. }
  18304. /**
  18305. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  18306. * returned by a Firestore query by performing the logical OR or AND of multiple
  18307. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  18308. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  18309. * {@link and} and can then be passed to {@link query} to create a new query
  18310. * instance that also contains the `QueryCompositeFilterConstraint`.
  18311. * @internal TODO remove this internal tag with OR Query support in the server
  18312. */ class cl extends sl {
  18313. /**
  18314. * @internal
  18315. */
  18316. constructor(
  18317. /** The type of this query constraint */
  18318. t, e) {
  18319. super(), this.type = t, this._queryConstraints = e;
  18320. }
  18321. static _create(t, e) {
  18322. return new cl(t, e);
  18323. }
  18324. _parse(t) {
  18325. const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));
  18326. return 1 === e.length ? e[0] : ve.create(e, this._getOperator());
  18327. }
  18328. _apply(t) {
  18329. const e = this._parse(t);
  18330. return 0 === e.getFilters().length ? t : (function(t, e) {
  18331. let n = t;
  18332. const s = e.getFlattenedFilters();
  18333. for (const t of s) bl(n, t), n = In(n, t);
  18334. }
  18335. // Checks if any of the provided filter operators are included in the given list of filters and
  18336. // returns the first one that is, or null if none are.
  18337. (t._query, e), new Ta(t.firestore, t.converter, In(t._query, e)));
  18338. }
  18339. _getQueryConstraints() {
  18340. return this._queryConstraints;
  18341. }
  18342. _getOperator() {
  18343. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  18344. }
  18345. }
  18346. /**
  18347. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  18348. * the given filter constraints. A disjunction filter includes a document if it
  18349. * satisfies any of the given filters.
  18350. *
  18351. * @param queryConstraints - Optional. The list of
  18352. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  18353. * created with calls to {@link where}, {@link or}, or {@link and}.
  18354. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18355. * @internal TODO remove this internal tag with OR Query support in the server
  18356. */ function al(...t) {
  18357. // Only support QueryFilterConstraints
  18358. return t.forEach((t => vl("or", t))), cl._create("or" /* CompositeOperator.OR */ , t);
  18359. }
  18360. /**
  18361. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  18362. * the given filter constraints. A conjunction filter includes a document if it
  18363. * satisfies all of the given filters.
  18364. *
  18365. * @param queryConstraints - Optional. The list of
  18366. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  18367. * created with calls to {@link where}, {@link or}, or {@link and}.
  18368. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18369. * @internal TODO remove this internal tag with OR Query support in the server
  18370. */ function hl(...t) {
  18371. // Only support QueryFilterConstraints
  18372. return t.forEach((t => vl("and", t))), cl._create("and" /* CompositeOperator.AND */ , t);
  18373. }
  18374. /**
  18375. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  18376. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  18377. * {@link orderBy} and can then be passed to {@link query} to create a new query
  18378. * instance that also contains this `QueryOrderByConstraint`.
  18379. *
  18380. * Note: Documents that do not contain the orderBy field will not be present in
  18381. * the query result.
  18382. */ class ll extends il {
  18383. /**
  18384. * @internal
  18385. */
  18386. constructor(t, e) {
  18387. super(), this._field = t, this._direction = e,
  18388. /** The type of this query constraint */
  18389. this.type = "orderBy";
  18390. }
  18391. static _create(t, e) {
  18392. return new ll(t, e);
  18393. }
  18394. _apply(t) {
  18395. const e = function(t, e, n) {
  18396. if (null !== t.startAt) throw new q(L.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  18397. if (null !== t.endAt) throw new q(L.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  18398. const s = new Ge(e, n);
  18399. return function(t, e) {
  18400. if (null === wn(t)) {
  18401. // This is the first order by. It must match any inequality.
  18402. const n = mn(t);
  18403. null !== n && Pl(t, n, e.field);
  18404. }
  18405. }(t, s), s;
  18406. }
  18407. /**
  18408. * Create a `Bound` from a query and a document.
  18409. *
  18410. * Note that the `Bound` will always include the key of the document
  18411. * and so only the provided document will compare equal to the returned
  18412. * position.
  18413. *
  18414. * Will throw if the document does not contain all fields of the order by
  18415. * of the query or if any of the fields in the order by are an uncommitted
  18416. * server timestamp.
  18417. */ (t._query, this._field, this._direction);
  18418. return new Ta(t.firestore, t.converter, function(t, e) {
  18419. // TODO(dimond): validate that orderBy does not list the same key twice.
  18420. const n = t.explicitOrderBy.concat([ e ]);
  18421. return new ln(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  18422. }(t._query, e));
  18423. }
  18424. }
  18425. /**
  18426. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  18427. * specified field, optionally in descending order instead of ascending.
  18428. *
  18429. * Note: Documents that do not contain the specified field will not be present
  18430. * in the query result.
  18431. *
  18432. * @param fieldPath - The field to sort by.
  18433. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  18434. * not specified, order will be ascending.
  18435. * @returns The created {@link QueryOrderByConstraint}.
  18436. */ function fl(t, e = "asc") {
  18437. const n = e, s = el("orderBy", t);
  18438. return ll._create(s, n);
  18439. }
  18440. /**
  18441. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  18442. * a Firestore query.
  18443. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  18444. * {@link limitToLast} and can then be passed to {@link query} to create a new
  18445. * query instance that also contains this `QueryLimitConstraint`.
  18446. */ class dl extends il {
  18447. /**
  18448. * @internal
  18449. */
  18450. constructor(
  18451. /** The type of this query constraint */
  18452. t, e, n) {
  18453. super(), this.type = t, this._limit = e, this._limitType = n;
  18454. }
  18455. static _create(t, e, n) {
  18456. return new dl(t, e, n);
  18457. }
  18458. _apply(t) {
  18459. return new Ta(t.firestore, t.converter, Tn(t._query, this._limit, this._limitType));
  18460. }
  18461. }
  18462. /**
  18463. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  18464. * documents.
  18465. *
  18466. * @param limit - The maximum number of items to return.
  18467. * @returns The created {@link QueryLimitConstraint}.
  18468. */ function _l(t) {
  18469. return wa("limit", t), dl._create("limit", t, "F" /* LimitType.First */);
  18470. }
  18471. /**
  18472. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  18473. * documents.
  18474. *
  18475. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  18476. * otherwise an exception will be thrown during execution.
  18477. *
  18478. * @param limit - The maximum number of items to return.
  18479. * @returns The created {@link QueryLimitConstraint}.
  18480. */ function wl(t) {
  18481. return wa("limitToLast", t), dl._create("limitToLast", t, "L" /* LimitType.Last */);
  18482. }
  18483. /**
  18484. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  18485. * result set returned by a Firestore query.
  18486. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  18487. * {@link (startAfter:1)} and can then be passed to {@link query} to create a
  18488. * new query instance that also contains this `QueryStartAtConstraint`.
  18489. */ class ml extends il {
  18490. /**
  18491. * @internal
  18492. */
  18493. constructor(
  18494. /** The type of this query constraint */
  18495. t, e, n) {
  18496. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  18497. }
  18498. static _create(t, e, n) {
  18499. return new ml(t, e, n);
  18500. }
  18501. _apply(t) {
  18502. const e = El(t, this.type, this._docOrFields, this._inclusive);
  18503. return new Ta(t.firestore, t.converter, function(t, e) {
  18504. return new ln(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  18505. }(t._query, e));
  18506. }
  18507. }
  18508. function gl(...t) {
  18509. return ml._create("startAt", t,
  18510. /*inclusive=*/ !0);
  18511. }
  18512. function yl(...t) {
  18513. return ml._create("startAfter", t,
  18514. /*inclusive=*/ !1);
  18515. }
  18516. /**
  18517. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  18518. * result set returned by a Firestore query.
  18519. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  18520. * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
  18521. * query instance that also contains this `QueryEndAtConstraint`.
  18522. */ class pl extends il {
  18523. /**
  18524. * @internal
  18525. */
  18526. constructor(
  18527. /** The type of this query constraint */
  18528. t, e, n) {
  18529. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  18530. }
  18531. static _create(t, e, n) {
  18532. return new pl(t, e, n);
  18533. }
  18534. _apply(t) {
  18535. const e = El(t, this.type, this._docOrFields, this._inclusive);
  18536. return new Ta(t.firestore, t.converter, function(t, e) {
  18537. return new ln(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  18538. }(t._query, e));
  18539. }
  18540. }
  18541. function Il(...t) {
  18542. return pl._create("endBefore", t,
  18543. /*inclusive=*/ !1);
  18544. }
  18545. function Tl(...t) {
  18546. return pl._create("endAt", t,
  18547. /*inclusive=*/ !0);
  18548. }
  18549. /** Helper function to create a bound from a document or fields */ function El(t, e, n, s) {
  18550. if (n[0] = _(n[0]), n[0] instanceof Zh) return function(t, e, n, s, i) {
  18551. if (!s) throw new q(L.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);
  18552. const r = [];
  18553. // Because people expect to continue/end a query at the exact document
  18554. // provided, we need to use the implicit sort order rather than the explicit
  18555. // sort order, because it's guaranteed to contain the document key. That way
  18556. // the position becomes unambiguous and the query continues/ends exactly at
  18557. // the provided document. Without the key (by using the explicit sort
  18558. // orders), multiple documents could match the position, yielding duplicate
  18559. // results.
  18560. for (const n of yn(t)) if (n.field.isKeyField()) r.push(he(e, s.key)); else {
  18561. const t = s.data.field(n.field);
  18562. if (Xt(t)) throw new q(L.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
  18563. if (null === t) {
  18564. const t = n.field.canonicalString();
  18565. throw new q(L.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);
  18566. }
  18567. r.push(t);
  18568. }
  18569. return new Ee(r, i);
  18570. }
  18571. /**
  18572. * Converts a list of field values to a `Bound` for the given query.
  18573. */ (t._query, t.firestore._databaseId, e, n[0]._document, s);
  18574. {
  18575. const i = Nh(t.firestore);
  18576. return function(t, e, n, s, i, r) {
  18577. // Use explicit order by's because it has to match the query the user made
  18578. const o = t.explicitOrderBy;
  18579. if (i.length > o.length) throw new q(L.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
  18580. const u = [];
  18581. for (let r = 0; r < i.length; r++) {
  18582. const c = i[r];
  18583. if (o[r].field.isKeyField()) {
  18584. if ("string" != typeof c) throw new q(L.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);
  18585. if (!gn(t) && -1 !== c.indexOf("/")) throw new q(L.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);
  18586. const n = t.path.child(ot.fromString(c));
  18587. if (!at.isDocumentKey(n)) throw new q(L.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
  18588. const i = new at(n);
  18589. u.push(he(e, i));
  18590. } else {
  18591. const t = Kh(n, s, c);
  18592. u.push(t);
  18593. }
  18594. }
  18595. return new Ee(u, r);
  18596. }
  18597. /**
  18598. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  18599. * appropriate errors if the value is anything other than a `DocumentReference`
  18600. * or `string`, or if the string is malformed.
  18601. */ (t._query, t.firestore._databaseId, i, e, n, s);
  18602. }
  18603. }
  18604. function Al(t, e, n) {
  18605. if ("string" == typeof (n = _(n))) {
  18606. if ("" === n) throw new q(L.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  18607. if (!gn(e) && -1 !== n.indexOf("/")) throw new q(L.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
  18608. const s = e.path.child(ot.fromString(n));
  18609. if (!at.isDocumentKey(s)) throw new q(L.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);
  18610. return he(t, new at(s));
  18611. }
  18612. if (n instanceof Ia) return he(t, n._key);
  18613. throw new q(L.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${da(n)}.`);
  18614. }
  18615. /**
  18616. * Validates that the value passed into a disjunctive filter satisfies all
  18617. * array requirements.
  18618. */ function Rl(t, e) {
  18619. if (!Array.isArray(t) || 0 === t.length) throw new q(L.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
  18620. if (t.length > 10) throw new q(L.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`);
  18621. }
  18622. /**
  18623. * Given an operator, returns the set of operators that cannot be used with it.
  18624. *
  18625. * Operators in a query must adhere to the following set of rules:
  18626. * 1. Only one array operator is allowed.
  18627. * 2. Only one disjunctive operator is allowed.
  18628. * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.
  18629. * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  18630. *
  18631. * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`
  18632. * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`
  18633. */ function bl(t, e) {
  18634. if (e.isInequality()) {
  18635. const n = mn(t), s = e.field;
  18636. if (null !== n && !n.isEqual(s)) throw new q(L.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${s.toString()}'`);
  18637. const i = wn(t);
  18638. null !== i && Pl(t, s, i);
  18639. }
  18640. const n = function(t, e) {
  18641. for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;
  18642. return null;
  18643. }(t.filters, function(t) {
  18644. switch (t) {
  18645. case "!=" /* Operator.NOT_EQUAL */ :
  18646. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  18647. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  18648. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "not-in" /* Operator.NOT_IN */ ];
  18649. case "in" /* Operator.IN */ :
  18650. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  18651. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  18652. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  18653. case "not-in" /* Operator.NOT_IN */ :
  18654. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  18655. default:
  18656. return [];
  18657. }
  18658. }(e.op));
  18659. if (null !== n)
  18660. // Special case when it's a duplicate op to give a slightly clearer error message.
  18661. throw n === e.op ? new q(L.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new q(L.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
  18662. }
  18663. function Pl(t, e, n) {
  18664. if (!n.isEqual(e)) throw new q(L.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);
  18665. }
  18666. function vl(t, e) {
  18667. if (!(e instanceof ol || e instanceof cl)) throw new q(L.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  18668. }
  18669. class Vl {
  18670. convertValue(t, e = "none") {
  18671. switch (se(t)) {
  18672. case 0 /* TypeOrder.NullValue */ :
  18673. return null;
  18674. case 1 /* TypeOrder.BooleanValue */ :
  18675. return t.booleanValue;
  18676. case 2 /* TypeOrder.NumberValue */ :
  18677. return Jt(t.integerValue || t.doubleValue);
  18678. case 3 /* TypeOrder.TimestampValue */ :
  18679. return this.convertTimestamp(t.timestampValue);
  18680. case 4 /* TypeOrder.ServerTimestampValue */ :
  18681. return this.convertServerTimestamp(t, e);
  18682. case 5 /* TypeOrder.StringValue */ :
  18683. return t.stringValue;
  18684. case 6 /* TypeOrder.BlobValue */ :
  18685. return this.convertBytes(Yt(t.bytesValue));
  18686. case 7 /* TypeOrder.RefValue */ :
  18687. return this.convertReference(t.referenceValue);
  18688. case 8 /* TypeOrder.GeoPointValue */ :
  18689. return this.convertGeoPoint(t.geoPointValue);
  18690. case 9 /* TypeOrder.ArrayValue */ :
  18691. return this.convertArray(t.arrayValue, e);
  18692. case 10 /* TypeOrder.ObjectValue */ :
  18693. return this.convertObject(t.mapValue, e);
  18694. default:
  18695. throw M();
  18696. }
  18697. }
  18698. convertObject(t, e) {
  18699. const n = {};
  18700. return Lt(t.fields, ((t, s) => {
  18701. n[t] = this.convertValue(s, e);
  18702. })), n;
  18703. }
  18704. convertGeoPoint(t) {
  18705. return new Ph(Jt(t.latitude), Jt(t.longitude));
  18706. }
  18707. convertArray(t, e) {
  18708. return (t.values || []).map((t => this.convertValue(t, e)));
  18709. }
  18710. convertServerTimestamp(t, e) {
  18711. switch (e) {
  18712. case "previous":
  18713. const n = Zt(t);
  18714. return null == n ? null : this.convertValue(n, e);
  18715. case "estimate":
  18716. return this.convertTimestamp(te(t));
  18717. default:
  18718. return null;
  18719. }
  18720. }
  18721. convertTimestamp(t) {
  18722. const e = Ht(t);
  18723. return new st(e.seconds, e.nanos);
  18724. }
  18725. convertDocumentKey(t, e) {
  18726. const n = ot.fromString(t);
  18727. F(gi(n));
  18728. const s = new $t(n.get(1), n.get(3)), i = new at(n.popFirst(5));
  18729. return s.isEqual(e) ||
  18730. // TODO(b/64130202): Somehow support foreign references.
  18731. N(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),
  18732. i;
  18733. }
  18734. }
  18735. /**
  18736. * @license
  18737. * Copyright 2020 Google LLC
  18738. *
  18739. * Licensed under the Apache License, Version 2.0 (the "License");
  18740. * you may not use this file except in compliance with the License.
  18741. * You may obtain a copy of the License at
  18742. *
  18743. * http://www.apache.org/licenses/LICENSE-2.0
  18744. *
  18745. * Unless required by applicable law or agreed to in writing, software
  18746. * distributed under the License is distributed on an "AS IS" BASIS,
  18747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18748. * See the License for the specific language governing permissions and
  18749. * limitations under the License.
  18750. */
  18751. /**
  18752. * Converts custom model object of type T into `DocumentData` by applying the
  18753. * converter if it exists.
  18754. *
  18755. * This function is used when converting user objects to `DocumentData`
  18756. * because we want to provide the user with a more specific error message if
  18757. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  18758. * call.
  18759. */ function Sl(t, e, n) {
  18760. let s;
  18761. // Cast to `any` in order to satisfy the union type constraint on
  18762. // toFirestore().
  18763. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18764. return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e,
  18765. s;
  18766. }
  18767. class Dl extends Vl {
  18768. constructor(t) {
  18769. super(), this.firestore = t;
  18770. }
  18771. convertBytes(t) {
  18772. return new Eh(t);
  18773. }
  18774. convertReference(t) {
  18775. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  18776. return new Ia(this.firestore, /* converter= */ null, e);
  18777. }
  18778. }
  18779. /**
  18780. * @license
  18781. * Copyright 2020 Google LLC
  18782. *
  18783. * Licensed under the Apache License, Version 2.0 (the "License");
  18784. * you may not use this file except in compliance with the License.
  18785. * You may obtain a copy of the License at
  18786. *
  18787. * http://www.apache.org/licenses/LICENSE-2.0
  18788. *
  18789. * Unless required by applicable law or agreed to in writing, software
  18790. * distributed under the License is distributed on an "AS IS" BASIS,
  18791. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18792. * See the License for the specific language governing permissions and
  18793. * limitations under the License.
  18794. */
  18795. /**
  18796. * Metadata about a snapshot, describing the state of the snapshot.
  18797. */ class Cl {
  18798. /** @hideconstructor */
  18799. constructor(t, e) {
  18800. this.hasPendingWrites = t, this.fromCache = e;
  18801. }
  18802. /**
  18803. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  18804. *
  18805. * @param other - The `SnapshotMetadata` to compare against.
  18806. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  18807. */ isEqual(t) {
  18808. return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
  18809. }
  18810. }
  18811. /**
  18812. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18813. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18814. * get a specific field.
  18815. *
  18816. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18817. * access will return 'undefined'. You can use the `exists()` method to
  18818. * explicitly verify a document's existence.
  18819. */ class xl extends Zh {
  18820. /** @hideconstructor protected */
  18821. constructor(t, e, n, s, i, r) {
  18822. super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;
  18823. }
  18824. /**
  18825. * Returns whether or not the data exists. True if the document exists.
  18826. */ exists() {
  18827. return super.exists();
  18828. }
  18829. /**
  18830. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18831. * the document doesn't exist.
  18832. *
  18833. * By default, `serverTimestamp()` values that have not yet been
  18834. * set to their final value will be returned as `null`. You can override
  18835. * this by passing an options object.
  18836. *
  18837. * @param options - An options object to configure how data is retrieved from
  18838. * the snapshot (for example the desired behavior for server timestamps that
  18839. * have not yet been set to their final value).
  18840. * @returns An `Object` containing all fields in the document or `undefined` if
  18841. * the document doesn't exist.
  18842. */ data(t = {}) {
  18843. if (this._document) {
  18844. if (this._converter) {
  18845. // We only want to use the converter and create a new DocumentSnapshot
  18846. // if a converter has been provided.
  18847. const e = new Nl(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
  18848. /* converter= */ null);
  18849. return this._converter.fromFirestore(e, t);
  18850. }
  18851. return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
  18852. }
  18853. }
  18854. /**
  18855. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18856. * document or field doesn't exist.
  18857. *
  18858. * By default, a `serverTimestamp()` that has not yet been set to
  18859. * its final value will be returned as `null`. You can override this by
  18860. * passing an options object.
  18861. *
  18862. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18863. * field.
  18864. * @param options - An options object to configure how the field is retrieved
  18865. * from the snapshot (for example the desired behavior for server timestamps
  18866. * that have not yet been set to their final value).
  18867. * @returns The data at the specified field location or undefined if no such
  18868. * field exists in the document.
  18869. */
  18870. // We are using `any` here to avoid an explicit cast by our users.
  18871. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18872. get(t, e = {}) {
  18873. if (this._document) {
  18874. const n = this._document.data.field(el("DocumentSnapshot.get", t));
  18875. if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
  18876. }
  18877. }
  18878. }
  18879. /**
  18880. * A `QueryDocumentSnapshot` contains data read from a document in your
  18881. * Firestore database as part of a query. The document is guaranteed to exist
  18882. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18883. * specific field.
  18884. *
  18885. * A `QueryDocumentSnapshot` offers the same API surface as a
  18886. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18887. * `exists` property will always be true and `data()` will never return
  18888. * 'undefined'.
  18889. */ class Nl extends xl {
  18890. /**
  18891. * Retrieves all fields in the document as an `Object`.
  18892. *
  18893. * By default, `serverTimestamp()` values that have not yet been
  18894. * set to their final value will be returned as `null`. You can override
  18895. * this by passing an options object.
  18896. *
  18897. * @override
  18898. * @param options - An options object to configure how data is retrieved from
  18899. * the snapshot (for example the desired behavior for server timestamps that
  18900. * have not yet been set to their final value).
  18901. * @returns An `Object` containing all fields in the document.
  18902. */
  18903. data(t = {}) {
  18904. return super.data(t);
  18905. }
  18906. }
  18907. /**
  18908. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  18909. * representing the results of a query. The documents can be accessed as an
  18910. * array via the `docs` property or enumerated using the `forEach` method. The
  18911. * number of documents can be determined via the `empty` and `size`
  18912. * properties.
  18913. */ class kl {
  18914. /** @hideconstructor */
  18915. constructor(t, e, n, s) {
  18916. this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new Cl(s.hasPendingWrites, s.fromCache),
  18917. this.query = n;
  18918. }
  18919. /** An array of all the documents in the `QuerySnapshot`. */ get docs() {
  18920. const t = [];
  18921. return this.forEach((e => t.push(e))), t;
  18922. }
  18923. /** The number of documents in the `QuerySnapshot`. */ get size() {
  18924. return this._snapshot.docs.size;
  18925. }
  18926. /** True if there are no documents in the `QuerySnapshot`. */ get empty() {
  18927. return 0 === this.size;
  18928. }
  18929. /**
  18930. * Enumerates all of the documents in the `QuerySnapshot`.
  18931. *
  18932. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  18933. * each document in the snapshot.
  18934. * @param thisArg - The `this` binding for the callback.
  18935. */ forEach(t, e) {
  18936. this._snapshot.docs.forEach((n => {
  18937. t.call(e, new Nl(this._firestore, this._userDataWriter, n.key, n, new Cl(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));
  18938. }));
  18939. }
  18940. /**
  18941. * Returns an array of the documents changes since the last snapshot. If this
  18942. * is the first snapshot, all documents will be in the list as 'added'
  18943. * changes.
  18944. *
  18945. * @param options - `SnapshotListenOptions` that control whether metadata-only
  18946. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  18947. * snapshot events.
  18948. */ docChanges(t = {}) {
  18949. const e = !!t.includeMetadataChanges;
  18950. if (e && this._snapshot.excludesMetadataChanges) throw new q(L.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
  18951. return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges =
  18952. /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
  18953. function(t, e) {
  18954. if (t._snapshot.oldDocs.isEmpty()) {
  18955. let e = 0;
  18956. return t._snapshot.docChanges.map((n => {
  18957. const s = new Nl(t._firestore, t._userDataWriter, n.doc.key, n.doc, new Cl(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);
  18958. return n.doc, {
  18959. type: "added",
  18960. doc: s,
  18961. oldIndex: -1,
  18962. newIndex: e++
  18963. };
  18964. }));
  18965. }
  18966. {
  18967. // A `DocumentSet` that is updated incrementally as changes are applied to use
  18968. // to lookup the index of a document.
  18969. let n = t._snapshot.oldDocs;
  18970. return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {
  18971. const s = new Nl(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Cl(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
  18972. let i = -1, r = -1;
  18973. return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)),
  18974. 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)),
  18975. {
  18976. type: Ol(e.type),
  18977. doc: s,
  18978. oldIndex: i,
  18979. newIndex: r
  18980. };
  18981. }));
  18982. }
  18983. }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
  18984. }
  18985. }
  18986. function Ol(t) {
  18987. switch (t) {
  18988. case 0 /* ChangeType.Added */ :
  18989. return "added";
  18990. case 2 /* ChangeType.Modified */ :
  18991. case 3 /* ChangeType.Metadata */ :
  18992. return "modified";
  18993. case 1 /* ChangeType.Removed */ :
  18994. return "removed";
  18995. default:
  18996. return M();
  18997. }
  18998. }
  18999. // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
  19000. // metadata
  19001. /**
  19002. * Returns true if the provided snapshots are equal.
  19003. *
  19004. * @param left - A snapshot to compare.
  19005. * @param right - A snapshot to compare.
  19006. * @returns true if the snapshots are equal.
  19007. */ function Ml(t, e) {
  19008. return t instanceof xl && e instanceof xl ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof kl && e instanceof kl && (t._firestore === e._firestore && va(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));
  19009. }
  19010. /**
  19011. * @license
  19012. * Copyright 2020 Google LLC
  19013. *
  19014. * Licensed under the Apache License, Version 2.0 (the "License");
  19015. * you may not use this file except in compliance with the License.
  19016. * You may obtain a copy of the License at
  19017. *
  19018. * http://www.apache.org/licenses/LICENSE-2.0
  19019. *
  19020. * Unless required by applicable law or agreed to in writing, software
  19021. * distributed under the License is distributed on an "AS IS" BASIS,
  19022. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19023. * See the License for the specific language governing permissions and
  19024. * limitations under the License.
  19025. */
  19026. /**
  19027. * Reads the document referred to by this `DocumentReference`.
  19028. *
  19029. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  19030. * for data from the server, but it may return cached data or fail if you are
  19031. * offline and the server cannot be reached. To specify this behavior, invoke
  19032. * {@link getDocFromCache} or {@link getDocFromServer}.
  19033. *
  19034. * @param reference - The reference of the document to fetch.
  19035. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  19036. * current document contents.
  19037. */ function Fl(t) {
  19038. t = _a(t, Ia);
  19039. const e = _a(t.firestore, oh);
  19040. return Ja(ah(e), t._key).then((n => Yl(e, t, n)));
  19041. }
  19042. class $l extends Vl {
  19043. constructor(t) {
  19044. super(), this.firestore = t;
  19045. }
  19046. convertBytes(t) {
  19047. return new Eh(t);
  19048. }
  19049. convertReference(t) {
  19050. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19051. return new Ia(this.firestore, /* converter= */ null, e);
  19052. }
  19053. }
  19054. /**
  19055. * Reads the document referred to by this `DocumentReference` from cache.
  19056. * Returns an error if the document is not currently cached.
  19057. *
  19058. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19059. * current document contents.
  19060. */ function Bl(t) {
  19061. t = _a(t, Ia);
  19062. const e = _a(t.firestore, oh), n = ah(e), s = new $l(e);
  19063. return Ha(n, t._key).then((n => new xl(e, s, t._key, n, new Cl(null !== n && n.hasLocalMutations,
  19064. /* fromCache= */ !0), t.converter)));
  19065. }
  19066. /**
  19067. * Reads the document referred to by this `DocumentReference` from the server.
  19068. * Returns an error if the network is not available.
  19069. *
  19070. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19071. * current document contents.
  19072. */ function Ll(t) {
  19073. t = _a(t, Ia);
  19074. const e = _a(t.firestore, oh);
  19075. return Ja(ah(e), t._key, {
  19076. source: "server"
  19077. }).then((n => Yl(e, t, n)));
  19078. }
  19079. /**
  19080. * Executes the query and returns the results as a `QuerySnapshot`.
  19081. *
  19082. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  19083. * waiting for data from the server, but it may return cached data or fail if
  19084. * you are offline and the server cannot be reached. To specify this behavior,
  19085. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  19086. *
  19087. * @returns A `Promise` that will be resolved with the results of the query.
  19088. */ function ql(t) {
  19089. t = _a(t, Ta);
  19090. const e = _a(t.firestore, oh), n = ah(e), s = new $l(e);
  19091. return nl(t._query), Xa(n, t._query).then((n => new kl(e, s, t, n)));
  19092. }
  19093. /**
  19094. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  19095. * Returns an empty result set if no documents matching the query are currently
  19096. * cached.
  19097. *
  19098. * @returns A `Promise` that will be resolved with the results of the query.
  19099. */ function Ul(t) {
  19100. t = _a(t, Ta);
  19101. const e = _a(t.firestore, oh), n = ah(e), s = new $l(e);
  19102. return Ya(n, t._query).then((n => new kl(e, s, t, n)));
  19103. }
  19104. /**
  19105. * Executes the query and returns the results as a `QuerySnapshot` from the
  19106. * server. Returns an error if the network is not available.
  19107. *
  19108. * @returns A `Promise` that will be resolved with the results of the query.
  19109. */ function Kl(t) {
  19110. t = _a(t, Ta);
  19111. const e = _a(t.firestore, oh), n = ah(e), s = new $l(e);
  19112. return Xa(n, t._query, {
  19113. source: "server"
  19114. }).then((n => new kl(e, s, t, n)));
  19115. }
  19116. function Gl(t, e, n) {
  19117. t = _a(t, Ia);
  19118. const s = _a(t.firestore, oh), i = Sl(t.converter, e, n);
  19119. return Jl(s, [ kh(Nh(s), "setDoc", t._key, i, null !== t.converter, n).toMutation(t._key, Wn.none()) ]);
  19120. }
  19121. function Ql(t, e, n, ...s) {
  19122. t = _a(t, Ia);
  19123. const i = _a(t.firestore, oh), r = Nh(i);
  19124. let o;
  19125. o = "string" == typeof (
  19126. // For Compat types, we have to "extract" the underlying types before
  19127. // performing validation.
  19128. e = _(e)) || e instanceof Ah ? Uh(r, "updateDoc", t._key, e, n, s) : qh(r, "updateDoc", t._key, e);
  19129. return Jl(i, [ o.toMutation(t._key, Wn.exists(!0)) ]);
  19130. }
  19131. /**
  19132. * Deletes the document referred to by the specified `DocumentReference`.
  19133. *
  19134. * @param reference - A reference to the document to delete.
  19135. * @returns A Promise resolved once the document has been successfully
  19136. * deleted from the backend (note that it won't resolve while you're offline).
  19137. */ function jl(t) {
  19138. return Jl(_a(t.firestore, oh), [ new os(t._key, Wn.none()) ]);
  19139. }
  19140. /**
  19141. * Add a new document to specified `CollectionReference` with the given data,
  19142. * assigning it a document ID automatically.
  19143. *
  19144. * @param reference - A reference to the collection to add this document to.
  19145. * @param data - An Object containing the data for the new document.
  19146. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  19147. * newly created document after it has been written to the backend (Note that it
  19148. * won't resolve while you're offline).
  19149. */ function Wl(t, e) {
  19150. const n = _a(t.firestore, oh), s = ba(t), i = Sl(t.converter, e);
  19151. return Jl(n, [ kh(Nh(t.firestore), "addDoc", s._key, i, null !== t.converter, {}).toMutation(s._key, Wn.exists(!1)) ]).then((() => s));
  19152. }
  19153. function zl(t, ...e) {
  19154. var n, s, i;
  19155. t = _(t);
  19156. let r = {
  19157. includeMetadataChanges: !1
  19158. }, o = 0;
  19159. "object" != typeof e[o] || sh(e[o]) || (r = e[o], o++);
  19160. const u = {
  19161. includeMetadataChanges: r.includeMetadataChanges
  19162. };
  19163. if (sh(e[o])) {
  19164. const t = e[o];
  19165. e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t),
  19166. e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);
  19167. }
  19168. let c, a, h;
  19169. if (t instanceof Ia) a = _a(t.firestore, oh), h = dn(t._key.path), c = {
  19170. next: n => {
  19171. e[o] && e[o](Yl(a, t, n));
  19172. },
  19173. error: e[o + 1],
  19174. complete: e[o + 2]
  19175. }; else {
  19176. const n = _a(t, Ta);
  19177. a = _a(n.firestore, oh), h = n._query;
  19178. const s = new $l(a);
  19179. c = {
  19180. next: t => {
  19181. e[o] && e[o](new kl(a, s, n, t));
  19182. },
  19183. error: e[o + 1],
  19184. complete: e[o + 2]
  19185. }, nl(t._query);
  19186. }
  19187. return function(t, e, n, s) {
  19188. const i = new Sa(s), r = new mc(e, i, n);
  19189. return t.asyncQueue.enqueueAndForget((async () => lc(await ja(t), r))), () => {
  19190. i.bc(), t.asyncQueue.enqueueAndForget((async () => fc(await ja(t), r)));
  19191. };
  19192. }(ah(a), h, u, c);
  19193. }
  19194. function Hl(t, e) {
  19195. return Za(ah(t = _a(t, oh)), sh(e) ? e : {
  19196. next: e
  19197. });
  19198. }
  19199. /**
  19200. * Locally writes `mutations` on the async queue.
  19201. * @internal
  19202. */ function Jl(t, e) {
  19203. return function(t, e) {
  19204. const n = new U;
  19205. return t.asyncQueue.enqueueAndForget((async () => Dc(await Ga(t), e, n))), n.promise;
  19206. }(ah(t), e);
  19207. }
  19208. /**
  19209. * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`
  19210. * to a {@link DocumentSnapshot}.
  19211. */ function Yl(t, e, n) {
  19212. const s = n.docs.get(e._key), i = new $l(t);
  19213. return new xl(t, i, e._key, s, new Cl(n.hasPendingWrites, n.fromCache), e.converter);
  19214. }
  19215. /**
  19216. * @license
  19217. * Copyright 2022 Google LLC
  19218. *
  19219. * Licensed under the Apache License, Version 2.0 (the "License");
  19220. * you may not use this file except in compliance with the License.
  19221. * You may obtain a copy of the License at
  19222. *
  19223. * http://www.apache.org/licenses/LICENSE-2.0
  19224. *
  19225. * Unless required by applicable law or agreed to in writing, software
  19226. * distributed under the License is distributed on an "AS IS" BASIS,
  19227. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19228. * See the License for the specific language governing permissions and
  19229. * limitations under the License.
  19230. */
  19231. /**
  19232. * Compares two `AggregateQuerySnapshot` instances for equality.
  19233. *
  19234. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  19235. * underlying queries that compare equal, and the same data.
  19236. *
  19237. * @param left - The first `AggregateQuerySnapshot` to compare.
  19238. * @param right - The second `AggregateQuerySnapshot` to compare.
  19239. *
  19240. * @returns `true` if the objects are "equal", as defined above, or `false`
  19241. * otherwise.
  19242. */ function Xl(t, e) {
  19243. return va(t.query, e.query) && w(t.data(), e.data());
  19244. }
  19245. /**
  19246. * @license
  19247. * Copyright 2022 Google LLC
  19248. *
  19249. * Licensed under the Apache License, Version 2.0 (the "License");
  19250. * you may not use this file except in compliance with the License.
  19251. * You may obtain a copy of the License at
  19252. *
  19253. * http://www.apache.org/licenses/LICENSE-2.0
  19254. *
  19255. * Unless required by applicable law or agreed to in writing, software
  19256. * distributed under the License is distributed on an "AS IS" BASIS,
  19257. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19258. * See the License for the specific language governing permissions and
  19259. * limitations under the License.
  19260. */
  19261. /**
  19262. * Calculates the number of documents in the result set of the given query,
  19263. * without actually downloading the documents.
  19264. *
  19265. * Using this function to count the documents is efficient because only the
  19266. * final count, not the documents' data, is downloaded. This function can even
  19267. * count the documents if the result set would be prohibitively large to
  19268. * download entirely (e.g. thousands of documents).
  19269. *
  19270. * The result received from the server is presented, unaltered, without
  19271. * considering any local state. That is, documents in the local cache are not
  19272. * taken into consideration, neither are local modifications not yet
  19273. * synchronized with the server. Previously-downloaded results, if any, are not
  19274. * used: every request using this source necessarily involves a round trip to
  19275. * the server.
  19276. *
  19277. * @param query - The query whose result set size to calculate.
  19278. * @returns A Promise that will be resolved with the count; the count can be
  19279. * retrieved from `snapshot.data().count`, where `snapshot` is the
  19280. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  19281. */ function Zl(t) {
  19282. const e = _a(t.firestore, oh);
  19283. return function(t, e, n) {
  19284. const s = new U;
  19285. return t.asyncQueue.enqueueAndForget((async () => {
  19286. try {
  19287. if ($u(await Ka(t))) {
  19288. const i = await Qa(t), r = new Na(e, i, n).run();
  19289. s.resolve(r);
  19290. } else s.reject(new q(L.UNAVAILABLE, "Failed to get count result because the client is offline."));
  19291. } catch (t) {
  19292. s.reject(t);
  19293. }
  19294. })), s.promise;
  19295. }(ah(e), t, new $l(e));
  19296. }
  19297. /**
  19298. * @license
  19299. * Copyright 2022 Google LLC
  19300. *
  19301. * Licensed under the Apache License, Version 2.0 (the "License");
  19302. * you may not use this file except in compliance with the License.
  19303. * You may obtain a copy of the License at
  19304. *
  19305. * http://www.apache.org/licenses/LICENSE-2.0
  19306. *
  19307. * Unless required by applicable law or agreed to in writing, software
  19308. * distributed under the License is distributed on an "AS IS" BASIS,
  19309. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19310. * See the License for the specific language governing permissions and
  19311. * limitations under the License.
  19312. */ const tf = {
  19313. maxAttempts: 5
  19314. };
  19315. /**
  19316. * @license
  19317. * Copyright 2020 Google LLC
  19318. *
  19319. * Licensed under the Apache License, Version 2.0 (the "License");
  19320. * you may not use this file except in compliance with the License.
  19321. * You may obtain a copy of the License at
  19322. *
  19323. * http://www.apache.org/licenses/LICENSE-2.0
  19324. *
  19325. * Unless required by applicable law or agreed to in writing, software
  19326. * distributed under the License is distributed on an "AS IS" BASIS,
  19327. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19328. * See the License for the specific language governing permissions and
  19329. * limitations under the License.
  19330. */
  19331. /**
  19332. * A write batch, used to perform multiple writes as a single atomic unit.
  19333. *
  19334. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  19335. * provides methods for adding writes to the write batch. None of the writes
  19336. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  19337. * called.
  19338. */
  19339. class ef {
  19340. /** @hideconstructor */
  19341. constructor(t, e) {
  19342. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  19343. this._dataReader = Nh(t);
  19344. }
  19345. set(t, e, n) {
  19346. this._verifyNotCommitted();
  19347. const s = nf(t, this._firestore), i = Sl(s.converter, e, n), r = kh(this._dataReader, "WriteBatch.set", s._key, i, null !== s.converter, n);
  19348. return this._mutations.push(r.toMutation(s._key, Wn.none())), this;
  19349. }
  19350. update(t, e, n, ...s) {
  19351. this._verifyNotCommitted();
  19352. const i = nf(t, this._firestore);
  19353. // For Compat types, we have to "extract" the underlying types before
  19354. // performing validation.
  19355. let r;
  19356. return r = "string" == typeof (e = _(e)) || e instanceof Ah ? Uh(this._dataReader, "WriteBatch.update", i._key, e, n, s) : qh(this._dataReader, "WriteBatch.update", i._key, e),
  19357. this._mutations.push(r.toMutation(i._key, Wn.exists(!0))), this;
  19358. }
  19359. /**
  19360. * Deletes the document referred to by the provided {@link DocumentReference}.
  19361. *
  19362. * @param documentRef - A reference to the document to be deleted.
  19363. * @returns This `WriteBatch` instance. Used for chaining method calls.
  19364. */ delete(t) {
  19365. this._verifyNotCommitted();
  19366. const e = nf(t, this._firestore);
  19367. return this._mutations = this._mutations.concat(new os(e._key, Wn.none())), this;
  19368. }
  19369. /**
  19370. * Commits all of the writes in this write batch as a single atomic unit.
  19371. *
  19372. * The result of these writes will only be reflected in document reads that
  19373. * occur after the returned promise resolves. If the client is offline, the
  19374. * write fails. If you would like to see local modifications or buffer writes
  19375. * until the client is online, use the full Firestore SDK.
  19376. *
  19377. * @returns A `Promise` resolved once all of the writes in the batch have been
  19378. * successfully written to the backend as an atomic unit (note that it won't
  19379. * resolve while you're offline).
  19380. */ commit() {
  19381. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  19382. }
  19383. _verifyNotCommitted() {
  19384. if (this._committed) throw new q(L.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  19385. }
  19386. }
  19387. function nf(t, e) {
  19388. if ((t = _(t)).firestore !== e) throw new q(L.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  19389. return t;
  19390. }
  19391. /**
  19392. * @license
  19393. * Copyright 2020 Google LLC
  19394. *
  19395. * Licensed under the Apache License, Version 2.0 (the "License");
  19396. * you may not use this file except in compliance with the License.
  19397. * You may obtain a copy of the License at
  19398. *
  19399. * http://www.apache.org/licenses/LICENSE-2.0
  19400. *
  19401. * Unless required by applicable law or agreed to in writing, software
  19402. * distributed under the License is distributed on an "AS IS" BASIS,
  19403. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19404. * See the License for the specific language governing permissions and
  19405. * limitations under the License.
  19406. */
  19407. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  19408. // legacy SDK.
  19409. /**
  19410. * A reference to a transaction.
  19411. *
  19412. * The `Transaction` object passed to a transaction's `updateFunction` provides
  19413. * the methods to read and write data within the transaction context. See
  19414. * {@link runTransaction}.
  19415. */
  19416. /**
  19417. * @license
  19418. * Copyright 2020 Google LLC
  19419. *
  19420. * Licensed under the Apache License, Version 2.0 (the "License");
  19421. * you may not use this file except in compliance with the License.
  19422. * You may obtain a copy of the License at
  19423. *
  19424. * http://www.apache.org/licenses/LICENSE-2.0
  19425. *
  19426. * Unless required by applicable law or agreed to in writing, software
  19427. * distributed under the License is distributed on an "AS IS" BASIS,
  19428. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19429. * See the License for the specific language governing permissions and
  19430. * limitations under the License.
  19431. */
  19432. /**
  19433. * A reference to a transaction.
  19434. *
  19435. * The `Transaction` object passed to a transaction's `updateFunction` provides
  19436. * the methods to read and write data within the transaction context. See
  19437. * {@link runTransaction}.
  19438. */
  19439. class sf extends class {
  19440. /** @hideconstructor */
  19441. constructor(t, e) {
  19442. this._firestore = t, this._transaction = e, this._dataReader = Nh(t);
  19443. }
  19444. /**
  19445. * Reads the document referenced by the provided {@link DocumentReference}.
  19446. *
  19447. * @param documentRef - A reference to the document to be read.
  19448. * @returns A `DocumentSnapshot` with the read data.
  19449. */ get(t) {
  19450. const e = nf(t, this._firestore), n = new Dl(this._firestore);
  19451. return this._transaction.lookup([ e._key ]).then((t => {
  19452. if (!t || 1 !== t.length) return M();
  19453. const s = t[0];
  19454. if (s.isFoundDocument()) return new Zh(this._firestore, n, s.key, s, e.converter);
  19455. if (s.isNoDocument()) return new Zh(this._firestore, n, e._key, null, e.converter);
  19456. throw M();
  19457. }));
  19458. }
  19459. set(t, e, n) {
  19460. const s = nf(t, this._firestore), i = Sl(s.converter, e, n), r = kh(this._dataReader, "Transaction.set", s._key, i, null !== s.converter, n);
  19461. return this._transaction.set(s._key, r), this;
  19462. }
  19463. update(t, e, n, ...s) {
  19464. const i = nf(t, this._firestore);
  19465. // For Compat types, we have to "extract" the underlying types before
  19466. // performing validation.
  19467. let r;
  19468. return r = "string" == typeof (e = _(e)) || e instanceof Ah ? Uh(this._dataReader, "Transaction.update", i._key, e, n, s) : qh(this._dataReader, "Transaction.update", i._key, e),
  19469. this._transaction.update(i._key, r), this;
  19470. }
  19471. /**
  19472. * Deletes the document referred to by the provided {@link DocumentReference}.
  19473. *
  19474. * @param documentRef - A reference to the document to be deleted.
  19475. * @returns This `Transaction` instance. Used for chaining method calls.
  19476. */ delete(t) {
  19477. const e = nf(t, this._firestore);
  19478. return this._transaction.delete(e._key), this;
  19479. }
  19480. } {
  19481. // This class implements the same logic as the Transaction API in the Lite SDK
  19482. // but is subclassed in order to return its own DocumentSnapshot types.
  19483. /** @hideconstructor */
  19484. constructor(t, e) {
  19485. super(t, e), this._firestore = t;
  19486. }
  19487. /**
  19488. * Reads the document referenced by the provided {@link DocumentReference}.
  19489. *
  19490. * @param documentRef - A reference to the document to be read.
  19491. * @returns A `DocumentSnapshot` with the read data.
  19492. */ get(t) {
  19493. const e = nf(t, this._firestore), n = new $l(this._firestore);
  19494. return super.get(t).then((t => new xl(this._firestore, n, e._key, t._document, new Cl(
  19495. /* hasPendingWrites= */ !1,
  19496. /* fromCache= */ !1), e.converter)));
  19497. }
  19498. }
  19499. /**
  19500. * Executes the given `updateFunction` and then attempts to commit the changes
  19501. * applied within the transaction. If any document read within the transaction
  19502. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  19503. * commit after 5 attempts, the transaction fails.
  19504. *
  19505. * The maximum number of writes allowed in a single transaction is 500.
  19506. *
  19507. * @param firestore - A reference to the Firestore database to run this
  19508. * transaction against.
  19509. * @param updateFunction - The function to execute within the transaction
  19510. * context.
  19511. * @param options - An options object to configure maximum number of attempts to
  19512. * commit.
  19513. * @returns If the transaction completed successfully or was explicitly aborted
  19514. * (the `updateFunction` returned a failed promise), the promise returned by the
  19515. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  19516. * rejected promise with the corresponding failure error is returned.
  19517. */ function rf(t, e, n) {
  19518. t = _a(t, oh);
  19519. const s = Object.assign(Object.assign({}, tf), n);
  19520. !function(t) {
  19521. if (t.maxAttempts < 1) throw new q(L.INVALID_ARGUMENT, "Max attempts must be at least 1");
  19522. }(s);
  19523. return function(t, e, n) {
  19524. const s = new U;
  19525. return t.asyncQueue.enqueueAndForget((async () => {
  19526. const i = await Qa(t);
  19527. new Oa(t.asyncQueue, i, n, e, s).run();
  19528. })), s.promise;
  19529. }(ah(t), (n => e(new sf(t, n))), s);
  19530. }
  19531. /**
  19532. * @license
  19533. * Copyright 2020 Google LLC
  19534. *
  19535. * Licensed under the Apache License, Version 2.0 (the "License");
  19536. * you may not use this file except in compliance with the License.
  19537. * You may obtain a copy of the License at
  19538. *
  19539. * http://www.apache.org/licenses/LICENSE-2.0
  19540. *
  19541. * Unless required by applicable law or agreed to in writing, software
  19542. * distributed under the License is distributed on an "AS IS" BASIS,
  19543. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19544. * See the License for the specific language governing permissions and
  19545. * limitations under the License.
  19546. */
  19547. /**
  19548. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  19549. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  19550. */ function of() {
  19551. return new Oh("deleteField");
  19552. }
  19553. /**
  19554. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  19555. * include a server-generated timestamp in the written data.
  19556. */ function uf() {
  19557. return new Fh("serverTimestamp");
  19558. }
  19559. /**
  19560. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  19561. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  19562. * value that already exists on the server. Each specified element that doesn't
  19563. * already exist in the array will be added to the end. If the field being
  19564. * modified is not already an array it will be overwritten with an array
  19565. * containing exactly the specified elements.
  19566. *
  19567. * @param elements - The elements to union into the array.
  19568. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  19569. * `updateDoc()`.
  19570. */ function cf(...t) {
  19571. // NOTE: We don't actually parse the data until it's used in set() or
  19572. // update() since we'd need the Firestore instance to do this.
  19573. return new $h("arrayUnion", t);
  19574. }
  19575. /**
  19576. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  19577. * updateDoc:1} that tells the server to remove the given elements from any
  19578. * array value that already exists on the server. All instances of each element
  19579. * specified will be removed from the array. If the field being modified is not
  19580. * already an array it will be overwritten with an empty array.
  19581. *
  19582. * @param elements - The elements to remove from the array.
  19583. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  19584. * `updateDoc()`
  19585. */ function af(...t) {
  19586. // NOTE: We don't actually parse the data until it's used in set() or
  19587. // update() since we'd need the Firestore instance to do this.
  19588. return new Bh("arrayRemove", t);
  19589. }
  19590. /**
  19591. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  19592. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  19593. * the given value.
  19594. *
  19595. * If either the operand or the current field value uses floating point
  19596. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  19597. * integers, values outside of JavaScript's safe number range
  19598. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  19599. * precision loss. Furthermore, once processed by the Firestore backend, all
  19600. * integer operations are capped between -2^63 and 2^63-1.
  19601. *
  19602. * If the current field value is not of type `number`, or if the field does not
  19603. * yet exist, the transformation sets the field to the given value.
  19604. *
  19605. * @param n - The value to increment by.
  19606. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  19607. * `updateDoc()`
  19608. */ function hf(t) {
  19609. return new Lh("increment", t);
  19610. }
  19611. /**
  19612. * @license
  19613. * Copyright 2020 Google LLC
  19614. *
  19615. * Licensed under the Apache License, Version 2.0 (the "License");
  19616. * you may not use this file except in compliance with the License.
  19617. * You may obtain a copy of the License at
  19618. *
  19619. * http://www.apache.org/licenses/LICENSE-2.0
  19620. *
  19621. * Unless required by applicable law or agreed to in writing, software
  19622. * distributed under the License is distributed on an "AS IS" BASIS,
  19623. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19624. * See the License for the specific language governing permissions and
  19625. * limitations under the License.
  19626. */
  19627. /**
  19628. * Creates a write batch, used for performing multiple writes as a single
  19629. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  19630. * is 500.
  19631. *
  19632. * Unlike transactions, write batches are persisted offline and therefore are
  19633. * preferable when you don't need to condition your writes on read data.
  19634. *
  19635. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  19636. * writes.
  19637. */ function lf(t) {
  19638. return ah(t = _a(t, oh)), new ef(t, (e => Jl(t, e)));
  19639. }
  19640. /**
  19641. * @license
  19642. * Copyright 2021 Google LLC
  19643. *
  19644. * Licensed under the Apache License, Version 2.0 (the "License");
  19645. * you may not use this file except in compliance with the License.
  19646. * You may obtain a copy of the License at
  19647. *
  19648. * http://www.apache.org/licenses/LICENSE-2.0
  19649. *
  19650. * Unless required by applicable law or agreed to in writing, software
  19651. * distributed under the License is distributed on an "AS IS" BASIS,
  19652. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19653. * See the License for the specific language governing permissions and
  19654. * limitations under the License.
  19655. */ function ff(t, e) {
  19656. var n;
  19657. const s = ah(t = _a(t, oh));
  19658. // PORTING NOTE: We don't return an error if the user has not enabled
  19659. // persistence since `enableIndexeddbPersistence()` can fail on the Web.
  19660. if (!(null === (n = s.offlineComponents) || void 0 === n ? void 0 : n.indexBackfillerScheduler)) return k("Cannot enable indexes when persistence is disabled"),
  19661. Promise.resolve();
  19662. const i = function(t) {
  19663. const e = "string" == typeof t ? function(t) {
  19664. try {
  19665. return JSON.parse(t);
  19666. } catch (t) {
  19667. throw new q(L.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == t ? void 0 : t.message));
  19668. }
  19669. }(t) : t, n = [];
  19670. if (Array.isArray(e.indexes)) for (const t of e.indexes) {
  19671. const e = df(t, "collectionGroup"), s = [];
  19672. if (Array.isArray(t.fields)) for (const e of t.fields) {
  19673. const t = Jh("setIndexConfiguration", df(e, "fieldPath"));
  19674. "CONTAINS" === e.arrayConfig ? s.push(new _t(t, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === e.order ? s.push(new _t(t, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === e.order && s.push(new _t(t, 1 /* IndexKind.DESCENDING */));
  19675. }
  19676. n.push(new ht(ht.UNKNOWN_ID, e, s, mt.empty()));
  19677. }
  19678. return n;
  19679. }(e);
  19680. return Ua(s).then((t => async function(t, e) {
  19681. const n = B(t), s = n.indexManager, i = [];
  19682. return n.persistence.runTransaction("Configure indexes", "readwrite", (t => s.getFieldIndexes(t).next((n => function(t, e, n, s, i) {
  19683. t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);
  19684. const r = t.length, o = e.length;
  19685. let u = 0, c = 0;
  19686. for (;u < o && c < r; ) {
  19687. const r = n(t[c], e[u]);
  19688. r < 0 ?
  19689. // The element was removed if the next element in our ordered
  19690. // walkthrough is only in `before`.
  19691. i(t[c++]) : r > 0 ?
  19692. // The element was added if the next element in our ordered walkthrough
  19693. // is only in `after`.
  19694. s(e[u++]) : (u++, c++);
  19695. }
  19696. for (;u < o; ) s(e[u++]);
  19697. for (;c < r; ) i(t[c++]);
  19698. }(n, e, dt, (e => {
  19699. i.push(s.addFieldIndex(t, e));
  19700. }), (e => {
  19701. i.push(s.deleteFieldIndex(t, e));
  19702. })))).next((() => Rt.waitFor(i)))));
  19703. }
  19704. /**
  19705. * @license
  19706. * Copyright 2019 Google LLC
  19707. *
  19708. * Licensed under the Apache License, Version 2.0 (the "License");
  19709. * you may not use this file except in compliance with the License.
  19710. * You may obtain a copy of the License at
  19711. *
  19712. * http://www.apache.org/licenses/LICENSE-2.0
  19713. *
  19714. * Unless required by applicable law or agreed to in writing, software
  19715. * distributed under the License is distributed on an "AS IS" BASIS,
  19716. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19717. * See the License for the specific language governing permissions and
  19718. * limitations under the License.
  19719. */
  19720. // The format of the LocalStorage key that stores the client state is:
  19721. // firestore_clients_<persistence_prefix>_<instance_key>
  19722. (t, i)));
  19723. }
  19724. function df(t, e) {
  19725. if ("string" != typeof t[e]) throw new q(L.INVALID_ARGUMENT, "Missing string value for: " + e);
  19726. return t[e];
  19727. }
  19728. /**
  19729. * @license
  19730. * Copyright 2021 Google LLC
  19731. *
  19732. * Licensed under the Apache License, Version 2.0 (the "License");
  19733. * you may not use this file except in compliance with the License.
  19734. * You may obtain a copy of the License at
  19735. *
  19736. * http://www.apache.org/licenses/LICENSE-2.0
  19737. *
  19738. * Unless required by applicable law or agreed to in writing, software
  19739. * distributed under the License is distributed on an "AS IS" BASIS,
  19740. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19741. * See the License for the specific language governing permissions and
  19742. * limitations under the License.
  19743. */ !function(t, e = !0) {
  19744. !function(t) {
  19745. V = t;
  19746. }(i), n(new r("firestore", ((t, {instanceIdentifier: n, options: s}) => {
  19747. const i = t.getProvider("app").getImmediate(), r = new oh(new j(t.getProvider("auth-internal")), new J(t.getProvider("app-check-internal")), function(t, e) {
  19748. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new q(L.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  19749. return new $t(t.options.projectId, e);
  19750. }(i, n), i);
  19751. return s = Object.assign({
  19752. useFetchStreams: e
  19753. }, s), r._setSettings(s), r;
  19754. }), "PUBLIC").setMultipleInstances(!0)), s(P, "3.8.1", t),
  19755. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  19756. s(P, "3.8.1", "esm2017");
  19757. }("rn", /* useFetchStreams= */ !1);
  19758. export { Vl as AbstractUserDataWriter, Ca as AggregateField, xa as AggregateQuerySnapshot, Eh as Bytes, rh as CACHE_SIZE_UNLIMITED, Ea as CollectionReference, Ia as DocumentReference, xl as DocumentSnapshot, Ah as FieldPath, bh as FieldValue, oh as Firestore, q as FirestoreError, Ph as GeoPoint, ih as LoadBundleTask, Ta as Query, cl as QueryCompositeFilterConstraint, il as QueryConstraint, Nl as QueryDocumentSnapshot, pl as QueryEndAtConstraint, ol as QueryFieldFilterConstraint, dl as QueryLimitConstraint, ll as QueryOrderByConstraint, kl as QuerySnapshot, ml as QueryStartAtConstraint, Cl as SnapshotMetadata, st as Timestamp, sf as Transaction, ef as WriteBatch, $t as _DatabaseId, at as _DocumentKey, Y as _EmptyAppCheckTokenProvider, G as _EmptyAuthCredentialsProvider, ct as _FieldPath, _a as _cast, $ as _debugAssert, jt as _isBase64Available, k as _logWarn, ha as _validateIsNotUsedTogether, Wl as addDoc, Xl as aggregateQuerySnapshotEqual, hl as and, af as arrayRemove, cf as arrayUnion, _h as clearIndexedDbPersistence, Aa as collection, Ra as collectionGroup, pa as connectFirestoreEmulator, jl as deleteDoc, of as deleteField, gh as disableNetwork, ba as doc, Rh as documentId, lh as enableIndexedDbPersistence, fh as enableMultiTabIndexedDbPersistence, mh as enableNetwork, Tl as endAt, Il as endBefore, ah as ensureFirestoreConfigured, Jl as executeWrite, Zl as getCountFromServer, Fl as getDoc, Bl as getDocFromCache, Ll as getDocFromServer, ql as getDocs, Ul as getDocsFromCache, Kl as getDocsFromServer, ch as getFirestore, hf as increment, uh as initializeFirestore, _l as limit, wl as limitToLast, ph as loadBundle, Ih as namedQuery, zl as onSnapshot, Hl as onSnapshotsInSync, al as or, fl as orderBy, rl as query, va as queryEqual, Pa as refEqual, rf as runTransaction, uf as serverTimestamp, Gl as setDoc, ff as setIndexConfiguration, C as setLogLevel, Ml as snapshotEqual, yl as startAfter, gl as startAt, yh as terminate, Ql as updateDoc, wh as waitForPendingWrites, ul as where, lf as writeBatch };
  19759. //# sourceMappingURL=index.rn.js.map