index.esm5.js 586 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416
  1. import { getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app';
  2. import { Component } from '@firebase/component';
  3. import { __spreadArray, __read, __values, __assign, __extends, __awaiter, __generator } from 'tslib';
  4. import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';
  5. import { Logger, LogLevel } from '@firebase/logger';
  6. var name = "@firebase/database";
  7. var version = "0.14.4";
  8. /**
  9. * @license
  10. * Copyright 2019 Google LLC
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. /** The semver (www.semver.org) version of the SDK. */
  25. var SDK_VERSION = '';
  26. /**
  27. * SDK_VERSION should be set before any database instance is created
  28. * @internal
  29. */
  30. function setSDKVersion(version) {
  31. SDK_VERSION = version;
  32. }
  33. /**
  34. * @license
  35. * Copyright 2017 Google LLC
  36. *
  37. * Licensed under the Apache License, Version 2.0 (the "License");
  38. * you may not use this file except in compliance with the License.
  39. * You may obtain a copy of the License at
  40. *
  41. * http://www.apache.org/licenses/LICENSE-2.0
  42. *
  43. * Unless required by applicable law or agreed to in writing, software
  44. * distributed under the License is distributed on an "AS IS" BASIS,
  45. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  46. * See the License for the specific language governing permissions and
  47. * limitations under the License.
  48. */
  49. /**
  50. * Wraps a DOM Storage object and:
  51. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  52. * - prefixes names with "firebase:" to avoid collisions with app data.
  53. *
  54. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  55. * and one for localStorage.
  56. *
  57. */
  58. var DOMStorageWrapper = /** @class */ (function () {
  59. /**
  60. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  61. */
  62. function DOMStorageWrapper(domStorage_) {
  63. this.domStorage_ = domStorage_;
  64. // Use a prefix to avoid collisions with other stuff saved by the app.
  65. this.prefix_ = 'firebase:';
  66. }
  67. /**
  68. * @param key - The key to save the value under
  69. * @param value - The value being stored, or null to remove the key.
  70. */
  71. DOMStorageWrapper.prototype.set = function (key, value) {
  72. if (value == null) {
  73. this.domStorage_.removeItem(this.prefixedName_(key));
  74. }
  75. else {
  76. this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
  77. }
  78. };
  79. /**
  80. * @returns The value that was stored under this key, or null
  81. */
  82. DOMStorageWrapper.prototype.get = function (key) {
  83. var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  84. if (storedVal == null) {
  85. return null;
  86. }
  87. else {
  88. return jsonEval(storedVal);
  89. }
  90. };
  91. DOMStorageWrapper.prototype.remove = function (key) {
  92. this.domStorage_.removeItem(this.prefixedName_(key));
  93. };
  94. DOMStorageWrapper.prototype.prefixedName_ = function (name) {
  95. return this.prefix_ + name;
  96. };
  97. DOMStorageWrapper.prototype.toString = function () {
  98. return this.domStorage_.toString();
  99. };
  100. return DOMStorageWrapper;
  101. }());
  102. /**
  103. * @license
  104. * Copyright 2017 Google LLC
  105. *
  106. * Licensed under the Apache License, Version 2.0 (the "License");
  107. * you may not use this file except in compliance with the License.
  108. * You may obtain a copy of the License at
  109. *
  110. * http://www.apache.org/licenses/LICENSE-2.0
  111. *
  112. * Unless required by applicable law or agreed to in writing, software
  113. * distributed under the License is distributed on an "AS IS" BASIS,
  114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  115. * See the License for the specific language governing permissions and
  116. * limitations under the License.
  117. */
  118. /**
  119. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  120. * (TODO: create interface for both to implement).
  121. */
  122. var MemoryStorage = /** @class */ (function () {
  123. function MemoryStorage() {
  124. this.cache_ = {};
  125. this.isInMemoryStorage = true;
  126. }
  127. MemoryStorage.prototype.set = function (key, value) {
  128. if (value == null) {
  129. delete this.cache_[key];
  130. }
  131. else {
  132. this.cache_[key] = value;
  133. }
  134. };
  135. MemoryStorage.prototype.get = function (key) {
  136. if (contains(this.cache_, key)) {
  137. return this.cache_[key];
  138. }
  139. return null;
  140. };
  141. MemoryStorage.prototype.remove = function (key) {
  142. delete this.cache_[key];
  143. };
  144. return MemoryStorage;
  145. }());
  146. /**
  147. * @license
  148. * Copyright 2017 Google LLC
  149. *
  150. * Licensed under the Apache License, Version 2.0 (the "License");
  151. * you may not use this file except in compliance with the License.
  152. * You may obtain a copy of the License at
  153. *
  154. * http://www.apache.org/licenses/LICENSE-2.0
  155. *
  156. * Unless required by applicable law or agreed to in writing, software
  157. * distributed under the License is distributed on an "AS IS" BASIS,
  158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  159. * See the License for the specific language governing permissions and
  160. * limitations under the License.
  161. */
  162. /**
  163. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  164. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  165. * to reflect this type
  166. *
  167. * @param domStorageName - Name of the underlying storage object
  168. * (e.g. 'localStorage' or 'sessionStorage').
  169. * @returns Turning off type information until a common interface is defined.
  170. */
  171. var createStoragefor = function (domStorageName) {
  172. try {
  173. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  174. // so it must be inside the try/catch.
  175. if (typeof window !== 'undefined' &&
  176. typeof window[domStorageName] !== 'undefined') {
  177. // Need to test cache. Just because it's here doesn't mean it works
  178. var domStorage = window[domStorageName];
  179. domStorage.setItem('firebase:sentinel', 'cache');
  180. domStorage.removeItem('firebase:sentinel');
  181. return new DOMStorageWrapper(domStorage);
  182. }
  183. }
  184. catch (e) { }
  185. // Failed to create wrapper. Just return in-memory storage.
  186. // TODO: log?
  187. return new MemoryStorage();
  188. };
  189. /** A storage object that lasts across sessions */
  190. var PersistentStorage = createStoragefor('localStorage');
  191. /** A storage object that only lasts one session */
  192. var SessionStorage = createStoragefor('sessionStorage');
  193. /**
  194. * @license
  195. * Copyright 2017 Google LLC
  196. *
  197. * Licensed under the Apache License, Version 2.0 (the "License");
  198. * you may not use this file except in compliance with the License.
  199. * You may obtain a copy of the License at
  200. *
  201. * http://www.apache.org/licenses/LICENSE-2.0
  202. *
  203. * Unless required by applicable law or agreed to in writing, software
  204. * distributed under the License is distributed on an "AS IS" BASIS,
  205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  206. * See the License for the specific language governing permissions and
  207. * limitations under the License.
  208. */
  209. var logClient = new Logger('@firebase/database');
  210. /**
  211. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  212. */
  213. var LUIDGenerator = (function () {
  214. var id = 1;
  215. return function () {
  216. return id++;
  217. };
  218. })();
  219. /**
  220. * Sha1 hash of the input string
  221. * @param str - The string to hash
  222. * @returns {!string} The resulting hash
  223. */
  224. var sha1 = function (str) {
  225. var utf8Bytes = stringToByteArray(str);
  226. var sha1 = new Sha1();
  227. sha1.update(utf8Bytes);
  228. var sha1Bytes = sha1.digest();
  229. return base64.encodeByteArray(sha1Bytes);
  230. };
  231. var buildLogMessage_ = function () {
  232. var varArgs = [];
  233. for (var _i = 0; _i < arguments.length; _i++) {
  234. varArgs[_i] = arguments[_i];
  235. }
  236. var message = '';
  237. for (var i = 0; i < varArgs.length; i++) {
  238. var arg = varArgs[i];
  239. if (Array.isArray(arg) ||
  240. (arg &&
  241. typeof arg === 'object' &&
  242. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  243. typeof arg.length === 'number')) {
  244. message += buildLogMessage_.apply(null, arg);
  245. }
  246. else if (typeof arg === 'object') {
  247. message += stringify(arg);
  248. }
  249. else {
  250. message += arg;
  251. }
  252. message += ' ';
  253. }
  254. return message;
  255. };
  256. /**
  257. * Use this for all debug messages in Firebase.
  258. */
  259. var logger = null;
  260. /**
  261. * Flag to check for log availability on first log message
  262. */
  263. var firstLog_ = true;
  264. /**
  265. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  266. * @param logger_ - A flag to turn on logging, or a custom logger
  267. * @param persistent - Whether or not to persist logging settings across refreshes
  268. */
  269. var enableLogging$1 = function (logger_, persistent) {
  270. assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  271. if (logger_ === true) {
  272. logClient.logLevel = LogLevel.VERBOSE;
  273. logger = logClient.log.bind(logClient);
  274. if (persistent) {
  275. SessionStorage.set('logging_enabled', true);
  276. }
  277. }
  278. else if (typeof logger_ === 'function') {
  279. logger = logger_;
  280. }
  281. else {
  282. logger = null;
  283. SessionStorage.remove('logging_enabled');
  284. }
  285. };
  286. var log = function () {
  287. var varArgs = [];
  288. for (var _i = 0; _i < arguments.length; _i++) {
  289. varArgs[_i] = arguments[_i];
  290. }
  291. if (firstLog_ === true) {
  292. firstLog_ = false;
  293. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  294. enableLogging$1(true);
  295. }
  296. }
  297. if (logger) {
  298. var message = buildLogMessage_.apply(null, varArgs);
  299. logger(message);
  300. }
  301. };
  302. var logWrapper = function (prefix) {
  303. return function () {
  304. var varArgs = [];
  305. for (var _i = 0; _i < arguments.length; _i++) {
  306. varArgs[_i] = arguments[_i];
  307. }
  308. log.apply(void 0, __spreadArray([prefix], __read(varArgs), false));
  309. };
  310. };
  311. var error = function () {
  312. var varArgs = [];
  313. for (var _i = 0; _i < arguments.length; _i++) {
  314. varArgs[_i] = arguments[_i];
  315. }
  316. var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false));
  317. logClient.error(message);
  318. };
  319. var fatal = function () {
  320. var varArgs = [];
  321. for (var _i = 0; _i < arguments.length; _i++) {
  322. varArgs[_i] = arguments[_i];
  323. }
  324. var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false)));
  325. logClient.error(message);
  326. throw new Error(message);
  327. };
  328. var warn = function () {
  329. var varArgs = [];
  330. for (var _i = 0; _i < arguments.length; _i++) {
  331. varArgs[_i] = arguments[_i];
  332. }
  333. var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false));
  334. logClient.warn(message);
  335. };
  336. /**
  337. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  338. * does not use https.
  339. */
  340. var warnIfPageIsSecure = function () {
  341. // Be very careful accessing browser globals. Who knows what may or may not exist.
  342. if (typeof window !== 'undefined' &&
  343. window.location &&
  344. window.location.protocol &&
  345. window.location.protocol.indexOf('https:') !== -1) {
  346. warn('Insecure Firebase access from a secure page. ' +
  347. 'Please use https in calls to new Firebase().');
  348. }
  349. };
  350. /**
  351. * Returns true if data is NaN, or +/- Infinity.
  352. */
  353. var isInvalidJSONNumber = function (data) {
  354. return (typeof data === 'number' &&
  355. (data !== data || // NaN
  356. data === Number.POSITIVE_INFINITY ||
  357. data === Number.NEGATIVE_INFINITY));
  358. };
  359. var executeWhenDOMReady = function (fn) {
  360. if (isNodeSdk() || document.readyState === 'complete') {
  361. fn();
  362. }
  363. else {
  364. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  365. // fire before onload), but fall back to onload.
  366. var called_1 = false;
  367. var wrappedFn_1 = function () {
  368. if (!document.body) {
  369. setTimeout(wrappedFn_1, Math.floor(10));
  370. return;
  371. }
  372. if (!called_1) {
  373. called_1 = true;
  374. fn();
  375. }
  376. };
  377. if (document.addEventListener) {
  378. document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
  379. // fallback to onload.
  380. window.addEventListener('load', wrappedFn_1, false);
  381. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  382. }
  383. else if (document.attachEvent) {
  384. // IE.
  385. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  386. document.attachEvent('onreadystatechange', function () {
  387. if (document.readyState === 'complete') {
  388. wrappedFn_1();
  389. }
  390. });
  391. // fallback to onload.
  392. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  393. window.attachEvent('onload', wrappedFn_1);
  394. // jQuery has an extra hack for IE that we could employ (based on
  395. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  396. // I'm hoping we don't need it.
  397. }
  398. }
  399. };
  400. /**
  401. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  402. */
  403. var MIN_NAME = '[MIN_NAME]';
  404. /**
  405. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  406. */
  407. var MAX_NAME = '[MAX_NAME]';
  408. /**
  409. * Compares valid Firebase key names, plus min and max name
  410. */
  411. var nameCompare = function (a, b) {
  412. if (a === b) {
  413. return 0;
  414. }
  415. else if (a === MIN_NAME || b === MAX_NAME) {
  416. return -1;
  417. }
  418. else if (b === MIN_NAME || a === MAX_NAME) {
  419. return 1;
  420. }
  421. else {
  422. var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  423. if (aAsInt !== null) {
  424. if (bAsInt !== null) {
  425. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  426. }
  427. else {
  428. return -1;
  429. }
  430. }
  431. else if (bAsInt !== null) {
  432. return 1;
  433. }
  434. else {
  435. return a < b ? -1 : 1;
  436. }
  437. }
  438. };
  439. /**
  440. * @returns {!number} comparison result.
  441. */
  442. var stringCompare = function (a, b) {
  443. if (a === b) {
  444. return 0;
  445. }
  446. else if (a < b) {
  447. return -1;
  448. }
  449. else {
  450. return 1;
  451. }
  452. };
  453. var requireKey = function (key, obj) {
  454. if (obj && key in obj) {
  455. return obj[key];
  456. }
  457. else {
  458. throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
  459. }
  460. };
  461. var ObjectToUniqueKey = function (obj) {
  462. if (typeof obj !== 'object' || obj === null) {
  463. return stringify(obj);
  464. }
  465. var keys = [];
  466. // eslint-disable-next-line guard-for-in
  467. for (var k in obj) {
  468. keys.push(k);
  469. }
  470. // Export as json, but with the keys sorted.
  471. keys.sort();
  472. var key = '{';
  473. for (var i = 0; i < keys.length; i++) {
  474. if (i !== 0) {
  475. key += ',';
  476. }
  477. key += stringify(keys[i]);
  478. key += ':';
  479. key += ObjectToUniqueKey(obj[keys[i]]);
  480. }
  481. key += '}';
  482. return key;
  483. };
  484. /**
  485. * Splits a string into a number of smaller segments of maximum size
  486. * @param str - The string
  487. * @param segsize - The maximum number of chars in the string.
  488. * @returns The string, split into appropriately-sized chunks
  489. */
  490. var splitStringBySize = function (str, segsize) {
  491. var len = str.length;
  492. if (len <= segsize) {
  493. return [str];
  494. }
  495. var dataSegs = [];
  496. for (var c = 0; c < len; c += segsize) {
  497. if (c + segsize > len) {
  498. dataSegs.push(str.substring(c, len));
  499. }
  500. else {
  501. dataSegs.push(str.substring(c, c + segsize));
  502. }
  503. }
  504. return dataSegs;
  505. };
  506. /**
  507. * Apply a function to each (key, value) pair in an object or
  508. * apply a function to each (index, value) pair in an array
  509. * @param obj - The object or array to iterate over
  510. * @param fn - The function to apply
  511. */
  512. function each(obj, fn) {
  513. for (var key in obj) {
  514. if (obj.hasOwnProperty(key)) {
  515. fn(key, obj[key]);
  516. }
  517. }
  518. }
  519. /**
  520. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  521. * I made one modification at the end and removed the NaN / Infinity
  522. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  523. * @param v - A double
  524. *
  525. */
  526. var doubleToIEEE754String = function (v) {
  527. assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  528. var ebits = 11, fbits = 52;
  529. var bias = (1 << (ebits - 1)) - 1;
  530. var s, e, f, ln, i;
  531. // Compute sign, exponent, fraction
  532. // Skip NaN / Infinity handling --MJL.
  533. if (v === 0) {
  534. e = 0;
  535. f = 0;
  536. s = 1 / v === -Infinity ? 1 : 0;
  537. }
  538. else {
  539. s = v < 0;
  540. v = Math.abs(v);
  541. if (v >= Math.pow(2, 1 - bias)) {
  542. // Normalized
  543. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  544. e = ln + bias;
  545. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  546. }
  547. else {
  548. // Denormalized
  549. e = 0;
  550. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  551. }
  552. }
  553. // Pack sign, exponent, fraction
  554. var bits = [];
  555. for (i = fbits; i; i -= 1) {
  556. bits.push(f % 2 ? 1 : 0);
  557. f = Math.floor(f / 2);
  558. }
  559. for (i = ebits; i; i -= 1) {
  560. bits.push(e % 2 ? 1 : 0);
  561. e = Math.floor(e / 2);
  562. }
  563. bits.push(s ? 1 : 0);
  564. bits.reverse();
  565. var str = bits.join('');
  566. // Return the data as a hex string. --MJL
  567. var hexByteString = '';
  568. for (i = 0; i < 64; i += 8) {
  569. var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  570. if (hexByte.length === 1) {
  571. hexByte = '0' + hexByte;
  572. }
  573. hexByteString = hexByteString + hexByte;
  574. }
  575. return hexByteString.toLowerCase();
  576. };
  577. /**
  578. * Used to detect if we're in a Chrome content script (which executes in an
  579. * isolated environment where long-polling doesn't work).
  580. */
  581. var isChromeExtensionContentScript = function () {
  582. return !!(typeof window === 'object' &&
  583. window['chrome'] &&
  584. window['chrome']['extension'] &&
  585. !/^chrome/.test(window.location.href));
  586. };
  587. /**
  588. * Used to detect if we're in a Windows 8 Store app.
  589. */
  590. var isWindowsStoreApp = function () {
  591. // Check for the presence of a couple WinRT globals
  592. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  593. };
  594. /**
  595. * Converts a server error code to a Javascript Error
  596. */
  597. function errorForServerCode(code, query) {
  598. var reason = 'Unknown Error';
  599. if (code === 'too_big') {
  600. reason =
  601. 'The data requested exceeds the maximum size ' +
  602. 'that can be accessed with a single request.';
  603. }
  604. else if (code === 'permission_denied') {
  605. reason = "Client doesn't have permission to access the desired data.";
  606. }
  607. else if (code === 'unavailable') {
  608. reason = 'The service is unavailable';
  609. }
  610. var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  611. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  612. error.code = code.toUpperCase();
  613. return error;
  614. }
  615. /**
  616. * Used to test for integer-looking strings
  617. */
  618. var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  619. /**
  620. * For use in keys, the minimum possible 32-bit integer.
  621. */
  622. var INTEGER_32_MIN = -2147483648;
  623. /**
  624. * For use in kyes, the maximum possible 32-bit integer.
  625. */
  626. var INTEGER_32_MAX = 2147483647;
  627. /**
  628. * If the string contains a 32-bit integer, return it. Else return null.
  629. */
  630. var tryParseInt = function (str) {
  631. if (INTEGER_REGEXP_.test(str)) {
  632. var intVal = Number(str);
  633. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  634. return intVal;
  635. }
  636. }
  637. return null;
  638. };
  639. /**
  640. * Helper to run some code but catch any exceptions and re-throw them later.
  641. * Useful for preventing user callbacks from breaking internal code.
  642. *
  643. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  644. * convenient (we don't have to try to figure out when is a safe point to
  645. * re-throw it), and the behavior seems reasonable:
  646. *
  647. * * If you aren't pausing on exceptions, you get an error in the console with
  648. * the correct stack trace.
  649. * * If you're pausing on all exceptions, the debugger will pause on your
  650. * exception and then again when we rethrow it.
  651. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  652. * on us re-throwing it.
  653. *
  654. * @param fn - The code to guard.
  655. */
  656. var exceptionGuard = function (fn) {
  657. try {
  658. fn();
  659. }
  660. catch (e) {
  661. // Re-throw exception when it's safe.
  662. setTimeout(function () {
  663. // It used to be that "throw e" would result in a good console error with
  664. // relevant context, but as of Chrome 39, you just get the firebase.js
  665. // file/line number where we re-throw it, which is useless. So we log
  666. // e.stack explicitly.
  667. var stack = e.stack || '';
  668. warn('Exception was thrown by user callback.', stack);
  669. throw e;
  670. }, Math.floor(0));
  671. }
  672. };
  673. /**
  674. * @returns {boolean} true if we think we're currently being crawled.
  675. */
  676. var beingCrawled = function () {
  677. var userAgent = (typeof window === 'object' &&
  678. window['navigator'] &&
  679. window['navigator']['userAgent']) ||
  680. '';
  681. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  682. // believe to support JavaScript/AJAX rendering.
  683. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  684. // would have seen the page" is flaky if we don't treat it as a crawler.
  685. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  686. };
  687. /**
  688. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  689. *
  690. * It is removed with clearTimeout() as normal.
  691. *
  692. * @param fn - Function to run.
  693. * @param time - Milliseconds to wait before running.
  694. * @returns The setTimeout() return value.
  695. */
  696. var setTimeoutNonBlocking = function (fn, time) {
  697. var timeout = setTimeout(fn, time);
  698. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  699. if (typeof timeout === 'number' &&
  700. // @ts-ignore Is only defined in Deno environments.
  701. typeof Deno !== 'undefined' &&
  702. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  703. Deno['unrefTimer']) {
  704. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  705. Deno.unrefTimer(timeout);
  706. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  707. }
  708. else if (typeof timeout === 'object' && timeout['unref']) {
  709. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  710. timeout['unref']();
  711. }
  712. return timeout;
  713. };
  714. /**
  715. * @license
  716. * Copyright 2021 Google LLC
  717. *
  718. * Licensed under the Apache License, Version 2.0 (the "License");
  719. * you may not use this file except in compliance with the License.
  720. * You may obtain a copy of the License at
  721. *
  722. * http://www.apache.org/licenses/LICENSE-2.0
  723. *
  724. * Unless required by applicable law or agreed to in writing, software
  725. * distributed under the License is distributed on an "AS IS" BASIS,
  726. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  727. * See the License for the specific language governing permissions and
  728. * limitations under the License.
  729. */
  730. /**
  731. * Abstraction around AppCheck's token fetching capabilities.
  732. */
  733. var AppCheckTokenProvider = /** @class */ (function () {
  734. function AppCheckTokenProvider(appName_, appCheckProvider) {
  735. var _this = this;
  736. this.appName_ = appName_;
  737. this.appCheckProvider = appCheckProvider;
  738. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  739. if (!this.appCheck) {
  740. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
  741. }
  742. }
  743. AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
  744. var _this = this;
  745. if (!this.appCheck) {
  746. return new Promise(function (resolve, reject) {
  747. // Support delayed initialization of FirebaseAppCheck. This allows our
  748. // customers to initialize the RTDB SDK before initializing Firebase
  749. // AppCheck and ensures that all requests are authenticated if a token
  750. // becomes available before the timoeout below expires.
  751. setTimeout(function () {
  752. if (_this.appCheck) {
  753. _this.getToken(forceRefresh).then(resolve, reject);
  754. }
  755. else {
  756. resolve(null);
  757. }
  758. }, 0);
  759. });
  760. }
  761. return this.appCheck.getToken(forceRefresh);
  762. };
  763. AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
  764. var _a;
  765. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
  766. };
  767. AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
  768. warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
  769. 'are invalid. This usually indicates your app was not initialized correctly.');
  770. };
  771. return AppCheckTokenProvider;
  772. }());
  773. /**
  774. * @license
  775. * Copyright 2017 Google LLC
  776. *
  777. * Licensed under the Apache License, Version 2.0 (the "License");
  778. * you may not use this file except in compliance with the License.
  779. * You may obtain a copy of the License at
  780. *
  781. * http://www.apache.org/licenses/LICENSE-2.0
  782. *
  783. * Unless required by applicable law or agreed to in writing, software
  784. * distributed under the License is distributed on an "AS IS" BASIS,
  785. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  786. * See the License for the specific language governing permissions and
  787. * limitations under the License.
  788. */
  789. /**
  790. * Abstraction around FirebaseApp's token fetching capabilities.
  791. */
  792. var FirebaseAuthTokenProvider = /** @class */ (function () {
  793. function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
  794. var _this = this;
  795. this.appName_ = appName_;
  796. this.firebaseOptions_ = firebaseOptions_;
  797. this.authProvider_ = authProvider_;
  798. this.auth_ = null;
  799. this.auth_ = authProvider_.getImmediate({ optional: true });
  800. if (!this.auth_) {
  801. authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
  802. }
  803. }
  804. FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
  805. var _this = this;
  806. if (!this.auth_) {
  807. return new Promise(function (resolve, reject) {
  808. // Support delayed initialization of FirebaseAuth. This allows our
  809. // customers to initialize the RTDB SDK before initializing Firebase
  810. // Auth and ensures that all requests are authenticated if a token
  811. // becomes available before the timoeout below expires.
  812. setTimeout(function () {
  813. if (_this.auth_) {
  814. _this.getToken(forceRefresh).then(resolve, reject);
  815. }
  816. else {
  817. resolve(null);
  818. }
  819. }, 0);
  820. });
  821. }
  822. return this.auth_.getToken(forceRefresh).catch(function (error) {
  823. // TODO: Need to figure out all the cases this is raised and whether
  824. // this makes sense.
  825. if (error && error.code === 'auth/token-not-initialized') {
  826. log('Got auth/token-not-initialized error. Treating as null token.');
  827. return null;
  828. }
  829. else {
  830. return Promise.reject(error);
  831. }
  832. });
  833. };
  834. FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
  835. // TODO: We might want to wrap the listener and call it with no args to
  836. // avoid a leaky abstraction, but that makes removing the listener harder.
  837. if (this.auth_) {
  838. this.auth_.addAuthTokenListener(listener);
  839. }
  840. else {
  841. this.authProvider_
  842. .get()
  843. .then(function (auth) { return auth.addAuthTokenListener(listener); });
  844. }
  845. };
  846. FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
  847. this.authProvider_
  848. .get()
  849. .then(function (auth) { return auth.removeAuthTokenListener(listener); });
  850. };
  851. FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
  852. var errorMessage = 'Provided authentication credentials for the app named "' +
  853. this.appName_ +
  854. '" are invalid. This usually indicates your app was not ' +
  855. 'initialized correctly. ';
  856. if ('credential' in this.firebaseOptions_) {
  857. errorMessage +=
  858. 'Make sure the "credential" property provided to initializeApp() ' +
  859. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  860. 'project.';
  861. }
  862. else if ('serviceAccount' in this.firebaseOptions_) {
  863. errorMessage +=
  864. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  865. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  866. 'project.';
  867. }
  868. else {
  869. errorMessage +=
  870. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  871. 'initializeApp() match the values provided for your app at ' +
  872. 'https://console.firebase.google.com/.';
  873. }
  874. warn(errorMessage);
  875. };
  876. return FirebaseAuthTokenProvider;
  877. }());
  878. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  879. var EmulatorTokenProvider = /** @class */ (function () {
  880. function EmulatorTokenProvider(accessToken) {
  881. this.accessToken = accessToken;
  882. }
  883. EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
  884. return Promise.resolve({
  885. accessToken: this.accessToken
  886. });
  887. };
  888. EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
  889. // Invoke the listener immediately to match the behavior in Firebase Auth
  890. // (see packages/auth/src/auth.js#L1807)
  891. listener(this.accessToken);
  892. };
  893. EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
  894. EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
  895. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  896. EmulatorTokenProvider.OWNER = 'owner';
  897. return EmulatorTokenProvider;
  898. }());
  899. /**
  900. * @license
  901. * Copyright 2017 Google LLC
  902. *
  903. * Licensed under the Apache License, Version 2.0 (the "License");
  904. * you may not use this file except in compliance with the License.
  905. * You may obtain a copy of the License at
  906. *
  907. * http://www.apache.org/licenses/LICENSE-2.0
  908. *
  909. * Unless required by applicable law or agreed to in writing, software
  910. * distributed under the License is distributed on an "AS IS" BASIS,
  911. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  912. * See the License for the specific language governing permissions and
  913. * limitations under the License.
  914. */
  915. var PROTOCOL_VERSION = '5';
  916. var VERSION_PARAM = 'v';
  917. var TRANSPORT_SESSION_PARAM = 's';
  918. var REFERER_PARAM = 'r';
  919. var FORGE_REF = 'f';
  920. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  921. // firebase.corp.google.com
  922. var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  923. var LAST_SESSION_PARAM = 'ls';
  924. var APPLICATION_ID_PARAM = 'p';
  925. var APP_CHECK_TOKEN_PARAM = 'ac';
  926. var WEBSOCKET = 'websocket';
  927. var LONG_POLLING = 'long_polling';
  928. /**
  929. * @license
  930. * Copyright 2017 Google LLC
  931. *
  932. * Licensed under the Apache License, Version 2.0 (the "License");
  933. * you may not use this file except in compliance with the License.
  934. * You may obtain a copy of the License at
  935. *
  936. * http://www.apache.org/licenses/LICENSE-2.0
  937. *
  938. * Unless required by applicable law or agreed to in writing, software
  939. * distributed under the License is distributed on an "AS IS" BASIS,
  940. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  941. * See the License for the specific language governing permissions and
  942. * limitations under the License.
  943. */
  944. /**
  945. * A class that holds metadata about a Repo object
  946. */
  947. var RepoInfo = /** @class */ (function () {
  948. /**
  949. * @param host - Hostname portion of the url for the repo
  950. * @param secure - Whether or not this repo is accessed over ssl
  951. * @param namespace - The namespace represented by the repo
  952. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  953. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  954. * @param persistenceKey - Override the default session persistence storage key
  955. */
  956. function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams, isUsingEmulator) {
  957. if (nodeAdmin === void 0) { nodeAdmin = false; }
  958. if (persistenceKey === void 0) { persistenceKey = ''; }
  959. if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
  960. if (isUsingEmulator === void 0) { isUsingEmulator = false; }
  961. this.secure = secure;
  962. this.namespace = namespace;
  963. this.webSocketOnly = webSocketOnly;
  964. this.nodeAdmin = nodeAdmin;
  965. this.persistenceKey = persistenceKey;
  966. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  967. this.isUsingEmulator = isUsingEmulator;
  968. this._host = host.toLowerCase();
  969. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  970. this.internalHost =
  971. PersistentStorage.get('host:' + host) || this._host;
  972. }
  973. RepoInfo.prototype.isCacheableHost = function () {
  974. return this.internalHost.substr(0, 2) === 's-';
  975. };
  976. RepoInfo.prototype.isCustomHost = function () {
  977. return (this._domain !== 'firebaseio.com' &&
  978. this._domain !== 'firebaseio-demo.com');
  979. };
  980. Object.defineProperty(RepoInfo.prototype, "host", {
  981. get: function () {
  982. return this._host;
  983. },
  984. set: function (newHost) {
  985. if (newHost !== this.internalHost) {
  986. this.internalHost = newHost;
  987. if (this.isCacheableHost()) {
  988. PersistentStorage.set('host:' + this._host, this.internalHost);
  989. }
  990. }
  991. },
  992. enumerable: false,
  993. configurable: true
  994. });
  995. RepoInfo.prototype.toString = function () {
  996. var str = this.toURLString();
  997. if (this.persistenceKey) {
  998. str += '<' + this.persistenceKey + '>';
  999. }
  1000. return str;
  1001. };
  1002. RepoInfo.prototype.toURLString = function () {
  1003. var protocol = this.secure ? 'https://' : 'http://';
  1004. var query = this.includeNamespaceInQueryParams
  1005. ? "?ns=".concat(this.namespace)
  1006. : '';
  1007. return "".concat(protocol).concat(this.host, "/").concat(query);
  1008. };
  1009. return RepoInfo;
  1010. }());
  1011. function repoInfoNeedsQueryParam(repoInfo) {
  1012. return (repoInfo.host !== repoInfo.internalHost ||
  1013. repoInfo.isCustomHost() ||
  1014. repoInfo.includeNamespaceInQueryParams);
  1015. }
  1016. /**
  1017. * Returns the websocket URL for this repo
  1018. * @param repoInfo - RepoInfo object
  1019. * @param type - of connection
  1020. * @param params - list
  1021. * @returns The URL for this repo
  1022. */
  1023. function repoInfoConnectionURL(repoInfo, type, params) {
  1024. assert(typeof type === 'string', 'typeof type must == string');
  1025. assert(typeof params === 'object', 'typeof params must == object');
  1026. var connURL;
  1027. if (type === WEBSOCKET) {
  1028. connURL =
  1029. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  1030. }
  1031. else if (type === LONG_POLLING) {
  1032. connURL =
  1033. (repoInfo.secure ? 'https://' : 'http://') +
  1034. repoInfo.internalHost +
  1035. '/.lp?';
  1036. }
  1037. else {
  1038. throw new Error('Unknown connection type: ' + type);
  1039. }
  1040. if (repoInfoNeedsQueryParam(repoInfo)) {
  1041. params['ns'] = repoInfo.namespace;
  1042. }
  1043. var pairs = [];
  1044. each(params, function (key, value) {
  1045. pairs.push(key + '=' + value);
  1046. });
  1047. return connURL + pairs.join('&');
  1048. }
  1049. /**
  1050. * @license
  1051. * Copyright 2017 Google LLC
  1052. *
  1053. * Licensed under the Apache License, Version 2.0 (the "License");
  1054. * you may not use this file except in compliance with the License.
  1055. * You may obtain a copy of the License at
  1056. *
  1057. * http://www.apache.org/licenses/LICENSE-2.0
  1058. *
  1059. * Unless required by applicable law or agreed to in writing, software
  1060. * distributed under the License is distributed on an "AS IS" BASIS,
  1061. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1062. * See the License for the specific language governing permissions and
  1063. * limitations under the License.
  1064. */
  1065. /**
  1066. * Tracks a collection of stats.
  1067. */
  1068. var StatsCollection = /** @class */ (function () {
  1069. function StatsCollection() {
  1070. this.counters_ = {};
  1071. }
  1072. StatsCollection.prototype.incrementCounter = function (name, amount) {
  1073. if (amount === void 0) { amount = 1; }
  1074. if (!contains(this.counters_, name)) {
  1075. this.counters_[name] = 0;
  1076. }
  1077. this.counters_[name] += amount;
  1078. };
  1079. StatsCollection.prototype.get = function () {
  1080. return deepCopy(this.counters_);
  1081. };
  1082. return StatsCollection;
  1083. }());
  1084. /**
  1085. * @license
  1086. * Copyright 2017 Google LLC
  1087. *
  1088. * Licensed under the Apache License, Version 2.0 (the "License");
  1089. * you may not use this file except in compliance with the License.
  1090. * You may obtain a copy of the License at
  1091. *
  1092. * http://www.apache.org/licenses/LICENSE-2.0
  1093. *
  1094. * Unless required by applicable law or agreed to in writing, software
  1095. * distributed under the License is distributed on an "AS IS" BASIS,
  1096. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1097. * See the License for the specific language governing permissions and
  1098. * limitations under the License.
  1099. */
  1100. var collections = {};
  1101. var reporters = {};
  1102. function statsManagerGetCollection(repoInfo) {
  1103. var hashString = repoInfo.toString();
  1104. if (!collections[hashString]) {
  1105. collections[hashString] = new StatsCollection();
  1106. }
  1107. return collections[hashString];
  1108. }
  1109. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  1110. var hashString = repoInfo.toString();
  1111. if (!reporters[hashString]) {
  1112. reporters[hashString] = creatorFunction();
  1113. }
  1114. return reporters[hashString];
  1115. }
  1116. /**
  1117. * @license
  1118. * Copyright 2017 Google LLC
  1119. *
  1120. * Licensed under the Apache License, Version 2.0 (the "License");
  1121. * you may not use this file except in compliance with the License.
  1122. * You may obtain a copy of the License at
  1123. *
  1124. * http://www.apache.org/licenses/LICENSE-2.0
  1125. *
  1126. * Unless required by applicable law or agreed to in writing, software
  1127. * distributed under the License is distributed on an "AS IS" BASIS,
  1128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1129. * See the License for the specific language governing permissions and
  1130. * limitations under the License.
  1131. */
  1132. /**
  1133. * This class ensures the packets from the server arrive in order
  1134. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1135. */
  1136. var PacketReceiver = /** @class */ (function () {
  1137. /**
  1138. * @param onMessage_
  1139. */
  1140. function PacketReceiver(onMessage_) {
  1141. this.onMessage_ = onMessage_;
  1142. this.pendingResponses = [];
  1143. this.currentResponseNum = 0;
  1144. this.closeAfterResponse = -1;
  1145. this.onClose = null;
  1146. }
  1147. PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
  1148. this.closeAfterResponse = responseNum;
  1149. this.onClose = callback;
  1150. if (this.closeAfterResponse < this.currentResponseNum) {
  1151. this.onClose();
  1152. this.onClose = null;
  1153. }
  1154. };
  1155. /**
  1156. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1157. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1158. * browsers will respond in the same order as the requests we sent
  1159. */
  1160. PacketReceiver.prototype.handleResponse = function (requestNum, data) {
  1161. var _this = this;
  1162. this.pendingResponses[requestNum] = data;
  1163. var _loop_1 = function () {
  1164. var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
  1165. delete this_1.pendingResponses[this_1.currentResponseNum];
  1166. var _loop_2 = function (i) {
  1167. if (toProcess[i]) {
  1168. exceptionGuard(function () {
  1169. _this.onMessage_(toProcess[i]);
  1170. });
  1171. }
  1172. };
  1173. for (var i = 0; i < toProcess.length; ++i) {
  1174. _loop_2(i);
  1175. }
  1176. if (this_1.currentResponseNum === this_1.closeAfterResponse) {
  1177. if (this_1.onClose) {
  1178. this_1.onClose();
  1179. this_1.onClose = null;
  1180. }
  1181. return "break";
  1182. }
  1183. this_1.currentResponseNum++;
  1184. };
  1185. var this_1 = this;
  1186. while (this.pendingResponses[this.currentResponseNum]) {
  1187. var state_1 = _loop_1();
  1188. if (state_1 === "break")
  1189. break;
  1190. }
  1191. };
  1192. return PacketReceiver;
  1193. }());
  1194. /**
  1195. * @license
  1196. * Copyright 2017 Google LLC
  1197. *
  1198. * Licensed under the Apache License, Version 2.0 (the "License");
  1199. * you may not use this file except in compliance with the License.
  1200. * You may obtain a copy of the License at
  1201. *
  1202. * http://www.apache.org/licenses/LICENSE-2.0
  1203. *
  1204. * Unless required by applicable law or agreed to in writing, software
  1205. * distributed under the License is distributed on an "AS IS" BASIS,
  1206. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1207. * See the License for the specific language governing permissions and
  1208. * limitations under the License.
  1209. */
  1210. // URL query parameters associated with longpolling
  1211. var FIREBASE_LONGPOLL_START_PARAM = 'start';
  1212. var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1213. var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1214. var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1215. var FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1216. var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1217. var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1218. var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1219. var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1220. var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1221. var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1222. var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1223. //Data size constants.
  1224. //TODO: Perf: the maximum length actually differs from browser to browser.
  1225. // We should check what browser we're on and set accordingly.
  1226. var MAX_URL_DATA_SIZE = 1870;
  1227. var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1228. var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1229. /**
  1230. * Keepalive period
  1231. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1232. * length of 30 seconds that we can't exceed.
  1233. */
  1234. var KEEPALIVE_REQUEST_INTERVAL = 25000;
  1235. /**
  1236. * How long to wait before aborting a long-polling connection attempt.
  1237. */
  1238. var LP_CONNECT_TIMEOUT = 30000;
  1239. /**
  1240. * This class manages a single long-polling connection.
  1241. */
  1242. var BrowserPollConnection = /** @class */ (function () {
  1243. /**
  1244. * @param connId An identifier for this connection, used for logging
  1245. * @param repoInfo The info for the endpoint to send data to.
  1246. * @param applicationId The Firebase App ID for this project.
  1247. * @param appCheckToken The AppCheck token for this client.
  1248. * @param authToken The AuthToken to use for this connection.
  1249. * @param transportSessionId Optional transportSessionid if we are
  1250. * reconnecting for an existing transport session
  1251. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1252. * already created a connection previously
  1253. */
  1254. function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1255. var _this = this;
  1256. this.connId = connId;
  1257. this.repoInfo = repoInfo;
  1258. this.applicationId = applicationId;
  1259. this.appCheckToken = appCheckToken;
  1260. this.authToken = authToken;
  1261. this.transportSessionId = transportSessionId;
  1262. this.lastSessionId = lastSessionId;
  1263. this.bytesSent = 0;
  1264. this.bytesReceived = 0;
  1265. this.everConnected_ = false;
  1266. this.log_ = logWrapper(connId);
  1267. this.stats_ = statsManagerGetCollection(repoInfo);
  1268. this.urlFn = function (params) {
  1269. // Always add the token if we have one.
  1270. if (_this.appCheckToken) {
  1271. params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1272. }
  1273. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1274. };
  1275. }
  1276. /**
  1277. * @param onMessage - Callback when messages arrive
  1278. * @param onDisconnect - Callback with connection lost.
  1279. */
  1280. BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
  1281. var _this = this;
  1282. this.curSegmentNum = 0;
  1283. this.onDisconnect_ = onDisconnect;
  1284. this.myPacketOrderer = new PacketReceiver(onMessage);
  1285. this.isClosed_ = false;
  1286. this.connectTimeoutTimer_ = setTimeout(function () {
  1287. _this.log_('Timed out trying to connect.');
  1288. // Make sure we clear the host cache
  1289. _this.onClosed_();
  1290. _this.connectTimeoutTimer_ = null;
  1291. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1292. }, Math.floor(LP_CONNECT_TIMEOUT));
  1293. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1294. executeWhenDOMReady(function () {
  1295. if (_this.isClosed_) {
  1296. return;
  1297. }
  1298. //Set up a callback that gets triggered once a connection is set up.
  1299. _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
  1300. var args = [];
  1301. for (var _i = 0; _i < arguments.length; _i++) {
  1302. args[_i] = arguments[_i];
  1303. }
  1304. var _a = __read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
  1305. _this.incrementIncomingBytes_(args);
  1306. if (!_this.scriptTagHolder) {
  1307. return; // we closed the connection.
  1308. }
  1309. if (_this.connectTimeoutTimer_) {
  1310. clearTimeout(_this.connectTimeoutTimer_);
  1311. _this.connectTimeoutTimer_ = null;
  1312. }
  1313. _this.everConnected_ = true;
  1314. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1315. _this.id = arg1;
  1316. _this.password = arg2;
  1317. }
  1318. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1319. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1320. if (arg1) {
  1321. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1322. // through our already open polls), so don't send any more.
  1323. _this.scriptTagHolder.sendNewPolls = false;
  1324. // arg1 in this case is the last response number sent by the server. We should try to receive
  1325. // all of the responses up to this one before closing
  1326. _this.myPacketOrderer.closeAfter(arg1, function () {
  1327. _this.onClosed_();
  1328. });
  1329. }
  1330. else {
  1331. _this.onClosed_();
  1332. }
  1333. }
  1334. else {
  1335. throw new Error('Unrecognized command received: ' + command);
  1336. }
  1337. }, function () {
  1338. var args = [];
  1339. for (var _i = 0; _i < arguments.length; _i++) {
  1340. args[_i] = arguments[_i];
  1341. }
  1342. var _a = __read(args, 2), pN = _a[0], data = _a[1];
  1343. _this.incrementIncomingBytes_(args);
  1344. _this.myPacketOrderer.handleResponse(pN, data);
  1345. }, function () {
  1346. _this.onClosed_();
  1347. }, _this.urlFn);
  1348. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1349. //from cache.
  1350. var urlParams = {};
  1351. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1352. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1353. if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
  1354. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1355. _this.scriptTagHolder.uniqueCallbackIdentifier;
  1356. }
  1357. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1358. if (_this.transportSessionId) {
  1359. urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
  1360. }
  1361. if (_this.lastSessionId) {
  1362. urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
  1363. }
  1364. if (_this.applicationId) {
  1365. urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
  1366. }
  1367. if (_this.appCheckToken) {
  1368. urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1369. }
  1370. if (typeof location !== 'undefined' &&
  1371. location.hostname &&
  1372. FORGE_DOMAIN_RE.test(location.hostname)) {
  1373. urlParams[REFERER_PARAM] = FORGE_REF;
  1374. }
  1375. var connectURL = _this.urlFn(urlParams);
  1376. _this.log_('Connecting via long-poll to ' + connectURL);
  1377. _this.scriptTagHolder.addTag(connectURL, function () {
  1378. /* do nothing */
  1379. });
  1380. });
  1381. };
  1382. /**
  1383. * Call this when a handshake has completed successfully and we want to consider the connection established
  1384. */
  1385. BrowserPollConnection.prototype.start = function () {
  1386. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1387. this.addDisconnectPingFrame(this.id, this.password);
  1388. };
  1389. /**
  1390. * Forces long polling to be considered as a potential transport
  1391. */
  1392. BrowserPollConnection.forceAllow = function () {
  1393. BrowserPollConnection.forceAllow_ = true;
  1394. };
  1395. /**
  1396. * Forces longpolling to not be considered as a potential transport
  1397. */
  1398. BrowserPollConnection.forceDisallow = function () {
  1399. BrowserPollConnection.forceDisallow_ = true;
  1400. };
  1401. // Static method, use string literal so it can be accessed in a generic way
  1402. BrowserPollConnection.isAvailable = function () {
  1403. if (isNodeSdk()) {
  1404. return false;
  1405. }
  1406. else if (BrowserPollConnection.forceAllow_) {
  1407. return true;
  1408. }
  1409. else {
  1410. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1411. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1412. return (!BrowserPollConnection.forceDisallow_ &&
  1413. typeof document !== 'undefined' &&
  1414. document.createElement != null &&
  1415. !isChromeExtensionContentScript() &&
  1416. !isWindowsStoreApp());
  1417. }
  1418. };
  1419. /**
  1420. * No-op for polling
  1421. */
  1422. BrowserPollConnection.prototype.markConnectionHealthy = function () { };
  1423. /**
  1424. * Stops polling and cleans up the iframe
  1425. */
  1426. BrowserPollConnection.prototype.shutdown_ = function () {
  1427. this.isClosed_ = true;
  1428. if (this.scriptTagHolder) {
  1429. this.scriptTagHolder.close();
  1430. this.scriptTagHolder = null;
  1431. }
  1432. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1433. if (this.myDisconnFrame) {
  1434. document.body.removeChild(this.myDisconnFrame);
  1435. this.myDisconnFrame = null;
  1436. }
  1437. if (this.connectTimeoutTimer_) {
  1438. clearTimeout(this.connectTimeoutTimer_);
  1439. this.connectTimeoutTimer_ = null;
  1440. }
  1441. };
  1442. /**
  1443. * Triggered when this transport is closed
  1444. */
  1445. BrowserPollConnection.prototype.onClosed_ = function () {
  1446. if (!this.isClosed_) {
  1447. this.log_('Longpoll is closing itself');
  1448. this.shutdown_();
  1449. if (this.onDisconnect_) {
  1450. this.onDisconnect_(this.everConnected_);
  1451. this.onDisconnect_ = null;
  1452. }
  1453. }
  1454. };
  1455. /**
  1456. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1457. * that we've left.
  1458. */
  1459. BrowserPollConnection.prototype.close = function () {
  1460. if (!this.isClosed_) {
  1461. this.log_('Longpoll is being closed.');
  1462. this.shutdown_();
  1463. }
  1464. };
  1465. /**
  1466. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1467. * broken into chunks (since URLs have a small maximum length).
  1468. * @param data - The JSON data to transmit.
  1469. */
  1470. BrowserPollConnection.prototype.send = function (data) {
  1471. var dataStr = stringify(data);
  1472. this.bytesSent += dataStr.length;
  1473. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1474. //first, lets get the base64-encoded data
  1475. var base64data = base64Encode(dataStr);
  1476. //We can only fit a certain amount in each URL, so we need to split this request
  1477. //up into multiple pieces if it doesn't fit in one request.
  1478. var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1479. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1480. //of segments so that we can reassemble the packet on the server.
  1481. for (var i = 0; i < dataSegs.length; i++) {
  1482. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1483. this.curSegmentNum++;
  1484. }
  1485. };
  1486. /**
  1487. * This is how we notify the server that we're leaving.
  1488. * We aren't able to send requests with DHTML on a window close event, but we can
  1489. * trigger XHR requests in some browsers (everything but Opera basically).
  1490. */
  1491. BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
  1492. if (isNodeSdk()) {
  1493. return;
  1494. }
  1495. this.myDisconnFrame = document.createElement('iframe');
  1496. var urlParams = {};
  1497. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1498. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1499. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1500. this.myDisconnFrame.src = this.urlFn(urlParams);
  1501. this.myDisconnFrame.style.display = 'none';
  1502. document.body.appendChild(this.myDisconnFrame);
  1503. };
  1504. /**
  1505. * Used to track the bytes received by this client
  1506. */
  1507. BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
  1508. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1509. var bytesReceived = stringify(args).length;
  1510. this.bytesReceived += bytesReceived;
  1511. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1512. };
  1513. return BrowserPollConnection;
  1514. }());
  1515. /*********************************************************************************************
  1516. * A wrapper around an iframe that is used as a long-polling script holder.
  1517. *********************************************************************************************/
  1518. var FirebaseIFrameScriptHolder = /** @class */ (function () {
  1519. /**
  1520. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1521. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1522. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1523. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1524. */
  1525. function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
  1526. this.onDisconnect = onDisconnect;
  1527. this.urlFn = urlFn;
  1528. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1529. //problems in some browsers.
  1530. this.outstandingRequests = new Set();
  1531. //A queue of the pending segments waiting for transmission to the server.
  1532. this.pendingSegs = [];
  1533. //A serial number. We use this for two things:
  1534. // 1) A way to ensure the browser doesn't cache responses to polls
  1535. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1536. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1537. // JSONP code in the order it was added to the iframe.
  1538. this.currentSerial = Math.floor(Math.random() * 100000000);
  1539. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1540. // incoming data from the server that we're waiting for).
  1541. this.sendNewPolls = true;
  1542. if (!isNodeSdk()) {
  1543. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1544. //iframes where we put the long-polling script tags. We have two callbacks:
  1545. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1546. // 2) Message Callback - Triggered when new data arrives.
  1547. this.uniqueCallbackIdentifier = LUIDGenerator();
  1548. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1549. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1550. onMessageCB;
  1551. //Create an iframe for us to add script tags to.
  1552. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1553. // Set the iframe's contents.
  1554. var script = '';
  1555. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1556. // for ie9, but ie8 needs to do it again in the document itself.
  1557. if (this.myIFrame.src &&
  1558. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1559. var currentDomain = document.domain;
  1560. script = '<script>document.domain="' + currentDomain + '";</script>';
  1561. }
  1562. var iframeContents = '<html><body>' + script + '</body></html>';
  1563. try {
  1564. this.myIFrame.doc.open();
  1565. this.myIFrame.doc.write(iframeContents);
  1566. this.myIFrame.doc.close();
  1567. }
  1568. catch (e) {
  1569. log('frame writing exception');
  1570. if (e.stack) {
  1571. log(e.stack);
  1572. }
  1573. log(e);
  1574. }
  1575. }
  1576. else {
  1577. this.commandCB = commandCB;
  1578. this.onMessageCB = onMessageCB;
  1579. }
  1580. }
  1581. /**
  1582. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1583. * actually use.
  1584. */
  1585. FirebaseIFrameScriptHolder.createIFrame_ = function () {
  1586. var iframe = document.createElement('iframe');
  1587. iframe.style.display = 'none';
  1588. // This is necessary in order to initialize the document inside the iframe
  1589. if (document.body) {
  1590. document.body.appendChild(iframe);
  1591. try {
  1592. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1593. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1594. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1595. var a = iframe.contentWindow.document;
  1596. if (!a) {
  1597. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1598. log('No IE domain setting required');
  1599. }
  1600. }
  1601. catch (e) {
  1602. var domain = document.domain;
  1603. iframe.src =
  1604. "javascript:void((function(){document.open();document.domain='" +
  1605. domain +
  1606. "';document.close();})())";
  1607. }
  1608. }
  1609. else {
  1610. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1611. // never gets hit.
  1612. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1613. }
  1614. // Get the document of the iframe in a browser-specific way.
  1615. if (iframe.contentDocument) {
  1616. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1617. }
  1618. else if (iframe.contentWindow) {
  1619. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1620. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1621. }
  1622. else if (iframe.document) {
  1623. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1624. iframe.doc = iframe.document; //others?
  1625. }
  1626. return iframe;
  1627. };
  1628. /**
  1629. * Cancel all outstanding queries and remove the frame.
  1630. */
  1631. FirebaseIFrameScriptHolder.prototype.close = function () {
  1632. var _this = this;
  1633. //Mark this iframe as dead, so no new requests are sent.
  1634. this.alive = false;
  1635. if (this.myIFrame) {
  1636. //We have to actually remove all of the html inside this iframe before removing it from the
  1637. //window, or IE will continue loading and executing the script tags we've already added, which
  1638. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1639. this.myIFrame.doc.body.textContent = '';
  1640. setTimeout(function () {
  1641. if (_this.myIFrame !== null) {
  1642. document.body.removeChild(_this.myIFrame);
  1643. _this.myIFrame = null;
  1644. }
  1645. }, Math.floor(0));
  1646. }
  1647. // Protect from being called recursively.
  1648. var onDisconnect = this.onDisconnect;
  1649. if (onDisconnect) {
  1650. this.onDisconnect = null;
  1651. onDisconnect();
  1652. }
  1653. };
  1654. /**
  1655. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1656. * @param id - The ID of this connection
  1657. * @param pw - The password for this connection
  1658. */
  1659. FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
  1660. this.myID = id;
  1661. this.myPW = pw;
  1662. this.alive = true;
  1663. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1664. while (this.newRequest_()) { }
  1665. };
  1666. /**
  1667. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1668. * too many outstanding requests and we are still alive.
  1669. *
  1670. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1671. * needed.
  1672. */
  1673. FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
  1674. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1675. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1676. // close the old request.
  1677. if (this.alive &&
  1678. this.sendNewPolls &&
  1679. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1680. //construct our url
  1681. this.currentSerial++;
  1682. var urlParams = {};
  1683. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1684. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1685. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1686. var theURL = this.urlFn(urlParams);
  1687. //Now add as much data as we can.
  1688. var curDataString = '';
  1689. var i = 0;
  1690. while (this.pendingSegs.length > 0) {
  1691. //first, lets see if the next segment will fit.
  1692. var nextSeg = this.pendingSegs[0];
  1693. if (nextSeg.d.length +
  1694. SEG_HEADER_SIZE +
  1695. curDataString.length <=
  1696. MAX_URL_DATA_SIZE) {
  1697. //great, the segment will fit. Lets append it.
  1698. var theSeg = this.pendingSegs.shift();
  1699. curDataString =
  1700. curDataString +
  1701. '&' +
  1702. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1703. i +
  1704. '=' +
  1705. theSeg.seg +
  1706. '&' +
  1707. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1708. i +
  1709. '=' +
  1710. theSeg.ts +
  1711. '&' +
  1712. FIREBASE_LONGPOLL_DATA_PARAM +
  1713. i +
  1714. '=' +
  1715. theSeg.d;
  1716. i++;
  1717. }
  1718. else {
  1719. break;
  1720. }
  1721. }
  1722. theURL = theURL + curDataString;
  1723. this.addLongPollTag_(theURL, this.currentSerial);
  1724. return true;
  1725. }
  1726. else {
  1727. return false;
  1728. }
  1729. };
  1730. /**
  1731. * Queue a packet for transmission to the server.
  1732. * @param segnum - A sequential id for this packet segment used for reassembly
  1733. * @param totalsegs - The total number of segments in this packet
  1734. * @param data - The data for this segment.
  1735. */
  1736. FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
  1737. //add this to the queue of segments to send.
  1738. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  1739. //send the data immediately if there isn't already data being transmitted, unless
  1740. //startLongPoll hasn't been called yet.
  1741. if (this.alive) {
  1742. this.newRequest_();
  1743. }
  1744. };
  1745. /**
  1746. * Add a script tag for a regular long-poll request.
  1747. * @param url - The URL of the script tag.
  1748. * @param serial - The serial number of the request.
  1749. */
  1750. FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
  1751. var _this = this;
  1752. //remember that we sent this request.
  1753. this.outstandingRequests.add(serial);
  1754. var doNewRequest = function () {
  1755. _this.outstandingRequests.delete(serial);
  1756. _this.newRequest_();
  1757. };
  1758. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  1759. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  1760. var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  1761. var readyStateCB = function () {
  1762. // Request completed. Cancel the keepalive.
  1763. clearTimeout(keepaliveTimeout);
  1764. // Trigger a new request so we can continue receiving data.
  1765. doNewRequest();
  1766. };
  1767. this.addTag(url, readyStateCB);
  1768. };
  1769. /**
  1770. * Add an arbitrary script tag to the iframe.
  1771. * @param url - The URL for the script tag source.
  1772. * @param loadCB - A callback to be triggered once the script has loaded.
  1773. */
  1774. FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
  1775. var _this = this;
  1776. if (isNodeSdk()) {
  1777. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1778. this.doNodeLongPoll(url, loadCB);
  1779. }
  1780. else {
  1781. setTimeout(function () {
  1782. try {
  1783. // if we're already closed, don't add this poll
  1784. if (!_this.sendNewPolls) {
  1785. return;
  1786. }
  1787. var newScript_1 = _this.myIFrame.doc.createElement('script');
  1788. newScript_1.type = 'text/javascript';
  1789. newScript_1.async = true;
  1790. newScript_1.src = url;
  1791. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1792. newScript_1.onload = newScript_1.onreadystatechange =
  1793. function () {
  1794. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1795. var rstate = newScript_1.readyState;
  1796. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  1797. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1798. newScript_1.onload = newScript_1.onreadystatechange = null;
  1799. if (newScript_1.parentNode) {
  1800. newScript_1.parentNode.removeChild(newScript_1);
  1801. }
  1802. loadCB();
  1803. }
  1804. };
  1805. newScript_1.onerror = function () {
  1806. log('Long-poll script failed to load: ' + url);
  1807. _this.sendNewPolls = false;
  1808. _this.close();
  1809. };
  1810. _this.myIFrame.doc.body.appendChild(newScript_1);
  1811. }
  1812. catch (e) {
  1813. // TODO: we should make this error visible somehow
  1814. }
  1815. }, Math.floor(1));
  1816. }
  1817. };
  1818. return FirebaseIFrameScriptHolder;
  1819. }());
  1820. /**
  1821. * @license
  1822. * Copyright 2017 Google LLC
  1823. *
  1824. * Licensed under the Apache License, Version 2.0 (the "License");
  1825. * you may not use this file except in compliance with the License.
  1826. * You may obtain a copy of the License at
  1827. *
  1828. * http://www.apache.org/licenses/LICENSE-2.0
  1829. *
  1830. * Unless required by applicable law or agreed to in writing, software
  1831. * distributed under the License is distributed on an "AS IS" BASIS,
  1832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1833. * See the License for the specific language governing permissions and
  1834. * limitations under the License.
  1835. */
  1836. var WEBSOCKET_MAX_FRAME_SIZE = 16384;
  1837. var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  1838. var WebSocketImpl = null;
  1839. if (typeof MozWebSocket !== 'undefined') {
  1840. WebSocketImpl = MozWebSocket;
  1841. }
  1842. else if (typeof WebSocket !== 'undefined') {
  1843. WebSocketImpl = WebSocket;
  1844. }
  1845. /**
  1846. * Create a new websocket connection with the given callbacks.
  1847. */
  1848. var WebSocketConnection = /** @class */ (function () {
  1849. /**
  1850. * @param connId identifier for this transport
  1851. * @param repoInfo The info for the websocket endpoint.
  1852. * @param applicationId The Firebase App ID for this project.
  1853. * @param appCheckToken The App Check Token for this client.
  1854. * @param authToken The Auth Token for this client.
  1855. * @param transportSessionId Optional transportSessionId if this is connecting
  1856. * to an existing transport session
  1857. * @param lastSessionId Optional lastSessionId if there was a previous
  1858. * connection
  1859. */
  1860. function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1861. this.connId = connId;
  1862. this.applicationId = applicationId;
  1863. this.appCheckToken = appCheckToken;
  1864. this.authToken = authToken;
  1865. this.keepaliveTimer = null;
  1866. this.frames = null;
  1867. this.totalFrames = 0;
  1868. this.bytesSent = 0;
  1869. this.bytesReceived = 0;
  1870. this.log_ = logWrapper(this.connId);
  1871. this.stats_ = statsManagerGetCollection(repoInfo);
  1872. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  1873. this.nodeAdmin = repoInfo.nodeAdmin;
  1874. }
  1875. /**
  1876. * @param repoInfo - The info for the websocket endpoint.
  1877. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  1878. * session
  1879. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  1880. * @returns connection url
  1881. */
  1882. WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  1883. var urlParams = {};
  1884. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1885. if (!isNodeSdk() &&
  1886. typeof location !== 'undefined' &&
  1887. location.hostname &&
  1888. FORGE_DOMAIN_RE.test(location.hostname)) {
  1889. urlParams[REFERER_PARAM] = FORGE_REF;
  1890. }
  1891. if (transportSessionId) {
  1892. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1893. }
  1894. if (lastSessionId) {
  1895. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1896. }
  1897. if (appCheckToken) {
  1898. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1899. }
  1900. if (applicationId) {
  1901. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1902. }
  1903. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1904. };
  1905. /**
  1906. * @param onMessage - Callback when messages arrive
  1907. * @param onDisconnect - Callback with connection lost.
  1908. */
  1909. WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
  1910. var _this = this;
  1911. this.onDisconnect = onDisconnect;
  1912. this.onMessage = onMessage;
  1913. this.log_('Websocket connecting to ' + this.connURL);
  1914. this.everConnected_ = false;
  1915. // Assume failure until proven otherwise.
  1916. PersistentStorage.set('previous_websocket_failure', true);
  1917. try {
  1918. var options = void 0;
  1919. if (isNodeSdk()) {
  1920. var device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1921. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1922. options = {
  1923. headers: {
  1924. 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
  1925. 'X-Firebase-GMPID': this.applicationId || ''
  1926. }
  1927. };
  1928. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1929. // Note that we send the credentials here even if they aren't admin credentials, which is
  1930. // not a problem.
  1931. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1932. // through the websocket connection once it is established.
  1933. if (this.authToken) {
  1934. options.headers['Authorization'] = "Bearer ".concat(this.authToken);
  1935. }
  1936. if (this.appCheckToken) {
  1937. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1938. }
  1939. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1940. var env = process['env'];
  1941. var proxy = this.connURL.indexOf('wss://') === 0
  1942. ? env['HTTPS_PROXY'] || env['https_proxy']
  1943. : env['HTTP_PROXY'] || env['http_proxy'];
  1944. if (proxy) {
  1945. options['proxy'] = { origin: proxy };
  1946. }
  1947. }
  1948. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1949. }
  1950. catch (e) {
  1951. this.log_('Error instantiating WebSocket.');
  1952. var error = e.message || e.data;
  1953. if (error) {
  1954. this.log_(error);
  1955. }
  1956. this.onClosed_();
  1957. return;
  1958. }
  1959. this.mySock.onopen = function () {
  1960. _this.log_('Websocket connected.');
  1961. _this.everConnected_ = true;
  1962. };
  1963. this.mySock.onclose = function () {
  1964. _this.log_('Websocket connection was disconnected.');
  1965. _this.mySock = null;
  1966. _this.onClosed_();
  1967. };
  1968. this.mySock.onmessage = function (m) {
  1969. _this.handleIncomingFrame(m);
  1970. };
  1971. this.mySock.onerror = function (e) {
  1972. _this.log_('WebSocket error. Closing connection.');
  1973. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1974. var error = e.message || e.data;
  1975. if (error) {
  1976. _this.log_(error);
  1977. }
  1978. _this.onClosed_();
  1979. };
  1980. };
  1981. /**
  1982. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1983. */
  1984. WebSocketConnection.prototype.start = function () { };
  1985. WebSocketConnection.forceDisallow = function () {
  1986. WebSocketConnection.forceDisallow_ = true;
  1987. };
  1988. WebSocketConnection.isAvailable = function () {
  1989. var isOldAndroid = false;
  1990. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1991. var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1992. var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1993. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1994. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1995. isOldAndroid = true;
  1996. }
  1997. }
  1998. }
  1999. return (!isOldAndroid &&
  2000. WebSocketImpl !== null &&
  2001. !WebSocketConnection.forceDisallow_);
  2002. };
  2003. /**
  2004. * Returns true if we previously failed to connect with this transport.
  2005. */
  2006. WebSocketConnection.previouslyFailed = function () {
  2007. // If our persistent storage is actually only in-memory storage,
  2008. // we default to assuming that it previously failed to be safe.
  2009. return (PersistentStorage.isInMemoryStorage ||
  2010. PersistentStorage.get('previous_websocket_failure') === true);
  2011. };
  2012. WebSocketConnection.prototype.markConnectionHealthy = function () {
  2013. PersistentStorage.remove('previous_websocket_failure');
  2014. };
  2015. WebSocketConnection.prototype.appendFrame_ = function (data) {
  2016. this.frames.push(data);
  2017. if (this.frames.length === this.totalFrames) {
  2018. var fullMess = this.frames.join('');
  2019. this.frames = null;
  2020. var jsonMess = jsonEval(fullMess);
  2021. //handle the message
  2022. this.onMessage(jsonMess);
  2023. }
  2024. };
  2025. /**
  2026. * @param frameCount - The number of frames we are expecting from the server
  2027. */
  2028. WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
  2029. this.totalFrames = frameCount;
  2030. this.frames = [];
  2031. };
  2032. /**
  2033. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  2034. * @returns Any remaining data to be process, or null if there is none
  2035. */
  2036. WebSocketConnection.prototype.extractFrameCount_ = function (data) {
  2037. assert(this.frames === null, 'We already have a frame buffer');
  2038. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  2039. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  2040. if (data.length <= 6) {
  2041. var frameCount = Number(data);
  2042. if (!isNaN(frameCount)) {
  2043. this.handleNewFrameCount_(frameCount);
  2044. return null;
  2045. }
  2046. }
  2047. this.handleNewFrameCount_(1);
  2048. return data;
  2049. };
  2050. /**
  2051. * Process a websocket frame that has arrived from the server.
  2052. * @param mess - The frame data
  2053. */
  2054. WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
  2055. if (this.mySock === null) {
  2056. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  2057. }
  2058. var data = mess['data'];
  2059. this.bytesReceived += data.length;
  2060. this.stats_.incrementCounter('bytes_received', data.length);
  2061. this.resetKeepAlive();
  2062. if (this.frames !== null) {
  2063. // we're buffering
  2064. this.appendFrame_(data);
  2065. }
  2066. else {
  2067. // try to parse out a frame count, otherwise, assume 1 and process it
  2068. var remainingData = this.extractFrameCount_(data);
  2069. if (remainingData !== null) {
  2070. this.appendFrame_(remainingData);
  2071. }
  2072. }
  2073. };
  2074. /**
  2075. * Send a message to the server
  2076. * @param data - The JSON object to transmit
  2077. */
  2078. WebSocketConnection.prototype.send = function (data) {
  2079. this.resetKeepAlive();
  2080. var dataStr = stringify(data);
  2081. this.bytesSent += dataStr.length;
  2082. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  2083. //We can only fit a certain amount in each websocket frame, so we need to split this request
  2084. //up into multiple pieces if it doesn't fit in one request.
  2085. var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  2086. //Send the length header
  2087. if (dataSegs.length > 1) {
  2088. this.sendString_(String(dataSegs.length));
  2089. }
  2090. //Send the actual data in segments.
  2091. for (var i = 0; i < dataSegs.length; i++) {
  2092. this.sendString_(dataSegs[i]);
  2093. }
  2094. };
  2095. WebSocketConnection.prototype.shutdown_ = function () {
  2096. this.isClosed_ = true;
  2097. if (this.keepaliveTimer) {
  2098. clearInterval(this.keepaliveTimer);
  2099. this.keepaliveTimer = null;
  2100. }
  2101. if (this.mySock) {
  2102. this.mySock.close();
  2103. this.mySock = null;
  2104. }
  2105. };
  2106. WebSocketConnection.prototype.onClosed_ = function () {
  2107. if (!this.isClosed_) {
  2108. this.log_('WebSocket is closing itself');
  2109. this.shutdown_();
  2110. // since this is an internal close, trigger the close listener
  2111. if (this.onDisconnect) {
  2112. this.onDisconnect(this.everConnected_);
  2113. this.onDisconnect = null;
  2114. }
  2115. }
  2116. };
  2117. /**
  2118. * External-facing close handler.
  2119. * Close the websocket and kill the connection.
  2120. */
  2121. WebSocketConnection.prototype.close = function () {
  2122. if (!this.isClosed_) {
  2123. this.log_('WebSocket is being closed');
  2124. this.shutdown_();
  2125. }
  2126. };
  2127. /**
  2128. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  2129. * the last activity.
  2130. */
  2131. WebSocketConnection.prototype.resetKeepAlive = function () {
  2132. var _this = this;
  2133. clearInterval(this.keepaliveTimer);
  2134. this.keepaliveTimer = setInterval(function () {
  2135. //If there has been no websocket activity for a while, send a no-op
  2136. if (_this.mySock) {
  2137. _this.sendString_('0');
  2138. }
  2139. _this.resetKeepAlive();
  2140. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2141. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  2142. };
  2143. /**
  2144. * Send a string over the websocket.
  2145. *
  2146. * @param str - String to send.
  2147. */
  2148. WebSocketConnection.prototype.sendString_ = function (str) {
  2149. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  2150. // calls for some unknown reason. We treat these as an error and disconnect.
  2151. // See https://app.asana.com/0/58926111402292/68021340250410
  2152. try {
  2153. this.mySock.send(str);
  2154. }
  2155. catch (e) {
  2156. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  2157. setTimeout(this.onClosed_.bind(this), 0);
  2158. }
  2159. };
  2160. /**
  2161. * Number of response before we consider the connection "healthy."
  2162. */
  2163. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  2164. /**
  2165. * Time to wait for the connection te become healthy before giving up.
  2166. */
  2167. WebSocketConnection.healthyTimeout = 30000;
  2168. return WebSocketConnection;
  2169. }());
  2170. /**
  2171. * @license
  2172. * Copyright 2017 Google LLC
  2173. *
  2174. * Licensed under the Apache License, Version 2.0 (the "License");
  2175. * you may not use this file except in compliance with the License.
  2176. * You may obtain a copy of the License at
  2177. *
  2178. * http://www.apache.org/licenses/LICENSE-2.0
  2179. *
  2180. * Unless required by applicable law or agreed to in writing, software
  2181. * distributed under the License is distributed on an "AS IS" BASIS,
  2182. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2183. * See the License for the specific language governing permissions and
  2184. * limitations under the License.
  2185. */
  2186. /**
  2187. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2188. * lifecycle.
  2189. *
  2190. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2191. * they are available.
  2192. */
  2193. var TransportManager = /** @class */ (function () {
  2194. /**
  2195. * @param repoInfo - Metadata around the namespace we're connecting to
  2196. */
  2197. function TransportManager(repoInfo) {
  2198. this.initTransports_(repoInfo);
  2199. }
  2200. Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
  2201. get: function () {
  2202. return [BrowserPollConnection, WebSocketConnection];
  2203. },
  2204. enumerable: false,
  2205. configurable: true
  2206. });
  2207. Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
  2208. /**
  2209. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2210. * TransportManager has already set up transports_
  2211. */
  2212. get: function () {
  2213. return this.globalTransportInitialized_;
  2214. },
  2215. enumerable: false,
  2216. configurable: true
  2217. });
  2218. TransportManager.prototype.initTransports_ = function (repoInfo) {
  2219. var e_1, _a;
  2220. var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2221. var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2222. if (repoInfo.webSocketOnly) {
  2223. if (!isWebSocketsAvailable) {
  2224. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2225. }
  2226. isSkipPollConnection = true;
  2227. }
  2228. if (isSkipPollConnection) {
  2229. this.transports_ = [WebSocketConnection];
  2230. }
  2231. else {
  2232. var transports = (this.transports_ = []);
  2233. try {
  2234. for (var _b = __values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
  2235. var transport = _c.value;
  2236. if (transport && transport['isAvailable']()) {
  2237. transports.push(transport);
  2238. }
  2239. }
  2240. }
  2241. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2242. finally {
  2243. try {
  2244. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  2245. }
  2246. finally { if (e_1) throw e_1.error; }
  2247. }
  2248. TransportManager.globalTransportInitialized_ = true;
  2249. }
  2250. };
  2251. /**
  2252. * @returns The constructor for the initial transport to use
  2253. */
  2254. TransportManager.prototype.initialTransport = function () {
  2255. if (this.transports_.length > 0) {
  2256. return this.transports_[0];
  2257. }
  2258. else {
  2259. throw new Error('No transports available');
  2260. }
  2261. };
  2262. /**
  2263. * @returns The constructor for the next transport, or null
  2264. */
  2265. TransportManager.prototype.upgradeTransport = function () {
  2266. if (this.transports_.length > 1) {
  2267. return this.transports_[1];
  2268. }
  2269. else {
  2270. return null;
  2271. }
  2272. };
  2273. // Keeps track of whether the TransportManager has already chosen a transport to use
  2274. TransportManager.globalTransportInitialized_ = false;
  2275. return TransportManager;
  2276. }());
  2277. /**
  2278. * @license
  2279. * Copyright 2017 Google LLC
  2280. *
  2281. * Licensed under the Apache License, Version 2.0 (the "License");
  2282. * you may not use this file except in compliance with the License.
  2283. * You may obtain a copy of the License at
  2284. *
  2285. * http://www.apache.org/licenses/LICENSE-2.0
  2286. *
  2287. * Unless required by applicable law or agreed to in writing, software
  2288. * distributed under the License is distributed on an "AS IS" BASIS,
  2289. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2290. * See the License for the specific language governing permissions and
  2291. * limitations under the License.
  2292. */
  2293. // Abort upgrade attempt if it takes longer than 60s.
  2294. var UPGRADE_TIMEOUT = 60000;
  2295. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2296. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2297. var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2298. // If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)
  2299. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2300. // but we've sent/received enough bytes, we don't cancel the connection.
  2301. var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2302. var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2303. var MESSAGE_TYPE = 't';
  2304. var MESSAGE_DATA = 'd';
  2305. var CONTROL_SHUTDOWN = 's';
  2306. var CONTROL_RESET = 'r';
  2307. var CONTROL_ERROR = 'e';
  2308. var CONTROL_PONG = 'o';
  2309. var SWITCH_ACK = 'a';
  2310. var END_TRANSMISSION = 'n';
  2311. var PING = 'p';
  2312. var SERVER_HELLO = 'h';
  2313. /**
  2314. * Creates a new real-time connection to the server using whichever method works
  2315. * best in the current browser.
  2316. */
  2317. var Connection = /** @class */ (function () {
  2318. /**
  2319. * @param id - an id for this connection
  2320. * @param repoInfo_ - the info for the endpoint to connect to
  2321. * @param applicationId_ - the Firebase App ID for this project
  2322. * @param appCheckToken_ - The App Check Token for this device.
  2323. * @param authToken_ - The auth token for this session.
  2324. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2325. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2326. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2327. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2328. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2329. */
  2330. function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2331. this.id = id;
  2332. this.repoInfo_ = repoInfo_;
  2333. this.applicationId_ = applicationId_;
  2334. this.appCheckToken_ = appCheckToken_;
  2335. this.authToken_ = authToken_;
  2336. this.onMessage_ = onMessage_;
  2337. this.onReady_ = onReady_;
  2338. this.onDisconnect_ = onDisconnect_;
  2339. this.onKill_ = onKill_;
  2340. this.lastSessionId = lastSessionId;
  2341. this.connectionCount = 0;
  2342. this.pendingDataMessages = [];
  2343. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2344. this.log_ = logWrapper('c:' + this.id + ':');
  2345. this.transportManager_ = new TransportManager(repoInfo_);
  2346. this.log_('Connection created');
  2347. this.start_();
  2348. }
  2349. /**
  2350. * Starts a connection attempt
  2351. */
  2352. Connection.prototype.start_ = function () {
  2353. var _this = this;
  2354. var conn = this.transportManager_.initialTransport();
  2355. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2356. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2357. // can consider the transport healthy.
  2358. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2359. var onMessageReceived = this.connReceiver_(this.conn_);
  2360. var onConnectionLost = this.disconnReceiver_(this.conn_);
  2361. this.tx_ = this.conn_;
  2362. this.rx_ = this.conn_;
  2363. this.secondaryConn_ = null;
  2364. this.isHealthy_ = false;
  2365. /*
  2366. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2367. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2368. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2369. * still have the context of your originating frame.
  2370. */
  2371. setTimeout(function () {
  2372. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2373. _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
  2374. }, Math.floor(0));
  2375. var healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2376. if (healthyTimeoutMS > 0) {
  2377. this.healthyTimeout_ = setTimeoutNonBlocking(function () {
  2378. _this.healthyTimeout_ = null;
  2379. if (!_this.isHealthy_) {
  2380. if (_this.conn_ &&
  2381. _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2382. _this.log_('Connection exceeded healthy timeout but has received ' +
  2383. _this.conn_.bytesReceived +
  2384. ' bytes. Marking connection healthy.');
  2385. _this.isHealthy_ = true;
  2386. _this.conn_.markConnectionHealthy();
  2387. }
  2388. else if (_this.conn_ &&
  2389. _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2390. _this.log_('Connection exceeded healthy timeout but has sent ' +
  2391. _this.conn_.bytesSent +
  2392. ' bytes. Leaving connection alive.');
  2393. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2394. // the server.
  2395. }
  2396. else {
  2397. _this.log_('Closing unhealthy connection after timeout.');
  2398. _this.close();
  2399. }
  2400. }
  2401. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2402. }, Math.floor(healthyTimeoutMS));
  2403. }
  2404. };
  2405. Connection.prototype.nextTransportId_ = function () {
  2406. return 'c:' + this.id + ':' + this.connectionCount++;
  2407. };
  2408. Connection.prototype.disconnReceiver_ = function (conn) {
  2409. var _this = this;
  2410. return function (everConnected) {
  2411. if (conn === _this.conn_) {
  2412. _this.onConnectionLost_(everConnected);
  2413. }
  2414. else if (conn === _this.secondaryConn_) {
  2415. _this.log_('Secondary connection lost.');
  2416. _this.onSecondaryConnectionLost_();
  2417. }
  2418. else {
  2419. _this.log_('closing an old connection');
  2420. }
  2421. };
  2422. };
  2423. Connection.prototype.connReceiver_ = function (conn) {
  2424. var _this = this;
  2425. return function (message) {
  2426. if (_this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2427. if (conn === _this.rx_) {
  2428. _this.onPrimaryMessageReceived_(message);
  2429. }
  2430. else if (conn === _this.secondaryConn_) {
  2431. _this.onSecondaryMessageReceived_(message);
  2432. }
  2433. else {
  2434. _this.log_('message on old connection');
  2435. }
  2436. }
  2437. };
  2438. };
  2439. /**
  2440. * @param dataMsg - An arbitrary data message to be sent to the server
  2441. */
  2442. Connection.prototype.sendRequest = function (dataMsg) {
  2443. // wrap in a data message envelope and send it on
  2444. var msg = { t: 'd', d: dataMsg };
  2445. this.sendData_(msg);
  2446. };
  2447. Connection.prototype.tryCleanupConnection = function () {
  2448. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2449. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2450. this.conn_ = this.secondaryConn_;
  2451. this.secondaryConn_ = null;
  2452. // the server will shutdown the old connection
  2453. }
  2454. };
  2455. Connection.prototype.onSecondaryControl_ = function (controlData) {
  2456. if (MESSAGE_TYPE in controlData) {
  2457. var cmd = controlData[MESSAGE_TYPE];
  2458. if (cmd === SWITCH_ACK) {
  2459. this.upgradeIfSecondaryHealthy_();
  2460. }
  2461. else if (cmd === CONTROL_RESET) {
  2462. // Most likely the session wasn't valid. Abandon the switch attempt
  2463. this.log_('Got a reset on secondary, closing it');
  2464. this.secondaryConn_.close();
  2465. // If we were already using this connection for something, than we need to fully close
  2466. if (this.tx_ === this.secondaryConn_ ||
  2467. this.rx_ === this.secondaryConn_) {
  2468. this.close();
  2469. }
  2470. }
  2471. else if (cmd === CONTROL_PONG) {
  2472. this.log_('got pong on secondary.');
  2473. this.secondaryResponsesRequired_--;
  2474. this.upgradeIfSecondaryHealthy_();
  2475. }
  2476. }
  2477. };
  2478. Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
  2479. var layer = requireKey('t', parsedData);
  2480. var data = requireKey('d', parsedData);
  2481. if (layer === 'c') {
  2482. this.onSecondaryControl_(data);
  2483. }
  2484. else if (layer === 'd') {
  2485. // got a data message, but we're still second connection. Need to buffer it up
  2486. this.pendingDataMessages.push(data);
  2487. }
  2488. else {
  2489. throw new Error('Unknown protocol layer: ' + layer);
  2490. }
  2491. };
  2492. Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
  2493. if (this.secondaryResponsesRequired_ <= 0) {
  2494. this.log_('Secondary connection is healthy.');
  2495. this.isHealthy_ = true;
  2496. this.secondaryConn_.markConnectionHealthy();
  2497. this.proceedWithUpgrade_();
  2498. }
  2499. else {
  2500. // Send a ping to make sure the connection is healthy.
  2501. this.log_('sending ping on secondary.');
  2502. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2503. }
  2504. };
  2505. Connection.prototype.proceedWithUpgrade_ = function () {
  2506. // tell this connection to consider itself open
  2507. this.secondaryConn_.start();
  2508. // send ack
  2509. this.log_('sending client ack on secondary');
  2510. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2511. // send end packet on primary transport, switch to sending on this one
  2512. // can receive on this one, buffer responses until end received on primary transport
  2513. this.log_('Ending transmission on primary');
  2514. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2515. this.tx_ = this.secondaryConn_;
  2516. this.tryCleanupConnection();
  2517. };
  2518. Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
  2519. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2520. var layer = requireKey('t', parsedData);
  2521. var data = requireKey('d', parsedData);
  2522. if (layer === 'c') {
  2523. this.onControl_(data);
  2524. }
  2525. else if (layer === 'd') {
  2526. this.onDataMessage_(data);
  2527. }
  2528. };
  2529. Connection.prototype.onDataMessage_ = function (message) {
  2530. this.onPrimaryResponse_();
  2531. // We don't do anything with data messages, just kick them up a level
  2532. this.onMessage_(message);
  2533. };
  2534. Connection.prototype.onPrimaryResponse_ = function () {
  2535. if (!this.isHealthy_) {
  2536. this.primaryResponsesRequired_--;
  2537. if (this.primaryResponsesRequired_ <= 0) {
  2538. this.log_('Primary connection is healthy.');
  2539. this.isHealthy_ = true;
  2540. this.conn_.markConnectionHealthy();
  2541. }
  2542. }
  2543. };
  2544. Connection.prototype.onControl_ = function (controlData) {
  2545. var cmd = requireKey(MESSAGE_TYPE, controlData);
  2546. if (MESSAGE_DATA in controlData) {
  2547. var payload = controlData[MESSAGE_DATA];
  2548. if (cmd === SERVER_HELLO) {
  2549. var handshakePayload = __assign({}, payload);
  2550. if (this.repoInfo_.isUsingEmulator) {
  2551. // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.
  2552. handshakePayload.h = this.repoInfo_.host;
  2553. }
  2554. this.onHandshake_(handshakePayload);
  2555. }
  2556. else if (cmd === END_TRANSMISSION) {
  2557. this.log_('recvd end transmission on primary');
  2558. this.rx_ = this.secondaryConn_;
  2559. for (var i = 0; i < this.pendingDataMessages.length; ++i) {
  2560. this.onDataMessage_(this.pendingDataMessages[i]);
  2561. }
  2562. this.pendingDataMessages = [];
  2563. this.tryCleanupConnection();
  2564. }
  2565. else if (cmd === CONTROL_SHUTDOWN) {
  2566. // This was previously the 'onKill' callback passed to the lower-level connection
  2567. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2568. this.onConnectionShutdown_(payload);
  2569. }
  2570. else if (cmd === CONTROL_RESET) {
  2571. // payload in this case is the host we should contact
  2572. this.onReset_(payload);
  2573. }
  2574. else if (cmd === CONTROL_ERROR) {
  2575. error('Server Error: ' + payload);
  2576. }
  2577. else if (cmd === CONTROL_PONG) {
  2578. this.log_('got pong on primary.');
  2579. this.onPrimaryResponse_();
  2580. this.sendPingOnPrimaryIfNecessary_();
  2581. }
  2582. else {
  2583. error('Unknown control packet command: ' + cmd);
  2584. }
  2585. }
  2586. };
  2587. /**
  2588. * @param handshake - The handshake data returned from the server
  2589. */
  2590. Connection.prototype.onHandshake_ = function (handshake) {
  2591. var timestamp = handshake.ts;
  2592. var version = handshake.v;
  2593. var host = handshake.h;
  2594. this.sessionId = handshake.s;
  2595. this.repoInfo_.host = host;
  2596. // if we've already closed the connection, then don't bother trying to progress further
  2597. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2598. this.conn_.start();
  2599. this.onConnectionEstablished_(this.conn_, timestamp);
  2600. if (PROTOCOL_VERSION !== version) {
  2601. warn('Protocol version mismatch detected');
  2602. }
  2603. // TODO: do we want to upgrade? when? maybe a delay?
  2604. this.tryStartUpgrade_();
  2605. }
  2606. };
  2607. Connection.prototype.tryStartUpgrade_ = function () {
  2608. var conn = this.transportManager_.upgradeTransport();
  2609. if (conn) {
  2610. this.startUpgrade_(conn);
  2611. }
  2612. };
  2613. Connection.prototype.startUpgrade_ = function (conn) {
  2614. var _this = this;
  2615. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2616. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2617. // can consider the transport healthy.
  2618. this.secondaryResponsesRequired_ =
  2619. conn['responsesRequiredToBeHealthy'] || 0;
  2620. var onMessage = this.connReceiver_(this.secondaryConn_);
  2621. var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2622. this.secondaryConn_.open(onMessage, onDisconnect);
  2623. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2624. setTimeoutNonBlocking(function () {
  2625. if (_this.secondaryConn_) {
  2626. _this.log_('Timed out trying to upgrade.');
  2627. _this.secondaryConn_.close();
  2628. }
  2629. }, Math.floor(UPGRADE_TIMEOUT));
  2630. };
  2631. Connection.prototype.onReset_ = function (host) {
  2632. this.log_('Reset packet received. New host: ' + host);
  2633. this.repoInfo_.host = host;
  2634. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2635. // We don't currently support resets after the connection has already been established
  2636. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2637. this.close();
  2638. }
  2639. else {
  2640. // Close whatever connections we have open and start again.
  2641. this.closeConnections_();
  2642. this.start_();
  2643. }
  2644. };
  2645. Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
  2646. var _this = this;
  2647. this.log_('Realtime connection established.');
  2648. this.conn_ = conn;
  2649. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2650. if (this.onReady_) {
  2651. this.onReady_(timestamp, this.sessionId);
  2652. this.onReady_ = null;
  2653. }
  2654. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2655. // send some pings.
  2656. if (this.primaryResponsesRequired_ === 0) {
  2657. this.log_('Primary connection is healthy.');
  2658. this.isHealthy_ = true;
  2659. }
  2660. else {
  2661. setTimeoutNonBlocking(function () {
  2662. _this.sendPingOnPrimaryIfNecessary_();
  2663. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2664. }
  2665. };
  2666. Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
  2667. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2668. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2669. this.log_('sending ping on primary.');
  2670. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2671. }
  2672. };
  2673. Connection.prototype.onSecondaryConnectionLost_ = function () {
  2674. var conn = this.secondaryConn_;
  2675. this.secondaryConn_ = null;
  2676. if (this.tx_ === conn || this.rx_ === conn) {
  2677. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2678. this.close();
  2679. }
  2680. };
  2681. /**
  2682. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2683. * we should flush the host cache
  2684. */
  2685. Connection.prototype.onConnectionLost_ = function (everConnected) {
  2686. this.conn_ = null;
  2687. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2688. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2689. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2690. this.log_('Realtime connection failed.');
  2691. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2692. if (this.repoInfo_.isCacheableHost()) {
  2693. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2694. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2695. this.repoInfo_.internalHost = this.repoInfo_.host;
  2696. }
  2697. }
  2698. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2699. this.log_('Realtime connection lost.');
  2700. }
  2701. this.close();
  2702. };
  2703. Connection.prototype.onConnectionShutdown_ = function (reason) {
  2704. this.log_('Connection shutdown command received. Shutting down...');
  2705. if (this.onKill_) {
  2706. this.onKill_(reason);
  2707. this.onKill_ = null;
  2708. }
  2709. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2710. // so clear the callback.
  2711. this.onDisconnect_ = null;
  2712. this.close();
  2713. };
  2714. Connection.prototype.sendData_ = function (data) {
  2715. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2716. throw 'Connection is not connected';
  2717. }
  2718. else {
  2719. this.tx_.send(data);
  2720. }
  2721. };
  2722. /**
  2723. * Cleans up this connection, calling the appropriate callbacks
  2724. */
  2725. Connection.prototype.close = function () {
  2726. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2727. this.log_('Closing realtime connection.');
  2728. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2729. this.closeConnections_();
  2730. if (this.onDisconnect_) {
  2731. this.onDisconnect_();
  2732. this.onDisconnect_ = null;
  2733. }
  2734. }
  2735. };
  2736. Connection.prototype.closeConnections_ = function () {
  2737. this.log_('Shutting down all connections');
  2738. if (this.conn_) {
  2739. this.conn_.close();
  2740. this.conn_ = null;
  2741. }
  2742. if (this.secondaryConn_) {
  2743. this.secondaryConn_.close();
  2744. this.secondaryConn_ = null;
  2745. }
  2746. if (this.healthyTimeout_) {
  2747. clearTimeout(this.healthyTimeout_);
  2748. this.healthyTimeout_ = null;
  2749. }
  2750. };
  2751. return Connection;
  2752. }());
  2753. /**
  2754. * @license
  2755. * Copyright 2017 Google LLC
  2756. *
  2757. * Licensed under the Apache License, Version 2.0 (the "License");
  2758. * you may not use this file except in compliance with the License.
  2759. * You may obtain a copy of the License at
  2760. *
  2761. * http://www.apache.org/licenses/LICENSE-2.0
  2762. *
  2763. * Unless required by applicable law or agreed to in writing, software
  2764. * distributed under the License is distributed on an "AS IS" BASIS,
  2765. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2766. * See the License for the specific language governing permissions and
  2767. * limitations under the License.
  2768. */
  2769. /**
  2770. * Interface defining the set of actions that can be performed against the Firebase server
  2771. * (basically corresponds to our wire protocol).
  2772. *
  2773. * @interface
  2774. */
  2775. var ServerActions = /** @class */ (function () {
  2776. function ServerActions() {
  2777. }
  2778. ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
  2779. ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
  2780. /**
  2781. * Refreshes the auth token for the current connection.
  2782. * @param token - The authentication token
  2783. */
  2784. ServerActions.prototype.refreshAuthToken = function (token) { };
  2785. /**
  2786. * Refreshes the app check token for the current connection.
  2787. * @param token The app check token
  2788. */
  2789. ServerActions.prototype.refreshAppCheckToken = function (token) { };
  2790. ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
  2791. ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
  2792. ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
  2793. ServerActions.prototype.reportStats = function (stats) { };
  2794. return ServerActions;
  2795. }());
  2796. /**
  2797. * @license
  2798. * Copyright 2017 Google LLC
  2799. *
  2800. * Licensed under the Apache License, Version 2.0 (the "License");
  2801. * you may not use this file except in compliance with the License.
  2802. * You may obtain a copy of the License at
  2803. *
  2804. * http://www.apache.org/licenses/LICENSE-2.0
  2805. *
  2806. * Unless required by applicable law or agreed to in writing, software
  2807. * distributed under the License is distributed on an "AS IS" BASIS,
  2808. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2809. * See the License for the specific language governing permissions and
  2810. * limitations under the License.
  2811. */
  2812. /**
  2813. * Base class to be used if you want to emit events. Call the constructor with
  2814. * the set of allowed event names.
  2815. */
  2816. var EventEmitter = /** @class */ (function () {
  2817. function EventEmitter(allowedEvents_) {
  2818. this.allowedEvents_ = allowedEvents_;
  2819. this.listeners_ = {};
  2820. assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2821. }
  2822. /**
  2823. * To be called by derived classes to trigger events.
  2824. */
  2825. EventEmitter.prototype.trigger = function (eventType) {
  2826. var varArgs = [];
  2827. for (var _i = 1; _i < arguments.length; _i++) {
  2828. varArgs[_i - 1] = arguments[_i];
  2829. }
  2830. if (Array.isArray(this.listeners_[eventType])) {
  2831. // Clone the list, since callbacks could add/remove listeners.
  2832. var listeners = __spreadArray([], __read(this.listeners_[eventType]), false);
  2833. for (var i = 0; i < listeners.length; i++) {
  2834. listeners[i].callback.apply(listeners[i].context, varArgs);
  2835. }
  2836. }
  2837. };
  2838. EventEmitter.prototype.on = function (eventType, callback, context) {
  2839. this.validateEventType_(eventType);
  2840. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2841. this.listeners_[eventType].push({ callback: callback, context: context });
  2842. var eventData = this.getInitialEvent(eventType);
  2843. if (eventData) {
  2844. callback.apply(context, eventData);
  2845. }
  2846. };
  2847. EventEmitter.prototype.off = function (eventType, callback, context) {
  2848. this.validateEventType_(eventType);
  2849. var listeners = this.listeners_[eventType] || [];
  2850. for (var i = 0; i < listeners.length; i++) {
  2851. if (listeners[i].callback === callback &&
  2852. (!context || context === listeners[i].context)) {
  2853. listeners.splice(i, 1);
  2854. return;
  2855. }
  2856. }
  2857. };
  2858. EventEmitter.prototype.validateEventType_ = function (eventType) {
  2859. assert(this.allowedEvents_.find(function (et) {
  2860. return et === eventType;
  2861. }), 'Unknown event: ' + eventType);
  2862. };
  2863. return EventEmitter;
  2864. }());
  2865. /**
  2866. * @license
  2867. * Copyright 2017 Google LLC
  2868. *
  2869. * Licensed under the Apache License, Version 2.0 (the "License");
  2870. * you may not use this file except in compliance with the License.
  2871. * You may obtain a copy of the License at
  2872. *
  2873. * http://www.apache.org/licenses/LICENSE-2.0
  2874. *
  2875. * Unless required by applicable law or agreed to in writing, software
  2876. * distributed under the License is distributed on an "AS IS" BASIS,
  2877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2878. * See the License for the specific language governing permissions and
  2879. * limitations under the License.
  2880. */
  2881. /**
  2882. * Monitors online state (as reported by window.online/offline events).
  2883. *
  2884. * The expectation is that this could have many false positives (thinks we are online
  2885. * when we're not), but no false negatives. So we can safely use it to determine when
  2886. * we definitely cannot reach the internet.
  2887. */
  2888. var OnlineMonitor = /** @class */ (function (_super) {
  2889. __extends(OnlineMonitor, _super);
  2890. function OnlineMonitor() {
  2891. var _this = _super.call(this, ['online']) || this;
  2892. _this.online_ = true;
  2893. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2894. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2895. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2896. // for Cordova.
  2897. if (typeof window !== 'undefined' &&
  2898. typeof window.addEventListener !== 'undefined' &&
  2899. !isMobileCordova()) {
  2900. window.addEventListener('online', function () {
  2901. if (!_this.online_) {
  2902. _this.online_ = true;
  2903. _this.trigger('online', true);
  2904. }
  2905. }, false);
  2906. window.addEventListener('offline', function () {
  2907. if (_this.online_) {
  2908. _this.online_ = false;
  2909. _this.trigger('online', false);
  2910. }
  2911. }, false);
  2912. }
  2913. return _this;
  2914. }
  2915. OnlineMonitor.getInstance = function () {
  2916. return new OnlineMonitor();
  2917. };
  2918. OnlineMonitor.prototype.getInitialEvent = function (eventType) {
  2919. assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2920. return [this.online_];
  2921. };
  2922. OnlineMonitor.prototype.currentlyOnline = function () {
  2923. return this.online_;
  2924. };
  2925. return OnlineMonitor;
  2926. }(EventEmitter));
  2927. /**
  2928. * @license
  2929. * Copyright 2017 Google LLC
  2930. *
  2931. * Licensed under the Apache License, Version 2.0 (the "License");
  2932. * you may not use this file except in compliance with the License.
  2933. * You may obtain a copy of the License at
  2934. *
  2935. * http://www.apache.org/licenses/LICENSE-2.0
  2936. *
  2937. * Unless required by applicable law or agreed to in writing, software
  2938. * distributed under the License is distributed on an "AS IS" BASIS,
  2939. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2940. * See the License for the specific language governing permissions and
  2941. * limitations under the License.
  2942. */
  2943. /** Maximum key depth. */
  2944. var MAX_PATH_DEPTH = 32;
  2945. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2946. var MAX_PATH_LENGTH_BYTES = 768;
  2947. /**
  2948. * An immutable object representing a parsed path. It's immutable so that you
  2949. * can pass them around to other functions without worrying about them changing
  2950. * it.
  2951. */
  2952. var Path = /** @class */ (function () {
  2953. /**
  2954. * @param pathOrString - Path string to parse, or another path, or the raw
  2955. * tokens array
  2956. */
  2957. function Path(pathOrString, pieceNum) {
  2958. if (pieceNum === void 0) {
  2959. this.pieces_ = pathOrString.split('/');
  2960. // Remove empty pieces.
  2961. var copyTo = 0;
  2962. for (var i = 0; i < this.pieces_.length; i++) {
  2963. if (this.pieces_[i].length > 0) {
  2964. this.pieces_[copyTo] = this.pieces_[i];
  2965. copyTo++;
  2966. }
  2967. }
  2968. this.pieces_.length = copyTo;
  2969. this.pieceNum_ = 0;
  2970. }
  2971. else {
  2972. this.pieces_ = pathOrString;
  2973. this.pieceNum_ = pieceNum;
  2974. }
  2975. }
  2976. Path.prototype.toString = function () {
  2977. var pathString = '';
  2978. for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
  2979. if (this.pieces_[i] !== '') {
  2980. pathString += '/' + this.pieces_[i];
  2981. }
  2982. }
  2983. return pathString || '/';
  2984. };
  2985. return Path;
  2986. }());
  2987. function newEmptyPath() {
  2988. return new Path('');
  2989. }
  2990. function pathGetFront(path) {
  2991. if (path.pieceNum_ >= path.pieces_.length) {
  2992. return null;
  2993. }
  2994. return path.pieces_[path.pieceNum_];
  2995. }
  2996. /**
  2997. * @returns The number of segments in this path
  2998. */
  2999. function pathGetLength(path) {
  3000. return path.pieces_.length - path.pieceNum_;
  3001. }
  3002. function pathPopFront(path) {
  3003. var pieceNum = path.pieceNum_;
  3004. if (pieceNum < path.pieces_.length) {
  3005. pieceNum++;
  3006. }
  3007. return new Path(path.pieces_, pieceNum);
  3008. }
  3009. function pathGetBack(path) {
  3010. if (path.pieceNum_ < path.pieces_.length) {
  3011. return path.pieces_[path.pieces_.length - 1];
  3012. }
  3013. return null;
  3014. }
  3015. function pathToUrlEncodedString(path) {
  3016. var pathString = '';
  3017. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3018. if (path.pieces_[i] !== '') {
  3019. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  3020. }
  3021. }
  3022. return pathString || '/';
  3023. }
  3024. /**
  3025. * Shallow copy of the parts of the path.
  3026. *
  3027. */
  3028. function pathSlice(path, begin) {
  3029. if (begin === void 0) { begin = 0; }
  3030. return path.pieces_.slice(path.pieceNum_ + begin);
  3031. }
  3032. function pathParent(path) {
  3033. if (path.pieceNum_ >= path.pieces_.length) {
  3034. return null;
  3035. }
  3036. var pieces = [];
  3037. for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  3038. pieces.push(path.pieces_[i]);
  3039. }
  3040. return new Path(pieces, 0);
  3041. }
  3042. function pathChild(path, childPathObj) {
  3043. var pieces = [];
  3044. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3045. pieces.push(path.pieces_[i]);
  3046. }
  3047. if (childPathObj instanceof Path) {
  3048. for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  3049. pieces.push(childPathObj.pieces_[i]);
  3050. }
  3051. }
  3052. else {
  3053. var childPieces = childPathObj.split('/');
  3054. for (var i = 0; i < childPieces.length; i++) {
  3055. if (childPieces[i].length > 0) {
  3056. pieces.push(childPieces[i]);
  3057. }
  3058. }
  3059. }
  3060. return new Path(pieces, 0);
  3061. }
  3062. /**
  3063. * @returns True if there are no segments in this path
  3064. */
  3065. function pathIsEmpty(path) {
  3066. return path.pieceNum_ >= path.pieces_.length;
  3067. }
  3068. /**
  3069. * @returns The path from outerPath to innerPath
  3070. */
  3071. function newRelativePath(outerPath, innerPath) {
  3072. var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  3073. if (outer === null) {
  3074. return innerPath;
  3075. }
  3076. else if (outer === inner) {
  3077. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  3078. }
  3079. else {
  3080. throw new Error('INTERNAL ERROR: innerPath (' +
  3081. innerPath +
  3082. ') is not within ' +
  3083. 'outerPath (' +
  3084. outerPath +
  3085. ')');
  3086. }
  3087. }
  3088. /**
  3089. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  3090. */
  3091. function pathCompare(left, right) {
  3092. var leftKeys = pathSlice(left, 0);
  3093. var rightKeys = pathSlice(right, 0);
  3094. for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  3095. var cmp = nameCompare(leftKeys[i], rightKeys[i]);
  3096. if (cmp !== 0) {
  3097. return cmp;
  3098. }
  3099. }
  3100. if (leftKeys.length === rightKeys.length) {
  3101. return 0;
  3102. }
  3103. return leftKeys.length < rightKeys.length ? -1 : 1;
  3104. }
  3105. /**
  3106. * @returns true if paths are the same.
  3107. */
  3108. function pathEquals(path, other) {
  3109. if (pathGetLength(path) !== pathGetLength(other)) {
  3110. return false;
  3111. }
  3112. for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3113. if (path.pieces_[i] !== other.pieces_[j]) {
  3114. return false;
  3115. }
  3116. }
  3117. return true;
  3118. }
  3119. /**
  3120. * @returns True if this path is a parent of (or the same as) other
  3121. */
  3122. function pathContains(path, other) {
  3123. var i = path.pieceNum_;
  3124. var j = other.pieceNum_;
  3125. if (pathGetLength(path) > pathGetLength(other)) {
  3126. return false;
  3127. }
  3128. while (i < path.pieces_.length) {
  3129. if (path.pieces_[i] !== other.pieces_[j]) {
  3130. return false;
  3131. }
  3132. ++i;
  3133. ++j;
  3134. }
  3135. return true;
  3136. }
  3137. /**
  3138. * Dynamic (mutable) path used to count path lengths.
  3139. *
  3140. * This class is used to efficiently check paths for valid
  3141. * length (in UTF8 bytes) and depth (used in path validation).
  3142. *
  3143. * Throws Error exception if path is ever invalid.
  3144. *
  3145. * The definition of a path always begins with '/'.
  3146. */
  3147. var ValidationPath = /** @class */ (function () {
  3148. /**
  3149. * @param path - Initial Path.
  3150. * @param errorPrefix_ - Prefix for any error messages.
  3151. */
  3152. function ValidationPath(path, errorPrefix_) {
  3153. this.errorPrefix_ = errorPrefix_;
  3154. this.parts_ = pathSlice(path, 0);
  3155. /** Initialize to number of '/' chars needed in path. */
  3156. this.byteLength_ = Math.max(1, this.parts_.length);
  3157. for (var i = 0; i < this.parts_.length; i++) {
  3158. this.byteLength_ += stringLength(this.parts_[i]);
  3159. }
  3160. validationPathCheckValid(this);
  3161. }
  3162. return ValidationPath;
  3163. }());
  3164. function validationPathPush(validationPath, child) {
  3165. // Count the needed '/'
  3166. if (validationPath.parts_.length > 0) {
  3167. validationPath.byteLength_ += 1;
  3168. }
  3169. validationPath.parts_.push(child);
  3170. validationPath.byteLength_ += stringLength(child);
  3171. validationPathCheckValid(validationPath);
  3172. }
  3173. function validationPathPop(validationPath) {
  3174. var last = validationPath.parts_.pop();
  3175. validationPath.byteLength_ -= stringLength(last);
  3176. // Un-count the previous '/'
  3177. if (validationPath.parts_.length > 0) {
  3178. validationPath.byteLength_ -= 1;
  3179. }
  3180. }
  3181. function validationPathCheckValid(validationPath) {
  3182. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3183. throw new Error(validationPath.errorPrefix_ +
  3184. 'has a key path longer than ' +
  3185. MAX_PATH_LENGTH_BYTES +
  3186. ' bytes (' +
  3187. validationPath.byteLength_ +
  3188. ').');
  3189. }
  3190. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3191. throw new Error(validationPath.errorPrefix_ +
  3192. 'path specified exceeds the maximum depth that can be written (' +
  3193. MAX_PATH_DEPTH +
  3194. ') or object contains a cycle ' +
  3195. validationPathToErrorString(validationPath));
  3196. }
  3197. }
  3198. /**
  3199. * String for use in error messages - uses '.' notation for path.
  3200. */
  3201. function validationPathToErrorString(validationPath) {
  3202. if (validationPath.parts_.length === 0) {
  3203. return '';
  3204. }
  3205. return "in property '" + validationPath.parts_.join('.') + "'";
  3206. }
  3207. /**
  3208. * @license
  3209. * Copyright 2017 Google LLC
  3210. *
  3211. * Licensed under the Apache License, Version 2.0 (the "License");
  3212. * you may not use this file except in compliance with the License.
  3213. * You may obtain a copy of the License at
  3214. *
  3215. * http://www.apache.org/licenses/LICENSE-2.0
  3216. *
  3217. * Unless required by applicable law or agreed to in writing, software
  3218. * distributed under the License is distributed on an "AS IS" BASIS,
  3219. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3220. * See the License for the specific language governing permissions and
  3221. * limitations under the License.
  3222. */
  3223. var VisibilityMonitor = /** @class */ (function (_super) {
  3224. __extends(VisibilityMonitor, _super);
  3225. function VisibilityMonitor() {
  3226. var _this = _super.call(this, ['visible']) || this;
  3227. var hidden;
  3228. var visibilityChange;
  3229. if (typeof document !== 'undefined' &&
  3230. typeof document.addEventListener !== 'undefined') {
  3231. if (typeof document['hidden'] !== 'undefined') {
  3232. // Opera 12.10 and Firefox 18 and later support
  3233. visibilityChange = 'visibilitychange';
  3234. hidden = 'hidden';
  3235. }
  3236. else if (typeof document['mozHidden'] !== 'undefined') {
  3237. visibilityChange = 'mozvisibilitychange';
  3238. hidden = 'mozHidden';
  3239. }
  3240. else if (typeof document['msHidden'] !== 'undefined') {
  3241. visibilityChange = 'msvisibilitychange';
  3242. hidden = 'msHidden';
  3243. }
  3244. else if (typeof document['webkitHidden'] !== 'undefined') {
  3245. visibilityChange = 'webkitvisibilitychange';
  3246. hidden = 'webkitHidden';
  3247. }
  3248. }
  3249. // Initially, we always assume we are visible. This ensures that in browsers
  3250. // without page visibility support or in cases where we are never visible
  3251. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3252. // reconnects
  3253. _this.visible_ = true;
  3254. if (visibilityChange) {
  3255. document.addEventListener(visibilityChange, function () {
  3256. var visible = !document[hidden];
  3257. if (visible !== _this.visible_) {
  3258. _this.visible_ = visible;
  3259. _this.trigger('visible', visible);
  3260. }
  3261. }, false);
  3262. }
  3263. return _this;
  3264. }
  3265. VisibilityMonitor.getInstance = function () {
  3266. return new VisibilityMonitor();
  3267. };
  3268. VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
  3269. assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3270. return [this.visible_];
  3271. };
  3272. return VisibilityMonitor;
  3273. }(EventEmitter));
  3274. /**
  3275. * @license
  3276. * Copyright 2017 Google LLC
  3277. *
  3278. * Licensed under the Apache License, Version 2.0 (the "License");
  3279. * you may not use this file except in compliance with the License.
  3280. * You may obtain a copy of the License at
  3281. *
  3282. * http://www.apache.org/licenses/LICENSE-2.0
  3283. *
  3284. * Unless required by applicable law or agreed to in writing, software
  3285. * distributed under the License is distributed on an "AS IS" BASIS,
  3286. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3287. * See the License for the specific language governing permissions and
  3288. * limitations under the License.
  3289. */
  3290. var RECONNECT_MIN_DELAY = 1000;
  3291. var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3292. var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3293. var RECONNECT_DELAY_MULTIPLIER = 1.3;
  3294. var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3295. var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3296. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3297. var INVALID_TOKEN_THRESHOLD = 3;
  3298. /**
  3299. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3300. *
  3301. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3302. * in quotes to make sure the closure compiler does not minify them.
  3303. */
  3304. var PersistentConnection = /** @class */ (function (_super) {
  3305. __extends(PersistentConnection, _super);
  3306. /**
  3307. * @param repoInfo_ - Data about the namespace we are connecting to
  3308. * @param applicationId_ - The Firebase App ID for this project
  3309. * @param onDataUpdate_ - A callback for new data from the server
  3310. */
  3311. function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3312. var _this = _super.call(this) || this;
  3313. _this.repoInfo_ = repoInfo_;
  3314. _this.applicationId_ = applicationId_;
  3315. _this.onDataUpdate_ = onDataUpdate_;
  3316. _this.onConnectStatus_ = onConnectStatus_;
  3317. _this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3318. _this.authTokenProvider_ = authTokenProvider_;
  3319. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3320. _this.authOverride_ = authOverride_;
  3321. // Used for diagnostic logging.
  3322. _this.id = PersistentConnection.nextPersistentConnectionId_++;
  3323. _this.log_ = logWrapper('p:' + _this.id + ':');
  3324. _this.interruptReasons_ = {};
  3325. _this.listens = new Map();
  3326. _this.outstandingPuts_ = [];
  3327. _this.outstandingGets_ = [];
  3328. _this.outstandingPutCount_ = 0;
  3329. _this.outstandingGetCount_ = 0;
  3330. _this.onDisconnectRequestQueue_ = [];
  3331. _this.connected_ = false;
  3332. _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3333. _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3334. _this.securityDebugCallback_ = null;
  3335. _this.lastSessionId = null;
  3336. _this.establishConnectionTimer_ = null;
  3337. _this.visible_ = false;
  3338. // Before we get connected, we keep a queue of pending messages to send.
  3339. _this.requestCBHash_ = {};
  3340. _this.requestNumber_ = 0;
  3341. _this.realtime_ = null;
  3342. _this.authToken_ = null;
  3343. _this.appCheckToken_ = null;
  3344. _this.forceTokenRefresh_ = false;
  3345. _this.invalidAuthTokenCount_ = 0;
  3346. _this.invalidAppCheckTokenCount_ = 0;
  3347. _this.firstConnection_ = true;
  3348. _this.lastConnectionAttemptTime_ = null;
  3349. _this.lastConnectionEstablishedTime_ = null;
  3350. if (authOverride_ && !isNodeSdk()) {
  3351. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3352. }
  3353. VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
  3354. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3355. OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
  3356. }
  3357. return _this;
  3358. }
  3359. PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
  3360. var curReqNum = ++this.requestNumber_;
  3361. var msg = { r: curReqNum, a: action, b: body };
  3362. this.log_(stringify(msg));
  3363. assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3364. this.realtime_.sendRequest(msg);
  3365. if (onResponse) {
  3366. this.requestCBHash_[curReqNum] = onResponse;
  3367. }
  3368. };
  3369. PersistentConnection.prototype.get = function (query) {
  3370. this.initConnection_();
  3371. var deferred = new Deferred();
  3372. var request = {
  3373. p: query._path.toString(),
  3374. q: query._queryObject
  3375. };
  3376. var outstandingGet = {
  3377. action: 'g',
  3378. request: request,
  3379. onComplete: function (message) {
  3380. var payload = message['d'];
  3381. if (message['s'] === 'ok') {
  3382. deferred.resolve(payload);
  3383. }
  3384. else {
  3385. deferred.reject(payload);
  3386. }
  3387. }
  3388. };
  3389. this.outstandingGets_.push(outstandingGet);
  3390. this.outstandingGetCount_++;
  3391. var index = this.outstandingGets_.length - 1;
  3392. if (this.connected_) {
  3393. this.sendGet_(index);
  3394. }
  3395. return deferred.promise;
  3396. };
  3397. PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  3398. this.initConnection_();
  3399. var queryId = query._queryIdentifier;
  3400. var pathString = query._path.toString();
  3401. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3402. if (!this.listens.has(pathString)) {
  3403. this.listens.set(pathString, new Map());
  3404. }
  3405. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3406. assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
  3407. var listenSpec = {
  3408. onComplete: onComplete,
  3409. hashFn: currentHashFn,
  3410. query: query,
  3411. tag: tag
  3412. };
  3413. this.listens.get(pathString).set(queryId, listenSpec);
  3414. if (this.connected_) {
  3415. this.sendListen_(listenSpec);
  3416. }
  3417. };
  3418. PersistentConnection.prototype.sendGet_ = function (index) {
  3419. var _this = this;
  3420. var get = this.outstandingGets_[index];
  3421. this.sendRequest('g', get.request, function (message) {
  3422. delete _this.outstandingGets_[index];
  3423. _this.outstandingGetCount_--;
  3424. if (_this.outstandingGetCount_ === 0) {
  3425. _this.outstandingGets_ = [];
  3426. }
  3427. if (get.onComplete) {
  3428. get.onComplete(message);
  3429. }
  3430. });
  3431. };
  3432. PersistentConnection.prototype.sendListen_ = function (listenSpec) {
  3433. var _this = this;
  3434. var query = listenSpec.query;
  3435. var pathString = query._path.toString();
  3436. var queryId = query._queryIdentifier;
  3437. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3438. var req = { /*path*/ p: pathString };
  3439. var action = 'q';
  3440. // Only bother to send query if it's non-default.
  3441. if (listenSpec.tag) {
  3442. req['q'] = query._queryObject;
  3443. req['t'] = listenSpec.tag;
  3444. }
  3445. req[ /*hash*/'h'] = listenSpec.hashFn();
  3446. this.sendRequest(action, req, function (message) {
  3447. var payload = message[ /*data*/'d'];
  3448. var status = message[ /*status*/'s'];
  3449. // print warnings in any case...
  3450. PersistentConnection.warnOnListenWarnings_(payload, query);
  3451. var currentListenSpec = _this.listens.get(pathString) &&
  3452. _this.listens.get(pathString).get(queryId);
  3453. // only trigger actions if the listen hasn't been removed and readded
  3454. if (currentListenSpec === listenSpec) {
  3455. _this.log_('listen response', message);
  3456. if (status !== 'ok') {
  3457. _this.removeListen_(pathString, queryId);
  3458. }
  3459. if (listenSpec.onComplete) {
  3460. listenSpec.onComplete(status, payload);
  3461. }
  3462. }
  3463. });
  3464. };
  3465. PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
  3466. if (payload && typeof payload === 'object' && contains(payload, 'w')) {
  3467. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3468. var warnings = safeGet(payload, 'w');
  3469. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3470. var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3471. var indexPath = query._path.toString();
  3472. warn("Using an unspecified index. Your data will be downloaded and " +
  3473. "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
  3474. "".concat(indexPath, " to your security rules for better performance."));
  3475. }
  3476. }
  3477. };
  3478. PersistentConnection.prototype.refreshAuthToken = function (token) {
  3479. this.authToken_ = token;
  3480. this.log_('Auth token refreshed');
  3481. if (this.authToken_) {
  3482. this.tryAuth();
  3483. }
  3484. else {
  3485. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3486. //the credential so we dont become authenticated next time we connect.
  3487. if (this.connected_) {
  3488. this.sendRequest('unauth', {}, function () { });
  3489. }
  3490. }
  3491. this.reduceReconnectDelayIfAdminCredential_(token);
  3492. };
  3493. PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
  3494. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3495. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3496. var isFirebaseSecret = credential && credential.length === 40;
  3497. if (isFirebaseSecret || isAdmin(credential)) {
  3498. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3499. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3500. }
  3501. };
  3502. PersistentConnection.prototype.refreshAppCheckToken = function (token) {
  3503. this.appCheckToken_ = token;
  3504. this.log_('App check token refreshed');
  3505. if (this.appCheckToken_) {
  3506. this.tryAppCheck();
  3507. }
  3508. else {
  3509. //If we're connected we want to let the server know to unauthenticate us.
  3510. //If we're not connected, simply delete the credential so we dont become
  3511. // authenticated next time we connect.
  3512. if (this.connected_) {
  3513. this.sendRequest('unappeck', {}, function () { });
  3514. }
  3515. }
  3516. };
  3517. /**
  3518. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3519. * a auth revoked (the connection is closed).
  3520. */
  3521. PersistentConnection.prototype.tryAuth = function () {
  3522. var _this = this;
  3523. if (this.connected_ && this.authToken_) {
  3524. var token_1 = this.authToken_;
  3525. var authMethod = isValidFormat(token_1) ? 'auth' : 'gauth';
  3526. var requestData = { cred: token_1 };
  3527. if (this.authOverride_ === null) {
  3528. requestData['noauth'] = true;
  3529. }
  3530. else if (typeof this.authOverride_ === 'object') {
  3531. requestData['authvar'] = this.authOverride_;
  3532. }
  3533. this.sendRequest(authMethod, requestData, function (res) {
  3534. var status = res[ /*status*/'s'];
  3535. var data = res[ /*data*/'d'] || 'error';
  3536. if (_this.authToken_ === token_1) {
  3537. if (status === 'ok') {
  3538. _this.invalidAuthTokenCount_ = 0;
  3539. }
  3540. else {
  3541. // Triggers reconnect and force refresh for auth token
  3542. _this.onAuthRevoked_(status, data);
  3543. }
  3544. }
  3545. });
  3546. }
  3547. };
  3548. /**
  3549. * Attempts to authenticate with the given token. If the authentication
  3550. * attempt fails, it's triggered like the token was revoked (the connection is
  3551. * closed).
  3552. */
  3553. PersistentConnection.prototype.tryAppCheck = function () {
  3554. var _this = this;
  3555. if (this.connected_ && this.appCheckToken_) {
  3556. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
  3557. var status = res[ /*status*/'s'];
  3558. var data = res[ /*data*/'d'] || 'error';
  3559. if (status === 'ok') {
  3560. _this.invalidAppCheckTokenCount_ = 0;
  3561. }
  3562. else {
  3563. _this.onAppCheckRevoked_(status, data);
  3564. }
  3565. });
  3566. }
  3567. };
  3568. /**
  3569. * @inheritDoc
  3570. */
  3571. PersistentConnection.prototype.unlisten = function (query, tag) {
  3572. var pathString = query._path.toString();
  3573. var queryId = query._queryIdentifier;
  3574. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3575. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3576. var listen = this.removeListen_(pathString, queryId);
  3577. if (listen && this.connected_) {
  3578. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3579. }
  3580. };
  3581. PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
  3582. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3583. var req = { /*path*/ p: pathString };
  3584. var action = 'n';
  3585. // Only bother sending queryId if it's non-default.
  3586. if (tag) {
  3587. req['q'] = queryObj;
  3588. req['t'] = tag;
  3589. }
  3590. this.sendRequest(action, req);
  3591. };
  3592. PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
  3593. this.initConnection_();
  3594. if (this.connected_) {
  3595. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3596. }
  3597. else {
  3598. this.onDisconnectRequestQueue_.push({
  3599. pathString: pathString,
  3600. action: 'o',
  3601. data: data,
  3602. onComplete: onComplete
  3603. });
  3604. }
  3605. };
  3606. PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
  3607. this.initConnection_();
  3608. if (this.connected_) {
  3609. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3610. }
  3611. else {
  3612. this.onDisconnectRequestQueue_.push({
  3613. pathString: pathString,
  3614. action: 'om',
  3615. data: data,
  3616. onComplete: onComplete
  3617. });
  3618. }
  3619. };
  3620. PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
  3621. this.initConnection_();
  3622. if (this.connected_) {
  3623. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3624. }
  3625. else {
  3626. this.onDisconnectRequestQueue_.push({
  3627. pathString: pathString,
  3628. action: 'oc',
  3629. data: null,
  3630. onComplete: onComplete
  3631. });
  3632. }
  3633. };
  3634. PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
  3635. var request = { /*path*/ p: pathString, /*data*/ d: data };
  3636. this.log_('onDisconnect ' + action, request);
  3637. this.sendRequest(action, request, function (response) {
  3638. if (onComplete) {
  3639. setTimeout(function () {
  3640. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3641. }, Math.floor(0));
  3642. }
  3643. });
  3644. };
  3645. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  3646. this.putInternal('p', pathString, data, onComplete, hash);
  3647. };
  3648. PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
  3649. this.putInternal('m', pathString, data, onComplete, hash);
  3650. };
  3651. PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
  3652. this.initConnection_();
  3653. var request = {
  3654. /*path*/ p: pathString,
  3655. /*data*/ d: data
  3656. };
  3657. if (hash !== undefined) {
  3658. request[ /*hash*/'h'] = hash;
  3659. }
  3660. // TODO: Only keep track of the most recent put for a given path?
  3661. this.outstandingPuts_.push({
  3662. action: action,
  3663. request: request,
  3664. onComplete: onComplete
  3665. });
  3666. this.outstandingPutCount_++;
  3667. var index = this.outstandingPuts_.length - 1;
  3668. if (this.connected_) {
  3669. this.sendPut_(index);
  3670. }
  3671. else {
  3672. this.log_('Buffering put: ' + pathString);
  3673. }
  3674. };
  3675. PersistentConnection.prototype.sendPut_ = function (index) {
  3676. var _this = this;
  3677. var action = this.outstandingPuts_[index].action;
  3678. var request = this.outstandingPuts_[index].request;
  3679. var onComplete = this.outstandingPuts_[index].onComplete;
  3680. this.outstandingPuts_[index].queued = this.connected_;
  3681. this.sendRequest(action, request, function (message) {
  3682. _this.log_(action + ' response', message);
  3683. delete _this.outstandingPuts_[index];
  3684. _this.outstandingPutCount_--;
  3685. // Clean up array occasionally.
  3686. if (_this.outstandingPutCount_ === 0) {
  3687. _this.outstandingPuts_ = [];
  3688. }
  3689. if (onComplete) {
  3690. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3691. }
  3692. });
  3693. };
  3694. PersistentConnection.prototype.reportStats = function (stats) {
  3695. var _this = this;
  3696. // If we're not connected, we just drop the stats.
  3697. if (this.connected_) {
  3698. var request = { /*counters*/ c: stats };
  3699. this.log_('reportStats', request);
  3700. this.sendRequest(/*stats*/ 's', request, function (result) {
  3701. var status = result[ /*status*/'s'];
  3702. if (status !== 'ok') {
  3703. var errorReason = result[ /* data */'d'];
  3704. _this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3705. }
  3706. });
  3707. }
  3708. };
  3709. PersistentConnection.prototype.onDataMessage_ = function (message) {
  3710. if ('r' in message) {
  3711. // this is a response
  3712. this.log_('from server: ' + stringify(message));
  3713. var reqNum = message['r'];
  3714. var onResponse = this.requestCBHash_[reqNum];
  3715. if (onResponse) {
  3716. delete this.requestCBHash_[reqNum];
  3717. onResponse(message[ /*body*/'b']);
  3718. }
  3719. }
  3720. else if ('error' in message) {
  3721. throw 'A server-side error has occurred: ' + message['error'];
  3722. }
  3723. else if ('a' in message) {
  3724. // a and b are action and body, respectively
  3725. this.onDataPush_(message['a'], message['b']);
  3726. }
  3727. };
  3728. PersistentConnection.prototype.onDataPush_ = function (action, body) {
  3729. this.log_('handleServerMessage', action, body);
  3730. if (action === 'd') {
  3731. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3732. /*isMerge*/ false, body['t']);
  3733. }
  3734. else if (action === 'm') {
  3735. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3736. /*isMerge=*/ true, body['t']);
  3737. }
  3738. else if (action === 'c') {
  3739. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3740. }
  3741. else if (action === 'ac') {
  3742. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3743. }
  3744. else if (action === 'apc') {
  3745. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3746. }
  3747. else if (action === 'sd') {
  3748. this.onSecurityDebugPacket_(body);
  3749. }
  3750. else {
  3751. error('Unrecognized action received from server: ' +
  3752. stringify(action) +
  3753. '\nAre you using the latest client?');
  3754. }
  3755. };
  3756. PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
  3757. this.log_('connection ready');
  3758. this.connected_ = true;
  3759. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3760. this.handleTimestamp_(timestamp);
  3761. this.lastSessionId = sessionId;
  3762. if (this.firstConnection_) {
  3763. this.sendConnectStats_();
  3764. }
  3765. this.restoreState_();
  3766. this.firstConnection_ = false;
  3767. this.onConnectStatus_(true);
  3768. };
  3769. PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
  3770. var _this = this;
  3771. assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3772. if (this.establishConnectionTimer_) {
  3773. clearTimeout(this.establishConnectionTimer_);
  3774. }
  3775. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3776. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3777. this.establishConnectionTimer_ = setTimeout(function () {
  3778. _this.establishConnectionTimer_ = null;
  3779. _this.establishConnection_();
  3780. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3781. }, Math.floor(timeout));
  3782. };
  3783. PersistentConnection.prototype.initConnection_ = function () {
  3784. if (!this.realtime_ && this.firstConnection_) {
  3785. this.scheduleConnect_(0);
  3786. }
  3787. };
  3788. PersistentConnection.prototype.onVisible_ = function (visible) {
  3789. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3790. if (visible &&
  3791. !this.visible_ &&
  3792. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3793. this.log_('Window became visible. Reducing delay.');
  3794. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3795. if (!this.realtime_) {
  3796. this.scheduleConnect_(0);
  3797. }
  3798. }
  3799. this.visible_ = visible;
  3800. };
  3801. PersistentConnection.prototype.onOnline_ = function (online) {
  3802. if (online) {
  3803. this.log_('Browser went online.');
  3804. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3805. if (!this.realtime_) {
  3806. this.scheduleConnect_(0);
  3807. }
  3808. }
  3809. else {
  3810. this.log_('Browser went offline. Killing connection.');
  3811. if (this.realtime_) {
  3812. this.realtime_.close();
  3813. }
  3814. }
  3815. };
  3816. PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
  3817. this.log_('data client disconnected');
  3818. this.connected_ = false;
  3819. this.realtime_ = null;
  3820. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3821. this.cancelSentTransactions_();
  3822. // Clear out the pending requests.
  3823. this.requestCBHash_ = {};
  3824. if (this.shouldReconnect_()) {
  3825. if (!this.visible_) {
  3826. this.log_("Window isn't visible. Delaying reconnect.");
  3827. this.reconnectDelay_ = this.maxReconnectDelay_;
  3828. this.lastConnectionAttemptTime_ = new Date().getTime();
  3829. }
  3830. else if (this.lastConnectionEstablishedTime_) {
  3831. // If we've been connected long enough, reset reconnect delay to minimum.
  3832. var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3833. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3834. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3835. }
  3836. this.lastConnectionEstablishedTime_ = null;
  3837. }
  3838. var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3839. var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3840. reconnectDelay = Math.random() * reconnectDelay;
  3841. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3842. this.scheduleConnect_(reconnectDelay);
  3843. // Adjust reconnect delay for next time.
  3844. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3845. }
  3846. this.onConnectStatus_(false);
  3847. };
  3848. PersistentConnection.prototype.establishConnection_ = function () {
  3849. return __awaiter(this, void 0, void 0, function () {
  3850. var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
  3851. var _this = this;
  3852. return __generator(this, function (_b) {
  3853. switch (_b.label) {
  3854. case 0:
  3855. if (!this.shouldReconnect_()) return [3 /*break*/, 4];
  3856. this.log_('Making a connection attempt');
  3857. this.lastConnectionAttemptTime_ = new Date().getTime();
  3858. this.lastConnectionEstablishedTime_ = null;
  3859. onDataMessage = this.onDataMessage_.bind(this);
  3860. onReady = this.onReady_.bind(this);
  3861. onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
  3862. connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3863. lastSessionId = this.lastSessionId;
  3864. canceled_1 = false;
  3865. connection_1 = null;
  3866. closeFn = function () {
  3867. if (connection_1) {
  3868. connection_1.close();
  3869. }
  3870. else {
  3871. canceled_1 = true;
  3872. onDisconnect_1();
  3873. }
  3874. };
  3875. sendRequestFn = function (msg) {
  3876. assert(connection_1, "sendRequest call when we're not connected not allowed.");
  3877. connection_1.sendRequest(msg);
  3878. };
  3879. this.realtime_ = {
  3880. close: closeFn,
  3881. sendRequest: sendRequestFn
  3882. };
  3883. forceRefresh = this.forceTokenRefresh_;
  3884. this.forceTokenRefresh_ = false;
  3885. _b.label = 1;
  3886. case 1:
  3887. _b.trys.push([1, 3, , 4]);
  3888. return [4 /*yield*/, Promise.all([
  3889. this.authTokenProvider_.getToken(forceRefresh),
  3890. this.appCheckTokenProvider_.getToken(forceRefresh)
  3891. ])];
  3892. case 2:
  3893. _a = __read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
  3894. if (!canceled_1) {
  3895. log('getToken() completed. Creating connection.');
  3896. this.authToken_ = authToken && authToken.accessToken;
  3897. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3898. connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
  3899. /* onKill= */ function (reason) {
  3900. warn(reason + ' (' + _this.repoInfo_.toString() + ')');
  3901. _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3902. }, lastSessionId);
  3903. }
  3904. else {
  3905. log('getToken() completed but was canceled');
  3906. }
  3907. return [3 /*break*/, 4];
  3908. case 3:
  3909. error_1 = _b.sent();
  3910. this.log_('Failed to get token: ' + error_1);
  3911. if (!canceled_1) {
  3912. if (this.repoInfo_.nodeAdmin) {
  3913. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3914. // But getToken() may also just have temporarily failed, so we still want to
  3915. // continue retrying.
  3916. warn(error_1);
  3917. }
  3918. closeFn();
  3919. }
  3920. return [3 /*break*/, 4];
  3921. case 4: return [2 /*return*/];
  3922. }
  3923. });
  3924. });
  3925. };
  3926. PersistentConnection.prototype.interrupt = function (reason) {
  3927. log('Interrupting connection for reason: ' + reason);
  3928. this.interruptReasons_[reason] = true;
  3929. if (this.realtime_) {
  3930. this.realtime_.close();
  3931. }
  3932. else {
  3933. if (this.establishConnectionTimer_) {
  3934. clearTimeout(this.establishConnectionTimer_);
  3935. this.establishConnectionTimer_ = null;
  3936. }
  3937. if (this.connected_) {
  3938. this.onRealtimeDisconnect_();
  3939. }
  3940. }
  3941. };
  3942. PersistentConnection.prototype.resume = function (reason) {
  3943. log('Resuming connection for reason: ' + reason);
  3944. delete this.interruptReasons_[reason];
  3945. if (isEmpty(this.interruptReasons_)) {
  3946. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3947. if (!this.realtime_) {
  3948. this.scheduleConnect_(0);
  3949. }
  3950. }
  3951. };
  3952. PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
  3953. var delta = timestamp - new Date().getTime();
  3954. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3955. };
  3956. PersistentConnection.prototype.cancelSentTransactions_ = function () {
  3957. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  3958. var put = this.outstandingPuts_[i];
  3959. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3960. if (put.onComplete) {
  3961. put.onComplete('disconnect');
  3962. }
  3963. delete this.outstandingPuts_[i];
  3964. this.outstandingPutCount_--;
  3965. }
  3966. }
  3967. // Clean up array occasionally.
  3968. if (this.outstandingPutCount_ === 0) {
  3969. this.outstandingPuts_ = [];
  3970. }
  3971. };
  3972. PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
  3973. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3974. var queryId;
  3975. if (!query) {
  3976. queryId = 'default';
  3977. }
  3978. else {
  3979. queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
  3980. }
  3981. var listen = this.removeListen_(pathString, queryId);
  3982. if (listen && listen.onComplete) {
  3983. listen.onComplete('permission_denied');
  3984. }
  3985. };
  3986. PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
  3987. var normalizedPathString = new Path(pathString).toString(); // normalize path.
  3988. var listen;
  3989. if (this.listens.has(normalizedPathString)) {
  3990. var map = this.listens.get(normalizedPathString);
  3991. listen = map.get(queryId);
  3992. map.delete(queryId);
  3993. if (map.size === 0) {
  3994. this.listens.delete(normalizedPathString);
  3995. }
  3996. }
  3997. else {
  3998. // all listens for this path has already been removed
  3999. listen = undefined;
  4000. }
  4001. return listen;
  4002. };
  4003. PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
  4004. log('Auth token revoked: ' + statusCode + '/' + explanation);
  4005. this.authToken_ = null;
  4006. this.forceTokenRefresh_ = true;
  4007. this.realtime_.close();
  4008. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4009. // We'll wait a couple times before logging the warning / increasing the
  4010. // retry period since oauth tokens will report as "invalid" if they're
  4011. // just expired. Plus there may be transient issues that resolve themselves.
  4012. this.invalidAuthTokenCount_++;
  4013. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4014. // Set a long reconnect delay because recovery is unlikely
  4015. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  4016. // Notify the auth token provider that the token is invalid, which will log
  4017. // a warning
  4018. this.authTokenProvider_.notifyForInvalidToken();
  4019. }
  4020. }
  4021. };
  4022. PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
  4023. log('App check token revoked: ' + statusCode + '/' + explanation);
  4024. this.appCheckToken_ = null;
  4025. this.forceTokenRefresh_ = true;
  4026. // Note: We don't close the connection as the developer may not have
  4027. // enforcement enabled. The backend closes connections with enforcements.
  4028. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4029. // We'll wait a couple times before logging the warning / increasing the
  4030. // retry period since oauth tokens will report as "invalid" if they're
  4031. // just expired. Plus there may be transient issues that resolve themselves.
  4032. this.invalidAppCheckTokenCount_++;
  4033. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4034. this.appCheckTokenProvider_.notifyForInvalidToken();
  4035. }
  4036. }
  4037. };
  4038. PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
  4039. if (this.securityDebugCallback_) {
  4040. this.securityDebugCallback_(body);
  4041. }
  4042. else {
  4043. if ('msg' in body) {
  4044. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  4045. }
  4046. }
  4047. };
  4048. PersistentConnection.prototype.restoreState_ = function () {
  4049. var e_1, _a, e_2, _b;
  4050. //Re-authenticate ourselves if we have a credential stored.
  4051. this.tryAuth();
  4052. this.tryAppCheck();
  4053. try {
  4054. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  4055. // make sure to send listens before puts.
  4056. for (var _c = __values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
  4057. var queries = _d.value;
  4058. try {
  4059. for (var _e = (e_2 = void 0, __values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
  4060. var listenSpec = _f.value;
  4061. this.sendListen_(listenSpec);
  4062. }
  4063. }
  4064. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  4065. finally {
  4066. try {
  4067. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  4068. }
  4069. finally { if (e_2) throw e_2.error; }
  4070. }
  4071. }
  4072. }
  4073. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4074. finally {
  4075. try {
  4076. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  4077. }
  4078. finally { if (e_1) throw e_1.error; }
  4079. }
  4080. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  4081. if (this.outstandingPuts_[i]) {
  4082. this.sendPut_(i);
  4083. }
  4084. }
  4085. while (this.onDisconnectRequestQueue_.length) {
  4086. var request = this.onDisconnectRequestQueue_.shift();
  4087. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  4088. }
  4089. for (var i = 0; i < this.outstandingGets_.length; i++) {
  4090. if (this.outstandingGets_[i]) {
  4091. this.sendGet_(i);
  4092. }
  4093. }
  4094. };
  4095. /**
  4096. * Sends client stats for first connection
  4097. */
  4098. PersistentConnection.prototype.sendConnectStats_ = function () {
  4099. var stats = {};
  4100. var clientName = 'js';
  4101. if (isNodeSdk()) {
  4102. if (this.repoInfo_.nodeAdmin) {
  4103. clientName = 'admin_node';
  4104. }
  4105. else {
  4106. clientName = 'node';
  4107. }
  4108. }
  4109. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  4110. if (isMobileCordova()) {
  4111. stats['framework.cordova'] = 1;
  4112. }
  4113. else if (isReactNative()) {
  4114. stats['framework.reactnative'] = 1;
  4115. }
  4116. this.reportStats(stats);
  4117. };
  4118. PersistentConnection.prototype.shouldReconnect_ = function () {
  4119. var online = OnlineMonitor.getInstance().currentlyOnline();
  4120. return isEmpty(this.interruptReasons_) && online;
  4121. };
  4122. PersistentConnection.nextPersistentConnectionId_ = 0;
  4123. /**
  4124. * Counter for number of connections created. Mainly used for tagging in the logs
  4125. */
  4126. PersistentConnection.nextConnectionId_ = 0;
  4127. return PersistentConnection;
  4128. }(ServerActions));
  4129. /**
  4130. * @license
  4131. * Copyright 2017 Google LLC
  4132. *
  4133. * Licensed under the Apache License, Version 2.0 (the "License");
  4134. * you may not use this file except in compliance with the License.
  4135. * You may obtain a copy of the License at
  4136. *
  4137. * http://www.apache.org/licenses/LICENSE-2.0
  4138. *
  4139. * Unless required by applicable law or agreed to in writing, software
  4140. * distributed under the License is distributed on an "AS IS" BASIS,
  4141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4142. * See the License for the specific language governing permissions and
  4143. * limitations under the License.
  4144. */
  4145. var NamedNode = /** @class */ (function () {
  4146. function NamedNode(name, node) {
  4147. this.name = name;
  4148. this.node = node;
  4149. }
  4150. NamedNode.Wrap = function (name, node) {
  4151. return new NamedNode(name, node);
  4152. };
  4153. return NamedNode;
  4154. }());
  4155. /**
  4156. * @license
  4157. * Copyright 2017 Google LLC
  4158. *
  4159. * Licensed under the Apache License, Version 2.0 (the "License");
  4160. * you may not use this file except in compliance with the License.
  4161. * You may obtain a copy of the License at
  4162. *
  4163. * http://www.apache.org/licenses/LICENSE-2.0
  4164. *
  4165. * Unless required by applicable law or agreed to in writing, software
  4166. * distributed under the License is distributed on an "AS IS" BASIS,
  4167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4168. * See the License for the specific language governing permissions and
  4169. * limitations under the License.
  4170. */
  4171. var Index = /** @class */ (function () {
  4172. function Index() {
  4173. }
  4174. /**
  4175. * @returns A standalone comparison function for
  4176. * this index
  4177. */
  4178. Index.prototype.getCompare = function () {
  4179. return this.compare.bind(this);
  4180. };
  4181. /**
  4182. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4183. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4184. *
  4185. *
  4186. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4187. */
  4188. Index.prototype.indexedValueChanged = function (oldNode, newNode) {
  4189. var oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4190. var newWrapped = new NamedNode(MIN_NAME, newNode);
  4191. return this.compare(oldWrapped, newWrapped) !== 0;
  4192. };
  4193. /**
  4194. * @returns a node wrapper that will sort equal to or less than
  4195. * any other node wrapper, using this index
  4196. */
  4197. Index.prototype.minPost = function () {
  4198. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4199. return NamedNode.MIN;
  4200. };
  4201. return Index;
  4202. }());
  4203. /**
  4204. * @license
  4205. * Copyright 2017 Google LLC
  4206. *
  4207. * Licensed under the Apache License, Version 2.0 (the "License");
  4208. * you may not use this file except in compliance with the License.
  4209. * You may obtain a copy of the License at
  4210. *
  4211. * http://www.apache.org/licenses/LICENSE-2.0
  4212. *
  4213. * Unless required by applicable law or agreed to in writing, software
  4214. * distributed under the License is distributed on an "AS IS" BASIS,
  4215. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4216. * See the License for the specific language governing permissions and
  4217. * limitations under the License.
  4218. */
  4219. var __EMPTY_NODE;
  4220. var KeyIndex = /** @class */ (function (_super) {
  4221. __extends(KeyIndex, _super);
  4222. function KeyIndex() {
  4223. return _super !== null && _super.apply(this, arguments) || this;
  4224. }
  4225. Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
  4226. get: function () {
  4227. return __EMPTY_NODE;
  4228. },
  4229. set: function (val) {
  4230. __EMPTY_NODE = val;
  4231. },
  4232. enumerable: false,
  4233. configurable: true
  4234. });
  4235. KeyIndex.prototype.compare = function (a, b) {
  4236. return nameCompare(a.name, b.name);
  4237. };
  4238. KeyIndex.prototype.isDefinedOn = function (node) {
  4239. // We could probably return true here (since every node has a key), but it's never called
  4240. // so just leaving unimplemented for now.
  4241. throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4242. };
  4243. KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  4244. return false; // The key for a node never changes.
  4245. };
  4246. KeyIndex.prototype.minPost = function () {
  4247. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4248. return NamedNode.MIN;
  4249. };
  4250. KeyIndex.prototype.maxPost = function () {
  4251. // TODO: This should really be created once and cached in a static property, but
  4252. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4253. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4254. };
  4255. KeyIndex.prototype.makePost = function (indexValue, name) {
  4256. assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4257. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4258. return new NamedNode(indexValue, __EMPTY_NODE);
  4259. };
  4260. /**
  4261. * @returns String representation for inclusion in a query spec
  4262. */
  4263. KeyIndex.prototype.toString = function () {
  4264. return '.key';
  4265. };
  4266. return KeyIndex;
  4267. }(Index));
  4268. var KEY_INDEX = new KeyIndex();
  4269. /**
  4270. * @license
  4271. * Copyright 2017 Google LLC
  4272. *
  4273. * Licensed under the Apache License, Version 2.0 (the "License");
  4274. * you may not use this file except in compliance with the License.
  4275. * You may obtain a copy of the License at
  4276. *
  4277. * http://www.apache.org/licenses/LICENSE-2.0
  4278. *
  4279. * Unless required by applicable law or agreed to in writing, software
  4280. * distributed under the License is distributed on an "AS IS" BASIS,
  4281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4282. * See the License for the specific language governing permissions and
  4283. * limitations under the License.
  4284. */
  4285. /**
  4286. * An iterator over an LLRBNode.
  4287. */
  4288. var SortedMapIterator = /** @class */ (function () {
  4289. /**
  4290. * @param node - Node to iterate.
  4291. * @param isReverse_ - Whether or not to iterate in reverse
  4292. */
  4293. function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
  4294. if (resultGenerator_ === void 0) { resultGenerator_ = null; }
  4295. this.isReverse_ = isReverse_;
  4296. this.resultGenerator_ = resultGenerator_;
  4297. this.nodeStack_ = [];
  4298. var cmp = 1;
  4299. while (!node.isEmpty()) {
  4300. node = node;
  4301. cmp = startKey ? comparator(node.key, startKey) : 1;
  4302. // flip the comparison if we're going in reverse
  4303. if (isReverse_) {
  4304. cmp *= -1;
  4305. }
  4306. if (cmp < 0) {
  4307. // This node is less than our start key. ignore it
  4308. if (this.isReverse_) {
  4309. node = node.left;
  4310. }
  4311. else {
  4312. node = node.right;
  4313. }
  4314. }
  4315. else if (cmp === 0) {
  4316. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4317. this.nodeStack_.push(node);
  4318. break;
  4319. }
  4320. else {
  4321. // This node is greater than our start key, add it to the stack and move to the next one
  4322. this.nodeStack_.push(node);
  4323. if (this.isReverse_) {
  4324. node = node.right;
  4325. }
  4326. else {
  4327. node = node.left;
  4328. }
  4329. }
  4330. }
  4331. }
  4332. SortedMapIterator.prototype.getNext = function () {
  4333. if (this.nodeStack_.length === 0) {
  4334. return null;
  4335. }
  4336. var node = this.nodeStack_.pop();
  4337. var result;
  4338. if (this.resultGenerator_) {
  4339. result = this.resultGenerator_(node.key, node.value);
  4340. }
  4341. else {
  4342. result = { key: node.key, value: node.value };
  4343. }
  4344. if (this.isReverse_) {
  4345. node = node.left;
  4346. while (!node.isEmpty()) {
  4347. this.nodeStack_.push(node);
  4348. node = node.right;
  4349. }
  4350. }
  4351. else {
  4352. node = node.right;
  4353. while (!node.isEmpty()) {
  4354. this.nodeStack_.push(node);
  4355. node = node.left;
  4356. }
  4357. }
  4358. return result;
  4359. };
  4360. SortedMapIterator.prototype.hasNext = function () {
  4361. return this.nodeStack_.length > 0;
  4362. };
  4363. SortedMapIterator.prototype.peek = function () {
  4364. if (this.nodeStack_.length === 0) {
  4365. return null;
  4366. }
  4367. var node = this.nodeStack_[this.nodeStack_.length - 1];
  4368. if (this.resultGenerator_) {
  4369. return this.resultGenerator_(node.key, node.value);
  4370. }
  4371. else {
  4372. return { key: node.key, value: node.value };
  4373. }
  4374. };
  4375. return SortedMapIterator;
  4376. }());
  4377. /**
  4378. * Represents a node in a Left-leaning Red-Black tree.
  4379. */
  4380. var LLRBNode = /** @class */ (function () {
  4381. /**
  4382. * @param key - Key associated with this node.
  4383. * @param value - Value associated with this node.
  4384. * @param color - Whether this node is red.
  4385. * @param left - Left child.
  4386. * @param right - Right child.
  4387. */
  4388. function LLRBNode(key, value, color, left, right) {
  4389. this.key = key;
  4390. this.value = value;
  4391. this.color = color != null ? color : LLRBNode.RED;
  4392. this.left =
  4393. left != null ? left : SortedMap.EMPTY_NODE;
  4394. this.right =
  4395. right != null ? right : SortedMap.EMPTY_NODE;
  4396. }
  4397. /**
  4398. * Returns a copy of the current node, optionally replacing pieces of it.
  4399. *
  4400. * @param key - New key for the node, or null.
  4401. * @param value - New value for the node, or null.
  4402. * @param color - New color for the node, or null.
  4403. * @param left - New left child for the node, or null.
  4404. * @param right - New right child for the node, or null.
  4405. * @returns The node copy.
  4406. */
  4407. LLRBNode.prototype.copy = function (key, value, color, left, right) {
  4408. return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  4409. };
  4410. /**
  4411. * @returns The total number of nodes in the tree.
  4412. */
  4413. LLRBNode.prototype.count = function () {
  4414. return this.left.count() + 1 + this.right.count();
  4415. };
  4416. /**
  4417. * @returns True if the tree is empty.
  4418. */
  4419. LLRBNode.prototype.isEmpty = function () {
  4420. return false;
  4421. };
  4422. /**
  4423. * Traverses the tree in key order and calls the specified action function
  4424. * for each node.
  4425. *
  4426. * @param action - Callback function to be called for each
  4427. * node. If it returns true, traversal is aborted.
  4428. * @returns The first truthy value returned by action, or the last falsey
  4429. * value returned by action
  4430. */
  4431. LLRBNode.prototype.inorderTraversal = function (action) {
  4432. return (this.left.inorderTraversal(action) ||
  4433. !!action(this.key, this.value) ||
  4434. this.right.inorderTraversal(action));
  4435. };
  4436. /**
  4437. * Traverses the tree in reverse key order and calls the specified action function
  4438. * for each node.
  4439. *
  4440. * @param action - Callback function to be called for each
  4441. * node. If it returns true, traversal is aborted.
  4442. * @returns True if traversal was aborted.
  4443. */
  4444. LLRBNode.prototype.reverseTraversal = function (action) {
  4445. return (this.right.reverseTraversal(action) ||
  4446. action(this.key, this.value) ||
  4447. this.left.reverseTraversal(action));
  4448. };
  4449. /**
  4450. * @returns The minimum node in the tree.
  4451. */
  4452. LLRBNode.prototype.min_ = function () {
  4453. if (this.left.isEmpty()) {
  4454. return this;
  4455. }
  4456. else {
  4457. return this.left.min_();
  4458. }
  4459. };
  4460. /**
  4461. * @returns The maximum key in the tree.
  4462. */
  4463. LLRBNode.prototype.minKey = function () {
  4464. return this.min_().key;
  4465. };
  4466. /**
  4467. * @returns The maximum key in the tree.
  4468. */
  4469. LLRBNode.prototype.maxKey = function () {
  4470. if (this.right.isEmpty()) {
  4471. return this.key;
  4472. }
  4473. else {
  4474. return this.right.maxKey();
  4475. }
  4476. };
  4477. /**
  4478. * @param key - Key to insert.
  4479. * @param value - Value to insert.
  4480. * @param comparator - Comparator.
  4481. * @returns New tree, with the key/value added.
  4482. */
  4483. LLRBNode.prototype.insert = function (key, value, comparator) {
  4484. var n = this;
  4485. var cmp = comparator(key, n.key);
  4486. if (cmp < 0) {
  4487. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4488. }
  4489. else if (cmp === 0) {
  4490. n = n.copy(null, value, null, null, null);
  4491. }
  4492. else {
  4493. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4494. }
  4495. return n.fixUp_();
  4496. };
  4497. /**
  4498. * @returns New tree, with the minimum key removed.
  4499. */
  4500. LLRBNode.prototype.removeMin_ = function () {
  4501. if (this.left.isEmpty()) {
  4502. return SortedMap.EMPTY_NODE;
  4503. }
  4504. var n = this;
  4505. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4506. n = n.moveRedLeft_();
  4507. }
  4508. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4509. return n.fixUp_();
  4510. };
  4511. /**
  4512. * @param key - The key of the item to remove.
  4513. * @param comparator - Comparator.
  4514. * @returns New tree, with the specified item removed.
  4515. */
  4516. LLRBNode.prototype.remove = function (key, comparator) {
  4517. var n, smallest;
  4518. n = this;
  4519. if (comparator(key, n.key) < 0) {
  4520. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4521. n = n.moveRedLeft_();
  4522. }
  4523. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4524. }
  4525. else {
  4526. if (n.left.isRed_()) {
  4527. n = n.rotateRight_();
  4528. }
  4529. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4530. n = n.moveRedRight_();
  4531. }
  4532. if (comparator(key, n.key) === 0) {
  4533. if (n.right.isEmpty()) {
  4534. return SortedMap.EMPTY_NODE;
  4535. }
  4536. else {
  4537. smallest = n.right.min_();
  4538. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4539. }
  4540. }
  4541. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4542. }
  4543. return n.fixUp_();
  4544. };
  4545. /**
  4546. * @returns Whether this is a RED node.
  4547. */
  4548. LLRBNode.prototype.isRed_ = function () {
  4549. return this.color;
  4550. };
  4551. /**
  4552. * @returns New tree after performing any needed rotations.
  4553. */
  4554. LLRBNode.prototype.fixUp_ = function () {
  4555. var n = this;
  4556. if (n.right.isRed_() && !n.left.isRed_()) {
  4557. n = n.rotateLeft_();
  4558. }
  4559. if (n.left.isRed_() && n.left.left.isRed_()) {
  4560. n = n.rotateRight_();
  4561. }
  4562. if (n.left.isRed_() && n.right.isRed_()) {
  4563. n = n.colorFlip_();
  4564. }
  4565. return n;
  4566. };
  4567. /**
  4568. * @returns New tree, after moveRedLeft.
  4569. */
  4570. LLRBNode.prototype.moveRedLeft_ = function () {
  4571. var n = this.colorFlip_();
  4572. if (n.right.left.isRed_()) {
  4573. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4574. n = n.rotateLeft_();
  4575. n = n.colorFlip_();
  4576. }
  4577. return n;
  4578. };
  4579. /**
  4580. * @returns New tree, after moveRedRight.
  4581. */
  4582. LLRBNode.prototype.moveRedRight_ = function () {
  4583. var n = this.colorFlip_();
  4584. if (n.left.left.isRed_()) {
  4585. n = n.rotateRight_();
  4586. n = n.colorFlip_();
  4587. }
  4588. return n;
  4589. };
  4590. /**
  4591. * @returns New tree, after rotateLeft.
  4592. */
  4593. LLRBNode.prototype.rotateLeft_ = function () {
  4594. var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4595. return this.right.copy(null, null, this.color, nl, null);
  4596. };
  4597. /**
  4598. * @returns New tree, after rotateRight.
  4599. */
  4600. LLRBNode.prototype.rotateRight_ = function () {
  4601. var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4602. return this.left.copy(null, null, this.color, null, nr);
  4603. };
  4604. /**
  4605. * @returns Newt ree, after colorFlip.
  4606. */
  4607. LLRBNode.prototype.colorFlip_ = function () {
  4608. var left = this.left.copy(null, null, !this.left.color, null, null);
  4609. var right = this.right.copy(null, null, !this.right.color, null, null);
  4610. return this.copy(null, null, !this.color, left, right);
  4611. };
  4612. /**
  4613. * For testing.
  4614. *
  4615. * @returns True if all is well.
  4616. */
  4617. LLRBNode.prototype.checkMaxDepth_ = function () {
  4618. var blackDepth = this.check_();
  4619. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4620. };
  4621. LLRBNode.prototype.check_ = function () {
  4622. if (this.isRed_() && this.left.isRed_()) {
  4623. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4624. }
  4625. if (this.right.isRed_()) {
  4626. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4627. }
  4628. var blackDepth = this.left.check_();
  4629. if (blackDepth !== this.right.check_()) {
  4630. throw new Error('Black depths differ');
  4631. }
  4632. else {
  4633. return blackDepth + (this.isRed_() ? 0 : 1);
  4634. }
  4635. };
  4636. LLRBNode.RED = true;
  4637. LLRBNode.BLACK = false;
  4638. return LLRBNode;
  4639. }());
  4640. /**
  4641. * Represents an empty node (a leaf node in the Red-Black Tree).
  4642. */
  4643. var LLRBEmptyNode = /** @class */ (function () {
  4644. function LLRBEmptyNode() {
  4645. }
  4646. /**
  4647. * Returns a copy of the current node.
  4648. *
  4649. * @returns The node copy.
  4650. */
  4651. LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
  4652. return this;
  4653. };
  4654. /**
  4655. * Returns a copy of the tree, with the specified key/value added.
  4656. *
  4657. * @param key - Key to be added.
  4658. * @param value - Value to be added.
  4659. * @param comparator - Comparator.
  4660. * @returns New tree, with item added.
  4661. */
  4662. LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
  4663. return new LLRBNode(key, value, null);
  4664. };
  4665. /**
  4666. * Returns a copy of the tree, with the specified key removed.
  4667. *
  4668. * @param key - The key to remove.
  4669. * @param comparator - Comparator.
  4670. * @returns New tree, with item removed.
  4671. */
  4672. LLRBEmptyNode.prototype.remove = function (key, comparator) {
  4673. return this;
  4674. };
  4675. /**
  4676. * @returns The total number of nodes in the tree.
  4677. */
  4678. LLRBEmptyNode.prototype.count = function () {
  4679. return 0;
  4680. };
  4681. /**
  4682. * @returns True if the tree is empty.
  4683. */
  4684. LLRBEmptyNode.prototype.isEmpty = function () {
  4685. return true;
  4686. };
  4687. /**
  4688. * Traverses the tree in key order and calls the specified action function
  4689. * for each node.
  4690. *
  4691. * @param action - Callback function to be called for each
  4692. * node. If it returns true, traversal is aborted.
  4693. * @returns True if traversal was aborted.
  4694. */
  4695. LLRBEmptyNode.prototype.inorderTraversal = function (action) {
  4696. return false;
  4697. };
  4698. /**
  4699. * Traverses the tree in reverse key order and calls the specified action function
  4700. * for each node.
  4701. *
  4702. * @param action - Callback function to be called for each
  4703. * node. If it returns true, traversal is aborted.
  4704. * @returns True if traversal was aborted.
  4705. */
  4706. LLRBEmptyNode.prototype.reverseTraversal = function (action) {
  4707. return false;
  4708. };
  4709. LLRBEmptyNode.prototype.minKey = function () {
  4710. return null;
  4711. };
  4712. LLRBEmptyNode.prototype.maxKey = function () {
  4713. return null;
  4714. };
  4715. LLRBEmptyNode.prototype.check_ = function () {
  4716. return 0;
  4717. };
  4718. /**
  4719. * @returns Whether this node is red.
  4720. */
  4721. LLRBEmptyNode.prototype.isRed_ = function () {
  4722. return false;
  4723. };
  4724. return LLRBEmptyNode;
  4725. }());
  4726. /**
  4727. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4728. * tree.
  4729. */
  4730. var SortedMap = /** @class */ (function () {
  4731. /**
  4732. * @param comparator_ - Key comparator.
  4733. * @param root_ - Optional root node for the map.
  4734. */
  4735. function SortedMap(comparator_, root_) {
  4736. if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
  4737. this.comparator_ = comparator_;
  4738. this.root_ = root_;
  4739. }
  4740. /**
  4741. * Returns a copy of the map, with the specified key/value added or replaced.
  4742. * (TODO: We should perhaps rename this method to 'put')
  4743. *
  4744. * @param key - Key to be added.
  4745. * @param value - Value to be added.
  4746. * @returns New map, with item added.
  4747. */
  4748. SortedMap.prototype.insert = function (key, value) {
  4749. return new SortedMap(this.comparator_, this.root_
  4750. .insert(key, value, this.comparator_)
  4751. .copy(null, null, LLRBNode.BLACK, null, null));
  4752. };
  4753. /**
  4754. * Returns a copy of the map, with the specified key removed.
  4755. *
  4756. * @param key - The key to remove.
  4757. * @returns New map, with item removed.
  4758. */
  4759. SortedMap.prototype.remove = function (key) {
  4760. return new SortedMap(this.comparator_, this.root_
  4761. .remove(key, this.comparator_)
  4762. .copy(null, null, LLRBNode.BLACK, null, null));
  4763. };
  4764. /**
  4765. * Returns the value of the node with the given key, or null.
  4766. *
  4767. * @param key - The key to look up.
  4768. * @returns The value of the node with the given key, or null if the
  4769. * key doesn't exist.
  4770. */
  4771. SortedMap.prototype.get = function (key) {
  4772. var cmp;
  4773. var node = this.root_;
  4774. while (!node.isEmpty()) {
  4775. cmp = this.comparator_(key, node.key);
  4776. if (cmp === 0) {
  4777. return node.value;
  4778. }
  4779. else if (cmp < 0) {
  4780. node = node.left;
  4781. }
  4782. else if (cmp > 0) {
  4783. node = node.right;
  4784. }
  4785. }
  4786. return null;
  4787. };
  4788. /**
  4789. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4790. * @param key - The key to find the predecessor of
  4791. * @returns The predecessor key.
  4792. */
  4793. SortedMap.prototype.getPredecessorKey = function (key) {
  4794. var cmp, node = this.root_, rightParent = null;
  4795. while (!node.isEmpty()) {
  4796. cmp = this.comparator_(key, node.key);
  4797. if (cmp === 0) {
  4798. if (!node.left.isEmpty()) {
  4799. node = node.left;
  4800. while (!node.right.isEmpty()) {
  4801. node = node.right;
  4802. }
  4803. return node.key;
  4804. }
  4805. else if (rightParent) {
  4806. return rightParent.key;
  4807. }
  4808. else {
  4809. return null; // first item.
  4810. }
  4811. }
  4812. else if (cmp < 0) {
  4813. node = node.left;
  4814. }
  4815. else if (cmp > 0) {
  4816. rightParent = node;
  4817. node = node.right;
  4818. }
  4819. }
  4820. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4821. };
  4822. /**
  4823. * @returns True if the map is empty.
  4824. */
  4825. SortedMap.prototype.isEmpty = function () {
  4826. return this.root_.isEmpty();
  4827. };
  4828. /**
  4829. * @returns The total number of nodes in the map.
  4830. */
  4831. SortedMap.prototype.count = function () {
  4832. return this.root_.count();
  4833. };
  4834. /**
  4835. * @returns The minimum key in the map.
  4836. */
  4837. SortedMap.prototype.minKey = function () {
  4838. return this.root_.minKey();
  4839. };
  4840. /**
  4841. * @returns The maximum key in the map.
  4842. */
  4843. SortedMap.prototype.maxKey = function () {
  4844. return this.root_.maxKey();
  4845. };
  4846. /**
  4847. * Traverses the map in key order and calls the specified action function
  4848. * for each key/value pair.
  4849. *
  4850. * @param action - Callback function to be called
  4851. * for each key/value pair. If action returns true, traversal is aborted.
  4852. * @returns The first truthy value returned by action, or the last falsey
  4853. * value returned by action
  4854. */
  4855. SortedMap.prototype.inorderTraversal = function (action) {
  4856. return this.root_.inorderTraversal(action);
  4857. };
  4858. /**
  4859. * Traverses the map in reverse key order and calls the specified action function
  4860. * for each key/value pair.
  4861. *
  4862. * @param action - Callback function to be called
  4863. * for each key/value pair. If action returns true, traversal is aborted.
  4864. * @returns True if the traversal was aborted.
  4865. */
  4866. SortedMap.prototype.reverseTraversal = function (action) {
  4867. return this.root_.reverseTraversal(action);
  4868. };
  4869. /**
  4870. * Returns an iterator over the SortedMap.
  4871. * @returns The iterator.
  4872. */
  4873. SortedMap.prototype.getIterator = function (resultGenerator) {
  4874. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4875. };
  4876. SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
  4877. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4878. };
  4879. SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
  4880. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4881. };
  4882. SortedMap.prototype.getReverseIterator = function (resultGenerator) {
  4883. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4884. };
  4885. /**
  4886. * Always use the same empty node, to reduce memory.
  4887. */
  4888. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4889. return SortedMap;
  4890. }());
  4891. /**
  4892. * @license
  4893. * Copyright 2017 Google LLC
  4894. *
  4895. * Licensed under the Apache License, Version 2.0 (the "License");
  4896. * you may not use this file except in compliance with the License.
  4897. * You may obtain a copy of the License at
  4898. *
  4899. * http://www.apache.org/licenses/LICENSE-2.0
  4900. *
  4901. * Unless required by applicable law or agreed to in writing, software
  4902. * distributed under the License is distributed on an "AS IS" BASIS,
  4903. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4904. * See the License for the specific language governing permissions and
  4905. * limitations under the License.
  4906. */
  4907. function NAME_ONLY_COMPARATOR(left, right) {
  4908. return nameCompare(left.name, right.name);
  4909. }
  4910. function NAME_COMPARATOR(left, right) {
  4911. return nameCompare(left, right);
  4912. }
  4913. /**
  4914. * @license
  4915. * Copyright 2017 Google LLC
  4916. *
  4917. * Licensed under the Apache License, Version 2.0 (the "License");
  4918. * you may not use this file except in compliance with the License.
  4919. * You may obtain a copy of the License at
  4920. *
  4921. * http://www.apache.org/licenses/LICENSE-2.0
  4922. *
  4923. * Unless required by applicable law or agreed to in writing, software
  4924. * distributed under the License is distributed on an "AS IS" BASIS,
  4925. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4926. * See the License for the specific language governing permissions and
  4927. * limitations under the License.
  4928. */
  4929. var MAX_NODE$2;
  4930. function setMaxNode$1(val) {
  4931. MAX_NODE$2 = val;
  4932. }
  4933. var priorityHashText = function (priority) {
  4934. if (typeof priority === 'number') {
  4935. return 'number:' + doubleToIEEE754String(priority);
  4936. }
  4937. else {
  4938. return 'string:' + priority;
  4939. }
  4940. };
  4941. /**
  4942. * Validates that a priority snapshot Node is valid.
  4943. */
  4944. var validatePriorityNode = function (priorityNode) {
  4945. if (priorityNode.isLeafNode()) {
  4946. var val = priorityNode.val();
  4947. assert(typeof val === 'string' ||
  4948. typeof val === 'number' ||
  4949. (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
  4950. }
  4951. else {
  4952. assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4953. }
  4954. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4955. assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4956. };
  4957. /**
  4958. * @license
  4959. * Copyright 2017 Google LLC
  4960. *
  4961. * Licensed under the Apache License, Version 2.0 (the "License");
  4962. * you may not use this file except in compliance with the License.
  4963. * You may obtain a copy of the License at
  4964. *
  4965. * http://www.apache.org/licenses/LICENSE-2.0
  4966. *
  4967. * Unless required by applicable law or agreed to in writing, software
  4968. * distributed under the License is distributed on an "AS IS" BASIS,
  4969. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4970. * See the License for the specific language governing permissions and
  4971. * limitations under the License.
  4972. */
  4973. var __childrenNodeConstructor;
  4974. /**
  4975. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4976. * implements Node and stores the value of the node (a string,
  4977. * number, or boolean) accessible via getValue().
  4978. */
  4979. var LeafNode = /** @class */ (function () {
  4980. /**
  4981. * @param value_ - The value to store in this leaf node. The object type is
  4982. * possible in the event of a deferred value
  4983. * @param priorityNode_ - The priority of this node.
  4984. */
  4985. function LeafNode(value_, priorityNode_) {
  4986. if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
  4987. this.value_ = value_;
  4988. this.priorityNode_ = priorityNode_;
  4989. this.lazyHash_ = null;
  4990. assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4991. validatePriorityNode(this.priorityNode_);
  4992. }
  4993. Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
  4994. get: function () {
  4995. return __childrenNodeConstructor;
  4996. },
  4997. set: function (val) {
  4998. __childrenNodeConstructor = val;
  4999. },
  5000. enumerable: false,
  5001. configurable: true
  5002. });
  5003. /** @inheritDoc */
  5004. LeafNode.prototype.isLeafNode = function () {
  5005. return true;
  5006. };
  5007. /** @inheritDoc */
  5008. LeafNode.prototype.getPriority = function () {
  5009. return this.priorityNode_;
  5010. };
  5011. /** @inheritDoc */
  5012. LeafNode.prototype.updatePriority = function (newPriorityNode) {
  5013. return new LeafNode(this.value_, newPriorityNode);
  5014. };
  5015. /** @inheritDoc */
  5016. LeafNode.prototype.getImmediateChild = function (childName) {
  5017. // Hack to treat priority as a regular child
  5018. if (childName === '.priority') {
  5019. return this.priorityNode_;
  5020. }
  5021. else {
  5022. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5023. }
  5024. };
  5025. /** @inheritDoc */
  5026. LeafNode.prototype.getChild = function (path) {
  5027. if (pathIsEmpty(path)) {
  5028. return this;
  5029. }
  5030. else if (pathGetFront(path) === '.priority') {
  5031. return this.priorityNode_;
  5032. }
  5033. else {
  5034. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5035. }
  5036. };
  5037. LeafNode.prototype.hasChild = function () {
  5038. return false;
  5039. };
  5040. /** @inheritDoc */
  5041. LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
  5042. return null;
  5043. };
  5044. /** @inheritDoc */
  5045. LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5046. if (childName === '.priority') {
  5047. return this.updatePriority(newChildNode);
  5048. }
  5049. else if (newChildNode.isEmpty() && childName !== '.priority') {
  5050. return this;
  5051. }
  5052. else {
  5053. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  5054. }
  5055. };
  5056. /** @inheritDoc */
  5057. LeafNode.prototype.updateChild = function (path, newChildNode) {
  5058. var front = pathGetFront(path);
  5059. if (front === null) {
  5060. return newChildNode;
  5061. }
  5062. else if (newChildNode.isEmpty() && front !== '.priority') {
  5063. return this;
  5064. }
  5065. else {
  5066. assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5067. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  5068. }
  5069. };
  5070. /** @inheritDoc */
  5071. LeafNode.prototype.isEmpty = function () {
  5072. return false;
  5073. };
  5074. /** @inheritDoc */
  5075. LeafNode.prototype.numChildren = function () {
  5076. return 0;
  5077. };
  5078. /** @inheritDoc */
  5079. LeafNode.prototype.forEachChild = function (index, action) {
  5080. return false;
  5081. };
  5082. LeafNode.prototype.val = function (exportFormat) {
  5083. if (exportFormat && !this.getPriority().isEmpty()) {
  5084. return {
  5085. '.value': this.getValue(),
  5086. '.priority': this.getPriority().val()
  5087. };
  5088. }
  5089. else {
  5090. return this.getValue();
  5091. }
  5092. };
  5093. /** @inheritDoc */
  5094. LeafNode.prototype.hash = function () {
  5095. if (this.lazyHash_ === null) {
  5096. var toHash = '';
  5097. if (!this.priorityNode_.isEmpty()) {
  5098. toHash +=
  5099. 'priority:' +
  5100. priorityHashText(this.priorityNode_.val()) +
  5101. ':';
  5102. }
  5103. var type = typeof this.value_;
  5104. toHash += type + ':';
  5105. if (type === 'number') {
  5106. toHash += doubleToIEEE754String(this.value_);
  5107. }
  5108. else {
  5109. toHash += this.value_;
  5110. }
  5111. this.lazyHash_ = sha1(toHash);
  5112. }
  5113. return this.lazyHash_;
  5114. };
  5115. /**
  5116. * Returns the value of the leaf node.
  5117. * @returns The value of the node.
  5118. */
  5119. LeafNode.prototype.getValue = function () {
  5120. return this.value_;
  5121. };
  5122. LeafNode.prototype.compareTo = function (other) {
  5123. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  5124. return 1;
  5125. }
  5126. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  5127. return -1;
  5128. }
  5129. else {
  5130. assert(other.isLeafNode(), 'Unknown node type');
  5131. return this.compareToLeafNode_(other);
  5132. }
  5133. };
  5134. /**
  5135. * Comparison specifically for two leaf nodes
  5136. */
  5137. LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
  5138. var otherLeafType = typeof otherLeaf.value_;
  5139. var thisLeafType = typeof this.value_;
  5140. var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  5141. var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  5142. assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  5143. assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  5144. if (otherIndex === thisIndex) {
  5145. // Same type, compare values
  5146. if (thisLeafType === 'object') {
  5147. // Deferred value nodes are all equal, but we should also never get to this point...
  5148. return 0;
  5149. }
  5150. else {
  5151. // Note that this works because true > false, all others are number or string comparisons
  5152. if (this.value_ < otherLeaf.value_) {
  5153. return -1;
  5154. }
  5155. else if (this.value_ === otherLeaf.value_) {
  5156. return 0;
  5157. }
  5158. else {
  5159. return 1;
  5160. }
  5161. }
  5162. }
  5163. else {
  5164. return thisIndex - otherIndex;
  5165. }
  5166. };
  5167. LeafNode.prototype.withIndex = function () {
  5168. return this;
  5169. };
  5170. LeafNode.prototype.isIndexed = function () {
  5171. return true;
  5172. };
  5173. LeafNode.prototype.equals = function (other) {
  5174. if (other === this) {
  5175. return true;
  5176. }
  5177. else if (other.isLeafNode()) {
  5178. var otherLeaf = other;
  5179. return (this.value_ === otherLeaf.value_ &&
  5180. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5181. }
  5182. else {
  5183. return false;
  5184. }
  5185. };
  5186. /**
  5187. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5188. * the same type, the comparison falls back to their value
  5189. */
  5190. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5191. return LeafNode;
  5192. }());
  5193. /**
  5194. * @license
  5195. * Copyright 2017 Google LLC
  5196. *
  5197. * Licensed under the Apache License, Version 2.0 (the "License");
  5198. * you may not use this file except in compliance with the License.
  5199. * You may obtain a copy of the License at
  5200. *
  5201. * http://www.apache.org/licenses/LICENSE-2.0
  5202. *
  5203. * Unless required by applicable law or agreed to in writing, software
  5204. * distributed under the License is distributed on an "AS IS" BASIS,
  5205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5206. * See the License for the specific language governing permissions and
  5207. * limitations under the License.
  5208. */
  5209. var nodeFromJSON$1;
  5210. var MAX_NODE$1;
  5211. function setNodeFromJSON(val) {
  5212. nodeFromJSON$1 = val;
  5213. }
  5214. function setMaxNode(val) {
  5215. MAX_NODE$1 = val;
  5216. }
  5217. var PriorityIndex = /** @class */ (function (_super) {
  5218. __extends(PriorityIndex, _super);
  5219. function PriorityIndex() {
  5220. return _super !== null && _super.apply(this, arguments) || this;
  5221. }
  5222. PriorityIndex.prototype.compare = function (a, b) {
  5223. var aPriority = a.node.getPriority();
  5224. var bPriority = b.node.getPriority();
  5225. var indexCmp = aPriority.compareTo(bPriority);
  5226. if (indexCmp === 0) {
  5227. return nameCompare(a.name, b.name);
  5228. }
  5229. else {
  5230. return indexCmp;
  5231. }
  5232. };
  5233. PriorityIndex.prototype.isDefinedOn = function (node) {
  5234. return !node.getPriority().isEmpty();
  5235. };
  5236. PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  5237. return !oldNode.getPriority().equals(newNode.getPriority());
  5238. };
  5239. PriorityIndex.prototype.minPost = function () {
  5240. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5241. return NamedNode.MIN;
  5242. };
  5243. PriorityIndex.prototype.maxPost = function () {
  5244. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5245. };
  5246. PriorityIndex.prototype.makePost = function (indexValue, name) {
  5247. var priorityNode = nodeFromJSON$1(indexValue);
  5248. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5249. };
  5250. /**
  5251. * @returns String representation for inclusion in a query spec
  5252. */
  5253. PriorityIndex.prototype.toString = function () {
  5254. return '.priority';
  5255. };
  5256. return PriorityIndex;
  5257. }(Index));
  5258. var PRIORITY_INDEX = new PriorityIndex();
  5259. /**
  5260. * @license
  5261. * Copyright 2017 Google LLC
  5262. *
  5263. * Licensed under the Apache License, Version 2.0 (the "License");
  5264. * you may not use this file except in compliance with the License.
  5265. * You may obtain a copy of the License at
  5266. *
  5267. * http://www.apache.org/licenses/LICENSE-2.0
  5268. *
  5269. * Unless required by applicable law or agreed to in writing, software
  5270. * distributed under the License is distributed on an "AS IS" BASIS,
  5271. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5272. * See the License for the specific language governing permissions and
  5273. * limitations under the License.
  5274. */
  5275. var LOG_2 = Math.log(2);
  5276. var Base12Num = /** @class */ (function () {
  5277. function Base12Num(length) {
  5278. var logBase2 = function (num) {
  5279. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5280. return parseInt((Math.log(num) / LOG_2), 10);
  5281. };
  5282. var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
  5283. this.count = logBase2(length + 1);
  5284. this.current_ = this.count - 1;
  5285. var mask = bitMask(this.count);
  5286. this.bits_ = (length + 1) & mask;
  5287. }
  5288. Base12Num.prototype.nextBitIsOne = function () {
  5289. //noinspection JSBitwiseOperatorUsage
  5290. var result = !(this.bits_ & (0x1 << this.current_));
  5291. this.current_--;
  5292. return result;
  5293. };
  5294. return Base12Num;
  5295. }());
  5296. /**
  5297. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5298. * function
  5299. *
  5300. * Uses the algorithm described in the paper linked here:
  5301. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5302. *
  5303. * @param childList - Unsorted list of children
  5304. * @param cmp - The comparison method to be used
  5305. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5306. * type is not NamedNode
  5307. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5308. */
  5309. var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5310. childList.sort(cmp);
  5311. var buildBalancedTree = function (low, high) {
  5312. var length = high - low;
  5313. var namedNode;
  5314. var key;
  5315. if (length === 0) {
  5316. return null;
  5317. }
  5318. else if (length === 1) {
  5319. namedNode = childList[low];
  5320. key = keyFn ? keyFn(namedNode) : namedNode;
  5321. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5322. }
  5323. else {
  5324. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5325. var middle = parseInt((length / 2), 10) + low;
  5326. var left = buildBalancedTree(low, middle);
  5327. var right = buildBalancedTree(middle + 1, high);
  5328. namedNode = childList[middle];
  5329. key = keyFn ? keyFn(namedNode) : namedNode;
  5330. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5331. }
  5332. };
  5333. var buildFrom12Array = function (base12) {
  5334. var node = null;
  5335. var root = null;
  5336. var index = childList.length;
  5337. var buildPennant = function (chunkSize, color) {
  5338. var low = index - chunkSize;
  5339. var high = index;
  5340. index -= chunkSize;
  5341. var childTree = buildBalancedTree(low + 1, high);
  5342. var namedNode = childList[low];
  5343. var key = keyFn ? keyFn(namedNode) : namedNode;
  5344. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5345. };
  5346. var attachPennant = function (pennant) {
  5347. if (node) {
  5348. node.left = pennant;
  5349. node = pennant;
  5350. }
  5351. else {
  5352. root = pennant;
  5353. node = pennant;
  5354. }
  5355. };
  5356. for (var i = 0; i < base12.count; ++i) {
  5357. var isOne = base12.nextBitIsOne();
  5358. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5359. var chunkSize = Math.pow(2, base12.count - (i + 1));
  5360. if (isOne) {
  5361. buildPennant(chunkSize, LLRBNode.BLACK);
  5362. }
  5363. else {
  5364. // current == 2
  5365. buildPennant(chunkSize, LLRBNode.BLACK);
  5366. buildPennant(chunkSize, LLRBNode.RED);
  5367. }
  5368. }
  5369. return root;
  5370. };
  5371. var base12 = new Base12Num(childList.length);
  5372. var root = buildFrom12Array(base12);
  5373. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5374. return new SortedMap(mapSortFn || cmp, root);
  5375. };
  5376. /**
  5377. * @license
  5378. * Copyright 2017 Google LLC
  5379. *
  5380. * Licensed under the Apache License, Version 2.0 (the "License");
  5381. * you may not use this file except in compliance with the License.
  5382. * You may obtain a copy of the License at
  5383. *
  5384. * http://www.apache.org/licenses/LICENSE-2.0
  5385. *
  5386. * Unless required by applicable law or agreed to in writing, software
  5387. * distributed under the License is distributed on an "AS IS" BASIS,
  5388. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5389. * See the License for the specific language governing permissions and
  5390. * limitations under the License.
  5391. */
  5392. var _defaultIndexMap;
  5393. var fallbackObject = {};
  5394. var IndexMap = /** @class */ (function () {
  5395. function IndexMap(indexes_, indexSet_) {
  5396. this.indexes_ = indexes_;
  5397. this.indexSet_ = indexSet_;
  5398. }
  5399. Object.defineProperty(IndexMap, "Default", {
  5400. /**
  5401. * The default IndexMap for nodes without a priority
  5402. */
  5403. get: function () {
  5404. assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5405. _defaultIndexMap =
  5406. _defaultIndexMap ||
  5407. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5408. return _defaultIndexMap;
  5409. },
  5410. enumerable: false,
  5411. configurable: true
  5412. });
  5413. IndexMap.prototype.get = function (indexKey) {
  5414. var sortedMap = safeGet(this.indexes_, indexKey);
  5415. if (!sortedMap) {
  5416. throw new Error('No index defined for ' + indexKey);
  5417. }
  5418. if (sortedMap instanceof SortedMap) {
  5419. return sortedMap;
  5420. }
  5421. else {
  5422. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5423. // regular child map
  5424. return null;
  5425. }
  5426. };
  5427. IndexMap.prototype.hasIndex = function (indexDefinition) {
  5428. return contains(this.indexSet_, indexDefinition.toString());
  5429. };
  5430. IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
  5431. assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5432. var childList = [];
  5433. var sawIndexedValue = false;
  5434. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5435. var next = iter.getNext();
  5436. while (next) {
  5437. sawIndexedValue =
  5438. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5439. childList.push(next);
  5440. next = iter.getNext();
  5441. }
  5442. var newIndex;
  5443. if (sawIndexedValue) {
  5444. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5445. }
  5446. else {
  5447. newIndex = fallbackObject;
  5448. }
  5449. var indexName = indexDefinition.toString();
  5450. var newIndexSet = __assign({}, this.indexSet_);
  5451. newIndexSet[indexName] = indexDefinition;
  5452. var newIndexes = __assign({}, this.indexes_);
  5453. newIndexes[indexName] = newIndex;
  5454. return new IndexMap(newIndexes, newIndexSet);
  5455. };
  5456. /**
  5457. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5458. */
  5459. IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
  5460. var _this = this;
  5461. var newIndexes = map(this.indexes_, function (indexedChildren, indexName) {
  5462. var index = safeGet(_this.indexSet_, indexName);
  5463. assert(index, 'Missing index implementation for ' + indexName);
  5464. if (indexedChildren === fallbackObject) {
  5465. // Check to see if we need to index everything
  5466. if (index.isDefinedOn(namedNode.node)) {
  5467. // We need to build this index
  5468. var childList = [];
  5469. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5470. var next = iter.getNext();
  5471. while (next) {
  5472. if (next.name !== namedNode.name) {
  5473. childList.push(next);
  5474. }
  5475. next = iter.getNext();
  5476. }
  5477. childList.push(namedNode);
  5478. return buildChildSet(childList, index.getCompare());
  5479. }
  5480. else {
  5481. // No change, this remains a fallback
  5482. return fallbackObject;
  5483. }
  5484. }
  5485. else {
  5486. var existingSnap = existingChildren.get(namedNode.name);
  5487. var newChildren = indexedChildren;
  5488. if (existingSnap) {
  5489. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5490. }
  5491. return newChildren.insert(namedNode, namedNode.node);
  5492. }
  5493. });
  5494. return new IndexMap(newIndexes, this.indexSet_);
  5495. };
  5496. /**
  5497. * Create a new IndexMap instance with the given value removed
  5498. */
  5499. IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
  5500. var newIndexes = map(this.indexes_, function (indexedChildren) {
  5501. if (indexedChildren === fallbackObject) {
  5502. // This is the fallback. Just return it, nothing to do in this case
  5503. return indexedChildren;
  5504. }
  5505. else {
  5506. var existingSnap = existingChildren.get(namedNode.name);
  5507. if (existingSnap) {
  5508. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5509. }
  5510. else {
  5511. // No record of this child
  5512. return indexedChildren;
  5513. }
  5514. }
  5515. });
  5516. return new IndexMap(newIndexes, this.indexSet_);
  5517. };
  5518. return IndexMap;
  5519. }());
  5520. /**
  5521. * @license
  5522. * Copyright 2017 Google LLC
  5523. *
  5524. * Licensed under the Apache License, Version 2.0 (the "License");
  5525. * you may not use this file except in compliance with the License.
  5526. * You may obtain a copy of the License at
  5527. *
  5528. * http://www.apache.org/licenses/LICENSE-2.0
  5529. *
  5530. * Unless required by applicable law or agreed to in writing, software
  5531. * distributed under the License is distributed on an "AS IS" BASIS,
  5532. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5533. * See the License for the specific language governing permissions and
  5534. * limitations under the License.
  5535. */
  5536. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5537. var EMPTY_NODE;
  5538. /**
  5539. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5540. * (i.e. nodes with children). It implements Node and stores the
  5541. * list of children in the children property, sorted by child name.
  5542. */
  5543. var ChildrenNode = /** @class */ (function () {
  5544. /**
  5545. * @param children_ - List of children of this node..
  5546. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5547. */
  5548. function ChildrenNode(children_, priorityNode_, indexMap_) {
  5549. this.children_ = children_;
  5550. this.priorityNode_ = priorityNode_;
  5551. this.indexMap_ = indexMap_;
  5552. this.lazyHash_ = null;
  5553. /**
  5554. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5555. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5556. * class instead of an empty ChildrenNode.
  5557. */
  5558. if (this.priorityNode_) {
  5559. validatePriorityNode(this.priorityNode_);
  5560. }
  5561. if (this.children_.isEmpty()) {
  5562. assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5563. }
  5564. }
  5565. Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
  5566. get: function () {
  5567. return (EMPTY_NODE ||
  5568. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5569. },
  5570. enumerable: false,
  5571. configurable: true
  5572. });
  5573. /** @inheritDoc */
  5574. ChildrenNode.prototype.isLeafNode = function () {
  5575. return false;
  5576. };
  5577. /** @inheritDoc */
  5578. ChildrenNode.prototype.getPriority = function () {
  5579. return this.priorityNode_ || EMPTY_NODE;
  5580. };
  5581. /** @inheritDoc */
  5582. ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
  5583. if (this.children_.isEmpty()) {
  5584. // Don't allow priorities on empty nodes
  5585. return this;
  5586. }
  5587. else {
  5588. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5589. }
  5590. };
  5591. /** @inheritDoc */
  5592. ChildrenNode.prototype.getImmediateChild = function (childName) {
  5593. // Hack to treat priority as a regular child
  5594. if (childName === '.priority') {
  5595. return this.getPriority();
  5596. }
  5597. else {
  5598. var child = this.children_.get(childName);
  5599. return child === null ? EMPTY_NODE : child;
  5600. }
  5601. };
  5602. /** @inheritDoc */
  5603. ChildrenNode.prototype.getChild = function (path) {
  5604. var front = pathGetFront(path);
  5605. if (front === null) {
  5606. return this;
  5607. }
  5608. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5609. };
  5610. /** @inheritDoc */
  5611. ChildrenNode.prototype.hasChild = function (childName) {
  5612. return this.children_.get(childName) !== null;
  5613. };
  5614. /** @inheritDoc */
  5615. ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5616. assert(newChildNode, 'We should always be passing snapshot nodes');
  5617. if (childName === '.priority') {
  5618. return this.updatePriority(newChildNode);
  5619. }
  5620. else {
  5621. var namedNode = new NamedNode(childName, newChildNode);
  5622. var newChildren = void 0, newIndexMap = void 0;
  5623. if (newChildNode.isEmpty()) {
  5624. newChildren = this.children_.remove(childName);
  5625. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5626. }
  5627. else {
  5628. newChildren = this.children_.insert(childName, newChildNode);
  5629. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5630. }
  5631. var newPriority = newChildren.isEmpty()
  5632. ? EMPTY_NODE
  5633. : this.priorityNode_;
  5634. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5635. }
  5636. };
  5637. /** @inheritDoc */
  5638. ChildrenNode.prototype.updateChild = function (path, newChildNode) {
  5639. var front = pathGetFront(path);
  5640. if (front === null) {
  5641. return newChildNode;
  5642. }
  5643. else {
  5644. assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5645. var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5646. return this.updateImmediateChild(front, newImmediateChild);
  5647. }
  5648. };
  5649. /** @inheritDoc */
  5650. ChildrenNode.prototype.isEmpty = function () {
  5651. return this.children_.isEmpty();
  5652. };
  5653. /** @inheritDoc */
  5654. ChildrenNode.prototype.numChildren = function () {
  5655. return this.children_.count();
  5656. };
  5657. /** @inheritDoc */
  5658. ChildrenNode.prototype.val = function (exportFormat) {
  5659. if (this.isEmpty()) {
  5660. return null;
  5661. }
  5662. var obj = {};
  5663. var numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5664. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5665. obj[key] = childNode.val(exportFormat);
  5666. numKeys++;
  5667. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5668. maxKey = Math.max(maxKey, Number(key));
  5669. }
  5670. else {
  5671. allIntegerKeys = false;
  5672. }
  5673. });
  5674. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5675. // convert to array.
  5676. var array = [];
  5677. // eslint-disable-next-line guard-for-in
  5678. for (var key in obj) {
  5679. array[key] = obj[key];
  5680. }
  5681. return array;
  5682. }
  5683. else {
  5684. if (exportFormat && !this.getPriority().isEmpty()) {
  5685. obj['.priority'] = this.getPriority().val();
  5686. }
  5687. return obj;
  5688. }
  5689. };
  5690. /** @inheritDoc */
  5691. ChildrenNode.prototype.hash = function () {
  5692. if (this.lazyHash_ === null) {
  5693. var toHash_1 = '';
  5694. if (!this.getPriority().isEmpty()) {
  5695. toHash_1 +=
  5696. 'priority:' +
  5697. priorityHashText(this.getPriority().val()) +
  5698. ':';
  5699. }
  5700. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5701. var childHash = childNode.hash();
  5702. if (childHash !== '') {
  5703. toHash_1 += ':' + key + ':' + childHash;
  5704. }
  5705. });
  5706. this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
  5707. }
  5708. return this.lazyHash_;
  5709. };
  5710. /** @inheritDoc */
  5711. ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
  5712. var idx = this.resolveIndex_(index);
  5713. if (idx) {
  5714. var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5715. return predecessor ? predecessor.name : null;
  5716. }
  5717. else {
  5718. return this.children_.getPredecessorKey(childName);
  5719. }
  5720. };
  5721. ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
  5722. var idx = this.resolveIndex_(indexDefinition);
  5723. if (idx) {
  5724. var minKey = idx.minKey();
  5725. return minKey && minKey.name;
  5726. }
  5727. else {
  5728. return this.children_.minKey();
  5729. }
  5730. };
  5731. ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
  5732. var minKey = this.getFirstChildName(indexDefinition);
  5733. if (minKey) {
  5734. return new NamedNode(minKey, this.children_.get(minKey));
  5735. }
  5736. else {
  5737. return null;
  5738. }
  5739. };
  5740. /**
  5741. * Given an index, return the key name of the largest value we have, according to that index
  5742. */
  5743. ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
  5744. var idx = this.resolveIndex_(indexDefinition);
  5745. if (idx) {
  5746. var maxKey = idx.maxKey();
  5747. return maxKey && maxKey.name;
  5748. }
  5749. else {
  5750. return this.children_.maxKey();
  5751. }
  5752. };
  5753. ChildrenNode.prototype.getLastChild = function (indexDefinition) {
  5754. var maxKey = this.getLastChildName(indexDefinition);
  5755. if (maxKey) {
  5756. return new NamedNode(maxKey, this.children_.get(maxKey));
  5757. }
  5758. else {
  5759. return null;
  5760. }
  5761. };
  5762. ChildrenNode.prototype.forEachChild = function (index, action) {
  5763. var idx = this.resolveIndex_(index);
  5764. if (idx) {
  5765. return idx.inorderTraversal(function (wrappedNode) {
  5766. return action(wrappedNode.name, wrappedNode.node);
  5767. });
  5768. }
  5769. else {
  5770. return this.children_.inorderTraversal(action);
  5771. }
  5772. };
  5773. ChildrenNode.prototype.getIterator = function (indexDefinition) {
  5774. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5775. };
  5776. ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
  5777. var idx = this.resolveIndex_(indexDefinition);
  5778. if (idx) {
  5779. return idx.getIteratorFrom(startPost, function (key) { return key; });
  5780. }
  5781. else {
  5782. var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5783. var next = iterator.peek();
  5784. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5785. iterator.getNext();
  5786. next = iterator.peek();
  5787. }
  5788. return iterator;
  5789. }
  5790. };
  5791. ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
  5792. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5793. };
  5794. ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
  5795. var idx = this.resolveIndex_(indexDefinition);
  5796. if (idx) {
  5797. return idx.getReverseIteratorFrom(endPost, function (key) {
  5798. return key;
  5799. });
  5800. }
  5801. else {
  5802. var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5803. var next = iterator.peek();
  5804. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5805. iterator.getNext();
  5806. next = iterator.peek();
  5807. }
  5808. return iterator;
  5809. }
  5810. };
  5811. ChildrenNode.prototype.compareTo = function (other) {
  5812. if (this.isEmpty()) {
  5813. if (other.isEmpty()) {
  5814. return 0;
  5815. }
  5816. else {
  5817. return -1;
  5818. }
  5819. }
  5820. else if (other.isLeafNode() || other.isEmpty()) {
  5821. return 1;
  5822. }
  5823. else if (other === MAX_NODE) {
  5824. return -1;
  5825. }
  5826. else {
  5827. // Must be another node with children.
  5828. return 0;
  5829. }
  5830. };
  5831. ChildrenNode.prototype.withIndex = function (indexDefinition) {
  5832. if (indexDefinition === KEY_INDEX ||
  5833. this.indexMap_.hasIndex(indexDefinition)) {
  5834. return this;
  5835. }
  5836. else {
  5837. var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5838. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5839. }
  5840. };
  5841. ChildrenNode.prototype.isIndexed = function (index) {
  5842. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5843. };
  5844. ChildrenNode.prototype.equals = function (other) {
  5845. if (other === this) {
  5846. return true;
  5847. }
  5848. else if (other.isLeafNode()) {
  5849. return false;
  5850. }
  5851. else {
  5852. var otherChildrenNode = other;
  5853. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5854. return false;
  5855. }
  5856. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5857. var thisIter = this.getIterator(PRIORITY_INDEX);
  5858. var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5859. var thisCurrent = thisIter.getNext();
  5860. var otherCurrent = otherIter.getNext();
  5861. while (thisCurrent && otherCurrent) {
  5862. if (thisCurrent.name !== otherCurrent.name ||
  5863. !thisCurrent.node.equals(otherCurrent.node)) {
  5864. return false;
  5865. }
  5866. thisCurrent = thisIter.getNext();
  5867. otherCurrent = otherIter.getNext();
  5868. }
  5869. return thisCurrent === null && otherCurrent === null;
  5870. }
  5871. else {
  5872. return false;
  5873. }
  5874. }
  5875. };
  5876. /**
  5877. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5878. * instead.
  5879. *
  5880. */
  5881. ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
  5882. if (indexDefinition === KEY_INDEX) {
  5883. return null;
  5884. }
  5885. else {
  5886. return this.indexMap_.get(indexDefinition.toString());
  5887. }
  5888. };
  5889. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5890. return ChildrenNode;
  5891. }());
  5892. var MaxNode = /** @class */ (function (_super) {
  5893. __extends(MaxNode, _super);
  5894. function MaxNode() {
  5895. return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
  5896. }
  5897. MaxNode.prototype.compareTo = function (other) {
  5898. if (other === this) {
  5899. return 0;
  5900. }
  5901. else {
  5902. return 1;
  5903. }
  5904. };
  5905. MaxNode.prototype.equals = function (other) {
  5906. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5907. return other === this;
  5908. };
  5909. MaxNode.prototype.getPriority = function () {
  5910. return this;
  5911. };
  5912. MaxNode.prototype.getImmediateChild = function (childName) {
  5913. return ChildrenNode.EMPTY_NODE;
  5914. };
  5915. MaxNode.prototype.isEmpty = function () {
  5916. return false;
  5917. };
  5918. return MaxNode;
  5919. }(ChildrenNode));
  5920. /**
  5921. * Marker that will sort higher than any other snapshot.
  5922. */
  5923. var MAX_NODE = new MaxNode();
  5924. Object.defineProperties(NamedNode, {
  5925. MIN: {
  5926. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5927. },
  5928. MAX: {
  5929. value: new NamedNode(MAX_NAME, MAX_NODE)
  5930. }
  5931. });
  5932. /**
  5933. * Reference Extensions
  5934. */
  5935. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5936. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5937. setMaxNode$1(MAX_NODE);
  5938. setMaxNode(MAX_NODE);
  5939. /**
  5940. * @license
  5941. * Copyright 2017 Google LLC
  5942. *
  5943. * Licensed under the Apache License, Version 2.0 (the "License");
  5944. * you may not use this file except in compliance with the License.
  5945. * You may obtain a copy of the License at
  5946. *
  5947. * http://www.apache.org/licenses/LICENSE-2.0
  5948. *
  5949. * Unless required by applicable law or agreed to in writing, software
  5950. * distributed under the License is distributed on an "AS IS" BASIS,
  5951. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5952. * See the License for the specific language governing permissions and
  5953. * limitations under the License.
  5954. */
  5955. var USE_HINZE = true;
  5956. /**
  5957. * Constructs a snapshot node representing the passed JSON and returns it.
  5958. * @param json - JSON to create a node for.
  5959. * @param priority - Optional priority to use. This will be ignored if the
  5960. * passed JSON contains a .priority property.
  5961. */
  5962. function nodeFromJSON(json, priority) {
  5963. if (priority === void 0) { priority = null; }
  5964. if (json === null) {
  5965. return ChildrenNode.EMPTY_NODE;
  5966. }
  5967. if (typeof json === 'object' && '.priority' in json) {
  5968. priority = json['.priority'];
  5969. }
  5970. assert(priority === null ||
  5971. typeof priority === 'string' ||
  5972. typeof priority === 'number' ||
  5973. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5974. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5975. json = json['.value'];
  5976. }
  5977. // Valid leaf nodes include non-objects or server-value wrapper objects
  5978. if (typeof json !== 'object' || '.sv' in json) {
  5979. var jsonLeaf = json;
  5980. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5981. }
  5982. if (!(json instanceof Array) && USE_HINZE) {
  5983. var children_1 = [];
  5984. var childrenHavePriority_1 = false;
  5985. var hinzeJsonObj = json;
  5986. each(hinzeJsonObj, function (key, child) {
  5987. if (key.substring(0, 1) !== '.') {
  5988. // Ignore metadata nodes
  5989. var childNode = nodeFromJSON(child);
  5990. if (!childNode.isEmpty()) {
  5991. childrenHavePriority_1 =
  5992. childrenHavePriority_1 || !childNode.getPriority().isEmpty();
  5993. children_1.push(new NamedNode(key, childNode));
  5994. }
  5995. }
  5996. });
  5997. if (children_1.length === 0) {
  5998. return ChildrenNode.EMPTY_NODE;
  5999. }
  6000. var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
  6001. if (childrenHavePriority_1) {
  6002. var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
  6003. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  6004. }
  6005. else {
  6006. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  6007. }
  6008. }
  6009. else {
  6010. var node_1 = ChildrenNode.EMPTY_NODE;
  6011. each(json, function (key, childData) {
  6012. if (contains(json, key)) {
  6013. if (key.substring(0, 1) !== '.') {
  6014. // ignore metadata nodes.
  6015. var childNode = nodeFromJSON(childData);
  6016. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  6017. node_1 = node_1.updateImmediateChild(key, childNode);
  6018. }
  6019. }
  6020. }
  6021. });
  6022. return node_1.updatePriority(nodeFromJSON(priority));
  6023. }
  6024. }
  6025. setNodeFromJSON(nodeFromJSON);
  6026. /**
  6027. * @license
  6028. * Copyright 2017 Google LLC
  6029. *
  6030. * Licensed under the Apache License, Version 2.0 (the "License");
  6031. * you may not use this file except in compliance with the License.
  6032. * You may obtain a copy of the License at
  6033. *
  6034. * http://www.apache.org/licenses/LICENSE-2.0
  6035. *
  6036. * Unless required by applicable law or agreed to in writing, software
  6037. * distributed under the License is distributed on an "AS IS" BASIS,
  6038. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6039. * See the License for the specific language governing permissions and
  6040. * limitations under the License.
  6041. */
  6042. var PathIndex = /** @class */ (function (_super) {
  6043. __extends(PathIndex, _super);
  6044. function PathIndex(indexPath_) {
  6045. var _this = _super.call(this) || this;
  6046. _this.indexPath_ = indexPath_;
  6047. assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  6048. return _this;
  6049. }
  6050. PathIndex.prototype.extractChild = function (snap) {
  6051. return snap.getChild(this.indexPath_);
  6052. };
  6053. PathIndex.prototype.isDefinedOn = function (node) {
  6054. return !node.getChild(this.indexPath_).isEmpty();
  6055. };
  6056. PathIndex.prototype.compare = function (a, b) {
  6057. var aChild = this.extractChild(a.node);
  6058. var bChild = this.extractChild(b.node);
  6059. var indexCmp = aChild.compareTo(bChild);
  6060. if (indexCmp === 0) {
  6061. return nameCompare(a.name, b.name);
  6062. }
  6063. else {
  6064. return indexCmp;
  6065. }
  6066. };
  6067. PathIndex.prototype.makePost = function (indexValue, name) {
  6068. var valueNode = nodeFromJSON(indexValue);
  6069. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  6070. return new NamedNode(name, node);
  6071. };
  6072. PathIndex.prototype.maxPost = function () {
  6073. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  6074. return new NamedNode(MAX_NAME, node);
  6075. };
  6076. PathIndex.prototype.toString = function () {
  6077. return pathSlice(this.indexPath_, 0).join('/');
  6078. };
  6079. return PathIndex;
  6080. }(Index));
  6081. /**
  6082. * @license
  6083. * Copyright 2017 Google LLC
  6084. *
  6085. * Licensed under the Apache License, Version 2.0 (the "License");
  6086. * you may not use this file except in compliance with the License.
  6087. * You may obtain a copy of the License at
  6088. *
  6089. * http://www.apache.org/licenses/LICENSE-2.0
  6090. *
  6091. * Unless required by applicable law or agreed to in writing, software
  6092. * distributed under the License is distributed on an "AS IS" BASIS,
  6093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6094. * See the License for the specific language governing permissions and
  6095. * limitations under the License.
  6096. */
  6097. var ValueIndex = /** @class */ (function (_super) {
  6098. __extends(ValueIndex, _super);
  6099. function ValueIndex() {
  6100. return _super !== null && _super.apply(this, arguments) || this;
  6101. }
  6102. ValueIndex.prototype.compare = function (a, b) {
  6103. var indexCmp = a.node.compareTo(b.node);
  6104. if (indexCmp === 0) {
  6105. return nameCompare(a.name, b.name);
  6106. }
  6107. else {
  6108. return indexCmp;
  6109. }
  6110. };
  6111. ValueIndex.prototype.isDefinedOn = function (node) {
  6112. return true;
  6113. };
  6114. ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  6115. return !oldNode.equals(newNode);
  6116. };
  6117. ValueIndex.prototype.minPost = function () {
  6118. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6119. return NamedNode.MIN;
  6120. };
  6121. ValueIndex.prototype.maxPost = function () {
  6122. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6123. return NamedNode.MAX;
  6124. };
  6125. ValueIndex.prototype.makePost = function (indexValue, name) {
  6126. var valueNode = nodeFromJSON(indexValue);
  6127. return new NamedNode(name, valueNode);
  6128. };
  6129. /**
  6130. * @returns String representation for inclusion in a query spec
  6131. */
  6132. ValueIndex.prototype.toString = function () {
  6133. return '.value';
  6134. };
  6135. return ValueIndex;
  6136. }(Index));
  6137. var VALUE_INDEX = new ValueIndex();
  6138. /**
  6139. * @license
  6140. * Copyright 2017 Google LLC
  6141. *
  6142. * Licensed under the Apache License, Version 2.0 (the "License");
  6143. * you may not use this file except in compliance with the License.
  6144. * You may obtain a copy of the License at
  6145. *
  6146. * http://www.apache.org/licenses/LICENSE-2.0
  6147. *
  6148. * Unless required by applicable law or agreed to in writing, software
  6149. * distributed under the License is distributed on an "AS IS" BASIS,
  6150. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6151. * See the License for the specific language governing permissions and
  6152. * limitations under the License.
  6153. */
  6154. function changeValue(snapshotNode) {
  6155. return { type: "value" /* ChangeType.VALUE */, snapshotNode: snapshotNode };
  6156. }
  6157. function changeChildAdded(childName, snapshotNode) {
  6158. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode: snapshotNode, childName: childName };
  6159. }
  6160. function changeChildRemoved(childName, snapshotNode) {
  6161. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode: snapshotNode, childName: childName };
  6162. }
  6163. function changeChildChanged(childName, snapshotNode, oldSnap) {
  6164. return {
  6165. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  6166. snapshotNode: snapshotNode,
  6167. childName: childName,
  6168. oldSnap: oldSnap
  6169. };
  6170. }
  6171. function changeChildMoved(childName, snapshotNode) {
  6172. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode: snapshotNode, childName: childName };
  6173. }
  6174. /**
  6175. * @license
  6176. * Copyright 2017 Google LLC
  6177. *
  6178. * Licensed under the Apache License, Version 2.0 (the "License");
  6179. * you may not use this file except in compliance with the License.
  6180. * You may obtain a copy of the License at
  6181. *
  6182. * http://www.apache.org/licenses/LICENSE-2.0
  6183. *
  6184. * Unless required by applicable law or agreed to in writing, software
  6185. * distributed under the License is distributed on an "AS IS" BASIS,
  6186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6187. * See the License for the specific language governing permissions and
  6188. * limitations under the License.
  6189. */
  6190. /**
  6191. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  6192. */
  6193. var IndexedFilter = /** @class */ (function () {
  6194. function IndexedFilter(index_) {
  6195. this.index_ = index_;
  6196. }
  6197. IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6198. assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  6199. var oldChild = snap.getImmediateChild(key);
  6200. // Check if anything actually changed.
  6201. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  6202. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  6203. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  6204. // to avoid treating these cases as "nothing changed."
  6205. if (oldChild.isEmpty() === newChild.isEmpty()) {
  6206. // Nothing changed.
  6207. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  6208. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  6209. return snap;
  6210. }
  6211. }
  6212. if (optChangeAccumulator != null) {
  6213. if (newChild.isEmpty()) {
  6214. if (snap.hasChild(key)) {
  6215. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6216. }
  6217. else {
  6218. assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6219. }
  6220. }
  6221. else if (oldChild.isEmpty()) {
  6222. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6223. }
  6224. else {
  6225. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6226. }
  6227. }
  6228. if (snap.isLeafNode() && newChild.isEmpty()) {
  6229. return snap;
  6230. }
  6231. else {
  6232. // Make sure the node is indexed
  6233. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6234. }
  6235. };
  6236. IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6237. if (optChangeAccumulator != null) {
  6238. if (!oldSnap.isLeafNode()) {
  6239. oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6240. if (!newSnap.hasChild(key)) {
  6241. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6242. }
  6243. });
  6244. }
  6245. if (!newSnap.isLeafNode()) {
  6246. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6247. if (oldSnap.hasChild(key)) {
  6248. var oldChild = oldSnap.getImmediateChild(key);
  6249. if (!oldChild.equals(childNode)) {
  6250. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6251. }
  6252. }
  6253. else {
  6254. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6255. }
  6256. });
  6257. }
  6258. }
  6259. return newSnap.withIndex(this.index_);
  6260. };
  6261. IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6262. if (oldSnap.isEmpty()) {
  6263. return ChildrenNode.EMPTY_NODE;
  6264. }
  6265. else {
  6266. return oldSnap.updatePriority(newPriority);
  6267. }
  6268. };
  6269. IndexedFilter.prototype.filtersNodes = function () {
  6270. return false;
  6271. };
  6272. IndexedFilter.prototype.getIndexedFilter = function () {
  6273. return this;
  6274. };
  6275. IndexedFilter.prototype.getIndex = function () {
  6276. return this.index_;
  6277. };
  6278. return IndexedFilter;
  6279. }());
  6280. /**
  6281. * @license
  6282. * Copyright 2017 Google LLC
  6283. *
  6284. * Licensed under the Apache License, Version 2.0 (the "License");
  6285. * you may not use this file except in compliance with the License.
  6286. * You may obtain a copy of the License at
  6287. *
  6288. * http://www.apache.org/licenses/LICENSE-2.0
  6289. *
  6290. * Unless required by applicable law or agreed to in writing, software
  6291. * distributed under the License is distributed on an "AS IS" BASIS,
  6292. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6293. * See the License for the specific language governing permissions and
  6294. * limitations under the License.
  6295. */
  6296. /**
  6297. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6298. */
  6299. var RangedFilter = /** @class */ (function () {
  6300. function RangedFilter(params) {
  6301. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6302. this.index_ = params.getIndex();
  6303. this.startPost_ = RangedFilter.getStartPost_(params);
  6304. this.endPost_ = RangedFilter.getEndPost_(params);
  6305. this.startIsInclusive_ = !params.startAfterSet_;
  6306. this.endIsInclusive_ = !params.endBeforeSet_;
  6307. }
  6308. RangedFilter.prototype.getStartPost = function () {
  6309. return this.startPost_;
  6310. };
  6311. RangedFilter.prototype.getEndPost = function () {
  6312. return this.endPost_;
  6313. };
  6314. RangedFilter.prototype.matches = function (node) {
  6315. var isWithinStart = this.startIsInclusive_
  6316. ? this.index_.compare(this.getStartPost(), node) <= 0
  6317. : this.index_.compare(this.getStartPost(), node) < 0;
  6318. var isWithinEnd = this.endIsInclusive_
  6319. ? this.index_.compare(node, this.getEndPost()) <= 0
  6320. : this.index_.compare(node, this.getEndPost()) < 0;
  6321. return isWithinStart && isWithinEnd;
  6322. };
  6323. RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6324. if (!this.matches(new NamedNode(key, newChild))) {
  6325. newChild = ChildrenNode.EMPTY_NODE;
  6326. }
  6327. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6328. };
  6329. RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6330. if (newSnap.isLeafNode()) {
  6331. // Make sure we have a children node with the correct index, not a leaf node;
  6332. newSnap = ChildrenNode.EMPTY_NODE;
  6333. }
  6334. var filtered = newSnap.withIndex(this.index_);
  6335. // Don't support priorities on queries
  6336. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6337. var self = this;
  6338. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6339. if (!self.matches(new NamedNode(key, childNode))) {
  6340. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6341. }
  6342. });
  6343. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6344. };
  6345. RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6346. // Don't support priorities on queries
  6347. return oldSnap;
  6348. };
  6349. RangedFilter.prototype.filtersNodes = function () {
  6350. return true;
  6351. };
  6352. RangedFilter.prototype.getIndexedFilter = function () {
  6353. return this.indexedFilter_;
  6354. };
  6355. RangedFilter.prototype.getIndex = function () {
  6356. return this.index_;
  6357. };
  6358. RangedFilter.getStartPost_ = function (params) {
  6359. if (params.hasStart()) {
  6360. var startName = params.getIndexStartName();
  6361. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6362. }
  6363. else {
  6364. return params.getIndex().minPost();
  6365. }
  6366. };
  6367. RangedFilter.getEndPost_ = function (params) {
  6368. if (params.hasEnd()) {
  6369. var endName = params.getIndexEndName();
  6370. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6371. }
  6372. else {
  6373. return params.getIndex().maxPost();
  6374. }
  6375. };
  6376. return RangedFilter;
  6377. }());
  6378. /**
  6379. * @license
  6380. * Copyright 2017 Google LLC
  6381. *
  6382. * Licensed under the Apache License, Version 2.0 (the "License");
  6383. * you may not use this file except in compliance with the License.
  6384. * You may obtain a copy of the License at
  6385. *
  6386. * http://www.apache.org/licenses/LICENSE-2.0
  6387. *
  6388. * Unless required by applicable law or agreed to in writing, software
  6389. * distributed under the License is distributed on an "AS IS" BASIS,
  6390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6391. * See the License for the specific language governing permissions and
  6392. * limitations under the License.
  6393. */
  6394. /**
  6395. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6396. */
  6397. var LimitedFilter = /** @class */ (function () {
  6398. function LimitedFilter(params) {
  6399. var _this = this;
  6400. this.withinDirectionalStart = function (node) {
  6401. return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
  6402. };
  6403. this.withinDirectionalEnd = function (node) {
  6404. return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
  6405. };
  6406. this.withinStartPost = function (node) {
  6407. var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
  6408. return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6409. };
  6410. this.withinEndPost = function (node) {
  6411. var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
  6412. return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6413. };
  6414. this.rangedFilter_ = new RangedFilter(params);
  6415. this.index_ = params.getIndex();
  6416. this.limit_ = params.getLimit();
  6417. this.reverse_ = !params.isViewFromLeft();
  6418. this.startIsInclusive_ = !params.startAfterSet_;
  6419. this.endIsInclusive_ = !params.endBeforeSet_;
  6420. }
  6421. LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6422. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6423. newChild = ChildrenNode.EMPTY_NODE;
  6424. }
  6425. if (snap.getImmediateChild(key).equals(newChild)) {
  6426. // No change
  6427. return snap;
  6428. }
  6429. else if (snap.numChildren() < this.limit_) {
  6430. return this.rangedFilter_
  6431. .getIndexedFilter()
  6432. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6433. }
  6434. else {
  6435. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6436. }
  6437. };
  6438. LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6439. var filtered;
  6440. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6441. // Make sure we have a children node with the correct index, not a leaf node;
  6442. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6443. }
  6444. else {
  6445. if (this.limit_ * 2 < newSnap.numChildren() &&
  6446. newSnap.isIndexed(this.index_)) {
  6447. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6448. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6449. // anchor to the startPost, endPost, or last element as appropriate
  6450. var iterator = void 0;
  6451. if (this.reverse_) {
  6452. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6453. }
  6454. else {
  6455. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6456. }
  6457. var count = 0;
  6458. while (iterator.hasNext() && count < this.limit_) {
  6459. var next = iterator.getNext();
  6460. if (!this.withinDirectionalStart(next)) {
  6461. // if we have not reached the start, skip to the next element
  6462. continue;
  6463. }
  6464. else if (!this.withinDirectionalEnd(next)) {
  6465. // if we have reached the end, stop adding elements
  6466. break;
  6467. }
  6468. else {
  6469. filtered = filtered.updateImmediateChild(next.name, next.node);
  6470. count++;
  6471. }
  6472. }
  6473. }
  6474. else {
  6475. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6476. filtered = newSnap.withIndex(this.index_);
  6477. // Don't support priorities on queries
  6478. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6479. var iterator = void 0;
  6480. if (this.reverse_) {
  6481. iterator = filtered.getReverseIterator(this.index_);
  6482. }
  6483. else {
  6484. iterator = filtered.getIterator(this.index_);
  6485. }
  6486. var count = 0;
  6487. while (iterator.hasNext()) {
  6488. var next = iterator.getNext();
  6489. var inRange = count < this.limit_ &&
  6490. this.withinDirectionalStart(next) &&
  6491. this.withinDirectionalEnd(next);
  6492. if (inRange) {
  6493. count++;
  6494. }
  6495. else {
  6496. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6497. }
  6498. }
  6499. }
  6500. }
  6501. return this.rangedFilter_
  6502. .getIndexedFilter()
  6503. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6504. };
  6505. LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6506. // Don't support priorities on queries
  6507. return oldSnap;
  6508. };
  6509. LimitedFilter.prototype.filtersNodes = function () {
  6510. return true;
  6511. };
  6512. LimitedFilter.prototype.getIndexedFilter = function () {
  6513. return this.rangedFilter_.getIndexedFilter();
  6514. };
  6515. LimitedFilter.prototype.getIndex = function () {
  6516. return this.index_;
  6517. };
  6518. LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
  6519. // TODO: rename all cache stuff etc to general snap terminology
  6520. var cmp;
  6521. if (this.reverse_) {
  6522. var indexCmp_1 = this.index_.getCompare();
  6523. cmp = function (a, b) { return indexCmp_1(b, a); };
  6524. }
  6525. else {
  6526. cmp = this.index_.getCompare();
  6527. }
  6528. var oldEventCache = snap;
  6529. assert(oldEventCache.numChildren() === this.limit_, '');
  6530. var newChildNamedNode = new NamedNode(childKey, childSnap);
  6531. var windowBoundary = this.reverse_
  6532. ? oldEventCache.getFirstChild(this.index_)
  6533. : oldEventCache.getLastChild(this.index_);
  6534. var inRange = this.rangedFilter_.matches(newChildNamedNode);
  6535. if (oldEventCache.hasChild(childKey)) {
  6536. var oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6537. var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6538. while (nextChild != null &&
  6539. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6540. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6541. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6542. // the limited filter...
  6543. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6544. }
  6545. var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6546. var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6547. if (remainsInWindow) {
  6548. if (changeAccumulator != null) {
  6549. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6550. }
  6551. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6552. }
  6553. else {
  6554. if (changeAccumulator != null) {
  6555. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6556. }
  6557. var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6558. var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6559. if (nextChildInRange) {
  6560. if (changeAccumulator != null) {
  6561. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6562. }
  6563. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6564. }
  6565. else {
  6566. return newEventCache;
  6567. }
  6568. }
  6569. }
  6570. else if (childSnap.isEmpty()) {
  6571. // we're deleting a node, but it was not in the window, so ignore it
  6572. return snap;
  6573. }
  6574. else if (inRange) {
  6575. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6576. if (changeAccumulator != null) {
  6577. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6578. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6579. }
  6580. return oldEventCache
  6581. .updateImmediateChild(childKey, childSnap)
  6582. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6583. }
  6584. else {
  6585. return snap;
  6586. }
  6587. }
  6588. else {
  6589. return snap;
  6590. }
  6591. };
  6592. return LimitedFilter;
  6593. }());
  6594. /**
  6595. * @license
  6596. * Copyright 2017 Google LLC
  6597. *
  6598. * Licensed under the Apache License, Version 2.0 (the "License");
  6599. * you may not use this file except in compliance with the License.
  6600. * You may obtain a copy of the License at
  6601. *
  6602. * http://www.apache.org/licenses/LICENSE-2.0
  6603. *
  6604. * Unless required by applicable law or agreed to in writing, software
  6605. * distributed under the License is distributed on an "AS IS" BASIS,
  6606. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6607. * See the License for the specific language governing permissions and
  6608. * limitations under the License.
  6609. */
  6610. /**
  6611. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6612. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6613. * user-facing API level, so it is not done here.
  6614. *
  6615. * @internal
  6616. */
  6617. var QueryParams = /** @class */ (function () {
  6618. function QueryParams() {
  6619. this.limitSet_ = false;
  6620. this.startSet_ = false;
  6621. this.startNameSet_ = false;
  6622. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6623. this.endSet_ = false;
  6624. this.endNameSet_ = false;
  6625. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6626. this.limit_ = 0;
  6627. this.viewFrom_ = '';
  6628. this.indexStartValue_ = null;
  6629. this.indexStartName_ = '';
  6630. this.indexEndValue_ = null;
  6631. this.indexEndName_ = '';
  6632. this.index_ = PRIORITY_INDEX;
  6633. }
  6634. QueryParams.prototype.hasStart = function () {
  6635. return this.startSet_;
  6636. };
  6637. /**
  6638. * @returns True if it would return from left.
  6639. */
  6640. QueryParams.prototype.isViewFromLeft = function () {
  6641. if (this.viewFrom_ === '') {
  6642. // limit(), rather than limitToFirst or limitToLast was called.
  6643. // This means that only one of startSet_ and endSet_ is true. Use them
  6644. // to calculate which side of the view to anchor to. If neither is set,
  6645. // anchor to the end.
  6646. return this.startSet_;
  6647. }
  6648. else {
  6649. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6650. }
  6651. };
  6652. /**
  6653. * Only valid to call if hasStart() returns true
  6654. */
  6655. QueryParams.prototype.getIndexStartValue = function () {
  6656. assert(this.startSet_, 'Only valid if start has been set');
  6657. return this.indexStartValue_;
  6658. };
  6659. /**
  6660. * Only valid to call if hasStart() returns true.
  6661. * Returns the starting key name for the range defined by these query parameters
  6662. */
  6663. QueryParams.prototype.getIndexStartName = function () {
  6664. assert(this.startSet_, 'Only valid if start has been set');
  6665. if (this.startNameSet_) {
  6666. return this.indexStartName_;
  6667. }
  6668. else {
  6669. return MIN_NAME;
  6670. }
  6671. };
  6672. QueryParams.prototype.hasEnd = function () {
  6673. return this.endSet_;
  6674. };
  6675. /**
  6676. * Only valid to call if hasEnd() returns true.
  6677. */
  6678. QueryParams.prototype.getIndexEndValue = function () {
  6679. assert(this.endSet_, 'Only valid if end has been set');
  6680. return this.indexEndValue_;
  6681. };
  6682. /**
  6683. * Only valid to call if hasEnd() returns true.
  6684. * Returns the end key name for the range defined by these query parameters
  6685. */
  6686. QueryParams.prototype.getIndexEndName = function () {
  6687. assert(this.endSet_, 'Only valid if end has been set');
  6688. if (this.endNameSet_) {
  6689. return this.indexEndName_;
  6690. }
  6691. else {
  6692. return MAX_NAME;
  6693. }
  6694. };
  6695. QueryParams.prototype.hasLimit = function () {
  6696. return this.limitSet_;
  6697. };
  6698. /**
  6699. * @returns True if a limit has been set and it has been explicitly anchored
  6700. */
  6701. QueryParams.prototype.hasAnchoredLimit = function () {
  6702. return this.limitSet_ && this.viewFrom_ !== '';
  6703. };
  6704. /**
  6705. * Only valid to call if hasLimit() returns true
  6706. */
  6707. QueryParams.prototype.getLimit = function () {
  6708. assert(this.limitSet_, 'Only valid if limit has been set');
  6709. return this.limit_;
  6710. };
  6711. QueryParams.prototype.getIndex = function () {
  6712. return this.index_;
  6713. };
  6714. QueryParams.prototype.loadsAllData = function () {
  6715. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6716. };
  6717. QueryParams.prototype.isDefault = function () {
  6718. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6719. };
  6720. QueryParams.prototype.copy = function () {
  6721. var copy = new QueryParams();
  6722. copy.limitSet_ = this.limitSet_;
  6723. copy.limit_ = this.limit_;
  6724. copy.startSet_ = this.startSet_;
  6725. copy.startAfterSet_ = this.startAfterSet_;
  6726. copy.indexStartValue_ = this.indexStartValue_;
  6727. copy.startNameSet_ = this.startNameSet_;
  6728. copy.indexStartName_ = this.indexStartName_;
  6729. copy.endSet_ = this.endSet_;
  6730. copy.endBeforeSet_ = this.endBeforeSet_;
  6731. copy.indexEndValue_ = this.indexEndValue_;
  6732. copy.endNameSet_ = this.endNameSet_;
  6733. copy.indexEndName_ = this.indexEndName_;
  6734. copy.index_ = this.index_;
  6735. copy.viewFrom_ = this.viewFrom_;
  6736. return copy;
  6737. };
  6738. return QueryParams;
  6739. }());
  6740. function queryParamsGetNodeFilter(queryParams) {
  6741. if (queryParams.loadsAllData()) {
  6742. return new IndexedFilter(queryParams.getIndex());
  6743. }
  6744. else if (queryParams.hasLimit()) {
  6745. return new LimitedFilter(queryParams);
  6746. }
  6747. else {
  6748. return new RangedFilter(queryParams);
  6749. }
  6750. }
  6751. function queryParamsLimitToFirst(queryParams, newLimit) {
  6752. var newParams = queryParams.copy();
  6753. newParams.limitSet_ = true;
  6754. newParams.limit_ = newLimit;
  6755. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6756. return newParams;
  6757. }
  6758. function queryParamsLimitToLast(queryParams, newLimit) {
  6759. var newParams = queryParams.copy();
  6760. newParams.limitSet_ = true;
  6761. newParams.limit_ = newLimit;
  6762. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6763. return newParams;
  6764. }
  6765. function queryParamsStartAt(queryParams, indexValue, key) {
  6766. var newParams = queryParams.copy();
  6767. newParams.startSet_ = true;
  6768. if (indexValue === undefined) {
  6769. indexValue = null;
  6770. }
  6771. newParams.indexStartValue_ = indexValue;
  6772. if (key != null) {
  6773. newParams.startNameSet_ = true;
  6774. newParams.indexStartName_ = key;
  6775. }
  6776. else {
  6777. newParams.startNameSet_ = false;
  6778. newParams.indexStartName_ = '';
  6779. }
  6780. return newParams;
  6781. }
  6782. function queryParamsStartAfter(queryParams, indexValue, key) {
  6783. var params;
  6784. if (queryParams.index_ === KEY_INDEX || !!key) {
  6785. params = queryParamsStartAt(queryParams, indexValue, key);
  6786. }
  6787. else {
  6788. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6789. }
  6790. params.startAfterSet_ = true;
  6791. return params;
  6792. }
  6793. function queryParamsEndAt(queryParams, indexValue, key) {
  6794. var newParams = queryParams.copy();
  6795. newParams.endSet_ = true;
  6796. if (indexValue === undefined) {
  6797. indexValue = null;
  6798. }
  6799. newParams.indexEndValue_ = indexValue;
  6800. if (key !== undefined) {
  6801. newParams.endNameSet_ = true;
  6802. newParams.indexEndName_ = key;
  6803. }
  6804. else {
  6805. newParams.endNameSet_ = false;
  6806. newParams.indexEndName_ = '';
  6807. }
  6808. return newParams;
  6809. }
  6810. function queryParamsEndBefore(queryParams, indexValue, key) {
  6811. var params;
  6812. if (queryParams.index_ === KEY_INDEX || !!key) {
  6813. params = queryParamsEndAt(queryParams, indexValue, key);
  6814. }
  6815. else {
  6816. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6817. }
  6818. params.endBeforeSet_ = true;
  6819. return params;
  6820. }
  6821. function queryParamsOrderBy(queryParams, index) {
  6822. var newParams = queryParams.copy();
  6823. newParams.index_ = index;
  6824. return newParams;
  6825. }
  6826. /**
  6827. * Returns a set of REST query string parameters representing this query.
  6828. *
  6829. * @returns query string parameters
  6830. */
  6831. function queryParamsToRestQueryStringParameters(queryParams) {
  6832. var qs = {};
  6833. if (queryParams.isDefault()) {
  6834. return qs;
  6835. }
  6836. var orderBy;
  6837. if (queryParams.index_ === PRIORITY_INDEX) {
  6838. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6839. }
  6840. else if (queryParams.index_ === VALUE_INDEX) {
  6841. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6842. }
  6843. else if (queryParams.index_ === KEY_INDEX) {
  6844. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6845. }
  6846. else {
  6847. assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6848. orderBy = queryParams.index_.toString();
  6849. }
  6850. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);
  6851. if (queryParams.startSet_) {
  6852. var startParam = queryParams.startAfterSet_
  6853. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6854. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6855. qs[startParam] = stringify(queryParams.indexStartValue_);
  6856. if (queryParams.startNameSet_) {
  6857. qs[startParam] += ',' + stringify(queryParams.indexStartName_);
  6858. }
  6859. }
  6860. if (queryParams.endSet_) {
  6861. var endParam = queryParams.endBeforeSet_
  6862. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6863. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6864. qs[endParam] = stringify(queryParams.indexEndValue_);
  6865. if (queryParams.endNameSet_) {
  6866. qs[endParam] += ',' + stringify(queryParams.indexEndName_);
  6867. }
  6868. }
  6869. if (queryParams.limitSet_) {
  6870. if (queryParams.isViewFromLeft()) {
  6871. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6872. }
  6873. else {
  6874. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6875. }
  6876. }
  6877. return qs;
  6878. }
  6879. function queryParamsGetQueryObject(queryParams) {
  6880. var obj = {};
  6881. if (queryParams.startSet_) {
  6882. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6883. queryParams.indexStartValue_;
  6884. if (queryParams.startNameSet_) {
  6885. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6886. queryParams.indexStartName_;
  6887. }
  6888. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6889. !queryParams.startAfterSet_;
  6890. }
  6891. if (queryParams.endSet_) {
  6892. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6893. if (queryParams.endNameSet_) {
  6894. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6895. }
  6896. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6897. !queryParams.endBeforeSet_;
  6898. }
  6899. if (queryParams.limitSet_) {
  6900. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6901. var viewFrom = queryParams.viewFrom_;
  6902. if (viewFrom === '') {
  6903. if (queryParams.isViewFromLeft()) {
  6904. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6905. }
  6906. else {
  6907. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6908. }
  6909. }
  6910. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6911. }
  6912. // For now, priority index is the default, so we only specify if it's some other index
  6913. if (queryParams.index_ !== PRIORITY_INDEX) {
  6914. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6915. }
  6916. return obj;
  6917. }
  6918. /**
  6919. * @license
  6920. * Copyright 2017 Google LLC
  6921. *
  6922. * Licensed under the Apache License, Version 2.0 (the "License");
  6923. * you may not use this file except in compliance with the License.
  6924. * You may obtain a copy of the License at
  6925. *
  6926. * http://www.apache.org/licenses/LICENSE-2.0
  6927. *
  6928. * Unless required by applicable law or agreed to in writing, software
  6929. * distributed under the License is distributed on an "AS IS" BASIS,
  6930. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6931. * See the License for the specific language governing permissions and
  6932. * limitations under the License.
  6933. */
  6934. /**
  6935. * An implementation of ServerActions that communicates with the server via REST requests.
  6936. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6937. * persistent connection (using WebSockets or long-polling)
  6938. */
  6939. var ReadonlyRestClient = /** @class */ (function (_super) {
  6940. __extends(ReadonlyRestClient, _super);
  6941. /**
  6942. * @param repoInfo_ - Data about the namespace we are connecting to
  6943. * @param onDataUpdate_ - A callback for new data from the server
  6944. */
  6945. function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6946. var _this = _super.call(this) || this;
  6947. _this.repoInfo_ = repoInfo_;
  6948. _this.onDataUpdate_ = onDataUpdate_;
  6949. _this.authTokenProvider_ = authTokenProvider_;
  6950. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6951. /** @private {function(...[*])} */
  6952. _this.log_ = logWrapper('p:rest:');
  6953. /**
  6954. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6955. * that's been removed. :-/
  6956. */
  6957. _this.listens_ = {};
  6958. return _this;
  6959. }
  6960. ReadonlyRestClient.prototype.reportStats = function (stats) {
  6961. throw new Error('Method not implemented.');
  6962. };
  6963. ReadonlyRestClient.getListenId_ = function (query, tag) {
  6964. if (tag !== undefined) {
  6965. return 'tag$' + tag;
  6966. }
  6967. else {
  6968. assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6969. return query._path.toString();
  6970. }
  6971. };
  6972. /** @inheritDoc */
  6973. ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  6974. var _this = this;
  6975. var pathString = query._path.toString();
  6976. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6977. // Mark this listener so we can tell if it's removed.
  6978. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  6979. var thisListen = {};
  6980. this.listens_[listenId] = thisListen;
  6981. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6982. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  6983. var data = result;
  6984. if (error === 404) {
  6985. data = null;
  6986. error = null;
  6987. }
  6988. if (error === null) {
  6989. _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6990. }
  6991. if (safeGet(_this.listens_, listenId) === thisListen) {
  6992. var status_1;
  6993. if (!error) {
  6994. status_1 = 'ok';
  6995. }
  6996. else if (error === 401) {
  6997. status_1 = 'permission_denied';
  6998. }
  6999. else {
  7000. status_1 = 'rest_error:' + error;
  7001. }
  7002. onComplete(status_1, null);
  7003. }
  7004. });
  7005. };
  7006. /** @inheritDoc */
  7007. ReadonlyRestClient.prototype.unlisten = function (query, tag) {
  7008. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  7009. delete this.listens_[listenId];
  7010. };
  7011. ReadonlyRestClient.prototype.get = function (query) {
  7012. var _this = this;
  7013. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  7014. var pathString = query._path.toString();
  7015. var deferred = new Deferred();
  7016. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  7017. var data = result;
  7018. if (error === 404) {
  7019. data = null;
  7020. error = null;
  7021. }
  7022. if (error === null) {
  7023. _this.onDataUpdate_(pathString, data,
  7024. /*isMerge=*/ false,
  7025. /*tag=*/ null);
  7026. deferred.resolve(data);
  7027. }
  7028. else {
  7029. deferred.reject(new Error(data));
  7030. }
  7031. });
  7032. return deferred.promise;
  7033. };
  7034. /** @inheritDoc */
  7035. ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
  7036. // no-op since we just always call getToken.
  7037. };
  7038. /**
  7039. * Performs a REST request to the given path, with the provided query string parameters,
  7040. * and any auth credentials we have.
  7041. */
  7042. ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
  7043. var _this = this;
  7044. if (queryStringParameters === void 0) { queryStringParameters = {}; }
  7045. queryStringParameters['format'] = 'export';
  7046. return Promise.all([
  7047. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  7048. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  7049. ]).then(function (_a) {
  7050. var _b = __read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
  7051. if (authToken && authToken.accessToken) {
  7052. queryStringParameters['auth'] = authToken.accessToken;
  7053. }
  7054. if (appCheckToken && appCheckToken.token) {
  7055. queryStringParameters['ac'] = appCheckToken.token;
  7056. }
  7057. var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
  7058. _this.repoInfo_.host +
  7059. pathString +
  7060. '?' +
  7061. 'ns=' +
  7062. _this.repoInfo_.namespace +
  7063. querystring(queryStringParameters);
  7064. _this.log_('Sending REST request for ' + url);
  7065. var xhr = new XMLHttpRequest();
  7066. xhr.onreadystatechange = function () {
  7067. if (callback && xhr.readyState === 4) {
  7068. _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  7069. var res = null;
  7070. if (xhr.status >= 200 && xhr.status < 300) {
  7071. try {
  7072. res = jsonEval(xhr.responseText);
  7073. }
  7074. catch (e) {
  7075. warn('Failed to parse JSON response for ' +
  7076. url +
  7077. ': ' +
  7078. xhr.responseText);
  7079. }
  7080. callback(null, res);
  7081. }
  7082. else {
  7083. // 401 and 404 are expected.
  7084. if (xhr.status !== 401 && xhr.status !== 404) {
  7085. warn('Got unsuccessful REST response for ' +
  7086. url +
  7087. ' Status: ' +
  7088. xhr.status);
  7089. }
  7090. callback(xhr.status);
  7091. }
  7092. callback = null;
  7093. }
  7094. };
  7095. xhr.open('GET', url, /*asynchronous=*/ true);
  7096. xhr.send();
  7097. });
  7098. };
  7099. return ReadonlyRestClient;
  7100. }(ServerActions));
  7101. /**
  7102. * @license
  7103. * Copyright 2017 Google LLC
  7104. *
  7105. * Licensed under the Apache License, Version 2.0 (the "License");
  7106. * you may not use this file except in compliance with the License.
  7107. * You may obtain a copy of the License at
  7108. *
  7109. * http://www.apache.org/licenses/LICENSE-2.0
  7110. *
  7111. * Unless required by applicable law or agreed to in writing, software
  7112. * distributed under the License is distributed on an "AS IS" BASIS,
  7113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7114. * See the License for the specific language governing permissions and
  7115. * limitations under the License.
  7116. */
  7117. /**
  7118. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  7119. */
  7120. var SnapshotHolder = /** @class */ (function () {
  7121. function SnapshotHolder() {
  7122. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  7123. }
  7124. SnapshotHolder.prototype.getNode = function (path) {
  7125. return this.rootNode_.getChild(path);
  7126. };
  7127. SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
  7128. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  7129. };
  7130. return SnapshotHolder;
  7131. }());
  7132. /**
  7133. * @license
  7134. * Copyright 2017 Google LLC
  7135. *
  7136. * Licensed under the Apache License, Version 2.0 (the "License");
  7137. * you may not use this file except in compliance with the License.
  7138. * You may obtain a copy of the License at
  7139. *
  7140. * http://www.apache.org/licenses/LICENSE-2.0
  7141. *
  7142. * Unless required by applicable law or agreed to in writing, software
  7143. * distributed under the License is distributed on an "AS IS" BASIS,
  7144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7145. * See the License for the specific language governing permissions and
  7146. * limitations under the License.
  7147. */
  7148. function newSparseSnapshotTree() {
  7149. return {
  7150. value: null,
  7151. children: new Map()
  7152. };
  7153. }
  7154. /**
  7155. * Stores the given node at the specified path. If there is already a node
  7156. * at a shallower path, it merges the new data into that snapshot node.
  7157. *
  7158. * @param path - Path to look up snapshot for.
  7159. * @param data - The new data, or null.
  7160. */
  7161. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  7162. if (pathIsEmpty(path)) {
  7163. sparseSnapshotTree.value = data;
  7164. sparseSnapshotTree.children.clear();
  7165. }
  7166. else if (sparseSnapshotTree.value !== null) {
  7167. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  7168. }
  7169. else {
  7170. var childKey = pathGetFront(path);
  7171. if (!sparseSnapshotTree.children.has(childKey)) {
  7172. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  7173. }
  7174. var child = sparseSnapshotTree.children.get(childKey);
  7175. path = pathPopFront(path);
  7176. sparseSnapshotTreeRemember(child, path, data);
  7177. }
  7178. }
  7179. /**
  7180. * Purge the data at path from the cache.
  7181. *
  7182. * @param path - Path to look up snapshot for.
  7183. * @returns True if this node should now be removed.
  7184. */
  7185. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  7186. if (pathIsEmpty(path)) {
  7187. sparseSnapshotTree.value = null;
  7188. sparseSnapshotTree.children.clear();
  7189. return true;
  7190. }
  7191. else {
  7192. if (sparseSnapshotTree.value !== null) {
  7193. if (sparseSnapshotTree.value.isLeafNode()) {
  7194. // We're trying to forget a node that doesn't exist
  7195. return false;
  7196. }
  7197. else {
  7198. var value = sparseSnapshotTree.value;
  7199. sparseSnapshotTree.value = null;
  7200. value.forEachChild(PRIORITY_INDEX, function (key, tree) {
  7201. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  7202. });
  7203. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  7204. }
  7205. }
  7206. else if (sparseSnapshotTree.children.size > 0) {
  7207. var childKey = pathGetFront(path);
  7208. path = pathPopFront(path);
  7209. if (sparseSnapshotTree.children.has(childKey)) {
  7210. var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  7211. if (safeToRemove) {
  7212. sparseSnapshotTree.children.delete(childKey);
  7213. }
  7214. }
  7215. return sparseSnapshotTree.children.size === 0;
  7216. }
  7217. else {
  7218. return true;
  7219. }
  7220. }
  7221. }
  7222. /**
  7223. * Recursively iterates through all of the stored tree and calls the
  7224. * callback on each one.
  7225. *
  7226. * @param prefixPath - Path to look up node for.
  7227. * @param func - The function to invoke for each tree.
  7228. */
  7229. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7230. if (sparseSnapshotTree.value !== null) {
  7231. func(prefixPath, sparseSnapshotTree.value);
  7232. }
  7233. else {
  7234. sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
  7235. var path = new Path(prefixPath.toString() + '/' + key);
  7236. sparseSnapshotTreeForEachTree(tree, path, func);
  7237. });
  7238. }
  7239. }
  7240. /**
  7241. * Iterates through each immediate child and triggers the callback.
  7242. * Only seems to be used in tests.
  7243. *
  7244. * @param func - The function to invoke for each child.
  7245. */
  7246. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7247. sparseSnapshotTree.children.forEach(function (tree, key) {
  7248. func(key, tree);
  7249. });
  7250. }
  7251. /**
  7252. * @license
  7253. * Copyright 2017 Google LLC
  7254. *
  7255. * Licensed under the Apache License, Version 2.0 (the "License");
  7256. * you may not use this file except in compliance with the License.
  7257. * You may obtain a copy of the License at
  7258. *
  7259. * http://www.apache.org/licenses/LICENSE-2.0
  7260. *
  7261. * Unless required by applicable law or agreed to in writing, software
  7262. * distributed under the License is distributed on an "AS IS" BASIS,
  7263. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7264. * See the License for the specific language governing permissions and
  7265. * limitations under the License.
  7266. */
  7267. /**
  7268. * Returns the delta from the previous call to get stats.
  7269. *
  7270. * @param collection_ - The collection to "listen" to.
  7271. */
  7272. var StatsListener = /** @class */ (function () {
  7273. function StatsListener(collection_) {
  7274. this.collection_ = collection_;
  7275. this.last_ = null;
  7276. }
  7277. StatsListener.prototype.get = function () {
  7278. var newStats = this.collection_.get();
  7279. var delta = __assign({}, newStats);
  7280. if (this.last_) {
  7281. each(this.last_, function (stat, value) {
  7282. delta[stat] = delta[stat] - value;
  7283. });
  7284. }
  7285. this.last_ = newStats;
  7286. return delta;
  7287. };
  7288. return StatsListener;
  7289. }());
  7290. /**
  7291. * @license
  7292. * Copyright 2017 Google LLC
  7293. *
  7294. * Licensed under the Apache License, Version 2.0 (the "License");
  7295. * you may not use this file except in compliance with the License.
  7296. * You may obtain a copy of the License at
  7297. *
  7298. * http://www.apache.org/licenses/LICENSE-2.0
  7299. *
  7300. * Unless required by applicable law or agreed to in writing, software
  7301. * distributed under the License is distributed on an "AS IS" BASIS,
  7302. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7303. * See the License for the specific language governing permissions and
  7304. * limitations under the License.
  7305. */
  7306. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7307. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7308. // seconds to try to ensure the Firebase connection is established / settled.
  7309. var FIRST_STATS_MIN_TIME = 10 * 1000;
  7310. var FIRST_STATS_MAX_TIME = 30 * 1000;
  7311. // We'll continue to report stats on average every 5 minutes.
  7312. var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7313. var StatsReporter = /** @class */ (function () {
  7314. function StatsReporter(collection, server_) {
  7315. this.server_ = server_;
  7316. this.statsToReport_ = {};
  7317. this.statsListener_ = new StatsListener(collection);
  7318. var timeout = FIRST_STATS_MIN_TIME +
  7319. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7320. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7321. }
  7322. StatsReporter.prototype.reportStats_ = function () {
  7323. var _this = this;
  7324. var stats = this.statsListener_.get();
  7325. var reportedStats = {};
  7326. var haveStatsToReport = false;
  7327. each(stats, function (stat, value) {
  7328. if (value > 0 && contains(_this.statsToReport_, stat)) {
  7329. reportedStats[stat] = value;
  7330. haveStatsToReport = true;
  7331. }
  7332. });
  7333. if (haveStatsToReport) {
  7334. this.server_.reportStats(reportedStats);
  7335. }
  7336. // queue our next run.
  7337. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7338. };
  7339. return StatsReporter;
  7340. }());
  7341. /**
  7342. * @license
  7343. * Copyright 2017 Google LLC
  7344. *
  7345. * Licensed under the Apache License, Version 2.0 (the "License");
  7346. * you may not use this file except in compliance with the License.
  7347. * You may obtain a copy of the License at
  7348. *
  7349. * http://www.apache.org/licenses/LICENSE-2.0
  7350. *
  7351. * Unless required by applicable law or agreed to in writing, software
  7352. * distributed under the License is distributed on an "AS IS" BASIS,
  7353. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7354. * See the License for the specific language governing permissions and
  7355. * limitations under the License.
  7356. */
  7357. /**
  7358. *
  7359. * @enum
  7360. */
  7361. var OperationType;
  7362. (function (OperationType) {
  7363. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7364. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7365. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7366. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7367. })(OperationType || (OperationType = {}));
  7368. function newOperationSourceUser() {
  7369. return {
  7370. fromUser: true,
  7371. fromServer: false,
  7372. queryId: null,
  7373. tagged: false
  7374. };
  7375. }
  7376. function newOperationSourceServer() {
  7377. return {
  7378. fromUser: false,
  7379. fromServer: true,
  7380. queryId: null,
  7381. tagged: false
  7382. };
  7383. }
  7384. function newOperationSourceServerTaggedQuery(queryId) {
  7385. return {
  7386. fromUser: false,
  7387. fromServer: true,
  7388. queryId: queryId,
  7389. tagged: true
  7390. };
  7391. }
  7392. /**
  7393. * @license
  7394. * Copyright 2017 Google LLC
  7395. *
  7396. * Licensed under the Apache License, Version 2.0 (the "License");
  7397. * you may not use this file except in compliance with the License.
  7398. * You may obtain a copy of the License at
  7399. *
  7400. * http://www.apache.org/licenses/LICENSE-2.0
  7401. *
  7402. * Unless required by applicable law or agreed to in writing, software
  7403. * distributed under the License is distributed on an "AS IS" BASIS,
  7404. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7405. * See the License for the specific language governing permissions and
  7406. * limitations under the License.
  7407. */
  7408. var AckUserWrite = /** @class */ (function () {
  7409. /**
  7410. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7411. */
  7412. function AckUserWrite(
  7413. /** @inheritDoc */ path,
  7414. /** @inheritDoc */ affectedTree,
  7415. /** @inheritDoc */ revert) {
  7416. this.path = path;
  7417. this.affectedTree = affectedTree;
  7418. this.revert = revert;
  7419. /** @inheritDoc */
  7420. this.type = OperationType.ACK_USER_WRITE;
  7421. /** @inheritDoc */
  7422. this.source = newOperationSourceUser();
  7423. }
  7424. AckUserWrite.prototype.operationForChild = function (childName) {
  7425. if (!pathIsEmpty(this.path)) {
  7426. assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7427. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7428. }
  7429. else if (this.affectedTree.value != null) {
  7430. assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7431. // All child locations are affected as well; just return same operation.
  7432. return this;
  7433. }
  7434. else {
  7435. var childTree = this.affectedTree.subtree(new Path(childName));
  7436. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7437. }
  7438. };
  7439. return AckUserWrite;
  7440. }());
  7441. /**
  7442. * @license
  7443. * Copyright 2017 Google LLC
  7444. *
  7445. * Licensed under the Apache License, Version 2.0 (the "License");
  7446. * you may not use this file except in compliance with the License.
  7447. * You may obtain a copy of the License at
  7448. *
  7449. * http://www.apache.org/licenses/LICENSE-2.0
  7450. *
  7451. * Unless required by applicable law or agreed to in writing, software
  7452. * distributed under the License is distributed on an "AS IS" BASIS,
  7453. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7454. * See the License for the specific language governing permissions and
  7455. * limitations under the License.
  7456. */
  7457. var ListenComplete = /** @class */ (function () {
  7458. function ListenComplete(source, path) {
  7459. this.source = source;
  7460. this.path = path;
  7461. /** @inheritDoc */
  7462. this.type = OperationType.LISTEN_COMPLETE;
  7463. }
  7464. ListenComplete.prototype.operationForChild = function (childName) {
  7465. if (pathIsEmpty(this.path)) {
  7466. return new ListenComplete(this.source, newEmptyPath());
  7467. }
  7468. else {
  7469. return new ListenComplete(this.source, pathPopFront(this.path));
  7470. }
  7471. };
  7472. return ListenComplete;
  7473. }());
  7474. /**
  7475. * @license
  7476. * Copyright 2017 Google LLC
  7477. *
  7478. * Licensed under the Apache License, Version 2.0 (the "License");
  7479. * you may not use this file except in compliance with the License.
  7480. * You may obtain a copy of the License at
  7481. *
  7482. * http://www.apache.org/licenses/LICENSE-2.0
  7483. *
  7484. * Unless required by applicable law or agreed to in writing, software
  7485. * distributed under the License is distributed on an "AS IS" BASIS,
  7486. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7487. * See the License for the specific language governing permissions and
  7488. * limitations under the License.
  7489. */
  7490. var Overwrite = /** @class */ (function () {
  7491. function Overwrite(source, path, snap) {
  7492. this.source = source;
  7493. this.path = path;
  7494. this.snap = snap;
  7495. /** @inheritDoc */
  7496. this.type = OperationType.OVERWRITE;
  7497. }
  7498. Overwrite.prototype.operationForChild = function (childName) {
  7499. if (pathIsEmpty(this.path)) {
  7500. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7501. }
  7502. else {
  7503. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7504. }
  7505. };
  7506. return Overwrite;
  7507. }());
  7508. /**
  7509. * @license
  7510. * Copyright 2017 Google LLC
  7511. *
  7512. * Licensed under the Apache License, Version 2.0 (the "License");
  7513. * you may not use this file except in compliance with the License.
  7514. * You may obtain a copy of the License at
  7515. *
  7516. * http://www.apache.org/licenses/LICENSE-2.0
  7517. *
  7518. * Unless required by applicable law or agreed to in writing, software
  7519. * distributed under the License is distributed on an "AS IS" BASIS,
  7520. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7521. * See the License for the specific language governing permissions and
  7522. * limitations under the License.
  7523. */
  7524. var Merge = /** @class */ (function () {
  7525. function Merge(
  7526. /** @inheritDoc */ source,
  7527. /** @inheritDoc */ path,
  7528. /** @inheritDoc */ children) {
  7529. this.source = source;
  7530. this.path = path;
  7531. this.children = children;
  7532. /** @inheritDoc */
  7533. this.type = OperationType.MERGE;
  7534. }
  7535. Merge.prototype.operationForChild = function (childName) {
  7536. if (pathIsEmpty(this.path)) {
  7537. var childTree = this.children.subtree(new Path(childName));
  7538. if (childTree.isEmpty()) {
  7539. // This child is unaffected
  7540. return null;
  7541. }
  7542. else if (childTree.value) {
  7543. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7544. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7545. }
  7546. else {
  7547. // This is a merge at a deeper level
  7548. return new Merge(this.source, newEmptyPath(), childTree);
  7549. }
  7550. }
  7551. else {
  7552. assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7553. return new Merge(this.source, pathPopFront(this.path), this.children);
  7554. }
  7555. };
  7556. Merge.prototype.toString = function () {
  7557. return ('Operation(' +
  7558. this.path +
  7559. ': ' +
  7560. this.source.toString() +
  7561. ' merge: ' +
  7562. this.children.toString() +
  7563. ')');
  7564. };
  7565. return Merge;
  7566. }());
  7567. /**
  7568. * @license
  7569. * Copyright 2017 Google LLC
  7570. *
  7571. * Licensed under the Apache License, Version 2.0 (the "License");
  7572. * you may not use this file except in compliance with the License.
  7573. * You may obtain a copy of the License at
  7574. *
  7575. * http://www.apache.org/licenses/LICENSE-2.0
  7576. *
  7577. * Unless required by applicable law or agreed to in writing, software
  7578. * distributed under the License is distributed on an "AS IS" BASIS,
  7579. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7580. * See the License for the specific language governing permissions and
  7581. * limitations under the License.
  7582. */
  7583. /**
  7584. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7585. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7586. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7587. * whether a node potentially had children removed due to a filter.
  7588. */
  7589. var CacheNode = /** @class */ (function () {
  7590. function CacheNode(node_, fullyInitialized_, filtered_) {
  7591. this.node_ = node_;
  7592. this.fullyInitialized_ = fullyInitialized_;
  7593. this.filtered_ = filtered_;
  7594. }
  7595. /**
  7596. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7597. */
  7598. CacheNode.prototype.isFullyInitialized = function () {
  7599. return this.fullyInitialized_;
  7600. };
  7601. /**
  7602. * Returns whether this node is potentially missing children due to a filter applied to the node
  7603. */
  7604. CacheNode.prototype.isFiltered = function () {
  7605. return this.filtered_;
  7606. };
  7607. CacheNode.prototype.isCompleteForPath = function (path) {
  7608. if (pathIsEmpty(path)) {
  7609. return this.isFullyInitialized() && !this.filtered_;
  7610. }
  7611. var childKey = pathGetFront(path);
  7612. return this.isCompleteForChild(childKey);
  7613. };
  7614. CacheNode.prototype.isCompleteForChild = function (key) {
  7615. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7616. };
  7617. CacheNode.prototype.getNode = function () {
  7618. return this.node_;
  7619. };
  7620. return CacheNode;
  7621. }());
  7622. /**
  7623. * @license
  7624. * Copyright 2017 Google LLC
  7625. *
  7626. * Licensed under the Apache License, Version 2.0 (the "License");
  7627. * you may not use this file except in compliance with the License.
  7628. * You may obtain a copy of the License at
  7629. *
  7630. * http://www.apache.org/licenses/LICENSE-2.0
  7631. *
  7632. * Unless required by applicable law or agreed to in writing, software
  7633. * distributed under the License is distributed on an "AS IS" BASIS,
  7634. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7635. * See the License for the specific language governing permissions and
  7636. * limitations under the License.
  7637. */
  7638. /**
  7639. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7640. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7641. * for details.
  7642. *
  7643. */
  7644. var EventGenerator = /** @class */ (function () {
  7645. function EventGenerator(query_) {
  7646. this.query_ = query_;
  7647. this.index_ = this.query_._queryParams.getIndex();
  7648. }
  7649. return EventGenerator;
  7650. }());
  7651. /**
  7652. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7653. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7654. *
  7655. * Notes:
  7656. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7657. * our index.
  7658. * - prevName will be calculated based on the index ordering.
  7659. */
  7660. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7661. var events = [];
  7662. var moves = [];
  7663. changes.forEach(function (change) {
  7664. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7665. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7666. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7667. }
  7668. });
  7669. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7670. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7671. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7672. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7673. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7674. return events;
  7675. }
  7676. /**
  7677. * Given changes of a single change type, generate the corresponding events.
  7678. */
  7679. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7680. var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
  7681. filteredChanges.sort(function (a, b) {
  7682. return eventGeneratorCompareChanges(eventGenerator, a, b);
  7683. });
  7684. filteredChanges.forEach(function (change) {
  7685. var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7686. registrations.forEach(function (registration) {
  7687. if (registration.respondsTo(change.type)) {
  7688. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7689. }
  7690. });
  7691. });
  7692. }
  7693. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7694. if (change.type === 'value' || change.type === 'child_removed') {
  7695. return change;
  7696. }
  7697. else {
  7698. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7699. return change;
  7700. }
  7701. }
  7702. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7703. if (a.childName == null || b.childName == null) {
  7704. throw assertionError('Should only compare child_ events.');
  7705. }
  7706. var aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7707. var bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7708. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7709. }
  7710. /**
  7711. * @license
  7712. * Copyright 2017 Google LLC
  7713. *
  7714. * Licensed under the Apache License, Version 2.0 (the "License");
  7715. * you may not use this file except in compliance with the License.
  7716. * You may obtain a copy of the License at
  7717. *
  7718. * http://www.apache.org/licenses/LICENSE-2.0
  7719. *
  7720. * Unless required by applicable law or agreed to in writing, software
  7721. * distributed under the License is distributed on an "AS IS" BASIS,
  7722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7723. * See the License for the specific language governing permissions and
  7724. * limitations under the License.
  7725. */
  7726. function newViewCache(eventCache, serverCache) {
  7727. return { eventCache: eventCache, serverCache: serverCache };
  7728. }
  7729. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7730. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7731. }
  7732. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7733. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7734. }
  7735. function viewCacheGetCompleteEventSnap(viewCache) {
  7736. return viewCache.eventCache.isFullyInitialized()
  7737. ? viewCache.eventCache.getNode()
  7738. : null;
  7739. }
  7740. function viewCacheGetCompleteServerSnap(viewCache) {
  7741. return viewCache.serverCache.isFullyInitialized()
  7742. ? viewCache.serverCache.getNode()
  7743. : null;
  7744. }
  7745. /**
  7746. * @license
  7747. * Copyright 2017 Google LLC
  7748. *
  7749. * Licensed under the Apache License, Version 2.0 (the "License");
  7750. * you may not use this file except in compliance with the License.
  7751. * You may obtain a copy of the License at
  7752. *
  7753. * http://www.apache.org/licenses/LICENSE-2.0
  7754. *
  7755. * Unless required by applicable law or agreed to in writing, software
  7756. * distributed under the License is distributed on an "AS IS" BASIS,
  7757. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7758. * See the License for the specific language governing permissions and
  7759. * limitations under the License.
  7760. */
  7761. var emptyChildrenSingleton;
  7762. /**
  7763. * Singleton empty children collection.
  7764. *
  7765. */
  7766. var EmptyChildren = function () {
  7767. if (!emptyChildrenSingleton) {
  7768. emptyChildrenSingleton = new SortedMap(stringCompare);
  7769. }
  7770. return emptyChildrenSingleton;
  7771. };
  7772. /**
  7773. * A tree with immutable elements.
  7774. */
  7775. var ImmutableTree = /** @class */ (function () {
  7776. function ImmutableTree(value, children) {
  7777. if (children === void 0) { children = EmptyChildren(); }
  7778. this.value = value;
  7779. this.children = children;
  7780. }
  7781. ImmutableTree.fromObject = function (obj) {
  7782. var tree = new ImmutableTree(null);
  7783. each(obj, function (childPath, childSnap) {
  7784. tree = tree.set(new Path(childPath), childSnap);
  7785. });
  7786. return tree;
  7787. };
  7788. /**
  7789. * True if the value is empty and there are no children
  7790. */
  7791. ImmutableTree.prototype.isEmpty = function () {
  7792. return this.value === null && this.children.isEmpty();
  7793. };
  7794. /**
  7795. * Given a path and predicate, return the first node and the path to that node
  7796. * where the predicate returns true.
  7797. *
  7798. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7799. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7800. *
  7801. * @param relativePath - The remainder of the path
  7802. * @param predicate - The predicate to satisfy to return a node
  7803. */
  7804. ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
  7805. if (this.value != null && predicate(this.value)) {
  7806. return { path: newEmptyPath(), value: this.value };
  7807. }
  7808. else {
  7809. if (pathIsEmpty(relativePath)) {
  7810. return null;
  7811. }
  7812. else {
  7813. var front = pathGetFront(relativePath);
  7814. var child = this.children.get(front);
  7815. if (child !== null) {
  7816. var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7817. if (childExistingPathAndValue != null) {
  7818. var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7819. return { path: fullPath, value: childExistingPathAndValue.value };
  7820. }
  7821. else {
  7822. return null;
  7823. }
  7824. }
  7825. else {
  7826. return null;
  7827. }
  7828. }
  7829. }
  7830. };
  7831. /**
  7832. * Find, if it exists, the shortest subpath of the given path that points a defined
  7833. * value in the tree
  7834. */
  7835. ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
  7836. return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
  7837. };
  7838. /**
  7839. * @returns The subtree at the given path
  7840. */
  7841. ImmutableTree.prototype.subtree = function (relativePath) {
  7842. if (pathIsEmpty(relativePath)) {
  7843. return this;
  7844. }
  7845. else {
  7846. var front = pathGetFront(relativePath);
  7847. var childTree = this.children.get(front);
  7848. if (childTree !== null) {
  7849. return childTree.subtree(pathPopFront(relativePath));
  7850. }
  7851. else {
  7852. return new ImmutableTree(null);
  7853. }
  7854. }
  7855. };
  7856. /**
  7857. * Sets a value at the specified path.
  7858. *
  7859. * @param relativePath - Path to set value at.
  7860. * @param toSet - Value to set.
  7861. * @returns Resulting tree.
  7862. */
  7863. ImmutableTree.prototype.set = function (relativePath, toSet) {
  7864. if (pathIsEmpty(relativePath)) {
  7865. return new ImmutableTree(toSet, this.children);
  7866. }
  7867. else {
  7868. var front = pathGetFront(relativePath);
  7869. var child = this.children.get(front) || new ImmutableTree(null);
  7870. var newChild = child.set(pathPopFront(relativePath), toSet);
  7871. var newChildren = this.children.insert(front, newChild);
  7872. return new ImmutableTree(this.value, newChildren);
  7873. }
  7874. };
  7875. /**
  7876. * Removes the value at the specified path.
  7877. *
  7878. * @param relativePath - Path to value to remove.
  7879. * @returns Resulting tree.
  7880. */
  7881. ImmutableTree.prototype.remove = function (relativePath) {
  7882. if (pathIsEmpty(relativePath)) {
  7883. if (this.children.isEmpty()) {
  7884. return new ImmutableTree(null);
  7885. }
  7886. else {
  7887. return new ImmutableTree(null, this.children);
  7888. }
  7889. }
  7890. else {
  7891. var front = pathGetFront(relativePath);
  7892. var child = this.children.get(front);
  7893. if (child) {
  7894. var newChild = child.remove(pathPopFront(relativePath));
  7895. var newChildren = void 0;
  7896. if (newChild.isEmpty()) {
  7897. newChildren = this.children.remove(front);
  7898. }
  7899. else {
  7900. newChildren = this.children.insert(front, newChild);
  7901. }
  7902. if (this.value === null && newChildren.isEmpty()) {
  7903. return new ImmutableTree(null);
  7904. }
  7905. else {
  7906. return new ImmutableTree(this.value, newChildren);
  7907. }
  7908. }
  7909. else {
  7910. return this;
  7911. }
  7912. }
  7913. };
  7914. /**
  7915. * Gets a value from the tree.
  7916. *
  7917. * @param relativePath - Path to get value for.
  7918. * @returns Value at path, or null.
  7919. */
  7920. ImmutableTree.prototype.get = function (relativePath) {
  7921. if (pathIsEmpty(relativePath)) {
  7922. return this.value;
  7923. }
  7924. else {
  7925. var front = pathGetFront(relativePath);
  7926. var child = this.children.get(front);
  7927. if (child) {
  7928. return child.get(pathPopFront(relativePath));
  7929. }
  7930. else {
  7931. return null;
  7932. }
  7933. }
  7934. };
  7935. /**
  7936. * Replace the subtree at the specified path with the given new tree.
  7937. *
  7938. * @param relativePath - Path to replace subtree for.
  7939. * @param newTree - New tree.
  7940. * @returns Resulting tree.
  7941. */
  7942. ImmutableTree.prototype.setTree = function (relativePath, newTree) {
  7943. if (pathIsEmpty(relativePath)) {
  7944. return newTree;
  7945. }
  7946. else {
  7947. var front = pathGetFront(relativePath);
  7948. var child = this.children.get(front) || new ImmutableTree(null);
  7949. var newChild = child.setTree(pathPopFront(relativePath), newTree);
  7950. var newChildren = void 0;
  7951. if (newChild.isEmpty()) {
  7952. newChildren = this.children.remove(front);
  7953. }
  7954. else {
  7955. newChildren = this.children.insert(front, newChild);
  7956. }
  7957. return new ImmutableTree(this.value, newChildren);
  7958. }
  7959. };
  7960. /**
  7961. * Performs a depth first fold on this tree. Transforms a tree into a single
  7962. * value, given a function that operates on the path to a node, an optional
  7963. * current value, and a map of child names to folded subtrees
  7964. */
  7965. ImmutableTree.prototype.fold = function (fn) {
  7966. return this.fold_(newEmptyPath(), fn);
  7967. };
  7968. /**
  7969. * Recursive helper for public-facing fold() method
  7970. */
  7971. ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
  7972. var accum = {};
  7973. this.children.inorderTraversal(function (childKey, childTree) {
  7974. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7975. });
  7976. return fn(pathSoFar, this.value, accum);
  7977. };
  7978. /**
  7979. * Find the first matching value on the given path. Return the result of applying f to it.
  7980. */
  7981. ImmutableTree.prototype.findOnPath = function (path, f) {
  7982. return this.findOnPath_(path, newEmptyPath(), f);
  7983. };
  7984. ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
  7985. var result = this.value ? f(pathSoFar, this.value) : false;
  7986. if (result) {
  7987. return result;
  7988. }
  7989. else {
  7990. if (pathIsEmpty(pathToFollow)) {
  7991. return null;
  7992. }
  7993. else {
  7994. var front = pathGetFront(pathToFollow);
  7995. var nextChild = this.children.get(front);
  7996. if (nextChild) {
  7997. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7998. }
  7999. else {
  8000. return null;
  8001. }
  8002. }
  8003. }
  8004. };
  8005. ImmutableTree.prototype.foreachOnPath = function (path, f) {
  8006. return this.foreachOnPath_(path, newEmptyPath(), f);
  8007. };
  8008. ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
  8009. if (pathIsEmpty(pathToFollow)) {
  8010. return this;
  8011. }
  8012. else {
  8013. if (this.value) {
  8014. f(currentRelativePath, this.value);
  8015. }
  8016. var front = pathGetFront(pathToFollow);
  8017. var nextChild = this.children.get(front);
  8018. if (nextChild) {
  8019. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  8020. }
  8021. else {
  8022. return new ImmutableTree(null);
  8023. }
  8024. }
  8025. };
  8026. /**
  8027. * Calls the given function for each node in the tree that has a value.
  8028. *
  8029. * @param f - A function to be called with the path from the root of the tree to
  8030. * a node, and the value at that node. Called in depth-first order.
  8031. */
  8032. ImmutableTree.prototype.foreach = function (f) {
  8033. this.foreach_(newEmptyPath(), f);
  8034. };
  8035. ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
  8036. this.children.inorderTraversal(function (childName, childTree) {
  8037. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  8038. });
  8039. if (this.value) {
  8040. f(currentRelativePath, this.value);
  8041. }
  8042. };
  8043. ImmutableTree.prototype.foreachChild = function (f) {
  8044. this.children.inorderTraversal(function (childName, childTree) {
  8045. if (childTree.value) {
  8046. f(childName, childTree.value);
  8047. }
  8048. });
  8049. };
  8050. return ImmutableTree;
  8051. }());
  8052. /**
  8053. * @license
  8054. * Copyright 2017 Google LLC
  8055. *
  8056. * Licensed under the Apache License, Version 2.0 (the "License");
  8057. * you may not use this file except in compliance with the License.
  8058. * You may obtain a copy of the License at
  8059. *
  8060. * http://www.apache.org/licenses/LICENSE-2.0
  8061. *
  8062. * Unless required by applicable law or agreed to in writing, software
  8063. * distributed under the License is distributed on an "AS IS" BASIS,
  8064. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8065. * See the License for the specific language governing permissions and
  8066. * limitations under the License.
  8067. */
  8068. /**
  8069. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  8070. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  8071. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  8072. * to reflect the write added.
  8073. */
  8074. var CompoundWrite = /** @class */ (function () {
  8075. function CompoundWrite(writeTree_) {
  8076. this.writeTree_ = writeTree_;
  8077. }
  8078. CompoundWrite.empty = function () {
  8079. return new CompoundWrite(new ImmutableTree(null));
  8080. };
  8081. return CompoundWrite;
  8082. }());
  8083. function compoundWriteAddWrite(compoundWrite, path, node) {
  8084. if (pathIsEmpty(path)) {
  8085. return new CompoundWrite(new ImmutableTree(node));
  8086. }
  8087. else {
  8088. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8089. if (rootmost != null) {
  8090. var rootMostPath = rootmost.path;
  8091. var value = rootmost.value;
  8092. var relativePath = newRelativePath(rootMostPath, path);
  8093. value = value.updateChild(relativePath, node);
  8094. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  8095. }
  8096. else {
  8097. var subtree = new ImmutableTree(node);
  8098. var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  8099. return new CompoundWrite(newWriteTree);
  8100. }
  8101. }
  8102. }
  8103. function compoundWriteAddWrites(compoundWrite, path, updates) {
  8104. var newWrite = compoundWrite;
  8105. each(updates, function (childKey, node) {
  8106. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  8107. });
  8108. return newWrite;
  8109. }
  8110. /**
  8111. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  8112. * location, which must be removed by calling this method with that path.
  8113. *
  8114. * @param compoundWrite - The CompoundWrite to remove.
  8115. * @param path - The path at which a write and all deeper writes should be removed
  8116. * @returns The new CompoundWrite with the removed path
  8117. */
  8118. function compoundWriteRemoveWrite(compoundWrite, path) {
  8119. if (pathIsEmpty(path)) {
  8120. return CompoundWrite.empty();
  8121. }
  8122. else {
  8123. var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  8124. return new CompoundWrite(newWriteTree);
  8125. }
  8126. }
  8127. /**
  8128. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  8129. * considered "complete".
  8130. *
  8131. * @param compoundWrite - The CompoundWrite to check.
  8132. * @param path - The path to check for
  8133. * @returns Whether there is a complete write at that path
  8134. */
  8135. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  8136. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  8137. }
  8138. /**
  8139. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  8140. * writes from deeper paths, but will return child nodes from a more shallow path.
  8141. *
  8142. * @param compoundWrite - The CompoundWrite to get the node from.
  8143. * @param path - The path to get a complete write
  8144. * @returns The node if complete at that path, or null otherwise.
  8145. */
  8146. function compoundWriteGetCompleteNode(compoundWrite, path) {
  8147. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8148. if (rootmost != null) {
  8149. return compoundWrite.writeTree_
  8150. .get(rootmost.path)
  8151. .getChild(newRelativePath(rootmost.path, path));
  8152. }
  8153. else {
  8154. return null;
  8155. }
  8156. }
  8157. /**
  8158. * Returns all children that are guaranteed to be a complete overwrite.
  8159. *
  8160. * @param compoundWrite - The CompoundWrite to get children from.
  8161. * @returns A list of all complete children.
  8162. */
  8163. function compoundWriteGetCompleteChildren(compoundWrite) {
  8164. var children = [];
  8165. var node = compoundWrite.writeTree_.value;
  8166. if (node != null) {
  8167. // If it's a leaf node, it has no children; so nothing to do.
  8168. if (!node.isLeafNode()) {
  8169. node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8170. children.push(new NamedNode(childName, childNode));
  8171. });
  8172. }
  8173. }
  8174. else {
  8175. compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
  8176. if (childTree.value != null) {
  8177. children.push(new NamedNode(childName, childTree.value));
  8178. }
  8179. });
  8180. }
  8181. return children;
  8182. }
  8183. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  8184. if (pathIsEmpty(path)) {
  8185. return compoundWrite;
  8186. }
  8187. else {
  8188. var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  8189. if (shadowingNode != null) {
  8190. return new CompoundWrite(new ImmutableTree(shadowingNode));
  8191. }
  8192. else {
  8193. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  8194. }
  8195. }
  8196. }
  8197. /**
  8198. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  8199. * @returns Whether this CompoundWrite is empty
  8200. */
  8201. function compoundWriteIsEmpty(compoundWrite) {
  8202. return compoundWrite.writeTree_.isEmpty();
  8203. }
  8204. /**
  8205. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  8206. * node
  8207. * @param node - The node to apply this CompoundWrite to
  8208. * @returns The node with all writes applied
  8209. */
  8210. function compoundWriteApply(compoundWrite, node) {
  8211. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  8212. }
  8213. function applySubtreeWrite(relativePath, writeTree, node) {
  8214. if (writeTree.value != null) {
  8215. // Since there a write is always a leaf, we're done here
  8216. return node.updateChild(relativePath, writeTree.value);
  8217. }
  8218. else {
  8219. var priorityWrite_1 = null;
  8220. writeTree.children.inorderTraversal(function (childKey, childTree) {
  8221. if (childKey === '.priority') {
  8222. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  8223. // to apply priorities to empty nodes that are later filled
  8224. assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  8225. priorityWrite_1 = childTree.value;
  8226. }
  8227. else {
  8228. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  8229. }
  8230. });
  8231. // If there was a priority write, we only apply it if the node is not empty
  8232. if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
  8233. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
  8234. }
  8235. return node;
  8236. }
  8237. }
  8238. /**
  8239. * @license
  8240. * Copyright 2017 Google LLC
  8241. *
  8242. * Licensed under the Apache License, Version 2.0 (the "License");
  8243. * you may not use this file except in compliance with the License.
  8244. * You may obtain a copy of the License at
  8245. *
  8246. * http://www.apache.org/licenses/LICENSE-2.0
  8247. *
  8248. * Unless required by applicable law or agreed to in writing, software
  8249. * distributed under the License is distributed on an "AS IS" BASIS,
  8250. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8251. * See the License for the specific language governing permissions and
  8252. * limitations under the License.
  8253. */
  8254. /**
  8255. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8256. *
  8257. */
  8258. function writeTreeChildWrites(writeTree, path) {
  8259. return newWriteTreeRef(path, writeTree);
  8260. }
  8261. /**
  8262. * Record a new overwrite from user code.
  8263. *
  8264. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8265. */
  8266. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8267. assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8268. if (visible === undefined) {
  8269. visible = true;
  8270. }
  8271. writeTree.allWrites.push({
  8272. path: path,
  8273. snap: snap,
  8274. writeId: writeId,
  8275. visible: visible
  8276. });
  8277. if (visible) {
  8278. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8279. }
  8280. writeTree.lastWriteId = writeId;
  8281. }
  8282. /**
  8283. * Record a new merge from user code.
  8284. */
  8285. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8286. assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8287. writeTree.allWrites.push({
  8288. path: path,
  8289. children: changedChildren,
  8290. writeId: writeId,
  8291. visible: true
  8292. });
  8293. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8294. writeTree.lastWriteId = writeId;
  8295. }
  8296. function writeTreeGetWrite(writeTree, writeId) {
  8297. for (var i = 0; i < writeTree.allWrites.length; i++) {
  8298. var record = writeTree.allWrites[i];
  8299. if (record.writeId === writeId) {
  8300. return record;
  8301. }
  8302. }
  8303. return null;
  8304. }
  8305. /**
  8306. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8307. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8308. *
  8309. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8310. * events as a result).
  8311. */
  8312. function writeTreeRemoveWrite(writeTree, writeId) {
  8313. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8314. // out of order.
  8315. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8316. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8317. var idx = writeTree.allWrites.findIndex(function (s) {
  8318. return s.writeId === writeId;
  8319. });
  8320. assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8321. var writeToRemove = writeTree.allWrites[idx];
  8322. writeTree.allWrites.splice(idx, 1);
  8323. var removedWriteWasVisible = writeToRemove.visible;
  8324. var removedWriteOverlapsWithOtherWrites = false;
  8325. var i = writeTree.allWrites.length - 1;
  8326. while (removedWriteWasVisible && i >= 0) {
  8327. var currentWrite = writeTree.allWrites[i];
  8328. if (currentWrite.visible) {
  8329. if (i >= idx &&
  8330. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8331. // The removed write was completely shadowed by a subsequent write.
  8332. removedWriteWasVisible = false;
  8333. }
  8334. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8335. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8336. removedWriteOverlapsWithOtherWrites = true;
  8337. }
  8338. }
  8339. i--;
  8340. }
  8341. if (!removedWriteWasVisible) {
  8342. return false;
  8343. }
  8344. else if (removedWriteOverlapsWithOtherWrites) {
  8345. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8346. writeTreeResetTree_(writeTree);
  8347. return true;
  8348. }
  8349. else {
  8350. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8351. if (writeToRemove.snap) {
  8352. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8353. }
  8354. else {
  8355. var children = writeToRemove.children;
  8356. each(children, function (childName) {
  8357. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8358. });
  8359. }
  8360. return true;
  8361. }
  8362. }
  8363. function writeTreeRecordContainsPath_(writeRecord, path) {
  8364. if (writeRecord.snap) {
  8365. return pathContains(writeRecord.path, path);
  8366. }
  8367. else {
  8368. for (var childName in writeRecord.children) {
  8369. if (writeRecord.children.hasOwnProperty(childName) &&
  8370. pathContains(pathChild(writeRecord.path, childName), path)) {
  8371. return true;
  8372. }
  8373. }
  8374. return false;
  8375. }
  8376. }
  8377. /**
  8378. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8379. */
  8380. function writeTreeResetTree_(writeTree) {
  8381. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8382. if (writeTree.allWrites.length > 0) {
  8383. writeTree.lastWriteId =
  8384. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8385. }
  8386. else {
  8387. writeTree.lastWriteId = -1;
  8388. }
  8389. }
  8390. /**
  8391. * The default filter used when constructing the tree. Keep everything that's visible.
  8392. */
  8393. function writeTreeDefaultFilter_(write) {
  8394. return write.visible;
  8395. }
  8396. /**
  8397. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8398. * event data at that path.
  8399. */
  8400. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8401. var compoundWrite = CompoundWrite.empty();
  8402. for (var i = 0; i < writes.length; ++i) {
  8403. var write = writes[i];
  8404. // Theory, a later set will either:
  8405. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8406. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8407. if (filter(write)) {
  8408. var writePath = write.path;
  8409. var relativePath = void 0;
  8410. if (write.snap) {
  8411. if (pathContains(treeRoot, writePath)) {
  8412. relativePath = newRelativePath(treeRoot, writePath);
  8413. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8414. }
  8415. else if (pathContains(writePath, treeRoot)) {
  8416. relativePath = newRelativePath(writePath, treeRoot);
  8417. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8418. }
  8419. else ;
  8420. }
  8421. else if (write.children) {
  8422. if (pathContains(treeRoot, writePath)) {
  8423. relativePath = newRelativePath(treeRoot, writePath);
  8424. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8425. }
  8426. else if (pathContains(writePath, treeRoot)) {
  8427. relativePath = newRelativePath(writePath, treeRoot);
  8428. if (pathIsEmpty(relativePath)) {
  8429. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8430. }
  8431. else {
  8432. var child = safeGet(write.children, pathGetFront(relativePath));
  8433. if (child) {
  8434. // There exists a child in this node that matches the root path
  8435. var deepNode = child.getChild(pathPopFront(relativePath));
  8436. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8437. }
  8438. }
  8439. }
  8440. else ;
  8441. }
  8442. else {
  8443. throw assertionError('WriteRecord should have .snap or .children');
  8444. }
  8445. }
  8446. }
  8447. return compoundWrite;
  8448. }
  8449. /**
  8450. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8451. * writes), attempt to calculate a complete snapshot for the given path
  8452. *
  8453. * @param writeIdsToExclude - An optional set to be excluded
  8454. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8455. */
  8456. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8457. if (!writeIdsToExclude && !includeHiddenWrites) {
  8458. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8459. if (shadowingNode != null) {
  8460. return shadowingNode;
  8461. }
  8462. else {
  8463. var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8464. if (compoundWriteIsEmpty(subMerge)) {
  8465. return completeServerCache;
  8466. }
  8467. else if (completeServerCache == null &&
  8468. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8469. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8470. return null;
  8471. }
  8472. else {
  8473. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8474. return compoundWriteApply(subMerge, layeredCache);
  8475. }
  8476. }
  8477. }
  8478. else {
  8479. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8480. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8481. return completeServerCache;
  8482. }
  8483. else {
  8484. // If the server cache is null, and we don't have a complete cache, we need to return null
  8485. if (!includeHiddenWrites &&
  8486. completeServerCache == null &&
  8487. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8488. return null;
  8489. }
  8490. else {
  8491. var filter = function (write) {
  8492. return ((write.visible || includeHiddenWrites) &&
  8493. (!writeIdsToExclude ||
  8494. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8495. (pathContains(write.path, treePath) ||
  8496. pathContains(treePath, write.path)));
  8497. };
  8498. var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8499. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8500. return compoundWriteApply(mergeAtPath, layeredCache);
  8501. }
  8502. }
  8503. }
  8504. }
  8505. /**
  8506. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8507. * Used when creating new views, to pre-fill their complete event children snapshot.
  8508. */
  8509. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8510. var completeChildren = ChildrenNode.EMPTY_NODE;
  8511. var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8512. if (topLevelSet) {
  8513. if (!topLevelSet.isLeafNode()) {
  8514. // we're shadowing everything. Return the children.
  8515. topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
  8516. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8517. });
  8518. }
  8519. return completeChildren;
  8520. }
  8521. else if (completeServerChildren) {
  8522. // Layer any children we have on top of this
  8523. // We know we don't have a top-level set, so just enumerate existing children
  8524. var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8525. completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8526. var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
  8527. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8528. });
  8529. // Add any complete children we have from the set
  8530. compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
  8531. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8532. });
  8533. return completeChildren;
  8534. }
  8535. else {
  8536. // We don't have anything to layer on top of. Layer on any children we have
  8537. // Note that we can return an empty snap if we have a defined delete
  8538. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8539. compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
  8540. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8541. });
  8542. return completeChildren;
  8543. }
  8544. }
  8545. /**
  8546. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8547. * applied to the event cache.
  8548. *
  8549. * Possibilities:
  8550. *
  8551. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8552. *
  8553. * 2. Some write is completely shadowing. No events to be raised
  8554. *
  8555. * 3. Is partially shadowed. Events
  8556. *
  8557. * Either existingEventSnap or existingServerSnap must exist
  8558. */
  8559. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8560. assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8561. var path = pathChild(treePath, childPath);
  8562. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8563. // At this point we can probably guarantee that we're in case 2, meaning no events
  8564. // May need to check visibility while doing the findRootMostValueAndPath call
  8565. return null;
  8566. }
  8567. else {
  8568. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8569. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8570. if (compoundWriteIsEmpty(childMerge)) {
  8571. // We're not shadowing at all. Case 1
  8572. return existingServerSnap.getChild(childPath);
  8573. }
  8574. else {
  8575. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8576. // However this is tricky to find out, since user updates don't necessary change the server
  8577. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8578. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8579. // only check if the updates change the serverNode.
  8580. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8581. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8582. }
  8583. }
  8584. }
  8585. /**
  8586. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8587. * complete child for this ChildKey.
  8588. */
  8589. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8590. var path = pathChild(treePath, childKey);
  8591. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8592. if (shadowingNode != null) {
  8593. return shadowingNode;
  8594. }
  8595. else {
  8596. if (existingServerSnap.isCompleteForChild(childKey)) {
  8597. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8598. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8599. }
  8600. else {
  8601. return null;
  8602. }
  8603. }
  8604. }
  8605. /**
  8606. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8607. * a higher path, this will return the child of that write relative to the write and this path.
  8608. * Returns null if there is no write at this path.
  8609. */
  8610. function writeTreeShadowingWrite(writeTree, path) {
  8611. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8612. }
  8613. /**
  8614. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8615. * the window, but may now be in the window.
  8616. */
  8617. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8618. var toIterate;
  8619. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8620. var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8621. if (shadowingNode != null) {
  8622. toIterate = shadowingNode;
  8623. }
  8624. else if (completeServerData != null) {
  8625. toIterate = compoundWriteApply(merge, completeServerData);
  8626. }
  8627. else {
  8628. // no children to iterate on
  8629. return [];
  8630. }
  8631. toIterate = toIterate.withIndex(index);
  8632. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8633. var nodes = [];
  8634. var cmp = index.getCompare();
  8635. var iter = reverse
  8636. ? toIterate.getReverseIteratorFrom(startPost, index)
  8637. : toIterate.getIteratorFrom(startPost, index);
  8638. var next = iter.getNext();
  8639. while (next && nodes.length < count) {
  8640. if (cmp(next, startPost) !== 0) {
  8641. nodes.push(next);
  8642. }
  8643. next = iter.getNext();
  8644. }
  8645. return nodes;
  8646. }
  8647. else {
  8648. return [];
  8649. }
  8650. }
  8651. function newWriteTree() {
  8652. return {
  8653. visibleWrites: CompoundWrite.empty(),
  8654. allWrites: [],
  8655. lastWriteId: -1
  8656. };
  8657. }
  8658. /**
  8659. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8660. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8661. * can lead to a more expensive calculation.
  8662. *
  8663. * @param writeIdsToExclude - Optional writes to exclude.
  8664. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8665. */
  8666. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8667. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8668. }
  8669. /**
  8670. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8671. * mix of the given server data and write data.
  8672. *
  8673. */
  8674. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8675. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8676. }
  8677. /**
  8678. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8679. * if anything, needs to be applied to the event cache.
  8680. *
  8681. * Possibilities:
  8682. *
  8683. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8684. *
  8685. * 2. Some write is completely shadowing. No events to be raised
  8686. *
  8687. * 3. Is partially shadowed. Events should be raised
  8688. *
  8689. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8690. *
  8691. *
  8692. */
  8693. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8694. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8695. }
  8696. /**
  8697. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8698. * a higher path, this will return the child of that write relative to the write and this path.
  8699. * Returns null if there is no write at this path.
  8700. *
  8701. */
  8702. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8703. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8704. }
  8705. /**
  8706. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8707. * the window, but may now be in the window
  8708. */
  8709. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8710. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8711. }
  8712. /**
  8713. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8714. * complete child for this ChildKey.
  8715. */
  8716. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8717. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8718. }
  8719. /**
  8720. * Return a WriteTreeRef for a child.
  8721. */
  8722. function writeTreeRefChild(writeTreeRef, childName) {
  8723. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8724. }
  8725. function newWriteTreeRef(path, writeTree) {
  8726. return {
  8727. treePath: path,
  8728. writeTree: writeTree
  8729. };
  8730. }
  8731. /**
  8732. * @license
  8733. * Copyright 2017 Google LLC
  8734. *
  8735. * Licensed under the Apache License, Version 2.0 (the "License");
  8736. * you may not use this file except in compliance with the License.
  8737. * You may obtain a copy of the License at
  8738. *
  8739. * http://www.apache.org/licenses/LICENSE-2.0
  8740. *
  8741. * Unless required by applicable law or agreed to in writing, software
  8742. * distributed under the License is distributed on an "AS IS" BASIS,
  8743. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8744. * See the License for the specific language governing permissions and
  8745. * limitations under the License.
  8746. */
  8747. var ChildChangeAccumulator = /** @class */ (function () {
  8748. function ChildChangeAccumulator() {
  8749. this.changeMap = new Map();
  8750. }
  8751. ChildChangeAccumulator.prototype.trackChildChange = function (change) {
  8752. var type = change.type;
  8753. var childKey = change.childName;
  8754. assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8755. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8756. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8757. assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8758. var oldChange = this.changeMap.get(childKey);
  8759. if (oldChange) {
  8760. var oldType = oldChange.type;
  8761. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8762. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8763. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8764. }
  8765. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8766. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8767. this.changeMap.delete(childKey);
  8768. }
  8769. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8770. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8771. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8772. }
  8773. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8774. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8775. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8776. }
  8777. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8778. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8779. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8780. }
  8781. else {
  8782. throw assertionError('Illegal combination of changes: ' +
  8783. change +
  8784. ' occurred after ' +
  8785. oldChange);
  8786. }
  8787. }
  8788. else {
  8789. this.changeMap.set(childKey, change);
  8790. }
  8791. };
  8792. ChildChangeAccumulator.prototype.getChanges = function () {
  8793. return Array.from(this.changeMap.values());
  8794. };
  8795. return ChildChangeAccumulator;
  8796. }());
  8797. /**
  8798. * @license
  8799. * Copyright 2017 Google LLC
  8800. *
  8801. * Licensed under the Apache License, Version 2.0 (the "License");
  8802. * you may not use this file except in compliance with the License.
  8803. * You may obtain a copy of the License at
  8804. *
  8805. * http://www.apache.org/licenses/LICENSE-2.0
  8806. *
  8807. * Unless required by applicable law or agreed to in writing, software
  8808. * distributed under the License is distributed on an "AS IS" BASIS,
  8809. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8810. * See the License for the specific language governing permissions and
  8811. * limitations under the License.
  8812. */
  8813. /**
  8814. * An implementation of CompleteChildSource that never returns any additional children
  8815. */
  8816. // eslint-disable-next-line @typescript-eslint/naming-convention
  8817. var NoCompleteChildSource_ = /** @class */ (function () {
  8818. function NoCompleteChildSource_() {
  8819. }
  8820. NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
  8821. return null;
  8822. };
  8823. NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
  8824. return null;
  8825. };
  8826. return NoCompleteChildSource_;
  8827. }());
  8828. /**
  8829. * Singleton instance.
  8830. */
  8831. var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8832. /**
  8833. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8834. * old event caches available to calculate complete children.
  8835. */
  8836. var WriteTreeCompleteChildSource = /** @class */ (function () {
  8837. function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
  8838. if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
  8839. this.writes_ = writes_;
  8840. this.viewCache_ = viewCache_;
  8841. this.optCompleteServerCache_ = optCompleteServerCache_;
  8842. }
  8843. WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
  8844. var node = this.viewCache_.eventCache;
  8845. if (node.isCompleteForChild(childKey)) {
  8846. return node.getNode().getImmediateChild(childKey);
  8847. }
  8848. else {
  8849. var serverNode = this.optCompleteServerCache_ != null
  8850. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8851. : this.viewCache_.serverCache;
  8852. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8853. }
  8854. };
  8855. WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
  8856. var completeServerData = this.optCompleteServerCache_ != null
  8857. ? this.optCompleteServerCache_
  8858. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8859. var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8860. if (nodes.length === 0) {
  8861. return null;
  8862. }
  8863. else {
  8864. return nodes[0];
  8865. }
  8866. };
  8867. return WriteTreeCompleteChildSource;
  8868. }());
  8869. /**
  8870. * @license
  8871. * Copyright 2017 Google LLC
  8872. *
  8873. * Licensed under the Apache License, Version 2.0 (the "License");
  8874. * you may not use this file except in compliance with the License.
  8875. * You may obtain a copy of the License at
  8876. *
  8877. * http://www.apache.org/licenses/LICENSE-2.0
  8878. *
  8879. * Unless required by applicable law or agreed to in writing, software
  8880. * distributed under the License is distributed on an "AS IS" BASIS,
  8881. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8882. * See the License for the specific language governing permissions and
  8883. * limitations under the License.
  8884. */
  8885. function newViewProcessor(filter) {
  8886. return { filter: filter };
  8887. }
  8888. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8889. assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8890. assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8891. }
  8892. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8893. var accumulator = new ChildChangeAccumulator();
  8894. var newViewCache, filterServerNode;
  8895. if (operation.type === OperationType.OVERWRITE) {
  8896. var overwrite = operation;
  8897. if (overwrite.source.fromUser) {
  8898. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8899. }
  8900. else {
  8901. assert(overwrite.source.fromServer, 'Unknown source.');
  8902. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8903. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8904. // again
  8905. filterServerNode =
  8906. overwrite.source.tagged ||
  8907. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8908. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8909. }
  8910. }
  8911. else if (operation.type === OperationType.MERGE) {
  8912. var merge = operation;
  8913. if (merge.source.fromUser) {
  8914. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8915. }
  8916. else {
  8917. assert(merge.source.fromServer, 'Unknown source.');
  8918. // We filter the node if it's a tagged update or the node has been previously filtered
  8919. filterServerNode =
  8920. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8921. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8922. }
  8923. }
  8924. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8925. var ackUserWrite = operation;
  8926. if (!ackUserWrite.revert) {
  8927. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8928. }
  8929. else {
  8930. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8931. }
  8932. }
  8933. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8934. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8935. }
  8936. else {
  8937. throw assertionError('Unknown operation type: ' + operation.type);
  8938. }
  8939. var changes = accumulator.getChanges();
  8940. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8941. return { viewCache: newViewCache, changes: changes };
  8942. }
  8943. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8944. var eventSnap = newViewCache.eventCache;
  8945. if (eventSnap.isFullyInitialized()) {
  8946. var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8947. var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8948. if (accumulator.length > 0 ||
  8949. !oldViewCache.eventCache.isFullyInitialized() ||
  8950. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8951. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8952. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8953. }
  8954. }
  8955. }
  8956. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8957. var oldEventSnap = viewCache.eventCache;
  8958. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8959. // we have a shadowing write, ignore changes
  8960. return viewCache;
  8961. }
  8962. else {
  8963. var newEventCache = void 0, serverNode = void 0;
  8964. if (pathIsEmpty(changePath)) {
  8965. // TODO: figure out how this plays with "sliding ack windows"
  8966. assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8967. if (viewCache.serverCache.isFiltered()) {
  8968. // We need to special case this, because we need to only apply writes to complete children, or
  8969. // we might end up raising events for incomplete children. If the server data is filtered deep
  8970. // writes cannot be guaranteed to be complete
  8971. var serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8972. var completeChildren = serverCache instanceof ChildrenNode
  8973. ? serverCache
  8974. : ChildrenNode.EMPTY_NODE;
  8975. var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8976. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8977. }
  8978. else {
  8979. var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8980. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8981. }
  8982. }
  8983. else {
  8984. var childKey = pathGetFront(changePath);
  8985. if (childKey === '.priority') {
  8986. assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8987. var oldEventNode = oldEventSnap.getNode();
  8988. serverNode = viewCache.serverCache.getNode();
  8989. // we might have overwrites for this priority
  8990. var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8991. if (updatedPriority != null) {
  8992. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8993. }
  8994. else {
  8995. // priority didn't change, keep old node
  8996. newEventCache = oldEventSnap.getNode();
  8997. }
  8998. }
  8999. else {
  9000. var childChangePath = pathPopFront(changePath);
  9001. // update child
  9002. var newEventChild = void 0;
  9003. if (oldEventSnap.isCompleteForChild(childKey)) {
  9004. serverNode = viewCache.serverCache.getNode();
  9005. var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  9006. if (eventChildUpdate != null) {
  9007. newEventChild = oldEventSnap
  9008. .getNode()
  9009. .getImmediateChild(childKey)
  9010. .updateChild(childChangePath, eventChildUpdate);
  9011. }
  9012. else {
  9013. // Nothing changed, just keep the old child
  9014. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9015. }
  9016. }
  9017. else {
  9018. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9019. }
  9020. if (newEventChild != null) {
  9021. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  9022. }
  9023. else {
  9024. // no complete child available or no change
  9025. newEventCache = oldEventSnap.getNode();
  9026. }
  9027. }
  9028. }
  9029. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  9030. }
  9031. }
  9032. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  9033. var oldServerSnap = oldViewCache.serverCache;
  9034. var newServerCache;
  9035. var serverFilter = filterServerNode
  9036. ? viewProcessor.filter
  9037. : viewProcessor.filter.getIndexedFilter();
  9038. if (pathIsEmpty(changePath)) {
  9039. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  9040. }
  9041. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  9042. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  9043. var newServerNode = oldServerSnap
  9044. .getNode()
  9045. .updateChild(changePath, changedSnap);
  9046. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  9047. }
  9048. else {
  9049. var childKey = pathGetFront(changePath);
  9050. if (!oldServerSnap.isCompleteForPath(changePath) &&
  9051. pathGetLength(changePath) > 1) {
  9052. // We don't update incomplete nodes with updates intended for other listeners
  9053. return oldViewCache;
  9054. }
  9055. var childChangePath = pathPopFront(changePath);
  9056. var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  9057. var newChildNode = childNode.updateChild(childChangePath, changedSnap);
  9058. if (childKey === '.priority') {
  9059. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  9060. }
  9061. else {
  9062. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  9063. }
  9064. }
  9065. var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  9066. var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  9067. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  9068. }
  9069. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  9070. var oldEventSnap = oldViewCache.eventCache;
  9071. var newViewCache, newEventCache;
  9072. var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  9073. if (pathIsEmpty(changePath)) {
  9074. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  9075. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  9076. }
  9077. else {
  9078. var childKey = pathGetFront(changePath);
  9079. if (childKey === '.priority') {
  9080. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  9081. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  9082. }
  9083. else {
  9084. var childChangePath = pathPopFront(changePath);
  9085. var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9086. var newChild = void 0;
  9087. if (pathIsEmpty(childChangePath)) {
  9088. // Child overwrite, we can replace the child
  9089. newChild = changedSnap;
  9090. }
  9091. else {
  9092. var childNode = source.getCompleteChild(childKey);
  9093. if (childNode != null) {
  9094. if (pathGetBack(childChangePath) === '.priority' &&
  9095. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  9096. // This is a priority update on an empty node. If this node exists on the server, the
  9097. // server will send down the priority in the update, so ignore for now
  9098. newChild = childNode;
  9099. }
  9100. else {
  9101. newChild = childNode.updateChild(childChangePath, changedSnap);
  9102. }
  9103. }
  9104. else {
  9105. // There is no complete child node available
  9106. newChild = ChildrenNode.EMPTY_NODE;
  9107. }
  9108. }
  9109. if (!oldChild.equals(newChild)) {
  9110. var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  9111. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  9112. }
  9113. else {
  9114. newViewCache = oldViewCache;
  9115. }
  9116. }
  9117. }
  9118. return newViewCache;
  9119. }
  9120. function viewProcessorCacheHasChild(viewCache, childKey) {
  9121. return viewCache.eventCache.isCompleteForChild(childKey);
  9122. }
  9123. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  9124. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9125. // window leaving room for new items. It's important we process these changes first, so we
  9126. // iterate the changes twice, first processing any that affect items currently in view.
  9127. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9128. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9129. // not the other.
  9130. var curViewCache = viewCache;
  9131. changedChildren.foreach(function (relativePath, childNode) {
  9132. var writePath = pathChild(path, relativePath);
  9133. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9134. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9135. }
  9136. });
  9137. changedChildren.foreach(function (relativePath, childNode) {
  9138. var writePath = pathChild(path, relativePath);
  9139. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9140. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9141. }
  9142. });
  9143. return curViewCache;
  9144. }
  9145. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  9146. merge.foreach(function (relativePath, childNode) {
  9147. node = node.updateChild(relativePath, childNode);
  9148. });
  9149. return node;
  9150. }
  9151. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  9152. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  9153. // wait for the complete data update coming soon.
  9154. if (viewCache.serverCache.getNode().isEmpty() &&
  9155. !viewCache.serverCache.isFullyInitialized()) {
  9156. return viewCache;
  9157. }
  9158. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9159. // window leaving room for new items. It's important we process these changes first, so we
  9160. // iterate the changes twice, first processing any that affect items currently in view.
  9161. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9162. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9163. // not the other.
  9164. var curViewCache = viewCache;
  9165. var viewMergeTree;
  9166. if (pathIsEmpty(path)) {
  9167. viewMergeTree = changedChildren;
  9168. }
  9169. else {
  9170. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  9171. }
  9172. var serverNode = viewCache.serverCache.getNode();
  9173. viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
  9174. if (serverNode.hasChild(childKey)) {
  9175. var serverChild = viewCache.serverCache
  9176. .getNode()
  9177. .getImmediateChild(childKey);
  9178. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  9179. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9180. }
  9181. });
  9182. viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
  9183. var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  9184. childMergeTree.value === null;
  9185. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  9186. var serverChild = viewCache.serverCache
  9187. .getNode()
  9188. .getImmediateChild(childKey);
  9189. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  9190. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9191. }
  9192. });
  9193. return curViewCache;
  9194. }
  9195. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  9196. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  9197. return viewCache;
  9198. }
  9199. // Only filter server node if it is currently filtered
  9200. var filterServerNode = viewCache.serverCache.isFiltered();
  9201. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  9202. // now that it won't be shadowed.
  9203. var serverCache = viewCache.serverCache;
  9204. if (affectedTree.value != null) {
  9205. // This is an overwrite.
  9206. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  9207. serverCache.isCompleteForPath(ackPath)) {
  9208. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  9209. }
  9210. else if (pathIsEmpty(ackPath)) {
  9211. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  9212. // should just re-apply whatever we have in our cache as a merge.
  9213. var changedChildren_1 = new ImmutableTree(null);
  9214. serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
  9215. changedChildren_1 = changedChildren_1.set(new Path(name), node);
  9216. });
  9217. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
  9218. }
  9219. else {
  9220. return viewCache;
  9221. }
  9222. }
  9223. else {
  9224. // This is a merge.
  9225. var changedChildren_2 = new ImmutableTree(null);
  9226. affectedTree.foreach(function (mergePath, value) {
  9227. var serverCachePath = pathChild(ackPath, mergePath);
  9228. if (serverCache.isCompleteForPath(serverCachePath)) {
  9229. changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  9230. }
  9231. });
  9232. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
  9233. }
  9234. }
  9235. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  9236. var oldServerNode = viewCache.serverCache;
  9237. var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  9238. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  9239. }
  9240. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  9241. var complete;
  9242. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  9243. return viewCache;
  9244. }
  9245. else {
  9246. var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  9247. var oldEventCache = viewCache.eventCache.getNode();
  9248. var newEventCache = void 0;
  9249. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9250. var newNode = void 0;
  9251. if (viewCache.serverCache.isFullyInitialized()) {
  9252. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9253. }
  9254. else {
  9255. var serverChildren = viewCache.serverCache.getNode();
  9256. assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9257. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9258. }
  9259. newNode = newNode;
  9260. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9261. }
  9262. else {
  9263. var childKey = pathGetFront(path);
  9264. var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9265. if (newChild == null &&
  9266. viewCache.serverCache.isCompleteForChild(childKey)) {
  9267. newChild = oldEventCache.getImmediateChild(childKey);
  9268. }
  9269. if (newChild != null) {
  9270. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9271. }
  9272. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9273. // No complete child available, delete the existing one, if any
  9274. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9275. }
  9276. else {
  9277. newEventCache = oldEventCache;
  9278. }
  9279. if (newEventCache.isEmpty() &&
  9280. viewCache.serverCache.isFullyInitialized()) {
  9281. // We might have reverted all child writes. Maybe the old event was a leaf node
  9282. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9283. if (complete.isLeafNode()) {
  9284. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9285. }
  9286. }
  9287. }
  9288. complete =
  9289. viewCache.serverCache.isFullyInitialized() ||
  9290. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9291. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9292. }
  9293. }
  9294. /**
  9295. * @license
  9296. * Copyright 2017 Google LLC
  9297. *
  9298. * Licensed under the Apache License, Version 2.0 (the "License");
  9299. * you may not use this file except in compliance with the License.
  9300. * You may obtain a copy of the License at
  9301. *
  9302. * http://www.apache.org/licenses/LICENSE-2.0
  9303. *
  9304. * Unless required by applicable law or agreed to in writing, software
  9305. * distributed under the License is distributed on an "AS IS" BASIS,
  9306. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9307. * See the License for the specific language governing permissions and
  9308. * limitations under the License.
  9309. */
  9310. /**
  9311. * A view represents a specific location and query that has 1 or more event registrations.
  9312. *
  9313. * It does several things:
  9314. * - Maintains the list of event registrations for this location/query.
  9315. * - Maintains a cache of the data visible for this location/query.
  9316. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9317. * registrations returns the set of events to be raised.
  9318. */
  9319. var View = /** @class */ (function () {
  9320. function View(query_, initialViewCache) {
  9321. this.query_ = query_;
  9322. this.eventRegistrations_ = [];
  9323. var params = this.query_._queryParams;
  9324. var indexFilter = new IndexedFilter(params.getIndex());
  9325. var filter = queryParamsGetNodeFilter(params);
  9326. this.processor_ = newViewProcessor(filter);
  9327. var initialServerCache = initialViewCache.serverCache;
  9328. var initialEventCache = initialViewCache.eventCache;
  9329. // Don't filter server node with other filter than index, wait for tagged listen
  9330. var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9331. var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9332. var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9333. var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9334. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9335. this.eventGenerator_ = new EventGenerator(this.query_);
  9336. }
  9337. Object.defineProperty(View.prototype, "query", {
  9338. get: function () {
  9339. return this.query_;
  9340. },
  9341. enumerable: false,
  9342. configurable: true
  9343. });
  9344. return View;
  9345. }());
  9346. function viewGetServerCache(view) {
  9347. return view.viewCache_.serverCache.getNode();
  9348. }
  9349. function viewGetCompleteNode(view) {
  9350. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9351. }
  9352. function viewGetCompleteServerCache(view, path) {
  9353. var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9354. if (cache) {
  9355. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9356. // we need to see if it contains the child we're interested in.
  9357. if (view.query._queryParams.loadsAllData() ||
  9358. (!pathIsEmpty(path) &&
  9359. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9360. return cache.getChild(path);
  9361. }
  9362. }
  9363. return null;
  9364. }
  9365. function viewIsEmpty(view) {
  9366. return view.eventRegistrations_.length === 0;
  9367. }
  9368. function viewAddEventRegistration(view, eventRegistration) {
  9369. view.eventRegistrations_.push(eventRegistration);
  9370. }
  9371. /**
  9372. * @param eventRegistration - If null, remove all callbacks.
  9373. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9374. * @returns Cancel events, if cancelError was provided.
  9375. */
  9376. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9377. var cancelEvents = [];
  9378. if (cancelError) {
  9379. assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9380. var path_1 = view.query._path;
  9381. view.eventRegistrations_.forEach(function (registration) {
  9382. var maybeEvent = registration.createCancelEvent(cancelError, path_1);
  9383. if (maybeEvent) {
  9384. cancelEvents.push(maybeEvent);
  9385. }
  9386. });
  9387. }
  9388. if (eventRegistration) {
  9389. var remaining = [];
  9390. for (var i = 0; i < view.eventRegistrations_.length; ++i) {
  9391. var existing = view.eventRegistrations_[i];
  9392. if (!existing.matches(eventRegistration)) {
  9393. remaining.push(existing);
  9394. }
  9395. else if (eventRegistration.hasAnyCallback()) {
  9396. // We're removing just this one
  9397. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9398. break;
  9399. }
  9400. }
  9401. view.eventRegistrations_ = remaining;
  9402. }
  9403. else {
  9404. view.eventRegistrations_ = [];
  9405. }
  9406. return cancelEvents;
  9407. }
  9408. /**
  9409. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9410. */
  9411. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9412. if (operation.type === OperationType.MERGE &&
  9413. operation.source.queryId !== null) {
  9414. assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9415. assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9416. }
  9417. var oldViewCache = view.viewCache_;
  9418. var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9419. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9420. assert(result.viewCache.serverCache.isFullyInitialized() ||
  9421. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9422. view.viewCache_ = result.viewCache;
  9423. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9424. }
  9425. function viewGetInitialEvents(view, registration) {
  9426. var eventSnap = view.viewCache_.eventCache;
  9427. var initialChanges = [];
  9428. if (!eventSnap.getNode().isLeafNode()) {
  9429. var eventNode = eventSnap.getNode();
  9430. eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  9431. initialChanges.push(changeChildAdded(key, childNode));
  9432. });
  9433. }
  9434. if (eventSnap.isFullyInitialized()) {
  9435. initialChanges.push(changeValue(eventSnap.getNode()));
  9436. }
  9437. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9438. }
  9439. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9440. var registrations = eventRegistration
  9441. ? [eventRegistration]
  9442. : view.eventRegistrations_;
  9443. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9444. }
  9445. /**
  9446. * @license
  9447. * Copyright 2017 Google LLC
  9448. *
  9449. * Licensed under the Apache License, Version 2.0 (the "License");
  9450. * you may not use this file except in compliance with the License.
  9451. * You may obtain a copy of the License at
  9452. *
  9453. * http://www.apache.org/licenses/LICENSE-2.0
  9454. *
  9455. * Unless required by applicable law or agreed to in writing, software
  9456. * distributed under the License is distributed on an "AS IS" BASIS,
  9457. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9458. * See the License for the specific language governing permissions and
  9459. * limitations under the License.
  9460. */
  9461. var referenceConstructor$1;
  9462. /**
  9463. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9464. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9465. * and user writes (set, transaction, update).
  9466. *
  9467. * It's responsible for:
  9468. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9469. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9470. * applyUserOverwrite, etc.)
  9471. */
  9472. var SyncPoint = /** @class */ (function () {
  9473. function SyncPoint() {
  9474. /**
  9475. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9476. * queryId and the value is the View for that query.
  9477. *
  9478. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9479. */
  9480. this.views = new Map();
  9481. }
  9482. return SyncPoint;
  9483. }());
  9484. function syncPointSetReferenceConstructor(val) {
  9485. assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9486. referenceConstructor$1 = val;
  9487. }
  9488. function syncPointGetReferenceConstructor() {
  9489. assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9490. return referenceConstructor$1;
  9491. }
  9492. function syncPointIsEmpty(syncPoint) {
  9493. return syncPoint.views.size === 0;
  9494. }
  9495. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9496. var e_1, _a;
  9497. var queryId = operation.source.queryId;
  9498. if (queryId !== null) {
  9499. var view = syncPoint.views.get(queryId);
  9500. assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9501. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9502. }
  9503. else {
  9504. var events = [];
  9505. try {
  9506. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9507. var view = _c.value;
  9508. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9509. }
  9510. }
  9511. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  9512. finally {
  9513. try {
  9514. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9515. }
  9516. finally { if (e_1) throw e_1.error; }
  9517. }
  9518. return events;
  9519. }
  9520. }
  9521. /**
  9522. * Get a view for the specified query.
  9523. *
  9524. * @param query - The query to return a view for
  9525. * @param writesCache
  9526. * @param serverCache
  9527. * @param serverCacheComplete
  9528. * @returns Events to raise.
  9529. */
  9530. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9531. var queryId = query._queryIdentifier;
  9532. var view = syncPoint.views.get(queryId);
  9533. if (!view) {
  9534. // TODO: make writesCache take flag for complete server node
  9535. var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9536. var eventCacheComplete = false;
  9537. if (eventCache) {
  9538. eventCacheComplete = true;
  9539. }
  9540. else if (serverCache instanceof ChildrenNode) {
  9541. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9542. eventCacheComplete = false;
  9543. }
  9544. else {
  9545. eventCache = ChildrenNode.EMPTY_NODE;
  9546. eventCacheComplete = false;
  9547. }
  9548. var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9549. return new View(query, viewCache);
  9550. }
  9551. return view;
  9552. }
  9553. /**
  9554. * Add an event callback for the specified query.
  9555. *
  9556. * @param query
  9557. * @param eventRegistration
  9558. * @param writesCache
  9559. * @param serverCache - Complete server cache, if we have it.
  9560. * @param serverCacheComplete
  9561. * @returns Events to raise.
  9562. */
  9563. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9564. var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9565. if (!syncPoint.views.has(query._queryIdentifier)) {
  9566. syncPoint.views.set(query._queryIdentifier, view);
  9567. }
  9568. // This is guaranteed to exist now, we just created anything that was missing
  9569. viewAddEventRegistration(view, eventRegistration);
  9570. return viewGetInitialEvents(view, eventRegistration);
  9571. }
  9572. /**
  9573. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9574. *
  9575. * If query is the default query, we'll check all views for the specified eventRegistration.
  9576. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9577. *
  9578. * @param eventRegistration - If null, remove all callbacks.
  9579. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9580. * @returns removed queries and any cancel events
  9581. */
  9582. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9583. var e_2, _a;
  9584. var queryId = query._queryIdentifier;
  9585. var removed = [];
  9586. var cancelEvents = [];
  9587. var hadCompleteView = syncPointHasCompleteView(syncPoint);
  9588. if (queryId === 'default') {
  9589. try {
  9590. // When you do ref.off(...), we search all views for the registration to remove.
  9591. for (var _b = __values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9592. var _d = __read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
  9593. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9594. if (viewIsEmpty(view)) {
  9595. syncPoint.views.delete(viewQueryId);
  9596. // We'll deal with complete views later.
  9597. if (!view.query._queryParams.loadsAllData()) {
  9598. removed.push(view.query);
  9599. }
  9600. }
  9601. }
  9602. }
  9603. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  9604. finally {
  9605. try {
  9606. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9607. }
  9608. finally { if (e_2) throw e_2.error; }
  9609. }
  9610. }
  9611. else {
  9612. // remove the callback from the specific view.
  9613. var view = syncPoint.views.get(queryId);
  9614. if (view) {
  9615. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9616. if (viewIsEmpty(view)) {
  9617. syncPoint.views.delete(queryId);
  9618. // We'll deal with complete views later.
  9619. if (!view.query._queryParams.loadsAllData()) {
  9620. removed.push(view.query);
  9621. }
  9622. }
  9623. }
  9624. }
  9625. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9626. // We removed our last complete view.
  9627. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9628. }
  9629. return { removed: removed, events: cancelEvents };
  9630. }
  9631. function syncPointGetQueryViews(syncPoint) {
  9632. var e_3, _a;
  9633. var result = [];
  9634. try {
  9635. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9636. var view = _c.value;
  9637. if (!view.query._queryParams.loadsAllData()) {
  9638. result.push(view);
  9639. }
  9640. }
  9641. }
  9642. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  9643. finally {
  9644. try {
  9645. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9646. }
  9647. finally { if (e_3) throw e_3.error; }
  9648. }
  9649. return result;
  9650. }
  9651. /**
  9652. * @param path - The path to the desired complete snapshot
  9653. * @returns A complete cache, if it exists
  9654. */
  9655. function syncPointGetCompleteServerCache(syncPoint, path) {
  9656. var e_4, _a;
  9657. var serverCache = null;
  9658. try {
  9659. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9660. var view = _c.value;
  9661. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9662. }
  9663. }
  9664. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  9665. finally {
  9666. try {
  9667. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9668. }
  9669. finally { if (e_4) throw e_4.error; }
  9670. }
  9671. return serverCache;
  9672. }
  9673. function syncPointViewForQuery(syncPoint, query) {
  9674. var params = query._queryParams;
  9675. if (params.loadsAllData()) {
  9676. return syncPointGetCompleteView(syncPoint);
  9677. }
  9678. else {
  9679. var queryId = query._queryIdentifier;
  9680. return syncPoint.views.get(queryId);
  9681. }
  9682. }
  9683. function syncPointViewExistsForQuery(syncPoint, query) {
  9684. return syncPointViewForQuery(syncPoint, query) != null;
  9685. }
  9686. function syncPointHasCompleteView(syncPoint) {
  9687. return syncPointGetCompleteView(syncPoint) != null;
  9688. }
  9689. function syncPointGetCompleteView(syncPoint) {
  9690. var e_5, _a;
  9691. try {
  9692. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9693. var view = _c.value;
  9694. if (view.query._queryParams.loadsAllData()) {
  9695. return view;
  9696. }
  9697. }
  9698. }
  9699. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  9700. finally {
  9701. try {
  9702. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9703. }
  9704. finally { if (e_5) throw e_5.error; }
  9705. }
  9706. return null;
  9707. }
  9708. /**
  9709. * @license
  9710. * Copyright 2017 Google LLC
  9711. *
  9712. * Licensed under the Apache License, Version 2.0 (the "License");
  9713. * you may not use this file except in compliance with the License.
  9714. * You may obtain a copy of the License at
  9715. *
  9716. * http://www.apache.org/licenses/LICENSE-2.0
  9717. *
  9718. * Unless required by applicable law or agreed to in writing, software
  9719. * distributed under the License is distributed on an "AS IS" BASIS,
  9720. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9721. * See the License for the specific language governing permissions and
  9722. * limitations under the License.
  9723. */
  9724. var referenceConstructor;
  9725. function syncTreeSetReferenceConstructor(val) {
  9726. assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9727. referenceConstructor = val;
  9728. }
  9729. function syncTreeGetReferenceConstructor() {
  9730. assert(referenceConstructor, 'Reference.ts has not been loaded');
  9731. return referenceConstructor;
  9732. }
  9733. /**
  9734. * Static tracker for next query tag.
  9735. */
  9736. var syncTreeNextQueryTag_ = 1;
  9737. /**
  9738. * SyncTree is the central class for managing event callback registration, data caching, views
  9739. * (query processing), and event generation. There are typically two SyncTree instances for
  9740. * each Repo, one for the normal Firebase data, and one for the .info data.
  9741. *
  9742. * It has a number of responsibilities, including:
  9743. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9744. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9745. * (applyUserOverwrite(), applyUserMerge()).
  9746. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9747. * applyServerMerge()).
  9748. * - Generating user-facing events for server and user changes (all of the apply* methods
  9749. * return the set of events that need to be raised as a result).
  9750. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9751. * to the correct set of paths and queries to satisfy the current set of user event
  9752. * callbacks (listens are started/stopped using the provided listenProvider).
  9753. *
  9754. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9755. * events are returned to the caller rather than raised synchronously.
  9756. *
  9757. */
  9758. var SyncTree = /** @class */ (function () {
  9759. /**
  9760. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9761. * to server data.
  9762. */
  9763. function SyncTree(listenProvider_) {
  9764. this.listenProvider_ = listenProvider_;
  9765. /**
  9766. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9767. */
  9768. this.syncPointTree_ = new ImmutableTree(null);
  9769. /**
  9770. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9771. */
  9772. this.pendingWriteTree_ = newWriteTree();
  9773. this.tagToQueryMap = new Map();
  9774. this.queryToTagMap = new Map();
  9775. }
  9776. return SyncTree;
  9777. }());
  9778. /**
  9779. * Apply the data changes for a user-generated set() or transaction() call.
  9780. *
  9781. * @returns Events to raise.
  9782. */
  9783. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9784. // Record pending write.
  9785. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9786. if (!visible) {
  9787. return [];
  9788. }
  9789. else {
  9790. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9791. }
  9792. }
  9793. /**
  9794. * Apply the data from a user-generated update() call
  9795. *
  9796. * @returns Events to raise.
  9797. */
  9798. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9799. // Record pending merge.
  9800. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9801. var changeTree = ImmutableTree.fromObject(changedChildren);
  9802. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9803. }
  9804. /**
  9805. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9806. *
  9807. * @param revert - True if the given write failed and needs to be reverted
  9808. * @returns Events to raise.
  9809. */
  9810. function syncTreeAckUserWrite(syncTree, writeId, revert) {
  9811. if (revert === void 0) { revert = false; }
  9812. var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9813. var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9814. if (!needToReevaluate) {
  9815. return [];
  9816. }
  9817. else {
  9818. var affectedTree_1 = new ImmutableTree(null);
  9819. if (write.snap != null) {
  9820. // overwrite
  9821. affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
  9822. }
  9823. else {
  9824. each(write.children, function (pathString) {
  9825. affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
  9826. });
  9827. }
  9828. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
  9829. }
  9830. }
  9831. /**
  9832. * Apply new server data for the specified path..
  9833. *
  9834. * @returns Events to raise.
  9835. */
  9836. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9837. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9838. }
  9839. /**
  9840. * Apply new server data to be merged in at the specified path.
  9841. *
  9842. * @returns Events to raise.
  9843. */
  9844. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9845. var changeTree = ImmutableTree.fromObject(changedChildren);
  9846. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9847. }
  9848. /**
  9849. * Apply a listen complete for a query
  9850. *
  9851. * @returns Events to raise.
  9852. */
  9853. function syncTreeApplyListenComplete(syncTree, path) {
  9854. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9855. }
  9856. /**
  9857. * Apply a listen complete for a tagged query
  9858. *
  9859. * @returns Events to raise.
  9860. */
  9861. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9862. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9863. if (queryKey) {
  9864. var r = syncTreeParseQueryKey_(queryKey);
  9865. var queryPath = r.path, queryId = r.queryId;
  9866. var relativePath = newRelativePath(queryPath, path);
  9867. var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9868. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9869. }
  9870. else {
  9871. // We've already removed the query. No big deal, ignore the update
  9872. return [];
  9873. }
  9874. }
  9875. /**
  9876. * Remove event callback(s).
  9877. *
  9878. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9879. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9880. *
  9881. * @param eventRegistration - If null, all callbacks are removed.
  9882. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9883. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9884. * deduping needs to take place. This flag allows toggling of that behavior
  9885. * @returns Cancel events, if cancelError was provided.
  9886. */
  9887. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
  9888. if (skipListenerDedup === void 0) { skipListenerDedup = false; }
  9889. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9890. var path = query._path;
  9891. var maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9892. var cancelEvents = [];
  9893. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9894. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9895. // not loadsAllData().
  9896. if (maybeSyncPoint &&
  9897. (query._queryIdentifier === 'default' ||
  9898. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9899. var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9900. if (syncPointIsEmpty(maybeSyncPoint)) {
  9901. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9902. }
  9903. var removed = removedAndEvents.removed;
  9904. cancelEvents = removedAndEvents.events;
  9905. if (!skipListenerDedup) {
  9906. /**
  9907. * We may have just removed one of many listeners and can short-circuit this whole process
  9908. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9909. * properly set up.
  9910. */
  9911. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9912. // queryId === 'default'
  9913. var removingDefault = -1 !==
  9914. removed.findIndex(function (query) {
  9915. return query._queryParams.loadsAllData();
  9916. });
  9917. var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
  9918. return syncPointHasCompleteView(parentSyncPoint);
  9919. });
  9920. if (removingDefault && !covered) {
  9921. var subtree = syncTree.syncPointTree_.subtree(path);
  9922. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9923. // removal
  9924. if (!subtree.isEmpty()) {
  9925. // We need to fold over our subtree and collect the listeners to send
  9926. var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9927. // Ok, we've collected all the listens we need. Set them up.
  9928. for (var i = 0; i < newViews.length; ++i) {
  9929. var view = newViews[i], newQuery = view.query;
  9930. var listener = syncTreeCreateListenerForView_(syncTree, view);
  9931. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9932. }
  9933. }
  9934. // Otherwise there's nothing below us, so nothing we need to start listening on
  9935. }
  9936. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9937. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9938. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9939. if (!covered && removed.length > 0 && !cancelError) {
  9940. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9941. // default. Otherwise, we need to iterate through and cancel each individual query
  9942. if (removingDefault) {
  9943. // We don't tag default listeners
  9944. var defaultTag = null;
  9945. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9946. }
  9947. else {
  9948. removed.forEach(function (queryToRemove) {
  9949. var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9950. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9951. });
  9952. }
  9953. }
  9954. }
  9955. // Now, clear all of the tags we're tracking for the removed listens
  9956. syncTreeRemoveTags_(syncTree, removed);
  9957. }
  9958. return cancelEvents;
  9959. }
  9960. /**
  9961. * Apply new server data for the specified tagged query.
  9962. *
  9963. * @returns Events to raise.
  9964. */
  9965. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9966. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9967. if (queryKey != null) {
  9968. var r = syncTreeParseQueryKey_(queryKey);
  9969. var queryPath = r.path, queryId = r.queryId;
  9970. var relativePath = newRelativePath(queryPath, path);
  9971. var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9972. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9973. }
  9974. else {
  9975. // Query must have been removed already
  9976. return [];
  9977. }
  9978. }
  9979. /**
  9980. * Apply server data to be merged in for the specified tagged query.
  9981. *
  9982. * @returns Events to raise.
  9983. */
  9984. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9985. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9986. if (queryKey) {
  9987. var r = syncTreeParseQueryKey_(queryKey);
  9988. var queryPath = r.path, queryId = r.queryId;
  9989. var relativePath = newRelativePath(queryPath, path);
  9990. var changeTree = ImmutableTree.fromObject(changedChildren);
  9991. var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9992. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9993. }
  9994. else {
  9995. // We've already removed the query. No big deal, ignore the update
  9996. return [];
  9997. }
  9998. }
  9999. /**
  10000. * Add an event callback for the specified query.
  10001. *
  10002. * @returns Events to raise.
  10003. */
  10004. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
  10005. if (skipSetupListener === void 0) { skipSetupListener = false; }
  10006. var path = query._path;
  10007. var serverCache = null;
  10008. var foundAncestorDefaultView = false;
  10009. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10010. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10011. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10012. var relativePath = newRelativePath(pathToSyncPoint, path);
  10013. serverCache =
  10014. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10015. foundAncestorDefaultView =
  10016. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  10017. });
  10018. var syncPoint = syncTree.syncPointTree_.get(path);
  10019. if (!syncPoint) {
  10020. syncPoint = new SyncPoint();
  10021. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10022. }
  10023. else {
  10024. foundAncestorDefaultView =
  10025. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  10026. serverCache =
  10027. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10028. }
  10029. var serverCacheComplete;
  10030. if (serverCache != null) {
  10031. serverCacheComplete = true;
  10032. }
  10033. else {
  10034. serverCacheComplete = false;
  10035. serverCache = ChildrenNode.EMPTY_NODE;
  10036. var subtree = syncTree.syncPointTree_.subtree(path);
  10037. subtree.foreachChild(function (childName, childSyncPoint) {
  10038. var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  10039. if (completeCache) {
  10040. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  10041. }
  10042. });
  10043. }
  10044. var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  10045. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  10046. // We need to track a tag for this query
  10047. var queryKey = syncTreeMakeQueryKey_(query);
  10048. assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  10049. var tag = syncTreeGetNextQueryTag_();
  10050. syncTree.queryToTagMap.set(queryKey, tag);
  10051. syncTree.tagToQueryMap.set(tag, queryKey);
  10052. }
  10053. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  10054. var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  10055. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  10056. var view = syncPointViewForQuery(syncPoint, query);
  10057. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  10058. }
  10059. return events;
  10060. }
  10061. /**
  10062. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  10063. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  10064. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  10065. * <incremented total> as the write is applied locally and then acknowledged at the server.
  10066. *
  10067. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  10068. *
  10069. * @param path - The path to the data we want
  10070. * @param writeIdsToExclude - A specific set to be excluded
  10071. */
  10072. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  10073. var includeHiddenSets = true;
  10074. var writeTree = syncTree.pendingWriteTree_;
  10075. var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
  10076. var relativePath = newRelativePath(pathSoFar, path);
  10077. var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  10078. if (serverCache) {
  10079. return serverCache;
  10080. }
  10081. });
  10082. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  10083. }
  10084. function syncTreeGetServerValue(syncTree, query) {
  10085. var path = query._path;
  10086. var serverCache = null;
  10087. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10088. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10089. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10090. var relativePath = newRelativePath(pathToSyncPoint, path);
  10091. serverCache =
  10092. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10093. });
  10094. var syncPoint = syncTree.syncPointTree_.get(path);
  10095. if (!syncPoint) {
  10096. syncPoint = new SyncPoint();
  10097. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10098. }
  10099. else {
  10100. serverCache =
  10101. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10102. }
  10103. var serverCacheComplete = serverCache != null;
  10104. var serverCacheNode = serverCacheComplete
  10105. ? new CacheNode(serverCache, true, false)
  10106. : null;
  10107. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  10108. var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  10109. return viewGetCompleteNode(view);
  10110. }
  10111. /**
  10112. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  10113. *
  10114. * NOTES:
  10115. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  10116. *
  10117. * - We call applyOperation() on each SyncPoint passing three things:
  10118. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  10119. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  10120. * 3. A snapshot Node with cached server data, if we have it.
  10121. *
  10122. * - We concatenate all of the events returned by each SyncPoint and return the result.
  10123. */
  10124. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  10125. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  10126. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  10127. }
  10128. /**
  10129. * Recursive helper for applyOperationToSyncPoints_
  10130. */
  10131. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  10132. if (pathIsEmpty(operation.path)) {
  10133. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  10134. }
  10135. else {
  10136. var syncPoint = syncPointTree.get(newEmptyPath());
  10137. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10138. if (serverCache == null && syncPoint != null) {
  10139. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10140. }
  10141. var events = [];
  10142. var childName = pathGetFront(operation.path);
  10143. var childOperation = operation.operationForChild(childName);
  10144. var childTree = syncPointTree.children.get(childName);
  10145. if (childTree && childOperation) {
  10146. var childServerCache = serverCache
  10147. ? serverCache.getImmediateChild(childName)
  10148. : null;
  10149. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10150. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10151. }
  10152. if (syncPoint) {
  10153. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10154. }
  10155. return events;
  10156. }
  10157. }
  10158. /**
  10159. * Recursive helper for applyOperationToSyncPoints_
  10160. */
  10161. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  10162. var syncPoint = syncPointTree.get(newEmptyPath());
  10163. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10164. if (serverCache == null && syncPoint != null) {
  10165. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10166. }
  10167. var events = [];
  10168. syncPointTree.children.inorderTraversal(function (childName, childTree) {
  10169. var childServerCache = serverCache
  10170. ? serverCache.getImmediateChild(childName)
  10171. : null;
  10172. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10173. var childOperation = operation.operationForChild(childName);
  10174. if (childOperation) {
  10175. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10176. }
  10177. });
  10178. if (syncPoint) {
  10179. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10180. }
  10181. return events;
  10182. }
  10183. function syncTreeCreateListenerForView_(syncTree, view) {
  10184. var query = view.query;
  10185. var tag = syncTreeTagForQuery(syncTree, query);
  10186. return {
  10187. hashFn: function () {
  10188. var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  10189. return cache.hash();
  10190. },
  10191. onComplete: function (status) {
  10192. if (status === 'ok') {
  10193. if (tag) {
  10194. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  10195. }
  10196. else {
  10197. return syncTreeApplyListenComplete(syncTree, query._path);
  10198. }
  10199. }
  10200. else {
  10201. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  10202. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  10203. var error = errorForServerCode(status, query);
  10204. return syncTreeRemoveEventRegistration(syncTree, query,
  10205. /*eventRegistration*/ null, error);
  10206. }
  10207. }
  10208. };
  10209. }
  10210. /**
  10211. * Return the tag associated with the given query.
  10212. */
  10213. function syncTreeTagForQuery(syncTree, query) {
  10214. var queryKey = syncTreeMakeQueryKey_(query);
  10215. return syncTree.queryToTagMap.get(queryKey);
  10216. }
  10217. /**
  10218. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  10219. */
  10220. function syncTreeMakeQueryKey_(query) {
  10221. return query._path.toString() + '$' + query._queryIdentifier;
  10222. }
  10223. /**
  10224. * Return the query associated with the given tag, if we have one
  10225. */
  10226. function syncTreeQueryKeyForTag_(syncTree, tag) {
  10227. return syncTree.tagToQueryMap.get(tag);
  10228. }
  10229. /**
  10230. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  10231. */
  10232. function syncTreeParseQueryKey_(queryKey) {
  10233. var splitIndex = queryKey.indexOf('$');
  10234. assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  10235. return {
  10236. queryId: queryKey.substr(splitIndex + 1),
  10237. path: new Path(queryKey.substr(0, splitIndex))
  10238. };
  10239. }
  10240. /**
  10241. * A helper method to apply tagged operations
  10242. */
  10243. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  10244. var syncPoint = syncTree.syncPointTree_.get(queryPath);
  10245. assert(syncPoint, "Missing sync point for query tag that we're tracking");
  10246. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  10247. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  10248. }
  10249. /**
  10250. * This collapses multiple unfiltered views into a single view, since we only need a single
  10251. * listener for them.
  10252. */
  10253. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  10254. return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10255. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  10256. var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  10257. return [completeView];
  10258. }
  10259. else {
  10260. // No complete view here, flatten any deeper listens into an array
  10261. var views_1 = [];
  10262. if (maybeChildSyncPoint) {
  10263. views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
  10264. }
  10265. each(childMap, function (_key, childViews) {
  10266. views_1 = views_1.concat(childViews);
  10267. });
  10268. return views_1;
  10269. }
  10270. });
  10271. }
  10272. /**
  10273. * Normalizes a query to a query we send the server for listening
  10274. *
  10275. * @returns The normalized query
  10276. */
  10277. function syncTreeQueryForListening_(query) {
  10278. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  10279. // We treat queries that load all data as default queries
  10280. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  10281. // from Query
  10282. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  10283. }
  10284. else {
  10285. return query;
  10286. }
  10287. }
  10288. function syncTreeRemoveTags_(syncTree, queries) {
  10289. for (var j = 0; j < queries.length; ++j) {
  10290. var removedQuery = queries[j];
  10291. if (!removedQuery._queryParams.loadsAllData()) {
  10292. // We should have a tag for this
  10293. var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  10294. var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  10295. syncTree.queryToTagMap.delete(removedQueryKey);
  10296. syncTree.tagToQueryMap.delete(removedQueryTag);
  10297. }
  10298. }
  10299. }
  10300. /**
  10301. * Static accessor for query tags.
  10302. */
  10303. function syncTreeGetNextQueryTag_() {
  10304. return syncTreeNextQueryTag_++;
  10305. }
  10306. /**
  10307. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  10308. *
  10309. * @returns This method can return events to support synchronous data sources
  10310. */
  10311. function syncTreeSetupListener_(syncTree, query, view) {
  10312. var path = query._path;
  10313. var tag = syncTreeTagForQuery(syncTree, query);
  10314. var listener = syncTreeCreateListenerForView_(syncTree, view);
  10315. var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10316. var subtree = syncTree.syncPointTree_.subtree(path);
  10317. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10318. // may need to shadow other listens as well.
  10319. if (tag) {
  10320. assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10321. }
  10322. else {
  10323. // Shadow everything at or below this location, this is a default listener.
  10324. var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10325. if (!pathIsEmpty(relativePath) &&
  10326. maybeChildSyncPoint &&
  10327. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10328. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10329. }
  10330. else {
  10331. // No default listener here, flatten any deeper queries into an array
  10332. var queries_1 = [];
  10333. if (maybeChildSyncPoint) {
  10334. queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
  10335. }
  10336. each(childMap, function (_key, childQueries) {
  10337. queries_1 = queries_1.concat(childQueries);
  10338. });
  10339. return queries_1;
  10340. }
  10341. });
  10342. for (var i = 0; i < queriesToStop.length; ++i) {
  10343. var queryToStop = queriesToStop[i];
  10344. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10345. }
  10346. }
  10347. return events;
  10348. }
  10349. /**
  10350. * @license
  10351. * Copyright 2017 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. var ExistingValueProvider = /** @class */ (function () {
  10366. function ExistingValueProvider(node_) {
  10367. this.node_ = node_;
  10368. }
  10369. ExistingValueProvider.prototype.getImmediateChild = function (childName) {
  10370. var child = this.node_.getImmediateChild(childName);
  10371. return new ExistingValueProvider(child);
  10372. };
  10373. ExistingValueProvider.prototype.node = function () {
  10374. return this.node_;
  10375. };
  10376. return ExistingValueProvider;
  10377. }());
  10378. var DeferredValueProvider = /** @class */ (function () {
  10379. function DeferredValueProvider(syncTree, path) {
  10380. this.syncTree_ = syncTree;
  10381. this.path_ = path;
  10382. }
  10383. DeferredValueProvider.prototype.getImmediateChild = function (childName) {
  10384. var childPath = pathChild(this.path_, childName);
  10385. return new DeferredValueProvider(this.syncTree_, childPath);
  10386. };
  10387. DeferredValueProvider.prototype.node = function () {
  10388. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10389. };
  10390. return DeferredValueProvider;
  10391. }());
  10392. /**
  10393. * Generate placeholders for deferred values.
  10394. */
  10395. var generateWithValues = function (values) {
  10396. values = values || {};
  10397. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10398. return values;
  10399. };
  10400. /**
  10401. * Value to use when firing local events. When writing server values, fire
  10402. * local events with an approximate value, otherwise return value as-is.
  10403. */
  10404. var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10405. if (!value || typeof value !== 'object') {
  10406. return value;
  10407. }
  10408. assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10409. if (typeof value['.sv'] === 'string') {
  10410. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10411. }
  10412. else if (typeof value['.sv'] === 'object') {
  10413. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10414. }
  10415. else {
  10416. assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10417. }
  10418. };
  10419. var resolveScalarDeferredValue = function (op, existing, serverValues) {
  10420. switch (op) {
  10421. case 'timestamp':
  10422. return serverValues['timestamp'];
  10423. default:
  10424. assert(false, 'Unexpected server value: ' + op);
  10425. }
  10426. };
  10427. var resolveComplexDeferredValue = function (op, existing, unused) {
  10428. if (!op.hasOwnProperty('increment')) {
  10429. assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10430. }
  10431. var delta = op['increment'];
  10432. if (typeof delta !== 'number') {
  10433. assert(false, 'Unexpected increment value: ' + delta);
  10434. }
  10435. var existingNode = existing.node();
  10436. assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10437. // Incrementing a non-number sets the value to the incremented amount
  10438. if (!existingNode.isLeafNode()) {
  10439. return delta;
  10440. }
  10441. var leaf = existingNode;
  10442. var existingVal = leaf.getValue();
  10443. if (typeof existingVal !== 'number') {
  10444. return delta;
  10445. }
  10446. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10447. return existingVal + delta;
  10448. };
  10449. /**
  10450. * Recursively replace all deferred values and priorities in the tree with the
  10451. * specified generated replacement values.
  10452. * @param path - path to which write is relative
  10453. * @param node - new data written at path
  10454. * @param syncTree - current data
  10455. */
  10456. var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10457. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10458. };
  10459. /**
  10460. * Recursively replace all deferred values and priorities in the node with the
  10461. * specified generated replacement values. If there are no server values in the node,
  10462. * it'll be returned as-is.
  10463. */
  10464. var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10465. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10466. };
  10467. function resolveDeferredValue(node, existingVal, serverValues) {
  10468. var rawPri = node.getPriority().val();
  10469. var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10470. var newNode;
  10471. if (node.isLeafNode()) {
  10472. var leafNode = node;
  10473. var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10474. if (value !== leafNode.getValue() ||
  10475. priority !== leafNode.getPriority().val()) {
  10476. return new LeafNode(value, nodeFromJSON(priority));
  10477. }
  10478. else {
  10479. return node;
  10480. }
  10481. }
  10482. else {
  10483. var childrenNode = node;
  10484. newNode = childrenNode;
  10485. if (priority !== childrenNode.getPriority().val()) {
  10486. newNode = newNode.updatePriority(new LeafNode(priority));
  10487. }
  10488. childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  10489. var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10490. if (newChildNode !== childNode) {
  10491. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10492. }
  10493. });
  10494. return newNode;
  10495. }
  10496. }
  10497. /**
  10498. * @license
  10499. * Copyright 2017 Google LLC
  10500. *
  10501. * Licensed under the Apache License, Version 2.0 (the "License");
  10502. * you may not use this file except in compliance with the License.
  10503. * You may obtain a copy of the License at
  10504. *
  10505. * http://www.apache.org/licenses/LICENSE-2.0
  10506. *
  10507. * Unless required by applicable law or agreed to in writing, software
  10508. * distributed under the License is distributed on an "AS IS" BASIS,
  10509. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10510. * See the License for the specific language governing permissions and
  10511. * limitations under the License.
  10512. */
  10513. /**
  10514. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10515. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10516. * children.
  10517. */
  10518. var Tree = /** @class */ (function () {
  10519. /**
  10520. * @param name - Optional name of the node.
  10521. * @param parent - Optional parent node.
  10522. * @param node - Optional node to wrap.
  10523. */
  10524. function Tree(name, parent, node) {
  10525. if (name === void 0) { name = ''; }
  10526. if (parent === void 0) { parent = null; }
  10527. if (node === void 0) { node = { children: {}, childCount: 0 }; }
  10528. this.name = name;
  10529. this.parent = parent;
  10530. this.node = node;
  10531. }
  10532. return Tree;
  10533. }());
  10534. /**
  10535. * Returns a sub-Tree for the given path.
  10536. *
  10537. * @param pathObj - Path to look up.
  10538. * @returns Tree for path.
  10539. */
  10540. function treeSubTree(tree, pathObj) {
  10541. // TODO: Require pathObj to be Path?
  10542. var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10543. var child = tree, next = pathGetFront(path);
  10544. while (next !== null) {
  10545. var childNode = safeGet(child.node.children, next) || {
  10546. children: {},
  10547. childCount: 0
  10548. };
  10549. child = new Tree(next, child, childNode);
  10550. path = pathPopFront(path);
  10551. next = pathGetFront(path);
  10552. }
  10553. return child;
  10554. }
  10555. /**
  10556. * Returns the data associated with this tree node.
  10557. *
  10558. * @returns The data or null if no data exists.
  10559. */
  10560. function treeGetValue(tree) {
  10561. return tree.node.value;
  10562. }
  10563. /**
  10564. * Sets data to this tree node.
  10565. *
  10566. * @param value - Value to set.
  10567. */
  10568. function treeSetValue(tree, value) {
  10569. tree.node.value = value;
  10570. treeUpdateParents(tree);
  10571. }
  10572. /**
  10573. * @returns Whether the tree has any children.
  10574. */
  10575. function treeHasChildren(tree) {
  10576. return tree.node.childCount > 0;
  10577. }
  10578. /**
  10579. * @returns Whethe rthe tree is empty (no value or children).
  10580. */
  10581. function treeIsEmpty(tree) {
  10582. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10583. }
  10584. /**
  10585. * Calls action for each child of this tree node.
  10586. *
  10587. * @param action - Action to be called for each child.
  10588. */
  10589. function treeForEachChild(tree, action) {
  10590. each(tree.node.children, function (child, childTree) {
  10591. action(new Tree(child, tree, childTree));
  10592. });
  10593. }
  10594. /**
  10595. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10596. *
  10597. * @param action - Action to be called for each child.
  10598. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10599. * false.
  10600. * @param childrenFirst - Whether to call action on children before calling it on
  10601. * parent.
  10602. */
  10603. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10604. if (includeSelf && !childrenFirst) {
  10605. action(tree);
  10606. }
  10607. treeForEachChild(tree, function (child) {
  10608. treeForEachDescendant(child, action, true, childrenFirst);
  10609. });
  10610. if (includeSelf && childrenFirst) {
  10611. action(tree);
  10612. }
  10613. }
  10614. /**
  10615. * Calls action on each ancestor node.
  10616. *
  10617. * @param action - Action to be called on each parent; return
  10618. * true to abort.
  10619. * @param includeSelf - Whether to call action on this node as well.
  10620. * @returns true if the action callback returned true.
  10621. */
  10622. function treeForEachAncestor(tree, action, includeSelf) {
  10623. var node = includeSelf ? tree : tree.parent;
  10624. while (node !== null) {
  10625. if (action(node)) {
  10626. return true;
  10627. }
  10628. node = node.parent;
  10629. }
  10630. return false;
  10631. }
  10632. /**
  10633. * @returns The path of this tree node, as a Path.
  10634. */
  10635. function treeGetPath(tree) {
  10636. return new Path(tree.parent === null
  10637. ? tree.name
  10638. : treeGetPath(tree.parent) + '/' + tree.name);
  10639. }
  10640. /**
  10641. * Adds or removes this child from its parent based on whether it's empty or not.
  10642. */
  10643. function treeUpdateParents(tree) {
  10644. if (tree.parent !== null) {
  10645. treeUpdateChild(tree.parent, tree.name, tree);
  10646. }
  10647. }
  10648. /**
  10649. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10650. *
  10651. * @param childName - The name of the child to update.
  10652. * @param child - The child to update.
  10653. */
  10654. function treeUpdateChild(tree, childName, child) {
  10655. var childEmpty = treeIsEmpty(child);
  10656. var childExists = contains(tree.node.children, childName);
  10657. if (childEmpty && childExists) {
  10658. delete tree.node.children[childName];
  10659. tree.node.childCount--;
  10660. treeUpdateParents(tree);
  10661. }
  10662. else if (!childEmpty && !childExists) {
  10663. tree.node.children[childName] = child.node;
  10664. tree.node.childCount++;
  10665. treeUpdateParents(tree);
  10666. }
  10667. }
  10668. /**
  10669. * @license
  10670. * Copyright 2017 Google LLC
  10671. *
  10672. * Licensed under the Apache License, Version 2.0 (the "License");
  10673. * you may not use this file except in compliance with the License.
  10674. * You may obtain a copy of the License at
  10675. *
  10676. * http://www.apache.org/licenses/LICENSE-2.0
  10677. *
  10678. * Unless required by applicable law or agreed to in writing, software
  10679. * distributed under the License is distributed on an "AS IS" BASIS,
  10680. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10681. * See the License for the specific language governing permissions and
  10682. * limitations under the License.
  10683. */
  10684. /**
  10685. * True for invalid Firebase keys
  10686. */
  10687. var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10688. /**
  10689. * True for invalid Firebase paths.
  10690. * Allows '/' in paths.
  10691. */
  10692. var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10693. /**
  10694. * Maximum number of characters to allow in leaf value
  10695. */
  10696. var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10697. var isValidKey = function (key) {
  10698. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10699. };
  10700. var isValidPathString = function (pathString) {
  10701. return (typeof pathString === 'string' &&
  10702. pathString.length !== 0 &&
  10703. !INVALID_PATH_REGEX_.test(pathString));
  10704. };
  10705. var isValidRootPathString = function (pathString) {
  10706. if (pathString) {
  10707. // Allow '/.info/' at the beginning.
  10708. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10709. }
  10710. return isValidPathString(pathString);
  10711. };
  10712. var isValidPriority = function (priority) {
  10713. return (priority === null ||
  10714. typeof priority === 'string' ||
  10715. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10716. (priority &&
  10717. typeof priority === 'object' &&
  10718. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10719. contains(priority, '.sv')));
  10720. };
  10721. /**
  10722. * Pre-validate a datum passed as an argument to Firebase function.
  10723. */
  10724. var validateFirebaseDataArg = function (fnName, value, path, optional) {
  10725. if (optional && value === undefined) {
  10726. return;
  10727. }
  10728. validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
  10729. };
  10730. /**
  10731. * Validate a data object client-side before sending to server.
  10732. */
  10733. var validateFirebaseData = function (errorPrefix, data, path_) {
  10734. var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10735. if (data === undefined) {
  10736. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10737. }
  10738. if (typeof data === 'function') {
  10739. throw new Error(errorPrefix +
  10740. 'contains a function ' +
  10741. validationPathToErrorString(path) +
  10742. ' with contents = ' +
  10743. data.toString());
  10744. }
  10745. if (isInvalidJSONNumber(data)) {
  10746. throw new Error(errorPrefix +
  10747. 'contains ' +
  10748. data.toString() +
  10749. ' ' +
  10750. validationPathToErrorString(path));
  10751. }
  10752. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10753. if (typeof data === 'string' &&
  10754. data.length > MAX_LEAF_SIZE_ / 3 &&
  10755. stringLength(data) > MAX_LEAF_SIZE_) {
  10756. throw new Error(errorPrefix +
  10757. 'contains a string greater than ' +
  10758. MAX_LEAF_SIZE_ +
  10759. ' utf8 bytes ' +
  10760. validationPathToErrorString(path) +
  10761. " ('" +
  10762. data.substring(0, 50) +
  10763. "...')");
  10764. }
  10765. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10766. // to save extra walking of large objects.
  10767. if (data && typeof data === 'object') {
  10768. var hasDotValue_1 = false;
  10769. var hasActualChild_1 = false;
  10770. each(data, function (key, value) {
  10771. if (key === '.value') {
  10772. hasDotValue_1 = true;
  10773. }
  10774. else if (key !== '.priority' && key !== '.sv') {
  10775. hasActualChild_1 = true;
  10776. if (!isValidKey(key)) {
  10777. throw new Error(errorPrefix +
  10778. ' contains an invalid key (' +
  10779. key +
  10780. ') ' +
  10781. validationPathToErrorString(path) +
  10782. '. Keys must be non-empty strings ' +
  10783. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10784. }
  10785. }
  10786. validationPathPush(path, key);
  10787. validateFirebaseData(errorPrefix, value, path);
  10788. validationPathPop(path);
  10789. });
  10790. if (hasDotValue_1 && hasActualChild_1) {
  10791. throw new Error(errorPrefix +
  10792. ' contains ".value" child ' +
  10793. validationPathToErrorString(path) +
  10794. ' in addition to actual children.');
  10795. }
  10796. }
  10797. };
  10798. /**
  10799. * Pre-validate paths passed in the firebase function.
  10800. */
  10801. var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10802. var i, curPath;
  10803. for (i = 0; i < mergePaths.length; i++) {
  10804. curPath = mergePaths[i];
  10805. var keys = pathSlice(curPath);
  10806. for (var j = 0; j < keys.length; j++) {
  10807. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10808. else if (!isValidKey(keys[j])) {
  10809. throw new Error(errorPrefix +
  10810. 'contains an invalid key (' +
  10811. keys[j] +
  10812. ') in path ' +
  10813. curPath.toString() +
  10814. '. Keys must be non-empty strings ' +
  10815. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10816. }
  10817. }
  10818. }
  10819. // Check that update keys are not descendants of each other.
  10820. // We rely on the property that sorting guarantees that ancestors come
  10821. // right before descendants.
  10822. mergePaths.sort(pathCompare);
  10823. var prevPath = null;
  10824. for (i = 0; i < mergePaths.length; i++) {
  10825. curPath = mergePaths[i];
  10826. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10827. throw new Error(errorPrefix +
  10828. 'contains a path ' +
  10829. prevPath.toString() +
  10830. ' that is ancestor of another path ' +
  10831. curPath.toString());
  10832. }
  10833. prevPath = curPath;
  10834. }
  10835. };
  10836. /**
  10837. * pre-validate an object passed as an argument to firebase function (
  10838. * must be an object - e.g. for firebase.update()).
  10839. */
  10840. var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10841. if (optional && data === undefined) {
  10842. return;
  10843. }
  10844. var errorPrefix$1 = errorPrefix(fnName, 'values');
  10845. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10846. throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
  10847. }
  10848. var mergePaths = [];
  10849. each(data, function (key, value) {
  10850. var curPath = new Path(key);
  10851. validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
  10852. if (pathGetBack(curPath) === '.priority') {
  10853. if (!isValidPriority(value)) {
  10854. throw new Error(errorPrefix$1 +
  10855. "contains an invalid value for '" +
  10856. curPath.toString() +
  10857. "', which must be a valid " +
  10858. 'Firebase priority (a string, finite number, server value, or null).');
  10859. }
  10860. }
  10861. mergePaths.push(curPath);
  10862. });
  10863. validateFirebaseMergePaths(errorPrefix$1, mergePaths);
  10864. };
  10865. var validatePriority = function (fnName, priority, optional) {
  10866. if (optional && priority === undefined) {
  10867. return;
  10868. }
  10869. if (isInvalidJSONNumber(priority)) {
  10870. throw new Error(errorPrefix(fnName, 'priority') +
  10871. 'is ' +
  10872. priority.toString() +
  10873. ', but must be a valid Firebase priority (a string, finite number, ' +
  10874. 'server value, or null).');
  10875. }
  10876. // Special case to allow importing data with a .sv.
  10877. if (!isValidPriority(priority)) {
  10878. throw new Error(errorPrefix(fnName, 'priority') +
  10879. 'must be a valid Firebase priority ' +
  10880. '(a string, finite number, server value, or null).');
  10881. }
  10882. };
  10883. var validateKey = function (fnName, argumentName, key, optional) {
  10884. if (optional && key === undefined) {
  10885. return;
  10886. }
  10887. if (!isValidKey(key)) {
  10888. throw new Error(errorPrefix(fnName, argumentName) +
  10889. 'was an invalid key = "' +
  10890. key +
  10891. '". Firebase keys must be non-empty strings and ' +
  10892. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10893. }
  10894. };
  10895. /**
  10896. * @internal
  10897. */
  10898. var validatePathString = function (fnName, argumentName, pathString, optional) {
  10899. if (optional && pathString === undefined) {
  10900. return;
  10901. }
  10902. if (!isValidPathString(pathString)) {
  10903. throw new Error(errorPrefix(fnName, argumentName) +
  10904. 'was an invalid path = "' +
  10905. pathString +
  10906. '". Paths must be non-empty strings and ' +
  10907. 'can\'t contain ".", "#", "$", "[", or "]"');
  10908. }
  10909. };
  10910. var validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10911. if (pathString) {
  10912. // Allow '/.info/' at the beginning.
  10913. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10914. }
  10915. validatePathString(fnName, argumentName, pathString, optional);
  10916. };
  10917. /**
  10918. * @internal
  10919. */
  10920. var validateWritablePath = function (fnName, path) {
  10921. if (pathGetFront(path) === '.info') {
  10922. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10923. }
  10924. };
  10925. var validateUrl = function (fnName, parsedUrl) {
  10926. // TODO = Validate server better.
  10927. var pathString = parsedUrl.path.toString();
  10928. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10929. parsedUrl.repoInfo.host.length === 0 ||
  10930. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10931. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10932. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10933. throw new Error(errorPrefix(fnName, 'url') +
  10934. 'must be a valid firebase URL and ' +
  10935. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10936. }
  10937. };
  10938. /**
  10939. * @license
  10940. * Copyright 2017 Google LLC
  10941. *
  10942. * Licensed under the Apache License, Version 2.0 (the "License");
  10943. * you may not use this file except in compliance with the License.
  10944. * You may obtain a copy of the License at
  10945. *
  10946. * http://www.apache.org/licenses/LICENSE-2.0
  10947. *
  10948. * Unless required by applicable law or agreed to in writing, software
  10949. * distributed under the License is distributed on an "AS IS" BASIS,
  10950. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10951. * See the License for the specific language governing permissions and
  10952. * limitations under the License.
  10953. */
  10954. /**
  10955. * The event queue serves a few purposes:
  10956. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10957. * events being queued.
  10958. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10959. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10960. * left off, ensuring that the events are still raised synchronously and in order.
  10961. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10962. * events are raised synchronously.
  10963. *
  10964. * NOTE: This can all go away if/when we move to async events.
  10965. *
  10966. */
  10967. var EventQueue = /** @class */ (function () {
  10968. function EventQueue() {
  10969. this.eventLists_ = [];
  10970. /**
  10971. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10972. */
  10973. this.recursionDepth_ = 0;
  10974. }
  10975. return EventQueue;
  10976. }());
  10977. /**
  10978. * @param eventDataList - The new events to queue.
  10979. */
  10980. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10981. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10982. var currList = null;
  10983. for (var i = 0; i < eventDataList.length; i++) {
  10984. var data = eventDataList[i];
  10985. var path = data.getPath();
  10986. if (currList !== null && !pathEquals(path, currList.path)) {
  10987. eventQueue.eventLists_.push(currList);
  10988. currList = null;
  10989. }
  10990. if (currList === null) {
  10991. currList = { events: [], path: path };
  10992. }
  10993. currList.events.push(data);
  10994. }
  10995. if (currList) {
  10996. eventQueue.eventLists_.push(currList);
  10997. }
  10998. }
  10999. /**
  11000. * Queues the specified events and synchronously raises all events (including previously queued ones)
  11001. * for the specified path.
  11002. *
  11003. * It is assumed that the new events are all for the specified path.
  11004. *
  11005. * @param path - The path to raise events for.
  11006. * @param eventDataList - The new events to raise.
  11007. */
  11008. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  11009. eventQueueQueueEvents(eventQueue, eventDataList);
  11010. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11011. return pathEquals(eventPath, path);
  11012. });
  11013. }
  11014. /**
  11015. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  11016. * locations related to the specified change path (i.e. all ancestors and descendants).
  11017. *
  11018. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  11019. *
  11020. * @param changedPath - The path to raise events for.
  11021. * @param eventDataList - The events to raise
  11022. */
  11023. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  11024. eventQueueQueueEvents(eventQueue, eventDataList);
  11025. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11026. return pathContains(eventPath, changedPath) ||
  11027. pathContains(changedPath, eventPath);
  11028. });
  11029. }
  11030. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  11031. eventQueue.recursionDepth_++;
  11032. var sentAll = true;
  11033. for (var i = 0; i < eventQueue.eventLists_.length; i++) {
  11034. var eventList = eventQueue.eventLists_[i];
  11035. if (eventList) {
  11036. var eventPath = eventList.path;
  11037. if (predicate(eventPath)) {
  11038. eventListRaise(eventQueue.eventLists_[i]);
  11039. eventQueue.eventLists_[i] = null;
  11040. }
  11041. else {
  11042. sentAll = false;
  11043. }
  11044. }
  11045. }
  11046. if (sentAll) {
  11047. eventQueue.eventLists_ = [];
  11048. }
  11049. eventQueue.recursionDepth_--;
  11050. }
  11051. /**
  11052. * Iterates through the list and raises each event
  11053. */
  11054. function eventListRaise(eventList) {
  11055. for (var i = 0; i < eventList.events.length; i++) {
  11056. var eventData = eventList.events[i];
  11057. if (eventData !== null) {
  11058. eventList.events[i] = null;
  11059. var eventFn = eventData.getEventRunner();
  11060. if (logger) {
  11061. log('event: ' + eventData.toString());
  11062. }
  11063. exceptionGuard(eventFn);
  11064. }
  11065. }
  11066. }
  11067. /**
  11068. * @license
  11069. * Copyright 2017 Google LLC
  11070. *
  11071. * Licensed under the Apache License, Version 2.0 (the "License");
  11072. * you may not use this file except in compliance with the License.
  11073. * You may obtain a copy of the License at
  11074. *
  11075. * http://www.apache.org/licenses/LICENSE-2.0
  11076. *
  11077. * Unless required by applicable law or agreed to in writing, software
  11078. * distributed under the License is distributed on an "AS IS" BASIS,
  11079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11080. * See the License for the specific language governing permissions and
  11081. * limitations under the License.
  11082. */
  11083. var INTERRUPT_REASON = 'repo_interrupt';
  11084. /**
  11085. * If a transaction does not succeed after 25 retries, we abort it. Among other
  11086. * things this ensure that if there's ever a bug causing a mismatch between
  11087. * client / server hashes for some data, we won't retry indefinitely.
  11088. */
  11089. var MAX_TRANSACTION_RETRIES = 25;
  11090. /**
  11091. * A connection to a single data repository.
  11092. */
  11093. var Repo = /** @class */ (function () {
  11094. function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  11095. this.repoInfo_ = repoInfo_;
  11096. this.forceRestClient_ = forceRestClient_;
  11097. this.authTokenProvider_ = authTokenProvider_;
  11098. this.appCheckProvider_ = appCheckProvider_;
  11099. this.dataUpdateCount = 0;
  11100. this.statsListener_ = null;
  11101. this.eventQueue_ = new EventQueue();
  11102. this.nextWriteId_ = 1;
  11103. this.interceptServerDataCallback_ = null;
  11104. /** A list of data pieces and paths to be set when this client disconnects. */
  11105. this.onDisconnect_ = newSparseSnapshotTree();
  11106. /** Stores queues of outstanding transactions for Firebase locations. */
  11107. this.transactionQueueTree_ = new Tree();
  11108. // TODO: This should be @private but it's used by test_access.js and internal.js
  11109. this.persistentConnection_ = null;
  11110. // This key is intentionally not updated if RepoInfo is later changed or replaced
  11111. this.key = this.repoInfo_.toURLString();
  11112. }
  11113. /**
  11114. * @returns The URL corresponding to the root of this Firebase.
  11115. */
  11116. Repo.prototype.toString = function () {
  11117. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  11118. };
  11119. return Repo;
  11120. }());
  11121. function repoStart(repo, appId, authOverride) {
  11122. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  11123. if (repo.forceRestClient_ || beingCrawled()) {
  11124. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
  11125. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11126. }, repo.authTokenProvider_, repo.appCheckProvider_);
  11127. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  11128. setTimeout(function () { return repoOnConnectStatus(repo, /* connectStatus= */ true); }, 0);
  11129. }
  11130. else {
  11131. // Validate authOverride
  11132. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  11133. if (typeof authOverride !== 'object') {
  11134. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  11135. }
  11136. try {
  11137. stringify(authOverride);
  11138. }
  11139. catch (e) {
  11140. throw new Error('Invalid authOverride provided: ' + e);
  11141. }
  11142. }
  11143. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
  11144. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11145. }, function (connectStatus) {
  11146. repoOnConnectStatus(repo, connectStatus);
  11147. }, function (updates) {
  11148. repoOnServerInfoUpdate(repo, updates);
  11149. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  11150. repo.server_ = repo.persistentConnection_;
  11151. }
  11152. repo.authTokenProvider_.addTokenChangeListener(function (token) {
  11153. repo.server_.refreshAuthToken(token);
  11154. });
  11155. repo.appCheckProvider_.addTokenChangeListener(function (result) {
  11156. repo.server_.refreshAppCheckToken(result.token);
  11157. });
  11158. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  11159. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  11160. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
  11161. // Used for .info.
  11162. repo.infoData_ = new SnapshotHolder();
  11163. repo.infoSyncTree_ = new SyncTree({
  11164. startListening: function (query, tag, currentHashFn, onComplete) {
  11165. var infoEvents = [];
  11166. var node = repo.infoData_.getNode(query._path);
  11167. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  11168. // on initial data...
  11169. if (!node.isEmpty()) {
  11170. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  11171. setTimeout(function () {
  11172. onComplete('ok');
  11173. }, 0);
  11174. }
  11175. return infoEvents;
  11176. },
  11177. stopListening: function () { }
  11178. });
  11179. repoUpdateInfo(repo, 'connected', false);
  11180. repo.serverSyncTree_ = new SyncTree({
  11181. startListening: function (query, tag, currentHashFn, onComplete) {
  11182. repo.server_.listen(query, currentHashFn, tag, function (status, data) {
  11183. var events = onComplete(status, data);
  11184. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11185. });
  11186. // No synchronous events for network-backed sync trees
  11187. return [];
  11188. },
  11189. stopListening: function (query, tag) {
  11190. repo.server_.unlisten(query, tag);
  11191. }
  11192. });
  11193. }
  11194. /**
  11195. * @returns The time in milliseconds, taking the server offset into account if we have one.
  11196. */
  11197. function repoServerTime(repo) {
  11198. var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  11199. var offset = offsetNode.val() || 0;
  11200. return new Date().getTime() + offset;
  11201. }
  11202. /**
  11203. * Generate ServerValues using some variables from the repo object.
  11204. */
  11205. function repoGenerateServerValues(repo) {
  11206. return generateWithValues({
  11207. timestamp: repoServerTime(repo)
  11208. });
  11209. }
  11210. /**
  11211. * Called by realtime when we get new messages from the server.
  11212. */
  11213. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  11214. // For testing.
  11215. repo.dataUpdateCount++;
  11216. var path = new Path(pathString);
  11217. data = repo.interceptServerDataCallback_
  11218. ? repo.interceptServerDataCallback_(pathString, data)
  11219. : data;
  11220. var events = [];
  11221. if (tag) {
  11222. if (isMerge) {
  11223. var taggedChildren = map(data, function (raw) { return nodeFromJSON(raw); });
  11224. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  11225. }
  11226. else {
  11227. var taggedSnap = nodeFromJSON(data);
  11228. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  11229. }
  11230. }
  11231. else if (isMerge) {
  11232. var changedChildren = map(data, function (raw) { return nodeFromJSON(raw); });
  11233. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  11234. }
  11235. else {
  11236. var snap = nodeFromJSON(data);
  11237. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  11238. }
  11239. var affectedPath = path;
  11240. if (events.length > 0) {
  11241. // Since we have a listener outstanding for each transaction, receiving any events
  11242. // is a proxy for some change having occurred.
  11243. affectedPath = repoRerunTransactions(repo, path);
  11244. }
  11245. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  11246. }
  11247. function repoOnConnectStatus(repo, connectStatus) {
  11248. repoUpdateInfo(repo, 'connected', connectStatus);
  11249. if (connectStatus === false) {
  11250. repoRunOnDisconnectEvents(repo);
  11251. }
  11252. }
  11253. function repoOnServerInfoUpdate(repo, updates) {
  11254. each(updates, function (key, value) {
  11255. repoUpdateInfo(repo, key, value);
  11256. });
  11257. }
  11258. function repoUpdateInfo(repo, pathString, value) {
  11259. var path = new Path('/.info/' + pathString);
  11260. var newNode = nodeFromJSON(value);
  11261. repo.infoData_.updateSnapshot(path, newNode);
  11262. var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  11263. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11264. }
  11265. function repoGetNextWriteId(repo) {
  11266. return repo.nextWriteId_++;
  11267. }
  11268. /**
  11269. * The purpose of `getValue` is to return the latest known value
  11270. * satisfying `query`.
  11271. *
  11272. * This method will first check for in-memory cached values
  11273. * belonging to active listeners. If they are found, such values
  11274. * are considered to be the most up-to-date.
  11275. *
  11276. * If the client is not connected, this method will wait until the
  11277. * repo has established a connection and then request the value for `query`.
  11278. * If the client is not able to retrieve the query result for another reason,
  11279. * it reports an error.
  11280. *
  11281. * @param query - The query to surface a value for.
  11282. */
  11283. function repoGetValue(repo, query, eventRegistration) {
  11284. // Only active queries are cached. There is no persisted cache.
  11285. var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  11286. if (cached != null) {
  11287. return Promise.resolve(cached);
  11288. }
  11289. return repo.server_.get(query).then(function (payload) {
  11290. var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  11291. /**
  11292. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  11293. * Add an event registration,
  11294. * Update data at the path,
  11295. * Raise any events,
  11296. * Cleanup the SyncTree
  11297. */
  11298. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  11299. var events;
  11300. if (query._queryParams.loadsAllData()) {
  11301. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  11302. }
  11303. else {
  11304. var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  11305. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  11306. }
  11307. /*
  11308. * We need to raise events in the scenario where `get()` is called at a parent path, and
  11309. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  11310. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  11311. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  11312. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  11313. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  11314. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  11315. * ensure the corresponding child events will get fired.
  11316. */
  11317. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11318. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  11319. return node;
  11320. }, function (err) {
  11321. repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
  11322. return Promise.reject(new Error(err));
  11323. });
  11324. }
  11325. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  11326. repoLog(repo, 'set', {
  11327. path: path.toString(),
  11328. value: newVal,
  11329. priority: newPriority
  11330. });
  11331. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11332. // (b) store unresolved paths on JSON parse
  11333. var serverValues = repoGenerateServerValues(repo);
  11334. var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11335. var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11336. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11337. var writeId = repoGetNextWriteId(repo);
  11338. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11339. eventQueueQueueEvents(repo.eventQueue_, events);
  11340. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {
  11341. var success = status === 'ok';
  11342. if (!success) {
  11343. warn('set at ' + path + ' failed: ' + status);
  11344. }
  11345. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11346. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11347. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11348. });
  11349. var affectedPath = repoAbortTransactions(repo, path);
  11350. repoRerunTransactions(repo, affectedPath);
  11351. // We queued the events above, so just flush the queue here
  11352. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11353. }
  11354. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11355. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11356. // Start with our existing data and merge each child into it.
  11357. var empty = true;
  11358. var serverValues = repoGenerateServerValues(repo);
  11359. var changedChildren = {};
  11360. each(childrenToMerge, function (changedKey, changedValue) {
  11361. empty = false;
  11362. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11363. });
  11364. if (!empty) {
  11365. var writeId_1 = repoGetNextWriteId(repo);
  11366. var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
  11367. eventQueueQueueEvents(repo.eventQueue_, events);
  11368. repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
  11369. var success = status === 'ok';
  11370. if (!success) {
  11371. warn('update at ' + path + ' failed: ' + status);
  11372. }
  11373. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
  11374. var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11375. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11376. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11377. });
  11378. each(childrenToMerge, function (changedPath) {
  11379. var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11380. repoRerunTransactions(repo, affectedPath);
  11381. });
  11382. // We queued the events above, so just flush the queue here
  11383. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11384. }
  11385. else {
  11386. log("update() called with empty data. Don't do anything.");
  11387. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11388. }
  11389. }
  11390. /**
  11391. * Applies all of the changes stored up in the onDisconnect_ tree.
  11392. */
  11393. function repoRunOnDisconnectEvents(repo) {
  11394. repoLog(repo, 'onDisconnectEvents');
  11395. var serverValues = repoGenerateServerValues(repo);
  11396. var resolvedOnDisconnectTree = newSparseSnapshotTree();
  11397. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
  11398. var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11399. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11400. });
  11401. var events = [];
  11402. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
  11403. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11404. var affectedPath = repoAbortTransactions(repo, path);
  11405. repoRerunTransactions(repo, affectedPath);
  11406. });
  11407. repo.onDisconnect_ = newSparseSnapshotTree();
  11408. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11409. }
  11410. function repoOnDisconnectCancel(repo, path, onComplete) {
  11411. repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
  11412. if (status === 'ok') {
  11413. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11414. }
  11415. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11416. });
  11417. }
  11418. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11419. var newNode = nodeFromJSON(value);
  11420. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11421. if (status === 'ok') {
  11422. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11423. }
  11424. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11425. });
  11426. }
  11427. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11428. var newNode = nodeFromJSON(value, priority);
  11429. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11430. if (status === 'ok') {
  11431. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11432. }
  11433. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11434. });
  11435. }
  11436. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11437. if (isEmpty(childrenToMerge)) {
  11438. log("onDisconnect().update() called with empty data. Don't do anything.");
  11439. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11440. return;
  11441. }
  11442. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
  11443. if (status === 'ok') {
  11444. each(childrenToMerge, function (childName, childNode) {
  11445. var newChildNode = nodeFromJSON(childNode);
  11446. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11447. });
  11448. }
  11449. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11450. });
  11451. }
  11452. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11453. var events;
  11454. if (pathGetFront(query._path) === '.info') {
  11455. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11456. }
  11457. else {
  11458. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11459. }
  11460. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11461. }
  11462. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11463. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11464. // a little bit by handling the return values anyways.
  11465. var events;
  11466. if (pathGetFront(query._path) === '.info') {
  11467. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11468. }
  11469. else {
  11470. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11471. }
  11472. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11473. }
  11474. function repoInterrupt(repo) {
  11475. if (repo.persistentConnection_) {
  11476. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11477. }
  11478. }
  11479. function repoResume(repo) {
  11480. if (repo.persistentConnection_) {
  11481. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11482. }
  11483. }
  11484. function repoLog(repo) {
  11485. var varArgs = [];
  11486. for (var _i = 1; _i < arguments.length; _i++) {
  11487. varArgs[_i - 1] = arguments[_i];
  11488. }
  11489. var prefix = '';
  11490. if (repo.persistentConnection_) {
  11491. prefix = repo.persistentConnection_.id + ':';
  11492. }
  11493. log.apply(void 0, __spreadArray([prefix], __read(varArgs), false));
  11494. }
  11495. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11496. if (callback) {
  11497. exceptionGuard(function () {
  11498. if (status === 'ok') {
  11499. callback(null);
  11500. }
  11501. else {
  11502. var code = (status || 'error').toUpperCase();
  11503. var message = code;
  11504. if (errorReason) {
  11505. message += ': ' + errorReason;
  11506. }
  11507. var error = new Error(message);
  11508. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11509. error.code = code;
  11510. callback(error);
  11511. }
  11512. });
  11513. }
  11514. }
  11515. /**
  11516. * Creates a new transaction, adds it to the transactions we're tracking, and
  11517. * sends it to the server if possible.
  11518. *
  11519. * @param path - Path at which to do transaction.
  11520. * @param transactionUpdate - Update callback.
  11521. * @param onComplete - Completion callback.
  11522. * @param unwatcher - Function that will be called when the transaction no longer
  11523. * need data updates for `path`.
  11524. * @param applyLocally - Whether or not to make intermediate results visible
  11525. */
  11526. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11527. repoLog(repo, 'transaction on ' + path);
  11528. // Initialize transaction.
  11529. var transaction = {
  11530. path: path,
  11531. update: transactionUpdate,
  11532. onComplete: onComplete,
  11533. // One of TransactionStatus enums.
  11534. status: null,
  11535. // Used when combining transactions at different locations to figure out
  11536. // which one goes first.
  11537. order: LUIDGenerator(),
  11538. // Whether to raise local events for this transaction.
  11539. applyLocally: applyLocally,
  11540. // Count of how many times we've retried the transaction.
  11541. retryCount: 0,
  11542. // Function to call to clean up our .on() listener.
  11543. unwatcher: unwatcher,
  11544. // Stores why a transaction was aborted.
  11545. abortReason: null,
  11546. currentWriteId: null,
  11547. currentInputSnapshot: null,
  11548. currentOutputSnapshotRaw: null,
  11549. currentOutputSnapshotResolved: null
  11550. };
  11551. // Run transaction initially.
  11552. var currentState = repoGetLatestState(repo, path, undefined);
  11553. transaction.currentInputSnapshot = currentState;
  11554. var newVal = transaction.update(currentState.val());
  11555. if (newVal === undefined) {
  11556. // Abort transaction.
  11557. transaction.unwatcher();
  11558. transaction.currentOutputSnapshotRaw = null;
  11559. transaction.currentOutputSnapshotResolved = null;
  11560. if (transaction.onComplete) {
  11561. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11562. }
  11563. }
  11564. else {
  11565. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11566. // Mark as run and add to our queue.
  11567. transaction.status = 0 /* TransactionStatus.RUN */;
  11568. var queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11569. var nodeQueue = treeGetValue(queueNode) || [];
  11570. nodeQueue.push(transaction);
  11571. treeSetValue(queueNode, nodeQueue);
  11572. // Update visibleData and raise events
  11573. // Note: We intentionally raise events after updating all of our
  11574. // transaction state, since the user could start new transactions from the
  11575. // event callbacks.
  11576. var priorityForNode = void 0;
  11577. if (typeof newVal === 'object' &&
  11578. newVal !== null &&
  11579. contains(newVal, '.priority')) {
  11580. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11581. priorityForNode = safeGet(newVal, '.priority');
  11582. assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11583. 'Priority must be a valid string, finite number, server value, or null.');
  11584. }
  11585. else {
  11586. var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11587. ChildrenNode.EMPTY_NODE;
  11588. priorityForNode = currentNode.getPriority().val();
  11589. }
  11590. var serverValues = repoGenerateServerValues(repo);
  11591. var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11592. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11593. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11594. transaction.currentOutputSnapshotResolved = newNode;
  11595. transaction.currentWriteId = repoGetNextWriteId(repo);
  11596. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11597. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11598. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11599. }
  11600. }
  11601. /**
  11602. * @param excludeSets - A specific set to exclude
  11603. */
  11604. function repoGetLatestState(repo, path, excludeSets) {
  11605. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11606. ChildrenNode.EMPTY_NODE);
  11607. }
  11608. /**
  11609. * Sends any already-run transactions that aren't waiting for outstanding
  11610. * transactions to complete.
  11611. *
  11612. * Externally it's called with no arguments, but it calls itself recursively
  11613. * with a particular transactionQueueTree node to recurse through the tree.
  11614. *
  11615. * @param node - transactionQueueTree node to start at.
  11616. */
  11617. function repoSendReadyTransactions(repo, node) {
  11618. if (node === void 0) { node = repo.transactionQueueTree_; }
  11619. // Before recursing, make sure any completed transactions are removed.
  11620. if (!node) {
  11621. repoPruneCompletedTransactionsBelowNode(repo, node);
  11622. }
  11623. if (treeGetValue(node)) {
  11624. var queue = repoBuildTransactionQueue(repo, node);
  11625. assert(queue.length > 0, 'Sending zero length transaction queue');
  11626. var allRun = queue.every(function (transaction) { return transaction.status === 0 /* TransactionStatus.RUN */; });
  11627. // If they're all run (and not sent), we can send them. Else, we must wait.
  11628. if (allRun) {
  11629. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11630. }
  11631. }
  11632. else if (treeHasChildren(node)) {
  11633. treeForEachChild(node, function (childNode) {
  11634. repoSendReadyTransactions(repo, childNode);
  11635. });
  11636. }
  11637. }
  11638. /**
  11639. * Given a list of run transactions, send them to the server and then handle
  11640. * the result (success or failure).
  11641. *
  11642. * @param path - The location of the queue.
  11643. * @param queue - Queue of transactions under the specified location.
  11644. */
  11645. function repoSendTransactionQueue(repo, path, queue) {
  11646. // Mark transactions as sent and increment retry count!
  11647. var setsToIgnore = queue.map(function (txn) {
  11648. return txn.currentWriteId;
  11649. });
  11650. var latestState = repoGetLatestState(repo, path, setsToIgnore);
  11651. var snapToSend = latestState;
  11652. var latestHash = latestState.hash();
  11653. for (var i = 0; i < queue.length; i++) {
  11654. var txn = queue[i];
  11655. assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11656. txn.status = 1 /* TransactionStatus.SENT */;
  11657. txn.retryCount++;
  11658. var relativePath = newRelativePath(path, txn.path);
  11659. // If we've gotten to this point, the output snapshot must be defined.
  11660. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11661. }
  11662. var dataToSend = snapToSend.val(true);
  11663. var pathToSend = path;
  11664. // Send the put.
  11665. repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
  11666. repoLog(repo, 'transaction put response', {
  11667. path: pathToSend.toString(),
  11668. status: status
  11669. });
  11670. var events = [];
  11671. if (status === 'ok') {
  11672. // Queue up the callbacks and fire them after cleaning up all of our
  11673. // transaction state, since the callback could trigger more
  11674. // transactions or sets.
  11675. var callbacks = [];
  11676. var _loop_1 = function (i) {
  11677. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11678. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11679. if (queue[i].onComplete) {
  11680. // We never unset the output snapshot, and given that this
  11681. // transaction is complete, it should be set
  11682. callbacks.push(function () {
  11683. return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
  11684. });
  11685. }
  11686. queue[i].unwatcher();
  11687. };
  11688. for (var i = 0; i < queue.length; i++) {
  11689. _loop_1(i);
  11690. }
  11691. // Now remove the completed transactions.
  11692. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11693. // There may be pending transactions that we can now send.
  11694. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11695. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11696. // Finally, trigger onComplete callbacks.
  11697. for (var i = 0; i < callbacks.length; i++) {
  11698. exceptionGuard(callbacks[i]);
  11699. }
  11700. }
  11701. else {
  11702. // transactions are no longer sent. Update their status appropriately.
  11703. if (status === 'datastale') {
  11704. for (var i = 0; i < queue.length; i++) {
  11705. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11706. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11707. }
  11708. else {
  11709. queue[i].status = 0 /* TransactionStatus.RUN */;
  11710. }
  11711. }
  11712. }
  11713. else {
  11714. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11715. for (var i = 0; i < queue.length; i++) {
  11716. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11717. queue[i].abortReason = status;
  11718. }
  11719. }
  11720. repoRerunTransactions(repo, path);
  11721. }
  11722. }, latestHash);
  11723. }
  11724. /**
  11725. * Finds all transactions dependent on the data at changedPath and reruns them.
  11726. *
  11727. * Should be called any time cached data changes.
  11728. *
  11729. * Return the highest path that was affected by rerunning transactions. This
  11730. * is the path at which events need to be raised for.
  11731. *
  11732. * @param changedPath - The path in mergedData that changed.
  11733. * @returns The rootmost path that was affected by rerunning transactions.
  11734. */
  11735. function repoRerunTransactions(repo, changedPath) {
  11736. var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11737. var path = treeGetPath(rootMostTransactionNode);
  11738. var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11739. repoRerunTransactionQueue(repo, queue, path);
  11740. return path;
  11741. }
  11742. /**
  11743. * Does all the work of rerunning transactions (as well as cleans up aborted
  11744. * transactions and whatnot).
  11745. *
  11746. * @param queue - The queue of transactions to run.
  11747. * @param path - The path the queue is for.
  11748. */
  11749. function repoRerunTransactionQueue(repo, queue, path) {
  11750. if (queue.length === 0) {
  11751. return; // Nothing to do!
  11752. }
  11753. // Queue up the callbacks and fire them after cleaning up all of our
  11754. // transaction state, since the callback could trigger more transactions or
  11755. // sets.
  11756. var callbacks = [];
  11757. var events = [];
  11758. // Ignore all of the sets we're going to re-run.
  11759. var txnsToRerun = queue.filter(function (q) {
  11760. return q.status === 0 /* TransactionStatus.RUN */;
  11761. });
  11762. var setsToIgnore = txnsToRerun.map(function (q) {
  11763. return q.currentWriteId;
  11764. });
  11765. var _loop_2 = function (i) {
  11766. var transaction = queue[i];
  11767. var relativePath = newRelativePath(path, transaction.path);
  11768. var abortTransaction = false, abortReason;
  11769. assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11770. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11771. abortTransaction = true;
  11772. abortReason = transaction.abortReason;
  11773. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11774. }
  11775. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11776. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11777. abortTransaction = true;
  11778. abortReason = 'maxretry';
  11779. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11780. }
  11781. else {
  11782. // This code reruns a transaction
  11783. var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11784. transaction.currentInputSnapshot = currentNode;
  11785. var newData = queue[i].update(currentNode.val());
  11786. if (newData !== undefined) {
  11787. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11788. var newDataNode = nodeFromJSON(newData);
  11789. var hasExplicitPriority = typeof newData === 'object' &&
  11790. newData != null &&
  11791. contains(newData, '.priority');
  11792. if (!hasExplicitPriority) {
  11793. // Keep the old priority if there wasn't a priority explicitly specified.
  11794. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11795. }
  11796. var oldWriteId = transaction.currentWriteId;
  11797. var serverValues = repoGenerateServerValues(repo);
  11798. var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11799. transaction.currentOutputSnapshotRaw = newDataNode;
  11800. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11801. transaction.currentWriteId = repoGetNextWriteId(repo);
  11802. // Mutates setsToIgnore in place
  11803. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11804. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11805. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11806. }
  11807. else {
  11808. abortTransaction = true;
  11809. abortReason = 'nodata';
  11810. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11811. }
  11812. }
  11813. }
  11814. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11815. events = [];
  11816. if (abortTransaction) {
  11817. // Abort.
  11818. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11819. // Removing a listener can trigger pruning which can muck with
  11820. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11821. // until we're done.
  11822. (function (unwatcher) {
  11823. setTimeout(unwatcher, Math.floor(0));
  11824. })(queue[i].unwatcher);
  11825. if (queue[i].onComplete) {
  11826. if (abortReason === 'nodata') {
  11827. callbacks.push(function () {
  11828. return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
  11829. });
  11830. }
  11831. else {
  11832. callbacks.push(function () {
  11833. return queue[i].onComplete(new Error(abortReason), false, null);
  11834. });
  11835. }
  11836. }
  11837. }
  11838. };
  11839. for (var i = 0; i < queue.length; i++) {
  11840. _loop_2(i);
  11841. }
  11842. // Clean up completed transactions.
  11843. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11844. // Now fire callbacks, now that we're in a good, known state.
  11845. for (var i = 0; i < callbacks.length; i++) {
  11846. exceptionGuard(callbacks[i]);
  11847. }
  11848. // Try to send the transaction result to the server.
  11849. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11850. }
  11851. /**
  11852. * Returns the rootmost ancestor node of the specified path that has a pending
  11853. * transaction on it, or just returns the node for the given path if there are
  11854. * no pending transactions on any ancestor.
  11855. *
  11856. * @param path - The location to start at.
  11857. * @returns The rootmost node with a transaction.
  11858. */
  11859. function repoGetAncestorTransactionNode(repo, path) {
  11860. var front;
  11861. // Start at the root and walk deeper into the tree towards path until we
  11862. // find a node with pending transactions.
  11863. var transactionNode = repo.transactionQueueTree_;
  11864. front = pathGetFront(path);
  11865. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11866. transactionNode = treeSubTree(transactionNode, front);
  11867. path = pathPopFront(path);
  11868. front = pathGetFront(path);
  11869. }
  11870. return transactionNode;
  11871. }
  11872. /**
  11873. * Builds the queue of all transactions at or below the specified
  11874. * transactionNode.
  11875. *
  11876. * @param transactionNode
  11877. * @returns The generated queue.
  11878. */
  11879. function repoBuildTransactionQueue(repo, transactionNode) {
  11880. // Walk any child transaction queues and aggregate them into a single queue.
  11881. var transactionQueue = [];
  11882. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11883. // Sort them by the order the transactions were created.
  11884. transactionQueue.sort(function (a, b) { return a.order - b.order; });
  11885. return transactionQueue;
  11886. }
  11887. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11888. var nodeQueue = treeGetValue(node);
  11889. if (nodeQueue) {
  11890. for (var i = 0; i < nodeQueue.length; i++) {
  11891. queue.push(nodeQueue[i]);
  11892. }
  11893. }
  11894. treeForEachChild(node, function (child) {
  11895. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11896. });
  11897. }
  11898. /**
  11899. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11900. */
  11901. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11902. var queue = treeGetValue(node);
  11903. if (queue) {
  11904. var to = 0;
  11905. for (var from = 0; from < queue.length; from++) {
  11906. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11907. queue[to] = queue[from];
  11908. to++;
  11909. }
  11910. }
  11911. queue.length = to;
  11912. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11913. }
  11914. treeForEachChild(node, function (childNode) {
  11915. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11916. });
  11917. }
  11918. /**
  11919. * Aborts all transactions on ancestors or descendants of the specified path.
  11920. * Called when doing a set() or update() since we consider them incompatible
  11921. * with transactions.
  11922. *
  11923. * @param path - Path for which we want to abort related transactions.
  11924. */
  11925. function repoAbortTransactions(repo, path) {
  11926. var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11927. var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11928. treeForEachAncestor(transactionNode, function (node) {
  11929. repoAbortTransactionsOnNode(repo, node);
  11930. });
  11931. repoAbortTransactionsOnNode(repo, transactionNode);
  11932. treeForEachDescendant(transactionNode, function (node) {
  11933. repoAbortTransactionsOnNode(repo, node);
  11934. });
  11935. return affectedPath;
  11936. }
  11937. /**
  11938. * Abort transactions stored in this transaction queue node.
  11939. *
  11940. * @param node - Node to abort transactions for.
  11941. */
  11942. function repoAbortTransactionsOnNode(repo, node) {
  11943. var queue = treeGetValue(node);
  11944. if (queue) {
  11945. // Queue up the callbacks and fire them after cleaning up all of our
  11946. // transaction state, since the callback could trigger more transactions
  11947. // or sets.
  11948. var callbacks = [];
  11949. // Go through queue. Any already-sent transactions must be marked for
  11950. // abort, while the unsent ones can be immediately aborted and removed.
  11951. var events = [];
  11952. var lastSent = -1;
  11953. for (var i = 0; i < queue.length; i++) {
  11954. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11955. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11956. assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11957. lastSent = i;
  11958. // Mark transaction for abort when it comes back.
  11959. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11960. queue[i].abortReason = 'set';
  11961. }
  11962. else {
  11963. assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11964. // We can abort it immediately.
  11965. queue[i].unwatcher();
  11966. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11967. if (queue[i].onComplete) {
  11968. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11969. }
  11970. }
  11971. }
  11972. if (lastSent === -1) {
  11973. // We're not waiting for any sent transactions. We can clear the queue.
  11974. treeSetValue(node, undefined);
  11975. }
  11976. else {
  11977. // Remove the transactions we aborted.
  11978. queue.length = lastSent + 1;
  11979. }
  11980. // Now fire the callbacks.
  11981. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11982. for (var i = 0; i < callbacks.length; i++) {
  11983. exceptionGuard(callbacks[i]);
  11984. }
  11985. }
  11986. }
  11987. /**
  11988. * @license
  11989. * Copyright 2017 Google LLC
  11990. *
  11991. * Licensed under the Apache License, Version 2.0 (the "License");
  11992. * you may not use this file except in compliance with the License.
  11993. * You may obtain a copy of the License at
  11994. *
  11995. * http://www.apache.org/licenses/LICENSE-2.0
  11996. *
  11997. * Unless required by applicable law or agreed to in writing, software
  11998. * distributed under the License is distributed on an "AS IS" BASIS,
  11999. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12000. * See the License for the specific language governing permissions and
  12001. * limitations under the License.
  12002. */
  12003. function decodePath(pathString) {
  12004. var pathStringDecoded = '';
  12005. var pieces = pathString.split('/');
  12006. for (var i = 0; i < pieces.length; i++) {
  12007. if (pieces[i].length > 0) {
  12008. var piece = pieces[i];
  12009. try {
  12010. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  12011. }
  12012. catch (e) { }
  12013. pathStringDecoded += '/' + piece;
  12014. }
  12015. }
  12016. return pathStringDecoded;
  12017. }
  12018. /**
  12019. * @returns key value hash
  12020. */
  12021. function decodeQuery(queryString) {
  12022. var e_1, _a;
  12023. var results = {};
  12024. if (queryString.charAt(0) === '?') {
  12025. queryString = queryString.substring(1);
  12026. }
  12027. try {
  12028. for (var _b = __values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
  12029. var segment = _c.value;
  12030. if (segment.length === 0) {
  12031. continue;
  12032. }
  12033. var kv = segment.split('=');
  12034. if (kv.length === 2) {
  12035. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  12036. }
  12037. else {
  12038. warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
  12039. }
  12040. }
  12041. }
  12042. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  12043. finally {
  12044. try {
  12045. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12046. }
  12047. finally { if (e_1) throw e_1.error; }
  12048. }
  12049. return results;
  12050. }
  12051. var parseRepoInfo = function (dataURL, nodeAdmin) {
  12052. var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  12053. if (parsedUrl.domain === 'firebase.com') {
  12054. fatal(parsedUrl.host +
  12055. ' is no longer supported. ' +
  12056. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  12057. }
  12058. // Catch common error of uninitialized namespace value.
  12059. if ((!namespace || namespace === 'undefined') &&
  12060. parsedUrl.domain !== 'localhost') {
  12061. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  12062. }
  12063. if (!parsedUrl.secure) {
  12064. warnIfPageIsSecure();
  12065. }
  12066. var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  12067. return {
  12068. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  12069. /*persistenceKey=*/ '',
  12070. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  12071. path: new Path(parsedUrl.pathString)
  12072. };
  12073. };
  12074. var parseDatabaseURL = function (dataURL) {
  12075. // Default to empty strings in the event of a malformed string.
  12076. var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  12077. // Always default to SSL, unless otherwise specified.
  12078. var secure = true, scheme = 'https', port = 443;
  12079. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  12080. if (typeof dataURL === 'string') {
  12081. // Parse scheme.
  12082. var colonInd = dataURL.indexOf('//');
  12083. if (colonInd >= 0) {
  12084. scheme = dataURL.substring(0, colonInd - 1);
  12085. dataURL = dataURL.substring(colonInd + 2);
  12086. }
  12087. // Parse host, path, and query string.
  12088. var slashInd = dataURL.indexOf('/');
  12089. if (slashInd === -1) {
  12090. slashInd = dataURL.length;
  12091. }
  12092. var questionMarkInd = dataURL.indexOf('?');
  12093. if (questionMarkInd === -1) {
  12094. questionMarkInd = dataURL.length;
  12095. }
  12096. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  12097. if (slashInd < questionMarkInd) {
  12098. // For pathString, questionMarkInd will always come after slashInd
  12099. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  12100. }
  12101. var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  12102. // If we have a port, use scheme for determining if it's secure.
  12103. colonInd = host.indexOf(':');
  12104. if (colonInd >= 0) {
  12105. secure = scheme === 'https' || scheme === 'wss';
  12106. port = parseInt(host.substring(colonInd + 1), 10);
  12107. }
  12108. else {
  12109. colonInd = host.length;
  12110. }
  12111. var hostWithoutPort = host.slice(0, colonInd);
  12112. if (hostWithoutPort.toLowerCase() === 'localhost') {
  12113. domain = 'localhost';
  12114. }
  12115. else if (hostWithoutPort.split('.').length <= 2) {
  12116. domain = hostWithoutPort;
  12117. }
  12118. else {
  12119. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  12120. var dotInd = host.indexOf('.');
  12121. subdomain = host.substring(0, dotInd).toLowerCase();
  12122. domain = host.substring(dotInd + 1);
  12123. // Normalize namespaces to lowercase to share storage / connection.
  12124. namespace = subdomain;
  12125. }
  12126. // Always treat the value of the `ns` as the namespace name if it is present.
  12127. if ('ns' in queryParams) {
  12128. namespace = queryParams['ns'];
  12129. }
  12130. }
  12131. return {
  12132. host: host,
  12133. port: port,
  12134. domain: domain,
  12135. subdomain: subdomain,
  12136. secure: secure,
  12137. scheme: scheme,
  12138. pathString: pathString,
  12139. namespace: namespace
  12140. };
  12141. };
  12142. /**
  12143. * @license
  12144. * Copyright 2017 Google LLC
  12145. *
  12146. * Licensed under the Apache License, Version 2.0 (the "License");
  12147. * you may not use this file except in compliance with the License.
  12148. * You may obtain a copy of the License at
  12149. *
  12150. * http://www.apache.org/licenses/LICENSE-2.0
  12151. *
  12152. * Unless required by applicable law or agreed to in writing, software
  12153. * distributed under the License is distributed on an "AS IS" BASIS,
  12154. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12155. * See the License for the specific language governing permissions and
  12156. * limitations under the License.
  12157. */
  12158. // Modeled after base64 web-safe chars, but ordered by ASCII.
  12159. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  12160. /**
  12161. * Fancy ID generator that creates 20-character string identifiers with the
  12162. * following properties:
  12163. *
  12164. * 1. They're based on timestamp so that they sort *after* any existing ids.
  12165. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  12166. * collide with other clients' IDs.
  12167. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  12168. * that will sort properly).
  12169. * 4. They're monotonically increasing. Even if you generate more than one in
  12170. * the same timestamp, the latter ones will sort after the former ones. We do
  12171. * this by using the previous random bits but "incrementing" them by 1 (only
  12172. * in the case of a timestamp collision).
  12173. */
  12174. var nextPushId = (function () {
  12175. // Timestamp of last push, used to prevent local collisions if you push twice
  12176. // in one ms.
  12177. var lastPushTime = 0;
  12178. // We generate 72-bits of randomness which get turned into 12 characters and
  12179. // appended to the timestamp to prevent collisions with other clients. We
  12180. // store the last characters we generated because in the event of a collision,
  12181. // we'll use those same characters except "incremented" by one.
  12182. var lastRandChars = [];
  12183. return function (now) {
  12184. var duplicateTime = now === lastPushTime;
  12185. lastPushTime = now;
  12186. var i;
  12187. var timeStampChars = new Array(8);
  12188. for (i = 7; i >= 0; i--) {
  12189. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  12190. // NOTE: Can't use << here because javascript will convert to int and lose
  12191. // the upper bits.
  12192. now = Math.floor(now / 64);
  12193. }
  12194. assert(now === 0, 'Cannot push at time == 0');
  12195. var id = timeStampChars.join('');
  12196. if (!duplicateTime) {
  12197. for (i = 0; i < 12; i++) {
  12198. lastRandChars[i] = Math.floor(Math.random() * 64);
  12199. }
  12200. }
  12201. else {
  12202. // If the timestamp hasn't changed since last push, use the same random
  12203. // number, except incremented by 1.
  12204. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  12205. lastRandChars[i] = 0;
  12206. }
  12207. lastRandChars[i]++;
  12208. }
  12209. for (i = 0; i < 12; i++) {
  12210. id += PUSH_CHARS.charAt(lastRandChars[i]);
  12211. }
  12212. assert(id.length === 20, 'nextPushId: Length should be 20.');
  12213. return id;
  12214. };
  12215. })();
  12216. /**
  12217. * @license
  12218. * Copyright 2017 Google LLC
  12219. *
  12220. * Licensed under the Apache License, Version 2.0 (the "License");
  12221. * you may not use this file except in compliance with the License.
  12222. * You may obtain a copy of the License at
  12223. *
  12224. * http://www.apache.org/licenses/LICENSE-2.0
  12225. *
  12226. * Unless required by applicable law or agreed to in writing, software
  12227. * distributed under the License is distributed on an "AS IS" BASIS,
  12228. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12229. * See the License for the specific language governing permissions and
  12230. * limitations under the License.
  12231. */
  12232. /**
  12233. * Encapsulates the data needed to raise an event
  12234. */
  12235. var DataEvent = /** @class */ (function () {
  12236. /**
  12237. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  12238. * @param eventRegistration - The function to call to with the event data. User provided
  12239. * @param snapshot - The data backing the event
  12240. * @param prevName - Optional, the name of the previous child for child_* events.
  12241. */
  12242. function DataEvent(eventType, eventRegistration, snapshot, prevName) {
  12243. this.eventType = eventType;
  12244. this.eventRegistration = eventRegistration;
  12245. this.snapshot = snapshot;
  12246. this.prevName = prevName;
  12247. }
  12248. DataEvent.prototype.getPath = function () {
  12249. var ref = this.snapshot.ref;
  12250. if (this.eventType === 'value') {
  12251. return ref._path;
  12252. }
  12253. else {
  12254. return ref.parent._path;
  12255. }
  12256. };
  12257. DataEvent.prototype.getEventType = function () {
  12258. return this.eventType;
  12259. };
  12260. DataEvent.prototype.getEventRunner = function () {
  12261. return this.eventRegistration.getEventRunner(this);
  12262. };
  12263. DataEvent.prototype.toString = function () {
  12264. return (this.getPath().toString() +
  12265. ':' +
  12266. this.eventType +
  12267. ':' +
  12268. stringify(this.snapshot.exportVal()));
  12269. };
  12270. return DataEvent;
  12271. }());
  12272. var CancelEvent = /** @class */ (function () {
  12273. function CancelEvent(eventRegistration, error, path) {
  12274. this.eventRegistration = eventRegistration;
  12275. this.error = error;
  12276. this.path = path;
  12277. }
  12278. CancelEvent.prototype.getPath = function () {
  12279. return this.path;
  12280. };
  12281. CancelEvent.prototype.getEventType = function () {
  12282. return 'cancel';
  12283. };
  12284. CancelEvent.prototype.getEventRunner = function () {
  12285. return this.eventRegistration.getEventRunner(this);
  12286. };
  12287. CancelEvent.prototype.toString = function () {
  12288. return this.path.toString() + ':cancel';
  12289. };
  12290. return CancelEvent;
  12291. }());
  12292. /**
  12293. * @license
  12294. * Copyright 2017 Google LLC
  12295. *
  12296. * Licensed under the Apache License, Version 2.0 (the "License");
  12297. * you may not use this file except in compliance with the License.
  12298. * You may obtain a copy of the License at
  12299. *
  12300. * http://www.apache.org/licenses/LICENSE-2.0
  12301. *
  12302. * Unless required by applicable law or agreed to in writing, software
  12303. * distributed under the License is distributed on an "AS IS" BASIS,
  12304. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12305. * See the License for the specific language governing permissions and
  12306. * limitations under the License.
  12307. */
  12308. /**
  12309. * A wrapper class that converts events from the database@exp SDK to the legacy
  12310. * Database SDK. Events are not converted directly as event registration relies
  12311. * on reference comparison of the original user callback (see `matches()`) and
  12312. * relies on equality of the legacy SDK's `context` object.
  12313. */
  12314. var CallbackContext = /** @class */ (function () {
  12315. function CallbackContext(snapshotCallback, cancelCallback) {
  12316. this.snapshotCallback = snapshotCallback;
  12317. this.cancelCallback = cancelCallback;
  12318. }
  12319. CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
  12320. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  12321. };
  12322. CallbackContext.prototype.onCancel = function (error) {
  12323. assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  12324. return this.cancelCallback.call(null, error);
  12325. };
  12326. Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
  12327. get: function () {
  12328. return !!this.cancelCallback;
  12329. },
  12330. enumerable: false,
  12331. configurable: true
  12332. });
  12333. CallbackContext.prototype.matches = function (other) {
  12334. return (this.snapshotCallback === other.snapshotCallback ||
  12335. (this.snapshotCallback.userCallback !== undefined &&
  12336. this.snapshotCallback.userCallback ===
  12337. other.snapshotCallback.userCallback &&
  12338. this.snapshotCallback.context === other.snapshotCallback.context));
  12339. };
  12340. return CallbackContext;
  12341. }());
  12342. /**
  12343. * @license
  12344. * Copyright 2021 Google LLC
  12345. *
  12346. * Licensed under the Apache License, Version 2.0 (the "License");
  12347. * you may not use this file except in compliance with the License.
  12348. * You may obtain a copy of the License at
  12349. *
  12350. * http://www.apache.org/licenses/LICENSE-2.0
  12351. *
  12352. * Unless required by applicable law or agreed to in writing, software
  12353. * distributed under the License is distributed on an "AS IS" BASIS,
  12354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12355. * See the License for the specific language governing permissions and
  12356. * limitations under the License.
  12357. */
  12358. /**
  12359. * The `onDisconnect` class allows you to write or clear data when your client
  12360. * disconnects from the Database server. These updates occur whether your
  12361. * client disconnects cleanly or not, so you can rely on them to clean up data
  12362. * even if a connection is dropped or a client crashes.
  12363. *
  12364. * The `onDisconnect` class is most commonly used to manage presence in
  12365. * applications where it is useful to detect how many clients are connected and
  12366. * when other clients disconnect. See
  12367. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12368. * for more information.
  12369. *
  12370. * To avoid problems when a connection is dropped before the requests can be
  12371. * transferred to the Database server, these functions should be called before
  12372. * writing any data.
  12373. *
  12374. * Note that `onDisconnect` operations are only triggered once. If you want an
  12375. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12376. * the `onDisconnect` operations each time you reconnect.
  12377. */
  12378. var OnDisconnect = /** @class */ (function () {
  12379. /** @hideconstructor */
  12380. function OnDisconnect(_repo, _path) {
  12381. this._repo = _repo;
  12382. this._path = _path;
  12383. }
  12384. /**
  12385. * Cancels all previously queued `onDisconnect()` set or update events for this
  12386. * location and all children.
  12387. *
  12388. * If a write has been queued for this location via a `set()` or `update()` at a
  12389. * parent location, the write at this location will be canceled, though writes
  12390. * to sibling locations will still occur.
  12391. *
  12392. * @returns Resolves when synchronization to the server is complete.
  12393. */
  12394. OnDisconnect.prototype.cancel = function () {
  12395. var deferred = new Deferred();
  12396. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
  12397. return deferred.promise;
  12398. };
  12399. /**
  12400. * Ensures the data at this location is deleted when the client is disconnected
  12401. * (due to closing the browser, navigating to a new page, or network issues).
  12402. *
  12403. * @returns Resolves when synchronization to the server is complete.
  12404. */
  12405. OnDisconnect.prototype.remove = function () {
  12406. validateWritablePath('OnDisconnect.remove', this._path);
  12407. var deferred = new Deferred();
  12408. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
  12409. return deferred.promise;
  12410. };
  12411. /**
  12412. * Ensures the data at this location is set to the specified value when the
  12413. * client is disconnected (due to closing the browser, navigating to a new page,
  12414. * or network issues).
  12415. *
  12416. * `set()` is especially useful for implementing "presence" systems, where a
  12417. * value should be changed or cleared when a user disconnects so that they
  12418. * appear "offline" to other users. See
  12419. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12420. * for more information.
  12421. *
  12422. * Note that `onDisconnect` operations are only triggered once. If you want an
  12423. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12424. * the `onDisconnect` operations each time.
  12425. *
  12426. * @param value - The value to be written to this location on disconnect (can
  12427. * be an object, array, string, number, boolean, or null).
  12428. * @returns Resolves when synchronization to the Database is complete.
  12429. */
  12430. OnDisconnect.prototype.set = function (value) {
  12431. validateWritablePath('OnDisconnect.set', this._path);
  12432. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12433. var deferred = new Deferred();
  12434. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
  12435. return deferred.promise;
  12436. };
  12437. /**
  12438. * Ensures the data at this location is set to the specified value and priority
  12439. * when the client is disconnected (due to closing the browser, navigating to a
  12440. * new page, or network issues).
  12441. *
  12442. * @param value - The value to be written to this location on disconnect (can
  12443. * be an object, array, string, number, boolean, or null).
  12444. * @param priority - The priority to be written (string, number, or null).
  12445. * @returns Resolves when synchronization to the Database is complete.
  12446. */
  12447. OnDisconnect.prototype.setWithPriority = function (value, priority) {
  12448. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12449. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12450. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12451. var deferred = new Deferred();
  12452. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
  12453. return deferred.promise;
  12454. };
  12455. /**
  12456. * Writes multiple values at this location when the client is disconnected (due
  12457. * to closing the browser, navigating to a new page, or network issues).
  12458. *
  12459. * The `values` argument contains multiple property-value pairs that will be
  12460. * written to the Database together. Each child property can either be a simple
  12461. * property (for example, "name") or a relative path (for example, "name/first")
  12462. * from the current location to the data to update.
  12463. *
  12464. * As opposed to the `set()` method, `update()` can be use to selectively update
  12465. * only the referenced properties at the current location (instead of replacing
  12466. * all the child properties at the current location).
  12467. *
  12468. * @param values - Object containing multiple values.
  12469. * @returns Resolves when synchronization to the Database is complete.
  12470. */
  12471. OnDisconnect.prototype.update = function (values) {
  12472. validateWritablePath('OnDisconnect.update', this._path);
  12473. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12474. var deferred = new Deferred();
  12475. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
  12476. return deferred.promise;
  12477. };
  12478. return OnDisconnect;
  12479. }());
  12480. /**
  12481. * @license
  12482. * Copyright 2020 Google LLC
  12483. *
  12484. * Licensed under the Apache License, Version 2.0 (the "License");
  12485. * you may not use this file except in compliance with the License.
  12486. * You may obtain a copy of the License at
  12487. *
  12488. * http://www.apache.org/licenses/LICENSE-2.0
  12489. *
  12490. * Unless required by applicable law or agreed to in writing, software
  12491. * distributed under the License is distributed on an "AS IS" BASIS,
  12492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12493. * See the License for the specific language governing permissions and
  12494. * limitations under the License.
  12495. */
  12496. /**
  12497. * @internal
  12498. */
  12499. var QueryImpl = /** @class */ (function () {
  12500. /**
  12501. * @hideconstructor
  12502. */
  12503. function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
  12504. this._repo = _repo;
  12505. this._path = _path;
  12506. this._queryParams = _queryParams;
  12507. this._orderByCalled = _orderByCalled;
  12508. }
  12509. Object.defineProperty(QueryImpl.prototype, "key", {
  12510. get: function () {
  12511. if (pathIsEmpty(this._path)) {
  12512. return null;
  12513. }
  12514. else {
  12515. return pathGetBack(this._path);
  12516. }
  12517. },
  12518. enumerable: false,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(QueryImpl.prototype, "ref", {
  12522. get: function () {
  12523. return new ReferenceImpl(this._repo, this._path);
  12524. },
  12525. enumerable: false,
  12526. configurable: true
  12527. });
  12528. Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
  12529. get: function () {
  12530. var obj = queryParamsGetQueryObject(this._queryParams);
  12531. var id = ObjectToUniqueKey(obj);
  12532. return id === '{}' ? 'default' : id;
  12533. },
  12534. enumerable: false,
  12535. configurable: true
  12536. });
  12537. Object.defineProperty(QueryImpl.prototype, "_queryObject", {
  12538. /**
  12539. * An object representation of the query parameters used by this Query.
  12540. */
  12541. get: function () {
  12542. return queryParamsGetQueryObject(this._queryParams);
  12543. },
  12544. enumerable: false,
  12545. configurable: true
  12546. });
  12547. QueryImpl.prototype.isEqual = function (other) {
  12548. other = getModularInstance(other);
  12549. if (!(other instanceof QueryImpl)) {
  12550. return false;
  12551. }
  12552. var sameRepo = this._repo === other._repo;
  12553. var samePath = pathEquals(this._path, other._path);
  12554. var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12555. return sameRepo && samePath && sameQueryIdentifier;
  12556. };
  12557. QueryImpl.prototype.toJSON = function () {
  12558. return this.toString();
  12559. };
  12560. QueryImpl.prototype.toString = function () {
  12561. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12562. };
  12563. return QueryImpl;
  12564. }());
  12565. /**
  12566. * Validates that no other order by call has been made
  12567. */
  12568. function validateNoPreviousOrderByCall(query, fnName) {
  12569. if (query._orderByCalled === true) {
  12570. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12571. }
  12572. }
  12573. /**
  12574. * Validates start/end values for queries.
  12575. */
  12576. function validateQueryEndpoints(params) {
  12577. var startNode = null;
  12578. var endNode = null;
  12579. if (params.hasStart()) {
  12580. startNode = params.getIndexStartValue();
  12581. }
  12582. if (params.hasEnd()) {
  12583. endNode = params.getIndexEndValue();
  12584. }
  12585. if (params.getIndex() === KEY_INDEX) {
  12586. var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12587. 'startAt(), endAt(), or equalTo().';
  12588. var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12589. 'endAt(), endBefore(), or equalTo() must be a string.';
  12590. if (params.hasStart()) {
  12591. var startName = params.getIndexStartName();
  12592. if (startName !== MIN_NAME) {
  12593. throw new Error(tooManyArgsError);
  12594. }
  12595. else if (typeof startNode !== 'string') {
  12596. throw new Error(wrongArgTypeError);
  12597. }
  12598. }
  12599. if (params.hasEnd()) {
  12600. var endName = params.getIndexEndName();
  12601. if (endName !== MAX_NAME) {
  12602. throw new Error(tooManyArgsError);
  12603. }
  12604. else if (typeof endNode !== 'string') {
  12605. throw new Error(wrongArgTypeError);
  12606. }
  12607. }
  12608. }
  12609. else if (params.getIndex() === PRIORITY_INDEX) {
  12610. if ((startNode != null && !isValidPriority(startNode)) ||
  12611. (endNode != null && !isValidPriority(endNode))) {
  12612. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12613. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12614. '(null, a number, or a string).');
  12615. }
  12616. }
  12617. else {
  12618. assert(params.getIndex() instanceof PathIndex ||
  12619. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12620. if ((startNode != null && typeof startNode === 'object') ||
  12621. (endNode != null && typeof endNode === 'object')) {
  12622. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12623. 'equalTo() cannot be an object.');
  12624. }
  12625. }
  12626. }
  12627. /**
  12628. * Validates that limit* has been called with the correct combination of parameters
  12629. */
  12630. function validateLimit(params) {
  12631. if (params.hasStart() &&
  12632. params.hasEnd() &&
  12633. params.hasLimit() &&
  12634. !params.hasAnchoredLimit()) {
  12635. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12636. 'limitToFirst() or limitToLast() instead.');
  12637. }
  12638. }
  12639. /**
  12640. * @internal
  12641. */
  12642. var ReferenceImpl = /** @class */ (function (_super) {
  12643. __extends(ReferenceImpl, _super);
  12644. /** @hideconstructor */
  12645. function ReferenceImpl(repo, path) {
  12646. return _super.call(this, repo, path, new QueryParams(), false) || this;
  12647. }
  12648. Object.defineProperty(ReferenceImpl.prototype, "parent", {
  12649. get: function () {
  12650. var parentPath = pathParent(this._path);
  12651. return parentPath === null
  12652. ? null
  12653. : new ReferenceImpl(this._repo, parentPath);
  12654. },
  12655. enumerable: false,
  12656. configurable: true
  12657. });
  12658. Object.defineProperty(ReferenceImpl.prototype, "root", {
  12659. get: function () {
  12660. var ref = this;
  12661. while (ref.parent !== null) {
  12662. ref = ref.parent;
  12663. }
  12664. return ref;
  12665. },
  12666. enumerable: false,
  12667. configurable: true
  12668. });
  12669. return ReferenceImpl;
  12670. }(QueryImpl));
  12671. /**
  12672. * A `DataSnapshot` contains data from a Database location.
  12673. *
  12674. * Any time you read data from the Database, you receive the data as a
  12675. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12676. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12677. * JavaScript object by calling the `val()` method. Alternatively, you can
  12678. * traverse into the snapshot by calling `child()` to return child snapshots
  12679. * (which you could then call `val()` on).
  12680. *
  12681. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12682. * a Database location. It cannot be modified and will never change (to modify
  12683. * data, you always call the `set()` method on a `Reference` directly).
  12684. */
  12685. var DataSnapshot = /** @class */ (function () {
  12686. /**
  12687. * @param _node - A SnapshotNode to wrap.
  12688. * @param ref - The location this snapshot came from.
  12689. * @param _index - The iteration order for this snapshot
  12690. * @hideconstructor
  12691. */
  12692. function DataSnapshot(_node,
  12693. /**
  12694. * The location of this DataSnapshot.
  12695. */
  12696. ref, _index) {
  12697. this._node = _node;
  12698. this.ref = ref;
  12699. this._index = _index;
  12700. }
  12701. Object.defineProperty(DataSnapshot.prototype, "priority", {
  12702. /**
  12703. * Gets the priority value of the data in this `DataSnapshot`.
  12704. *
  12705. * Applications need not use priority but can order collections by
  12706. * ordinary properties (see
  12707. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12708. * ).
  12709. */
  12710. get: function () {
  12711. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12712. return this._node.getPriority().val();
  12713. },
  12714. enumerable: false,
  12715. configurable: true
  12716. });
  12717. Object.defineProperty(DataSnapshot.prototype, "key", {
  12718. /**
  12719. * The key (last part of the path) of the location of this `DataSnapshot`.
  12720. *
  12721. * The last token in a Database location is considered its key. For example,
  12722. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12723. * `DataSnapshot` will return the key for the location that generated it.
  12724. * However, accessing the key on the root URL of a Database will return
  12725. * `null`.
  12726. */
  12727. get: function () {
  12728. return this.ref.key;
  12729. },
  12730. enumerable: false,
  12731. configurable: true
  12732. });
  12733. Object.defineProperty(DataSnapshot.prototype, "size", {
  12734. /** Returns the number of child properties of this `DataSnapshot`. */
  12735. get: function () {
  12736. return this._node.numChildren();
  12737. },
  12738. enumerable: false,
  12739. configurable: true
  12740. });
  12741. /**
  12742. * Gets another `DataSnapshot` for the location at the specified relative path.
  12743. *
  12744. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12745. * another `DataSnapshot` for the location at the specified relative path. The
  12746. * relative path can either be a simple child name (for example, "ada") or a
  12747. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12748. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12749. * whose value is `null`) is returned.
  12750. *
  12751. * @param path - A relative path to the location of child data.
  12752. */
  12753. DataSnapshot.prototype.child = function (path) {
  12754. var childPath = new Path(path);
  12755. var childRef = child(this.ref, path);
  12756. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12757. };
  12758. /**
  12759. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12760. * efficient than using `snapshot.val() !== null`.
  12761. */
  12762. DataSnapshot.prototype.exists = function () {
  12763. return !this._node.isEmpty();
  12764. };
  12765. /**
  12766. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12767. *
  12768. * The `exportVal()` method is similar to `val()`, except priority information
  12769. * is included (if available), making it suitable for backing up your data.
  12770. *
  12771. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12772. * Array, string, number, boolean, or `null`).
  12773. */
  12774. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12775. DataSnapshot.prototype.exportVal = function () {
  12776. return this._node.val(true);
  12777. };
  12778. /**
  12779. * Enumerates the top-level children in the `DataSnapshot`.
  12780. *
  12781. * Because of the way JavaScript objects work, the ordering of data in the
  12782. * JavaScript object returned by `val()` is not guaranteed to match the
  12783. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12784. * where `forEach()` comes in handy. It guarantees the children of a
  12785. * `DataSnapshot` will be iterated in their query order.
  12786. *
  12787. * If no explicit `orderBy*()` method is used, results are returned
  12788. * ordered by key (unless priorities are used, in which case, results are
  12789. * returned by priority).
  12790. *
  12791. * @param action - A function that will be called for each child DataSnapshot.
  12792. * The callback can return true to cancel further enumeration.
  12793. * @returns true if enumeration was canceled due to your callback returning
  12794. * true.
  12795. */
  12796. DataSnapshot.prototype.forEach = function (action) {
  12797. var _this = this;
  12798. if (this._node.isLeafNode()) {
  12799. return false;
  12800. }
  12801. var childrenNode = this._node;
  12802. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12803. return !!childrenNode.forEachChild(this._index, function (key, node) {
  12804. return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
  12805. });
  12806. };
  12807. /**
  12808. * Returns true if the specified child path has (non-null) data.
  12809. *
  12810. * @param path - A relative path to the location of a potential child.
  12811. * @returns `true` if data exists at the specified child path; else
  12812. * `false`.
  12813. */
  12814. DataSnapshot.prototype.hasChild = function (path) {
  12815. var childPath = new Path(path);
  12816. return !this._node.getChild(childPath).isEmpty();
  12817. };
  12818. /**
  12819. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12820. * properties.
  12821. *
  12822. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12823. * children. If it does, you can enumerate them using `forEach()`. If it
  12824. * doesn't, then either this snapshot contains a primitive value (which can be
  12825. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12826. * `null`).
  12827. *
  12828. * @returns true if this snapshot has any children; else false.
  12829. */
  12830. DataSnapshot.prototype.hasChildren = function () {
  12831. if (this._node.isLeafNode()) {
  12832. return false;
  12833. }
  12834. else {
  12835. return !this._node.isEmpty();
  12836. }
  12837. };
  12838. /**
  12839. * Returns a JSON-serializable representation of this object.
  12840. */
  12841. DataSnapshot.prototype.toJSON = function () {
  12842. return this.exportVal();
  12843. };
  12844. /**
  12845. * Extracts a JavaScript value from a `DataSnapshot`.
  12846. *
  12847. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12848. * scalar type (string, number, or boolean), an array, or an object. It may
  12849. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12850. * data).
  12851. *
  12852. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12853. * Array, string, number, boolean, or `null`).
  12854. */
  12855. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12856. DataSnapshot.prototype.val = function () {
  12857. return this._node.val();
  12858. };
  12859. return DataSnapshot;
  12860. }());
  12861. /**
  12862. *
  12863. * Returns a `Reference` representing the location in the Database
  12864. * corresponding to the provided path. If no path is provided, the `Reference`
  12865. * will point to the root of the Database.
  12866. *
  12867. * @param db - The database instance to obtain a reference for.
  12868. * @param path - Optional path representing the location the returned
  12869. * `Reference` will point. If not provided, the returned `Reference` will
  12870. * point to the root of the Database.
  12871. * @returns If a path is provided, a `Reference`
  12872. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12873. * root of the Database.
  12874. */
  12875. function ref(db, path) {
  12876. db = getModularInstance(db);
  12877. db._checkNotDeleted('ref');
  12878. return path !== undefined ? child(db._root, path) : db._root;
  12879. }
  12880. /**
  12881. * Returns a `Reference` representing the location in the Database
  12882. * corresponding to the provided Firebase URL.
  12883. *
  12884. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12885. * has a different domain than the current `Database` instance.
  12886. *
  12887. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12888. * and are not applied to the returned `Reference`.
  12889. *
  12890. * @param db - The database instance to obtain a reference for.
  12891. * @param url - The Firebase URL at which the returned `Reference` will
  12892. * point.
  12893. * @returns A `Reference` pointing to the provided
  12894. * Firebase URL.
  12895. */
  12896. function refFromURL(db, url) {
  12897. db = getModularInstance(db);
  12898. db._checkNotDeleted('refFromURL');
  12899. var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12900. validateUrl('refFromURL', parsedURL);
  12901. var repoInfo = parsedURL.repoInfo;
  12902. if (!db._repo.repoInfo_.isCustomHost() &&
  12903. repoInfo.host !== db._repo.repoInfo_.host) {
  12904. fatal('refFromURL' +
  12905. ': Host name does not match the current database: ' +
  12906. '(found ' +
  12907. repoInfo.host +
  12908. ' but expected ' +
  12909. db._repo.repoInfo_.host +
  12910. ')');
  12911. }
  12912. return ref(db, parsedURL.path.toString());
  12913. }
  12914. /**
  12915. * Gets a `Reference` for the location at the specified relative path.
  12916. *
  12917. * The relative path can either be a simple child name (for example, "ada") or
  12918. * a deeper slash-separated path (for example, "ada/name/first").
  12919. *
  12920. * @param parent - The parent location.
  12921. * @param path - A relative path from this location to the desired child
  12922. * location.
  12923. * @returns The specified child location.
  12924. */
  12925. function child(parent, path) {
  12926. parent = getModularInstance(parent);
  12927. if (pathGetFront(parent._path) === null) {
  12928. validateRootPathString('child', 'path', path, false);
  12929. }
  12930. else {
  12931. validatePathString('child', 'path', path, false);
  12932. }
  12933. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12934. }
  12935. /**
  12936. * Returns an `OnDisconnect` object - see
  12937. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12938. * for more information on how to use it.
  12939. *
  12940. * @param ref - The reference to add OnDisconnect triggers for.
  12941. */
  12942. function onDisconnect(ref) {
  12943. ref = getModularInstance(ref);
  12944. return new OnDisconnect(ref._repo, ref._path);
  12945. }
  12946. /**
  12947. * Generates a new child location using a unique key and returns its
  12948. * `Reference`.
  12949. *
  12950. * This is the most common pattern for adding data to a collection of items.
  12951. *
  12952. * If you provide a value to `push()`, the value is written to the
  12953. * generated location. If you don't pass a value, nothing is written to the
  12954. * database and the child remains empty (but you can use the `Reference`
  12955. * elsewhere).
  12956. *
  12957. * The unique keys generated by `push()` are ordered by the current time, so the
  12958. * resulting list of items is chronologically sorted. The keys are also
  12959. * designed to be unguessable (they contain 72 random bits of entropy).
  12960. *
  12961. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12962. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12963. *
  12964. * @param parent - The parent location.
  12965. * @param value - Optional value to be written at the generated location.
  12966. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12967. * but can be used immediately as the `Reference` to the child location.
  12968. */
  12969. function push(parent, value) {
  12970. parent = getModularInstance(parent);
  12971. validateWritablePath('push', parent._path);
  12972. validateFirebaseDataArg('push', value, parent._path, true);
  12973. var now = repoServerTime(parent._repo);
  12974. var name = nextPushId(now);
  12975. // push() returns a ThennableReference whose promise is fulfilled with a
  12976. // regular Reference. We use child() to create handles to two different
  12977. // references. The first is turned into a ThennableReference below by adding
  12978. // then() and catch() methods and is used as the return value of push(). The
  12979. // second remains a regular Reference and is used as the fulfilled value of
  12980. // the first ThennableReference.
  12981. var thennablePushRef = child(parent, name);
  12982. var pushRef = child(parent, name);
  12983. var promise;
  12984. if (value != null) {
  12985. promise = set(pushRef, value).then(function () { return pushRef; });
  12986. }
  12987. else {
  12988. promise = Promise.resolve(pushRef);
  12989. }
  12990. thennablePushRef.then = promise.then.bind(promise);
  12991. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12992. return thennablePushRef;
  12993. }
  12994. /**
  12995. * Removes the data at this Database location.
  12996. *
  12997. * Any data at child locations will also be deleted.
  12998. *
  12999. * The effect of the remove will be visible immediately and the corresponding
  13000. * event 'value' will be triggered. Synchronization of the remove to the
  13001. * Firebase servers will also be started, and the returned Promise will resolve
  13002. * when complete. If provided, the onComplete callback will be called
  13003. * asynchronously after synchronization has finished.
  13004. *
  13005. * @param ref - The location to remove.
  13006. * @returns Resolves when remove on server is complete.
  13007. */
  13008. function remove(ref) {
  13009. validateWritablePath('remove', ref._path);
  13010. return set(ref, null);
  13011. }
  13012. /**
  13013. * Writes data to this Database location.
  13014. *
  13015. * This will overwrite any data at this location and all child locations.
  13016. *
  13017. * The effect of the write will be visible immediately, and the corresponding
  13018. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  13019. * the data to the Firebase servers will also be started, and the returned
  13020. * Promise will resolve when complete. If provided, the `onComplete` callback
  13021. * will be called asynchronously after synchronization has finished.
  13022. *
  13023. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  13024. * all data at this location and all child locations will be deleted.
  13025. *
  13026. * `set()` will remove any priority stored at this location, so if priority is
  13027. * meant to be preserved, you need to use `setWithPriority()` instead.
  13028. *
  13029. * Note that modifying data with `set()` will cancel any pending transactions
  13030. * at that location, so extreme care should be taken if mixing `set()` and
  13031. * `transaction()` to modify the same data.
  13032. *
  13033. * A single `set()` will generate a single "value" event at the location where
  13034. * the `set()` was performed.
  13035. *
  13036. * @param ref - The location to write to.
  13037. * @param value - The value to be written (string, number, boolean, object,
  13038. * array, or null).
  13039. * @returns Resolves when write to server is complete.
  13040. */
  13041. function set(ref, value) {
  13042. ref = getModularInstance(ref);
  13043. validateWritablePath('set', ref._path);
  13044. validateFirebaseDataArg('set', value, ref._path, false);
  13045. var deferred = new Deferred();
  13046. repoSetWithPriority(ref._repo, ref._path, value,
  13047. /*priority=*/ null, deferred.wrapCallback(function () { }));
  13048. return deferred.promise;
  13049. }
  13050. /**
  13051. * Sets a priority for the data at this Database location.
  13052. *
  13053. * Applications need not use priority but can order collections by
  13054. * ordinary properties (see
  13055. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13056. * ).
  13057. *
  13058. * @param ref - The location to write to.
  13059. * @param priority - The priority to be written (string, number, or null).
  13060. * @returns Resolves when write to server is complete.
  13061. */
  13062. function setPriority(ref, priority) {
  13063. ref = getModularInstance(ref);
  13064. validateWritablePath('setPriority', ref._path);
  13065. validatePriority('setPriority', priority, false);
  13066. var deferred = new Deferred();
  13067. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
  13068. return deferred.promise;
  13069. }
  13070. /**
  13071. * Writes data the Database location. Like `set()` but also specifies the
  13072. * priority for that data.
  13073. *
  13074. * Applications need not use priority but can order collections by
  13075. * ordinary properties (see
  13076. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13077. * ).
  13078. *
  13079. * @param ref - The location to write to.
  13080. * @param value - The value to be written (string, number, boolean, object,
  13081. * array, or null).
  13082. * @param priority - The priority to be written (string, number, or null).
  13083. * @returns Resolves when write to server is complete.
  13084. */
  13085. function setWithPriority(ref, value, priority) {
  13086. validateWritablePath('setWithPriority', ref._path);
  13087. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  13088. validatePriority('setWithPriority', priority, false);
  13089. if (ref.key === '.length' || ref.key === '.keys') {
  13090. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  13091. }
  13092. var deferred = new Deferred();
  13093. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
  13094. return deferred.promise;
  13095. }
  13096. /**
  13097. * Writes multiple values to the Database at once.
  13098. *
  13099. * The `values` argument contains multiple property-value pairs that will be
  13100. * written to the Database together. Each child property can either be a simple
  13101. * property (for example, "name") or a relative path (for example,
  13102. * "name/first") from the current location to the data to update.
  13103. *
  13104. * As opposed to the `set()` method, `update()` can be use to selectively update
  13105. * only the referenced properties at the current location (instead of replacing
  13106. * all the child properties at the current location).
  13107. *
  13108. * The effect of the write will be visible immediately, and the corresponding
  13109. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  13110. * the data to the Firebase servers will also be started, and the returned
  13111. * Promise will resolve when complete. If provided, the `onComplete` callback
  13112. * will be called asynchronously after synchronization has finished.
  13113. *
  13114. * A single `update()` will generate a single "value" event at the location
  13115. * where the `update()` was performed, regardless of how many children were
  13116. * modified.
  13117. *
  13118. * Note that modifying data with `update()` will cancel any pending
  13119. * transactions at that location, so extreme care should be taken if mixing
  13120. * `update()` and `transaction()` to modify the same data.
  13121. *
  13122. * Passing `null` to `update()` will remove the data at this location.
  13123. *
  13124. * See
  13125. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  13126. *
  13127. * @param ref - The location to write to.
  13128. * @param values - Object containing multiple values.
  13129. * @returns Resolves when update on server is complete.
  13130. */
  13131. function update(ref, values) {
  13132. validateFirebaseMergeDataArg('update', values, ref._path, false);
  13133. var deferred = new Deferred();
  13134. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
  13135. return deferred.promise;
  13136. }
  13137. /**
  13138. * Gets the most up-to-date result for this query.
  13139. *
  13140. * @param query - The query to run.
  13141. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  13142. * available, or rejects if the client is unable to return a value (e.g., if the
  13143. * server is unreachable and there is nothing cached).
  13144. */
  13145. function get(query) {
  13146. query = getModularInstance(query);
  13147. var callbackContext = new CallbackContext(function () { });
  13148. var container = new ValueEventRegistration(callbackContext);
  13149. return repoGetValue(query._repo, query, container).then(function (node) {
  13150. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  13151. });
  13152. }
  13153. /**
  13154. * Represents registration for 'value' events.
  13155. */
  13156. var ValueEventRegistration = /** @class */ (function () {
  13157. function ValueEventRegistration(callbackContext) {
  13158. this.callbackContext = callbackContext;
  13159. }
  13160. ValueEventRegistration.prototype.respondsTo = function (eventType) {
  13161. return eventType === 'value';
  13162. };
  13163. ValueEventRegistration.prototype.createEvent = function (change, query) {
  13164. var index = query._queryParams.getIndex();
  13165. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  13166. };
  13167. ValueEventRegistration.prototype.getEventRunner = function (eventData) {
  13168. var _this = this;
  13169. if (eventData.getEventType() === 'cancel') {
  13170. return function () {
  13171. return _this.callbackContext.onCancel(eventData.error);
  13172. };
  13173. }
  13174. else {
  13175. return function () {
  13176. return _this.callbackContext.onValue(eventData.snapshot, null);
  13177. };
  13178. }
  13179. };
  13180. ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
  13181. if (this.callbackContext.hasCancelCallback) {
  13182. return new CancelEvent(this, error, path);
  13183. }
  13184. else {
  13185. return null;
  13186. }
  13187. };
  13188. ValueEventRegistration.prototype.matches = function (other) {
  13189. if (!(other instanceof ValueEventRegistration)) {
  13190. return false;
  13191. }
  13192. else if (!other.callbackContext || !this.callbackContext) {
  13193. // If no callback specified, we consider it to match any callback.
  13194. return true;
  13195. }
  13196. else {
  13197. return other.callbackContext.matches(this.callbackContext);
  13198. }
  13199. };
  13200. ValueEventRegistration.prototype.hasAnyCallback = function () {
  13201. return this.callbackContext !== null;
  13202. };
  13203. return ValueEventRegistration;
  13204. }());
  13205. /**
  13206. * Represents the registration of a child_x event.
  13207. */
  13208. var ChildEventRegistration = /** @class */ (function () {
  13209. function ChildEventRegistration(eventType, callbackContext) {
  13210. this.eventType = eventType;
  13211. this.callbackContext = callbackContext;
  13212. }
  13213. ChildEventRegistration.prototype.respondsTo = function (eventType) {
  13214. var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  13215. eventToCheck =
  13216. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  13217. return this.eventType === eventToCheck;
  13218. };
  13219. ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
  13220. if (this.callbackContext.hasCancelCallback) {
  13221. return new CancelEvent(this, error, path);
  13222. }
  13223. else {
  13224. return null;
  13225. }
  13226. };
  13227. ChildEventRegistration.prototype.createEvent = function (change, query) {
  13228. assert(change.childName != null, 'Child events should have a childName.');
  13229. var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  13230. var index = query._queryParams.getIndex();
  13231. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  13232. };
  13233. ChildEventRegistration.prototype.getEventRunner = function (eventData) {
  13234. var _this = this;
  13235. if (eventData.getEventType() === 'cancel') {
  13236. return function () {
  13237. return _this.callbackContext.onCancel(eventData.error);
  13238. };
  13239. }
  13240. else {
  13241. return function () {
  13242. return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  13243. };
  13244. }
  13245. };
  13246. ChildEventRegistration.prototype.matches = function (other) {
  13247. if (other instanceof ChildEventRegistration) {
  13248. return (this.eventType === other.eventType &&
  13249. (!this.callbackContext ||
  13250. !other.callbackContext ||
  13251. this.callbackContext.matches(other.callbackContext)));
  13252. }
  13253. return false;
  13254. };
  13255. ChildEventRegistration.prototype.hasAnyCallback = function () {
  13256. return !!this.callbackContext;
  13257. };
  13258. return ChildEventRegistration;
  13259. }());
  13260. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  13261. var cancelCallback;
  13262. if (typeof cancelCallbackOrListenOptions === 'object') {
  13263. cancelCallback = undefined;
  13264. options = cancelCallbackOrListenOptions;
  13265. }
  13266. if (typeof cancelCallbackOrListenOptions === 'function') {
  13267. cancelCallback = cancelCallbackOrListenOptions;
  13268. }
  13269. if (options && options.onlyOnce) {
  13270. var userCallback_1 = callback;
  13271. var onceCallback = function (dataSnapshot, previousChildName) {
  13272. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13273. userCallback_1(dataSnapshot, previousChildName);
  13274. };
  13275. onceCallback.userCallback = callback.userCallback;
  13276. onceCallback.context = callback.context;
  13277. callback = onceCallback;
  13278. }
  13279. var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  13280. var container = eventType === 'value'
  13281. ? new ValueEventRegistration(callbackContext)
  13282. : new ChildEventRegistration(eventType, callbackContext);
  13283. repoAddEventCallbackForQuery(query._repo, query, container);
  13284. return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
  13285. }
  13286. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  13287. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  13288. }
  13289. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  13290. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  13291. }
  13292. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  13293. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  13294. }
  13295. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  13296. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  13297. }
  13298. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  13299. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  13300. }
  13301. /**
  13302. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  13303. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  13304. * the respective `on*` callbacks.
  13305. *
  13306. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  13307. * will not automatically remove listeners registered on child nodes, `off()`
  13308. * must also be called on any child listeners to remove the callback.
  13309. *
  13310. * If a callback is not specified, all callbacks for the specified eventType
  13311. * will be removed. Similarly, if no eventType is specified, all callbacks
  13312. * for the `Reference` will be removed.
  13313. *
  13314. * Individual listeners can also be removed by invoking their unsubscribe
  13315. * callbacks.
  13316. *
  13317. * @param query - The query that the listener was registered with.
  13318. * @param eventType - One of the following strings: "value", "child_added",
  13319. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  13320. * for the `Reference` will be removed.
  13321. * @param callback - The callback function that was passed to `on()` or
  13322. * `undefined` to remove all callbacks.
  13323. */
  13324. function off(query, eventType, callback) {
  13325. var container = null;
  13326. var expCallback = callback ? new CallbackContext(callback) : null;
  13327. if (eventType === 'value') {
  13328. container = new ValueEventRegistration(expCallback);
  13329. }
  13330. else if (eventType) {
  13331. container = new ChildEventRegistration(eventType, expCallback);
  13332. }
  13333. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13334. }
  13335. /**
  13336. * A `QueryConstraint` is used to narrow the set of documents returned by a
  13337. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  13338. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  13339. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  13340. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  13341. * {@link orderByValue} or {@link equalTo} and
  13342. * can then be passed to {@link query} to create a new query instance that
  13343. * also contains this `QueryConstraint`.
  13344. */
  13345. var QueryConstraint = /** @class */ (function () {
  13346. function QueryConstraint() {
  13347. }
  13348. return QueryConstraint;
  13349. }());
  13350. var QueryEndAtConstraint = /** @class */ (function (_super) {
  13351. __extends(QueryEndAtConstraint, _super);
  13352. function QueryEndAtConstraint(_value, _key) {
  13353. var _this = _super.call(this) || this;
  13354. _this._value = _value;
  13355. _this._key = _key;
  13356. return _this;
  13357. }
  13358. QueryEndAtConstraint.prototype._apply = function (query) {
  13359. validateFirebaseDataArg('endAt', this._value, query._path, true);
  13360. var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  13361. validateLimit(newParams);
  13362. validateQueryEndpoints(newParams);
  13363. if (query._queryParams.hasEnd()) {
  13364. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  13365. 'endBefore or equalTo).');
  13366. }
  13367. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13368. };
  13369. return QueryEndAtConstraint;
  13370. }(QueryConstraint));
  13371. /**
  13372. * Creates a `QueryConstraint` with the specified ending point.
  13373. *
  13374. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13375. * allows you to choose arbitrary starting and ending points for your queries.
  13376. *
  13377. * The ending point is inclusive, so children with exactly the specified value
  13378. * will be included in the query. The optional key argument can be used to
  13379. * further limit the range of the query. If it is specified, then children that
  13380. * have exactly the specified value must also have a key name less than or equal
  13381. * to the specified key.
  13382. *
  13383. * You can read more about `endAt()` in
  13384. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13385. *
  13386. * @param value - The value to end at. The argument type depends on which
  13387. * `orderBy*()` function was used in this query. Specify a value that matches
  13388. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13389. * value must be a string.
  13390. * @param key - The child key to end at, among the children with the previously
  13391. * specified priority. This argument is only allowed if ordering by child,
  13392. * value, or priority.
  13393. */
  13394. function endAt(value, key) {
  13395. validateKey('endAt', 'key', key, true);
  13396. return new QueryEndAtConstraint(value, key);
  13397. }
  13398. var QueryEndBeforeConstraint = /** @class */ (function (_super) {
  13399. __extends(QueryEndBeforeConstraint, _super);
  13400. function QueryEndBeforeConstraint(_value, _key) {
  13401. var _this = _super.call(this) || this;
  13402. _this._value = _value;
  13403. _this._key = _key;
  13404. return _this;
  13405. }
  13406. QueryEndBeforeConstraint.prototype._apply = function (query) {
  13407. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  13408. var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  13409. validateLimit(newParams);
  13410. validateQueryEndpoints(newParams);
  13411. if (query._queryParams.hasEnd()) {
  13412. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  13413. 'endBefore or equalTo).');
  13414. }
  13415. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13416. };
  13417. return QueryEndBeforeConstraint;
  13418. }(QueryConstraint));
  13419. /**
  13420. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  13421. *
  13422. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13423. * allows you to choose arbitrary starting and ending points for your queries.
  13424. *
  13425. * The ending point is exclusive. If only a value is provided, children
  13426. * with a value less than the specified value will be included in the query.
  13427. * If a key is specified, then children must have a value less than or equal
  13428. * to the specified value and a key name less than the specified key.
  13429. *
  13430. * @param value - The value to end before. The argument type depends on which
  13431. * `orderBy*()` function was used in this query. Specify a value that matches
  13432. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13433. * value must be a string.
  13434. * @param key - The child key to end before, among the children with the
  13435. * previously specified priority. This argument is only allowed if ordering by
  13436. * child, value, or priority.
  13437. */
  13438. function endBefore(value, key) {
  13439. validateKey('endBefore', 'key', key, true);
  13440. return new QueryEndBeforeConstraint(value, key);
  13441. }
  13442. var QueryStartAtConstraint = /** @class */ (function (_super) {
  13443. __extends(QueryStartAtConstraint, _super);
  13444. function QueryStartAtConstraint(_value, _key) {
  13445. var _this = _super.call(this) || this;
  13446. _this._value = _value;
  13447. _this._key = _key;
  13448. return _this;
  13449. }
  13450. QueryStartAtConstraint.prototype._apply = function (query) {
  13451. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13452. var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13453. validateLimit(newParams);
  13454. validateQueryEndpoints(newParams);
  13455. if (query._queryParams.hasStart()) {
  13456. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13457. 'startBefore or equalTo).');
  13458. }
  13459. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13460. };
  13461. return QueryStartAtConstraint;
  13462. }(QueryConstraint));
  13463. /**
  13464. * Creates a `QueryConstraint` with the specified starting point.
  13465. *
  13466. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13467. * allows you to choose arbitrary starting and ending points for your queries.
  13468. *
  13469. * The starting point is inclusive, so children with exactly the specified value
  13470. * will be included in the query. The optional key argument can be used to
  13471. * further limit the range of the query. If it is specified, then children that
  13472. * have exactly the specified value must also have a key name greater than or
  13473. * equal to the specified key.
  13474. *
  13475. * You can read more about `startAt()` in
  13476. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13477. *
  13478. * @param value - The value to start at. The argument type depends on which
  13479. * `orderBy*()` function was used in this query. Specify a value that matches
  13480. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13481. * value must be a string.
  13482. * @param key - The child key to start at. This argument is only allowed if
  13483. * ordering by child, value, or priority.
  13484. */
  13485. function startAt(value, key) {
  13486. if (value === void 0) { value = null; }
  13487. validateKey('startAt', 'key', key, true);
  13488. return new QueryStartAtConstraint(value, key);
  13489. }
  13490. var QueryStartAfterConstraint = /** @class */ (function (_super) {
  13491. __extends(QueryStartAfterConstraint, _super);
  13492. function QueryStartAfterConstraint(_value, _key) {
  13493. var _this = _super.call(this) || this;
  13494. _this._value = _value;
  13495. _this._key = _key;
  13496. return _this;
  13497. }
  13498. QueryStartAfterConstraint.prototype._apply = function (query) {
  13499. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13500. var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13501. validateLimit(newParams);
  13502. validateQueryEndpoints(newParams);
  13503. if (query._queryParams.hasStart()) {
  13504. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13505. 'startAfter, or equalTo).');
  13506. }
  13507. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13508. };
  13509. return QueryStartAfterConstraint;
  13510. }(QueryConstraint));
  13511. /**
  13512. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13513. *
  13514. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13515. * allows you to choose arbitrary starting and ending points for your queries.
  13516. *
  13517. * The starting point is exclusive. If only a value is provided, children
  13518. * with a value greater than the specified value will be included in the query.
  13519. * If a key is specified, then children must have a value greater than or equal
  13520. * to the specified value and a a key name greater than the specified key.
  13521. *
  13522. * @param value - The value to start after. The argument type depends on which
  13523. * `orderBy*()` function was used in this query. Specify a value that matches
  13524. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13525. * value must be a string.
  13526. * @param key - The child key to start after. This argument is only allowed if
  13527. * ordering by child, value, or priority.
  13528. */
  13529. function startAfter(value, key) {
  13530. validateKey('startAfter', 'key', key, true);
  13531. return new QueryStartAfterConstraint(value, key);
  13532. }
  13533. var QueryLimitToFirstConstraint = /** @class */ (function (_super) {
  13534. __extends(QueryLimitToFirstConstraint, _super);
  13535. function QueryLimitToFirstConstraint(_limit) {
  13536. var _this = _super.call(this) || this;
  13537. _this._limit = _limit;
  13538. return _this;
  13539. }
  13540. QueryLimitToFirstConstraint.prototype._apply = function (query) {
  13541. if (query._queryParams.hasLimit()) {
  13542. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13543. 'or limitToLast).');
  13544. }
  13545. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13546. };
  13547. return QueryLimitToFirstConstraint;
  13548. }(QueryConstraint));
  13549. /**
  13550. * Creates a new `QueryConstraint` that if limited to the first specific number
  13551. * of children.
  13552. *
  13553. * The `limitToFirst()` method is used to set a maximum number of children to be
  13554. * synced for a given callback. If we set a limit of 100, we will initially only
  13555. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13556. * stored in our Database, a `child_added` event will fire for each message.
  13557. * However, if we have over 100 messages, we will only receive a `child_added`
  13558. * event for the first 100 ordered messages. As items change, we will receive
  13559. * `child_removed` events for each item that drops out of the active list so
  13560. * that the total number stays at 100.
  13561. *
  13562. * You can read more about `limitToFirst()` in
  13563. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13564. *
  13565. * @param limit - The maximum number of nodes to include in this query.
  13566. */
  13567. function limitToFirst(limit) {
  13568. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13569. throw new Error('limitToFirst: First argument must be a positive integer.');
  13570. }
  13571. return new QueryLimitToFirstConstraint(limit);
  13572. }
  13573. var QueryLimitToLastConstraint = /** @class */ (function (_super) {
  13574. __extends(QueryLimitToLastConstraint, _super);
  13575. function QueryLimitToLastConstraint(_limit) {
  13576. var _this = _super.call(this) || this;
  13577. _this._limit = _limit;
  13578. return _this;
  13579. }
  13580. QueryLimitToLastConstraint.prototype._apply = function (query) {
  13581. if (query._queryParams.hasLimit()) {
  13582. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13583. 'or limitToLast).');
  13584. }
  13585. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13586. };
  13587. return QueryLimitToLastConstraint;
  13588. }(QueryConstraint));
  13589. /**
  13590. * Creates a new `QueryConstraint` that is limited to return only the last
  13591. * specified number of children.
  13592. *
  13593. * The `limitToLast()` method is used to set a maximum number of children to be
  13594. * synced for a given callback. If we set a limit of 100, we will initially only
  13595. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13596. * stored in our Database, a `child_added` event will fire for each message.
  13597. * However, if we have over 100 messages, we will only receive a `child_added`
  13598. * event for the last 100 ordered messages. As items change, we will receive
  13599. * `child_removed` events for each item that drops out of the active list so
  13600. * that the total number stays at 100.
  13601. *
  13602. * You can read more about `limitToLast()` in
  13603. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13604. *
  13605. * @param limit - The maximum number of nodes to include in this query.
  13606. */
  13607. function limitToLast(limit) {
  13608. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13609. throw new Error('limitToLast: First argument must be a positive integer.');
  13610. }
  13611. return new QueryLimitToLastConstraint(limit);
  13612. }
  13613. var QueryOrderByChildConstraint = /** @class */ (function (_super) {
  13614. __extends(QueryOrderByChildConstraint, _super);
  13615. function QueryOrderByChildConstraint(_path) {
  13616. var _this = _super.call(this) || this;
  13617. _this._path = _path;
  13618. return _this;
  13619. }
  13620. QueryOrderByChildConstraint.prototype._apply = function (query) {
  13621. validateNoPreviousOrderByCall(query, 'orderByChild');
  13622. var parsedPath = new Path(this._path);
  13623. if (pathIsEmpty(parsedPath)) {
  13624. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13625. }
  13626. var index = new PathIndex(parsedPath);
  13627. var newParams = queryParamsOrderBy(query._queryParams, index);
  13628. validateQueryEndpoints(newParams);
  13629. return new QueryImpl(query._repo, query._path, newParams,
  13630. /*orderByCalled=*/ true);
  13631. };
  13632. return QueryOrderByChildConstraint;
  13633. }(QueryConstraint));
  13634. /**
  13635. * Creates a new `QueryConstraint` that orders by the specified child key.
  13636. *
  13637. * Queries can only order by one key at a time. Calling `orderByChild()`
  13638. * multiple times on the same query is an error.
  13639. *
  13640. * Firebase queries allow you to order your data by any child key on the fly.
  13641. * However, if you know in advance what your indexes will be, you can define
  13642. * them via the .indexOn rule in your Security Rules for better performance. See
  13643. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13644. * rule for more information.
  13645. *
  13646. * You can read more about `orderByChild()` in
  13647. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13648. *
  13649. * @param path - The path to order by.
  13650. */
  13651. function orderByChild(path) {
  13652. if (path === '$key') {
  13653. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13654. }
  13655. else if (path === '$priority') {
  13656. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13657. }
  13658. else if (path === '$value') {
  13659. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13660. }
  13661. validatePathString('orderByChild', 'path', path, false);
  13662. return new QueryOrderByChildConstraint(path);
  13663. }
  13664. var QueryOrderByKeyConstraint = /** @class */ (function (_super) {
  13665. __extends(QueryOrderByKeyConstraint, _super);
  13666. function QueryOrderByKeyConstraint() {
  13667. return _super !== null && _super.apply(this, arguments) || this;
  13668. }
  13669. QueryOrderByKeyConstraint.prototype._apply = function (query) {
  13670. validateNoPreviousOrderByCall(query, 'orderByKey');
  13671. var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13672. validateQueryEndpoints(newParams);
  13673. return new QueryImpl(query._repo, query._path, newParams,
  13674. /*orderByCalled=*/ true);
  13675. };
  13676. return QueryOrderByKeyConstraint;
  13677. }(QueryConstraint));
  13678. /**
  13679. * Creates a new `QueryConstraint` that orders by the key.
  13680. *
  13681. * Sorts the results of a query by their (ascending) key values.
  13682. *
  13683. * You can read more about `orderByKey()` in
  13684. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13685. */
  13686. function orderByKey() {
  13687. return new QueryOrderByKeyConstraint();
  13688. }
  13689. var QueryOrderByPriorityConstraint = /** @class */ (function (_super) {
  13690. __extends(QueryOrderByPriorityConstraint, _super);
  13691. function QueryOrderByPriorityConstraint() {
  13692. return _super !== null && _super.apply(this, arguments) || this;
  13693. }
  13694. QueryOrderByPriorityConstraint.prototype._apply = function (query) {
  13695. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13696. var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13697. validateQueryEndpoints(newParams);
  13698. return new QueryImpl(query._repo, query._path, newParams,
  13699. /*orderByCalled=*/ true);
  13700. };
  13701. return QueryOrderByPriorityConstraint;
  13702. }(QueryConstraint));
  13703. /**
  13704. * Creates a new `QueryConstraint` that orders by priority.
  13705. *
  13706. * Applications need not use priority but can order collections by
  13707. * ordinary properties (see
  13708. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13709. * for alternatives to priority.
  13710. */
  13711. function orderByPriority() {
  13712. return new QueryOrderByPriorityConstraint();
  13713. }
  13714. var QueryOrderByValueConstraint = /** @class */ (function (_super) {
  13715. __extends(QueryOrderByValueConstraint, _super);
  13716. function QueryOrderByValueConstraint() {
  13717. return _super !== null && _super.apply(this, arguments) || this;
  13718. }
  13719. QueryOrderByValueConstraint.prototype._apply = function (query) {
  13720. validateNoPreviousOrderByCall(query, 'orderByValue');
  13721. var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13722. validateQueryEndpoints(newParams);
  13723. return new QueryImpl(query._repo, query._path, newParams,
  13724. /*orderByCalled=*/ true);
  13725. };
  13726. return QueryOrderByValueConstraint;
  13727. }(QueryConstraint));
  13728. /**
  13729. * Creates a new `QueryConstraint` that orders by value.
  13730. *
  13731. * If the children of a query are all scalar values (string, number, or
  13732. * boolean), you can order the results by their (ascending) values.
  13733. *
  13734. * You can read more about `orderByValue()` in
  13735. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13736. */
  13737. function orderByValue() {
  13738. return new QueryOrderByValueConstraint();
  13739. }
  13740. var QueryEqualToValueConstraint = /** @class */ (function (_super) {
  13741. __extends(QueryEqualToValueConstraint, _super);
  13742. function QueryEqualToValueConstraint(_value, _key) {
  13743. var _this = _super.call(this) || this;
  13744. _this._value = _value;
  13745. _this._key = _key;
  13746. return _this;
  13747. }
  13748. QueryEqualToValueConstraint.prototype._apply = function (query) {
  13749. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13750. if (query._queryParams.hasStart()) {
  13751. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13752. 'equalTo).');
  13753. }
  13754. if (query._queryParams.hasEnd()) {
  13755. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13756. 'equalTo).');
  13757. }
  13758. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13759. };
  13760. return QueryEqualToValueConstraint;
  13761. }(QueryConstraint));
  13762. /**
  13763. * Creates a `QueryConstraint` that includes children that match the specified
  13764. * value.
  13765. *
  13766. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13767. * allows you to choose arbitrary starting and ending points for your queries.
  13768. *
  13769. * The optional key argument can be used to further limit the range of the
  13770. * query. If it is specified, then children that have exactly the specified
  13771. * value must also have exactly the specified key as their key name. This can be
  13772. * used to filter result sets with many matches for the same value.
  13773. *
  13774. * You can read more about `equalTo()` in
  13775. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13776. *
  13777. * @param value - The value to match for. The argument type depends on which
  13778. * `orderBy*()` function was used in this query. Specify a value that matches
  13779. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13780. * value must be a string.
  13781. * @param key - The child key to start at, among the children with the
  13782. * previously specified priority. This argument is only allowed if ordering by
  13783. * child, value, or priority.
  13784. */
  13785. function equalTo(value, key) {
  13786. validateKey('equalTo', 'key', key, true);
  13787. return new QueryEqualToValueConstraint(value, key);
  13788. }
  13789. /**
  13790. * Creates a new immutable instance of `Query` that is extended to also include
  13791. * additional query constraints.
  13792. *
  13793. * @param query - The Query instance to use as a base for the new constraints.
  13794. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13795. * @throws if any of the provided query constraints cannot be combined with the
  13796. * existing or new constraints.
  13797. */
  13798. function query(query) {
  13799. var e_1, _a;
  13800. var queryConstraints = [];
  13801. for (var _i = 1; _i < arguments.length; _i++) {
  13802. queryConstraints[_i - 1] = arguments[_i];
  13803. }
  13804. var queryImpl = getModularInstance(query);
  13805. try {
  13806. for (var queryConstraints_1 = __values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
  13807. var constraint = queryConstraints_1_1.value;
  13808. queryImpl = constraint._apply(queryImpl);
  13809. }
  13810. }
  13811. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13812. finally {
  13813. try {
  13814. if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
  13815. }
  13816. finally { if (e_1) throw e_1.error; }
  13817. }
  13818. return queryImpl;
  13819. }
  13820. /**
  13821. * Define reference constructor in various modules
  13822. *
  13823. * We are doing this here to avoid several circular
  13824. * dependency issues
  13825. */
  13826. syncPointSetReferenceConstructor(ReferenceImpl);
  13827. syncTreeSetReferenceConstructor(ReferenceImpl);
  13828. /**
  13829. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13830. * modifying this definition, consult the definition in:
  13831. *
  13832. * https://github.com/firebase/firebase-admin-node
  13833. *
  13834. * and make sure the two are consistent.
  13835. */
  13836. var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13837. /**
  13838. * Creates and caches `Repo` instances.
  13839. */
  13840. var repos = {};
  13841. /**
  13842. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13843. */
  13844. var useRestClient = false;
  13845. /**
  13846. * Update an existing `Repo` in place to point to a new host/port.
  13847. */
  13848. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13849. repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
  13850. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13851. /*isUsingEmulator=*/ true);
  13852. if (tokenProvider) {
  13853. repo.authTokenProvider_ = tokenProvider;
  13854. }
  13855. }
  13856. /**
  13857. * This function should only ever be called to CREATE a new database instance.
  13858. * @internal
  13859. */
  13860. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13861. var dbUrl = url || app.options.databaseURL;
  13862. if (dbUrl === undefined) {
  13863. if (!app.options.projectId) {
  13864. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13865. ' a Project ID when calling firebase.initializeApp().');
  13866. }
  13867. log('Using default host for project ', app.options.projectId);
  13868. dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
  13869. }
  13870. var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13871. var repoInfo = parsedUrl.repoInfo;
  13872. var isEmulator;
  13873. var dbEmulatorHost = undefined;
  13874. if (typeof process !== 'undefined' && process.env) {
  13875. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13876. }
  13877. if (dbEmulatorHost) {
  13878. isEmulator = true;
  13879. dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
  13880. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13881. repoInfo = parsedUrl.repoInfo;
  13882. }
  13883. else {
  13884. isEmulator = !parsedUrl.repoInfo.secure;
  13885. }
  13886. var authTokenProvider = nodeAdmin && isEmulator
  13887. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13888. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13889. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13890. if (!pathIsEmpty(parsedUrl.path)) {
  13891. fatal('Database URL must point to the root of a Firebase Database ' +
  13892. '(not including a child path).');
  13893. }
  13894. var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13895. return new Database(repo, app);
  13896. }
  13897. /**
  13898. * Remove the repo and make sure it is disconnected.
  13899. *
  13900. */
  13901. function repoManagerDeleteRepo(repo, appName) {
  13902. var appRepos = repos[appName];
  13903. // This should never happen...
  13904. if (!appRepos || appRepos[repo.key] !== repo) {
  13905. fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
  13906. }
  13907. repoInterrupt(repo);
  13908. delete appRepos[repo.key];
  13909. }
  13910. /**
  13911. * Ensures a repo doesn't already exist and then creates one using the
  13912. * provided app.
  13913. *
  13914. * @param repoInfo - The metadata about the Repo
  13915. * @returns The Repo object for the specified server / repoName.
  13916. */
  13917. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13918. var appRepos = repos[app.name];
  13919. if (!appRepos) {
  13920. appRepos = {};
  13921. repos[app.name] = appRepos;
  13922. }
  13923. var repo = appRepos[repoInfo.toURLString()];
  13924. if (repo) {
  13925. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13926. }
  13927. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13928. appRepos[repoInfo.toURLString()] = repo;
  13929. return repo;
  13930. }
  13931. /**
  13932. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13933. */
  13934. function repoManagerForceRestClient(forceRestClient) {
  13935. useRestClient = forceRestClient;
  13936. }
  13937. /**
  13938. * Class representing a Firebase Realtime Database.
  13939. */
  13940. var Database = /** @class */ (function () {
  13941. /** @hideconstructor */
  13942. function Database(_repoInternal,
  13943. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13944. app) {
  13945. this._repoInternal = _repoInternal;
  13946. this.app = app;
  13947. /** Represents a `Database` instance. */
  13948. this['type'] = 'database';
  13949. /** Track if the instance has been used (root or repo accessed) */
  13950. this._instanceStarted = false;
  13951. }
  13952. Object.defineProperty(Database.prototype, "_repo", {
  13953. get: function () {
  13954. if (!this._instanceStarted) {
  13955. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13956. this._instanceStarted = true;
  13957. }
  13958. return this._repoInternal;
  13959. },
  13960. enumerable: false,
  13961. configurable: true
  13962. });
  13963. Object.defineProperty(Database.prototype, "_root", {
  13964. get: function () {
  13965. if (!this._rootInternal) {
  13966. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13967. }
  13968. return this._rootInternal;
  13969. },
  13970. enumerable: false,
  13971. configurable: true
  13972. });
  13973. Database.prototype._delete = function () {
  13974. if (this._rootInternal !== null) {
  13975. repoManagerDeleteRepo(this._repo, this.app.name);
  13976. this._repoInternal = null;
  13977. this._rootInternal = null;
  13978. }
  13979. return Promise.resolve();
  13980. };
  13981. Database.prototype._checkNotDeleted = function (apiName) {
  13982. if (this._rootInternal === null) {
  13983. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13984. }
  13985. };
  13986. return Database;
  13987. }());
  13988. function checkTransportInit() {
  13989. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13990. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13991. }
  13992. }
  13993. /**
  13994. * Force the use of websockets instead of longPolling.
  13995. */
  13996. function forceWebSockets() {
  13997. checkTransportInit();
  13998. BrowserPollConnection.forceDisallow();
  13999. }
  14000. /**
  14001. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  14002. */
  14003. function forceLongPolling() {
  14004. checkTransportInit();
  14005. WebSocketConnection.forceDisallow();
  14006. BrowserPollConnection.forceAllow();
  14007. }
  14008. /**
  14009. * Returns the instance of the Realtime Database SDK that is associated
  14010. * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
  14011. * with default settings if no instance exists or if the existing instance uses
  14012. * a custom database URL.
  14013. *
  14014. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  14015. * Database instance is associated with.
  14016. * @param url - The URL of the Realtime Database instance to connect to. If not
  14017. * provided, the SDK connects to the default instance of the Firebase App.
  14018. * @returns The `Database` instance of the provided app.
  14019. */
  14020. function getDatabase(app, url) {
  14021. if (app === void 0) { app = getApp(); }
  14022. var db = _getProvider(app, 'database').getImmediate({
  14023. identifier: url
  14024. });
  14025. if (!db._instanceStarted) {
  14026. var emulator = getDefaultEmulatorHostnameAndPort('database');
  14027. if (emulator) {
  14028. connectDatabaseEmulator.apply(void 0, __spreadArray([db], __read(emulator), false));
  14029. }
  14030. }
  14031. return db;
  14032. }
  14033. /**
  14034. * Modify the provided instance to communicate with the Realtime Database
  14035. * emulator.
  14036. *
  14037. * <p>Note: This method must be called before performing any other operation.
  14038. *
  14039. * @param db - The instance to modify.
  14040. * @param host - The emulator host (ex: localhost)
  14041. * @param port - The emulator port (ex: 8080)
  14042. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  14043. */
  14044. function connectDatabaseEmulator(db, host, port, options) {
  14045. if (options === void 0) { options = {}; }
  14046. db = getModularInstance(db);
  14047. db._checkNotDeleted('useEmulator');
  14048. if (db._instanceStarted) {
  14049. fatal('Cannot call useEmulator() after instance has already been initialized.');
  14050. }
  14051. var repo = db._repoInternal;
  14052. var tokenProvider = undefined;
  14053. if (repo.repoInfo_.nodeAdmin) {
  14054. if (options.mockUserToken) {
  14055. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  14056. }
  14057. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  14058. }
  14059. else if (options.mockUserToken) {
  14060. var token = typeof options.mockUserToken === 'string'
  14061. ? options.mockUserToken
  14062. : createMockUserToken(options.mockUserToken, db.app.options.projectId);
  14063. tokenProvider = new EmulatorTokenProvider(token);
  14064. }
  14065. // Modify the repo to apply emulator settings
  14066. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  14067. }
  14068. /**
  14069. * Disconnects from the server (all Database operations will be completed
  14070. * offline).
  14071. *
  14072. * The client automatically maintains a persistent connection to the Database
  14073. * server, which will remain active indefinitely and reconnect when
  14074. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  14075. * to control the client connection in cases where a persistent connection is
  14076. * undesirable.
  14077. *
  14078. * While offline, the client will no longer receive data updates from the
  14079. * Database. However, all Database operations performed locally will continue to
  14080. * immediately fire events, allowing your application to continue behaving
  14081. * normally. Additionally, each operation performed locally will automatically
  14082. * be queued and retried upon reconnection to the Database server.
  14083. *
  14084. * To reconnect to the Database and begin receiving remote events, see
  14085. * `goOnline()`.
  14086. *
  14087. * @param db - The instance to disconnect.
  14088. */
  14089. function goOffline(db) {
  14090. db = getModularInstance(db);
  14091. db._checkNotDeleted('goOffline');
  14092. repoInterrupt(db._repo);
  14093. }
  14094. /**
  14095. * Reconnects to the server and synchronizes the offline Database state
  14096. * with the server state.
  14097. *
  14098. * This method should be used after disabling the active connection with
  14099. * `goOffline()`. Once reconnected, the client will transmit the proper data
  14100. * and fire the appropriate events so that your client "catches up"
  14101. * automatically.
  14102. *
  14103. * @param db - The instance to reconnect.
  14104. */
  14105. function goOnline(db) {
  14106. db = getModularInstance(db);
  14107. db._checkNotDeleted('goOnline');
  14108. repoResume(db._repo);
  14109. }
  14110. function enableLogging(logger, persistent) {
  14111. enableLogging$1(logger, persistent);
  14112. }
  14113. /**
  14114. * @license
  14115. * Copyright 2021 Google LLC
  14116. *
  14117. * Licensed under the Apache License, Version 2.0 (the "License");
  14118. * you may not use this file except in compliance with the License.
  14119. * You may obtain a copy of the License at
  14120. *
  14121. * http://www.apache.org/licenses/LICENSE-2.0
  14122. *
  14123. * Unless required by applicable law or agreed to in writing, software
  14124. * distributed under the License is distributed on an "AS IS" BASIS,
  14125. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14126. * See the License for the specific language governing permissions and
  14127. * limitations under the License.
  14128. */
  14129. function registerDatabase(variant) {
  14130. setSDKVersion(SDK_VERSION$1);
  14131. _registerComponent(new Component('database', function (container, _a) {
  14132. var url = _a.instanceIdentifier;
  14133. var app = container.getProvider('app').getImmediate();
  14134. var authProvider = container.getProvider('auth-internal');
  14135. var appCheckProvider = container.getProvider('app-check-internal');
  14136. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  14137. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  14138. registerVersion(name, version, variant);
  14139. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  14140. registerVersion(name, version, 'esm5');
  14141. }
  14142. /**
  14143. * @license
  14144. * Copyright 2020 Google LLC
  14145. *
  14146. * Licensed under the Apache License, Version 2.0 (the "License");
  14147. * you may not use this file except in compliance with the License.
  14148. * You may obtain a copy of the License at
  14149. *
  14150. * http://www.apache.org/licenses/LICENSE-2.0
  14151. *
  14152. * Unless required by applicable law or agreed to in writing, software
  14153. * distributed under the License is distributed on an "AS IS" BASIS,
  14154. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14155. * See the License for the specific language governing permissions and
  14156. * limitations under the License.
  14157. */
  14158. var SERVER_TIMESTAMP = {
  14159. '.sv': 'timestamp'
  14160. };
  14161. /**
  14162. * Returns a placeholder value for auto-populating the current timestamp (time
  14163. * since the Unix epoch, in milliseconds) as determined by the Firebase
  14164. * servers.
  14165. */
  14166. function serverTimestamp() {
  14167. return SERVER_TIMESTAMP;
  14168. }
  14169. /**
  14170. * Returns a placeholder value that can be used to atomically increment the
  14171. * current database value by the provided delta.
  14172. *
  14173. * @param delta - the amount to modify the current value atomically.
  14174. * @returns A placeholder value for modifying data atomically server-side.
  14175. */
  14176. function increment(delta) {
  14177. return {
  14178. '.sv': {
  14179. 'increment': delta
  14180. }
  14181. };
  14182. }
  14183. /**
  14184. * @license
  14185. * Copyright 2020 Google LLC
  14186. *
  14187. * Licensed under the Apache License, Version 2.0 (the "License");
  14188. * you may not use this file except in compliance with the License.
  14189. * You may obtain a copy of the License at
  14190. *
  14191. * http://www.apache.org/licenses/LICENSE-2.0
  14192. *
  14193. * Unless required by applicable law or agreed to in writing, software
  14194. * distributed under the License is distributed on an "AS IS" BASIS,
  14195. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14196. * See the License for the specific language governing permissions and
  14197. * limitations under the License.
  14198. */
  14199. /**
  14200. * A type for the resolve value of {@link runTransaction}.
  14201. */
  14202. var TransactionResult = /** @class */ (function () {
  14203. /** @hideconstructor */
  14204. function TransactionResult(
  14205. /** Whether the transaction was successfully committed. */
  14206. committed,
  14207. /** The resulting data snapshot. */
  14208. snapshot) {
  14209. this.committed = committed;
  14210. this.snapshot = snapshot;
  14211. }
  14212. /** Returns a JSON-serializable representation of this object. */
  14213. TransactionResult.prototype.toJSON = function () {
  14214. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  14215. };
  14216. return TransactionResult;
  14217. }());
  14218. /**
  14219. * Atomically modifies the data at this location.
  14220. *
  14221. * Atomically modify the data at this location. Unlike a normal `set()`, which
  14222. * just overwrites the data regardless of its previous value, `runTransaction()` is
  14223. * used to modify the existing value to a new value, ensuring there are no
  14224. * conflicts with other clients writing to the same location at the same time.
  14225. *
  14226. * To accomplish this, you pass `runTransaction()` an update function which is
  14227. * used to transform the current value into a new value. If another client
  14228. * writes to the location before your new value is successfully written, your
  14229. * update function will be called again with the new current value, and the
  14230. * write will be retried. This will happen repeatedly until your write succeeds
  14231. * without conflict or you abort the transaction by not returning a value from
  14232. * your update function.
  14233. *
  14234. * Note: Modifying data with `set()` will cancel any pending transactions at
  14235. * that location, so extreme care should be taken if mixing `set()` and
  14236. * `runTransaction()` to update the same data.
  14237. *
  14238. * Note: When using transactions with Security and Firebase Rules in place, be
  14239. * aware that a client needs `.read` access in addition to `.write` access in
  14240. * order to perform a transaction. This is because the client-side nature of
  14241. * transactions requires the client to read the data in order to transactionally
  14242. * update it.
  14243. *
  14244. * @param ref - The location to atomically modify.
  14245. * @param transactionUpdate - A developer-supplied function which will be passed
  14246. * the current data stored at this location (as a JavaScript object). The
  14247. * function should return the new value it would like written (as a JavaScript
  14248. * object). If `undefined` is returned (i.e. you return with no arguments) the
  14249. * transaction will be aborted and the data at this location will not be
  14250. * modified.
  14251. * @param options - An options object to configure transactions.
  14252. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  14253. * callback to handle success and failure.
  14254. */
  14255. function runTransaction(ref,
  14256. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14257. transactionUpdate, options) {
  14258. var _a;
  14259. ref = getModularInstance(ref);
  14260. validateWritablePath('Reference.transaction', ref._path);
  14261. if (ref.key === '.length' || ref.key === '.keys') {
  14262. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  14263. }
  14264. var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  14265. var deferred = new Deferred();
  14266. var promiseComplete = function (error, committed, node) {
  14267. var dataSnapshot = null;
  14268. if (error) {
  14269. deferred.reject(error);
  14270. }
  14271. else {
  14272. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  14273. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  14274. }
  14275. };
  14276. // Add a watch to make sure we get server updates.
  14277. var unwatcher = onValue(ref, function () { });
  14278. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  14279. return deferred.promise;
  14280. }
  14281. /**
  14282. * @license
  14283. * Copyright 2017 Google LLC
  14284. *
  14285. * Licensed under the Apache License, Version 2.0 (the "License");
  14286. * you may not use this file except in compliance with the License.
  14287. * You may obtain a copy of the License at
  14288. *
  14289. * http://www.apache.org/licenses/LICENSE-2.0
  14290. *
  14291. * Unless required by applicable law or agreed to in writing, software
  14292. * distributed under the License is distributed on an "AS IS" BASIS,
  14293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14294. * See the License for the specific language governing permissions and
  14295. * limitations under the License.
  14296. */
  14297. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14298. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  14299. this.sendRequest('q', { p: pathString }, onComplete);
  14300. };
  14301. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14302. PersistentConnection.prototype.echo = function (data, onEcho) {
  14303. this.sendRequest('echo', { d: data }, onEcho);
  14304. };
  14305. /**
  14306. * @internal
  14307. */
  14308. var hijackHash = function (newHash) {
  14309. var oldPut = PersistentConnection.prototype.put;
  14310. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  14311. if (hash !== undefined) {
  14312. hash = newHash();
  14313. }
  14314. oldPut.call(this, pathString, data, onComplete, hash);
  14315. };
  14316. return function () {
  14317. PersistentConnection.prototype.put = oldPut;
  14318. };
  14319. };
  14320. /**
  14321. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  14322. * @internal
  14323. */
  14324. var forceRestClient = function (forceRestClient) {
  14325. repoManagerForceRestClient(forceRestClient);
  14326. };
  14327. /**
  14328. * Firebase Realtime Database
  14329. *
  14330. * @packageDocumentation
  14331. */
  14332. registerDatabase();
  14333. export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };
  14334. //# sourceMappingURL=index.esm5.js.map