index.standalone.js 586 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var Websocket = require('faye-websocket');
  4. var util = require('@firebase/util');
  5. var tslib = require('tslib');
  6. var logger$1 = require('@firebase/logger');
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket);
  9. /**
  10. * @license
  11. * Copyright 2017 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. var PROTOCOL_VERSION = '5';
  26. var VERSION_PARAM = 'v';
  27. var TRANSPORT_SESSION_PARAM = 's';
  28. var REFERER_PARAM = 'r';
  29. var FORGE_REF = 'f';
  30. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  31. // firebase.corp.google.com
  32. var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  33. var LAST_SESSION_PARAM = 'ls';
  34. var APPLICATION_ID_PARAM = 'p';
  35. var APP_CHECK_TOKEN_PARAM = 'ac';
  36. var WEBSOCKET = 'websocket';
  37. var LONG_POLLING = 'long_polling';
  38. /**
  39. * @license
  40. * Copyright 2017 Google LLC
  41. *
  42. * Licensed under the Apache License, Version 2.0 (the "License");
  43. * you may not use this file except in compliance with the License.
  44. * You may obtain a copy of the License at
  45. *
  46. * http://www.apache.org/licenses/LICENSE-2.0
  47. *
  48. * Unless required by applicable law or agreed to in writing, software
  49. * distributed under the License is distributed on an "AS IS" BASIS,
  50. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  51. * See the License for the specific language governing permissions and
  52. * limitations under the License.
  53. */
  54. /**
  55. * Wraps a DOM Storage object and:
  56. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  57. * - prefixes names with "firebase:" to avoid collisions with app data.
  58. *
  59. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  60. * and one for localStorage.
  61. *
  62. */
  63. var DOMStorageWrapper = /** @class */ (function () {
  64. /**
  65. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  66. */
  67. function DOMStorageWrapper(domStorage_) {
  68. this.domStorage_ = domStorage_;
  69. // Use a prefix to avoid collisions with other stuff saved by the app.
  70. this.prefix_ = 'firebase:';
  71. }
  72. /**
  73. * @param key - The key to save the value under
  74. * @param value - The value being stored, or null to remove the key.
  75. */
  76. DOMStorageWrapper.prototype.set = function (key, value) {
  77. if (value == null) {
  78. this.domStorage_.removeItem(this.prefixedName_(key));
  79. }
  80. else {
  81. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  82. }
  83. };
  84. /**
  85. * @returns The value that was stored under this key, or null
  86. */
  87. DOMStorageWrapper.prototype.get = function (key) {
  88. var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  89. if (storedVal == null) {
  90. return null;
  91. }
  92. else {
  93. return util.jsonEval(storedVal);
  94. }
  95. };
  96. DOMStorageWrapper.prototype.remove = function (key) {
  97. this.domStorage_.removeItem(this.prefixedName_(key));
  98. };
  99. DOMStorageWrapper.prototype.prefixedName_ = function (name) {
  100. return this.prefix_ + name;
  101. };
  102. DOMStorageWrapper.prototype.toString = function () {
  103. return this.domStorage_.toString();
  104. };
  105. return DOMStorageWrapper;
  106. }());
  107. /**
  108. * @license
  109. * Copyright 2017 Google LLC
  110. *
  111. * Licensed under the Apache License, Version 2.0 (the "License");
  112. * you may not use this file except in compliance with the License.
  113. * You may obtain a copy of the License at
  114. *
  115. * http://www.apache.org/licenses/LICENSE-2.0
  116. *
  117. * Unless required by applicable law or agreed to in writing, software
  118. * distributed under the License is distributed on an "AS IS" BASIS,
  119. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  120. * See the License for the specific language governing permissions and
  121. * limitations under the License.
  122. */
  123. /**
  124. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  125. * (TODO: create interface for both to implement).
  126. */
  127. var MemoryStorage = /** @class */ (function () {
  128. function MemoryStorage() {
  129. this.cache_ = {};
  130. this.isInMemoryStorage = true;
  131. }
  132. MemoryStorage.prototype.set = function (key, value) {
  133. if (value == null) {
  134. delete this.cache_[key];
  135. }
  136. else {
  137. this.cache_[key] = value;
  138. }
  139. };
  140. MemoryStorage.prototype.get = function (key) {
  141. if (util.contains(this.cache_, key)) {
  142. return this.cache_[key];
  143. }
  144. return null;
  145. };
  146. MemoryStorage.prototype.remove = function (key) {
  147. delete this.cache_[key];
  148. };
  149. return MemoryStorage;
  150. }());
  151. /**
  152. * @license
  153. * Copyright 2017 Google LLC
  154. *
  155. * Licensed under the Apache License, Version 2.0 (the "License");
  156. * you may not use this file except in compliance with the License.
  157. * You may obtain a copy of the License at
  158. *
  159. * http://www.apache.org/licenses/LICENSE-2.0
  160. *
  161. * Unless required by applicable law or agreed to in writing, software
  162. * distributed under the License is distributed on an "AS IS" BASIS,
  163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  164. * See the License for the specific language governing permissions and
  165. * limitations under the License.
  166. */
  167. /**
  168. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  169. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  170. * to reflect this type
  171. *
  172. * @param domStorageName - Name of the underlying storage object
  173. * (e.g. 'localStorage' or 'sessionStorage').
  174. * @returns Turning off type information until a common interface is defined.
  175. */
  176. var createStoragefor = function (domStorageName) {
  177. try {
  178. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  179. // so it must be inside the try/catch.
  180. if (typeof window !== 'undefined' &&
  181. typeof window[domStorageName] !== 'undefined') {
  182. // Need to test cache. Just because it's here doesn't mean it works
  183. var domStorage = window[domStorageName];
  184. domStorage.setItem('firebase:sentinel', 'cache');
  185. domStorage.removeItem('firebase:sentinel');
  186. return new DOMStorageWrapper(domStorage);
  187. }
  188. }
  189. catch (e) { }
  190. // Failed to create wrapper. Just return in-memory storage.
  191. // TODO: log?
  192. return new MemoryStorage();
  193. };
  194. /** A storage object that lasts across sessions */
  195. var PersistentStorage = createStoragefor('localStorage');
  196. /** A storage object that only lasts one session */
  197. var SessionStorage = createStoragefor('sessionStorage');
  198. /**
  199. * @license
  200. * Copyright 2017 Google LLC
  201. *
  202. * Licensed under the Apache License, Version 2.0 (the "License");
  203. * you may not use this file except in compliance with the License.
  204. * You may obtain a copy of the License at
  205. *
  206. * http://www.apache.org/licenses/LICENSE-2.0
  207. *
  208. * Unless required by applicable law or agreed to in writing, software
  209. * distributed under the License is distributed on an "AS IS" BASIS,
  210. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  211. * See the License for the specific language governing permissions and
  212. * limitations under the License.
  213. */
  214. var logClient = new logger$1.Logger('@firebase/database');
  215. /**
  216. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  217. */
  218. var LUIDGenerator = (function () {
  219. var id = 1;
  220. return function () {
  221. return id++;
  222. };
  223. })();
  224. /**
  225. * Sha1 hash of the input string
  226. * @param str - The string to hash
  227. * @returns {!string} The resulting hash
  228. */
  229. var sha1 = function (str) {
  230. var utf8Bytes = util.stringToByteArray(str);
  231. var sha1 = new util.Sha1();
  232. sha1.update(utf8Bytes);
  233. var sha1Bytes = sha1.digest();
  234. return util.base64.encodeByteArray(sha1Bytes);
  235. };
  236. var buildLogMessage_ = function () {
  237. var varArgs = [];
  238. for (var _i = 0; _i < arguments.length; _i++) {
  239. varArgs[_i] = arguments[_i];
  240. }
  241. var message = '';
  242. for (var i = 0; i < varArgs.length; i++) {
  243. var arg = varArgs[i];
  244. if (Array.isArray(arg) ||
  245. (arg &&
  246. typeof arg === 'object' &&
  247. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  248. typeof arg.length === 'number')) {
  249. message += buildLogMessage_.apply(null, arg);
  250. }
  251. else if (typeof arg === 'object') {
  252. message += util.stringify(arg);
  253. }
  254. else {
  255. message += arg;
  256. }
  257. message += ' ';
  258. }
  259. return message;
  260. };
  261. /**
  262. * Use this for all debug messages in Firebase.
  263. */
  264. var logger = null;
  265. /**
  266. * Flag to check for log availability on first log message
  267. */
  268. var firstLog_ = true;
  269. /**
  270. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  271. * @param logger_ - A flag to turn on logging, or a custom logger
  272. * @param persistent - Whether or not to persist logging settings across refreshes
  273. */
  274. var enableLogging$1 = function (logger_, persistent) {
  275. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  276. if (logger_ === true) {
  277. logClient.logLevel = logger$1.LogLevel.VERBOSE;
  278. logger = logClient.log.bind(logClient);
  279. if (persistent) {
  280. SessionStorage.set('logging_enabled', true);
  281. }
  282. }
  283. else if (typeof logger_ === 'function') {
  284. logger = logger_;
  285. }
  286. else {
  287. logger = null;
  288. SessionStorage.remove('logging_enabled');
  289. }
  290. };
  291. var log = function () {
  292. var varArgs = [];
  293. for (var _i = 0; _i < arguments.length; _i++) {
  294. varArgs[_i] = arguments[_i];
  295. }
  296. if (firstLog_ === true) {
  297. firstLog_ = false;
  298. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  299. enableLogging$1(true);
  300. }
  301. }
  302. if (logger) {
  303. var message = buildLogMessage_.apply(null, varArgs);
  304. logger(message);
  305. }
  306. };
  307. var logWrapper = function (prefix) {
  308. return function () {
  309. var varArgs = [];
  310. for (var _i = 0; _i < arguments.length; _i++) {
  311. varArgs[_i] = arguments[_i];
  312. }
  313. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  314. };
  315. };
  316. var error = function () {
  317. var varArgs = [];
  318. for (var _i = 0; _i < arguments.length; _i++) {
  319. varArgs[_i] = arguments[_i];
  320. }
  321. var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  322. logClient.error(message);
  323. };
  324. var fatal = function () {
  325. var varArgs = [];
  326. for (var _i = 0; _i < arguments.length; _i++) {
  327. varArgs[_i] = arguments[_i];
  328. }
  329. var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false)));
  330. logClient.error(message);
  331. throw new Error(message);
  332. };
  333. var warn = function () {
  334. var varArgs = [];
  335. for (var _i = 0; _i < arguments.length; _i++) {
  336. varArgs[_i] = arguments[_i];
  337. }
  338. var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  339. logClient.warn(message);
  340. };
  341. /**
  342. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  343. * does not use https.
  344. */
  345. var warnIfPageIsSecure = function () {
  346. // Be very careful accessing browser globals. Who knows what may or may not exist.
  347. if (typeof window !== 'undefined' &&
  348. window.location &&
  349. window.location.protocol &&
  350. window.location.protocol.indexOf('https:') !== -1) {
  351. warn('Insecure Firebase access from a secure page. ' +
  352. 'Please use https in calls to new Firebase().');
  353. }
  354. };
  355. /**
  356. * Returns true if data is NaN, or +/- Infinity.
  357. */
  358. var isInvalidJSONNumber = function (data) {
  359. return (typeof data === 'number' &&
  360. (data !== data || // NaN
  361. data === Number.POSITIVE_INFINITY ||
  362. data === Number.NEGATIVE_INFINITY));
  363. };
  364. var executeWhenDOMReady = function (fn) {
  365. if (util.isNodeSdk() || document.readyState === 'complete') {
  366. fn();
  367. }
  368. else {
  369. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  370. // fire before onload), but fall back to onload.
  371. var called_1 = false;
  372. var wrappedFn_1 = function () {
  373. if (!document.body) {
  374. setTimeout(wrappedFn_1, Math.floor(10));
  375. return;
  376. }
  377. if (!called_1) {
  378. called_1 = true;
  379. fn();
  380. }
  381. };
  382. if (document.addEventListener) {
  383. document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
  384. // fallback to onload.
  385. window.addEventListener('load', wrappedFn_1, false);
  386. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  387. }
  388. else if (document.attachEvent) {
  389. // IE.
  390. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  391. document.attachEvent('onreadystatechange', function () {
  392. if (document.readyState === 'complete') {
  393. wrappedFn_1();
  394. }
  395. });
  396. // fallback to onload.
  397. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  398. window.attachEvent('onload', wrappedFn_1);
  399. // jQuery has an extra hack for IE that we could employ (based on
  400. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  401. // I'm hoping we don't need it.
  402. }
  403. }
  404. };
  405. /**
  406. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  407. */
  408. var MIN_NAME = '[MIN_NAME]';
  409. /**
  410. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  411. */
  412. var MAX_NAME = '[MAX_NAME]';
  413. /**
  414. * Compares valid Firebase key names, plus min and max name
  415. */
  416. var nameCompare = function (a, b) {
  417. if (a === b) {
  418. return 0;
  419. }
  420. else if (a === MIN_NAME || b === MAX_NAME) {
  421. return -1;
  422. }
  423. else if (b === MIN_NAME || a === MAX_NAME) {
  424. return 1;
  425. }
  426. else {
  427. var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  428. if (aAsInt !== null) {
  429. if (bAsInt !== null) {
  430. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  431. }
  432. else {
  433. return -1;
  434. }
  435. }
  436. else if (bAsInt !== null) {
  437. return 1;
  438. }
  439. else {
  440. return a < b ? -1 : 1;
  441. }
  442. }
  443. };
  444. /**
  445. * @returns {!number} comparison result.
  446. */
  447. var stringCompare = function (a, b) {
  448. if (a === b) {
  449. return 0;
  450. }
  451. else if (a < b) {
  452. return -1;
  453. }
  454. else {
  455. return 1;
  456. }
  457. };
  458. var requireKey = function (key, obj) {
  459. if (obj && key in obj) {
  460. return obj[key];
  461. }
  462. else {
  463. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  464. }
  465. };
  466. var ObjectToUniqueKey = function (obj) {
  467. if (typeof obj !== 'object' || obj === null) {
  468. return util.stringify(obj);
  469. }
  470. var keys = [];
  471. // eslint-disable-next-line guard-for-in
  472. for (var k in obj) {
  473. keys.push(k);
  474. }
  475. // Export as json, but with the keys sorted.
  476. keys.sort();
  477. var key = '{';
  478. for (var i = 0; i < keys.length; i++) {
  479. if (i !== 0) {
  480. key += ',';
  481. }
  482. key += util.stringify(keys[i]);
  483. key += ':';
  484. key += ObjectToUniqueKey(obj[keys[i]]);
  485. }
  486. key += '}';
  487. return key;
  488. };
  489. /**
  490. * Splits a string into a number of smaller segments of maximum size
  491. * @param str - The string
  492. * @param segsize - The maximum number of chars in the string.
  493. * @returns The string, split into appropriately-sized chunks
  494. */
  495. var splitStringBySize = function (str, segsize) {
  496. var len = str.length;
  497. if (len <= segsize) {
  498. return [str];
  499. }
  500. var dataSegs = [];
  501. for (var c = 0; c < len; c += segsize) {
  502. if (c + segsize > len) {
  503. dataSegs.push(str.substring(c, len));
  504. }
  505. else {
  506. dataSegs.push(str.substring(c, c + segsize));
  507. }
  508. }
  509. return dataSegs;
  510. };
  511. /**
  512. * Apply a function to each (key, value) pair in an object or
  513. * apply a function to each (index, value) pair in an array
  514. * @param obj - The object or array to iterate over
  515. * @param fn - The function to apply
  516. */
  517. function each(obj, fn) {
  518. for (var key in obj) {
  519. if (obj.hasOwnProperty(key)) {
  520. fn(key, obj[key]);
  521. }
  522. }
  523. }
  524. /**
  525. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  526. * I made one modification at the end and removed the NaN / Infinity
  527. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  528. * @param v - A double
  529. *
  530. */
  531. var doubleToIEEE754String = function (v) {
  532. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  533. var ebits = 11, fbits = 52;
  534. var bias = (1 << (ebits - 1)) - 1;
  535. var s, e, f, ln, i;
  536. // Compute sign, exponent, fraction
  537. // Skip NaN / Infinity handling --MJL.
  538. if (v === 0) {
  539. e = 0;
  540. f = 0;
  541. s = 1 / v === -Infinity ? 1 : 0;
  542. }
  543. else {
  544. s = v < 0;
  545. v = Math.abs(v);
  546. if (v >= Math.pow(2, 1 - bias)) {
  547. // Normalized
  548. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  549. e = ln + bias;
  550. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  551. }
  552. else {
  553. // Denormalized
  554. e = 0;
  555. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  556. }
  557. }
  558. // Pack sign, exponent, fraction
  559. var bits = [];
  560. for (i = fbits; i; i -= 1) {
  561. bits.push(f % 2 ? 1 : 0);
  562. f = Math.floor(f / 2);
  563. }
  564. for (i = ebits; i; i -= 1) {
  565. bits.push(e % 2 ? 1 : 0);
  566. e = Math.floor(e / 2);
  567. }
  568. bits.push(s ? 1 : 0);
  569. bits.reverse();
  570. var str = bits.join('');
  571. // Return the data as a hex string. --MJL
  572. var hexByteString = '';
  573. for (i = 0; i < 64; i += 8) {
  574. var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  575. if (hexByte.length === 1) {
  576. hexByte = '0' + hexByte;
  577. }
  578. hexByteString = hexByteString + hexByte;
  579. }
  580. return hexByteString.toLowerCase();
  581. };
  582. /**
  583. * Used to detect if we're in a Chrome content script (which executes in an
  584. * isolated environment where long-polling doesn't work).
  585. */
  586. var isChromeExtensionContentScript = function () {
  587. return !!(typeof window === 'object' &&
  588. window['chrome'] &&
  589. window['chrome']['extension'] &&
  590. !/^chrome/.test(window.location.href));
  591. };
  592. /**
  593. * Used to detect if we're in a Windows 8 Store app.
  594. */
  595. var isWindowsStoreApp = function () {
  596. // Check for the presence of a couple WinRT globals
  597. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  598. };
  599. /**
  600. * Converts a server error code to a Javascript Error
  601. */
  602. function errorForServerCode(code, query) {
  603. var reason = 'Unknown Error';
  604. if (code === 'too_big') {
  605. reason =
  606. 'The data requested exceeds the maximum size ' +
  607. 'that can be accessed with a single request.';
  608. }
  609. else if (code === 'permission_denied') {
  610. reason = "Client doesn't have permission to access the desired data.";
  611. }
  612. else if (code === 'unavailable') {
  613. reason = 'The service is unavailable';
  614. }
  615. var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  616. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  617. error.code = code.toUpperCase();
  618. return error;
  619. }
  620. /**
  621. * Used to test for integer-looking strings
  622. */
  623. var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  624. /**
  625. * For use in keys, the minimum possible 32-bit integer.
  626. */
  627. var INTEGER_32_MIN = -2147483648;
  628. /**
  629. * For use in kyes, the maximum possible 32-bit integer.
  630. */
  631. var INTEGER_32_MAX = 2147483647;
  632. /**
  633. * If the string contains a 32-bit integer, return it. Else return null.
  634. */
  635. var tryParseInt = function (str) {
  636. if (INTEGER_REGEXP_.test(str)) {
  637. var intVal = Number(str);
  638. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  639. return intVal;
  640. }
  641. }
  642. return null;
  643. };
  644. /**
  645. * Helper to run some code but catch any exceptions and re-throw them later.
  646. * Useful for preventing user callbacks from breaking internal code.
  647. *
  648. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  649. * convenient (we don't have to try to figure out when is a safe point to
  650. * re-throw it), and the behavior seems reasonable:
  651. *
  652. * * If you aren't pausing on exceptions, you get an error in the console with
  653. * the correct stack trace.
  654. * * If you're pausing on all exceptions, the debugger will pause on your
  655. * exception and then again when we rethrow it.
  656. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  657. * on us re-throwing it.
  658. *
  659. * @param fn - The code to guard.
  660. */
  661. var exceptionGuard = function (fn) {
  662. try {
  663. fn();
  664. }
  665. catch (e) {
  666. // Re-throw exception when it's safe.
  667. setTimeout(function () {
  668. // It used to be that "throw e" would result in a good console error with
  669. // relevant context, but as of Chrome 39, you just get the firebase.js
  670. // file/line number where we re-throw it, which is useless. So we log
  671. // e.stack explicitly.
  672. var stack = e.stack || '';
  673. warn('Exception was thrown by user callback.', stack);
  674. throw e;
  675. }, Math.floor(0));
  676. }
  677. };
  678. /**
  679. * @returns {boolean} true if we think we're currently being crawled.
  680. */
  681. var beingCrawled = function () {
  682. var userAgent = (typeof window === 'object' &&
  683. window['navigator'] &&
  684. window['navigator']['userAgent']) ||
  685. '';
  686. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  687. // believe to support JavaScript/AJAX rendering.
  688. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  689. // would have seen the page" is flaky if we don't treat it as a crawler.
  690. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  691. };
  692. /**
  693. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  694. *
  695. * It is removed with clearTimeout() as normal.
  696. *
  697. * @param fn - Function to run.
  698. * @param time - Milliseconds to wait before running.
  699. * @returns The setTimeout() return value.
  700. */
  701. var setTimeoutNonBlocking = function (fn, time) {
  702. var timeout = setTimeout(fn, time);
  703. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  704. if (typeof timeout === 'number' &&
  705. // @ts-ignore Is only defined in Deno environments.
  706. typeof Deno !== 'undefined' &&
  707. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  708. Deno['unrefTimer']) {
  709. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  710. Deno.unrefTimer(timeout);
  711. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  712. }
  713. else if (typeof timeout === 'object' && timeout['unref']) {
  714. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  715. timeout['unref']();
  716. }
  717. return timeout;
  718. };
  719. /**
  720. * @license
  721. * Copyright 2017 Google LLC
  722. *
  723. * Licensed under the Apache License, Version 2.0 (the "License");
  724. * you may not use this file except in compliance with the License.
  725. * You may obtain a copy of the License at
  726. *
  727. * http://www.apache.org/licenses/LICENSE-2.0
  728. *
  729. * Unless required by applicable law or agreed to in writing, software
  730. * distributed under the License is distributed on an "AS IS" BASIS,
  731. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  732. * See the License for the specific language governing permissions and
  733. * limitations under the License.
  734. */
  735. /**
  736. * A class that holds metadata about a Repo object
  737. */
  738. var RepoInfo = /** @class */ (function () {
  739. /**
  740. * @param host - Hostname portion of the url for the repo
  741. * @param secure - Whether or not this repo is accessed over ssl
  742. * @param namespace - The namespace represented by the repo
  743. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  744. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  745. * @param persistenceKey - Override the default session persistence storage key
  746. */
  747. function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams, isUsingEmulator) {
  748. if (nodeAdmin === void 0) { nodeAdmin = false; }
  749. if (persistenceKey === void 0) { persistenceKey = ''; }
  750. if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
  751. if (isUsingEmulator === void 0) { isUsingEmulator = false; }
  752. this.secure = secure;
  753. this.namespace = namespace;
  754. this.webSocketOnly = webSocketOnly;
  755. this.nodeAdmin = nodeAdmin;
  756. this.persistenceKey = persistenceKey;
  757. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  758. this.isUsingEmulator = isUsingEmulator;
  759. this._host = host.toLowerCase();
  760. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  761. this.internalHost =
  762. PersistentStorage.get('host:' + host) || this._host;
  763. }
  764. RepoInfo.prototype.isCacheableHost = function () {
  765. return this.internalHost.substr(0, 2) === 's-';
  766. };
  767. RepoInfo.prototype.isCustomHost = function () {
  768. return (this._domain !== 'firebaseio.com' &&
  769. this._domain !== 'firebaseio-demo.com');
  770. };
  771. Object.defineProperty(RepoInfo.prototype, "host", {
  772. get: function () {
  773. return this._host;
  774. },
  775. set: function (newHost) {
  776. if (newHost !== this.internalHost) {
  777. this.internalHost = newHost;
  778. if (this.isCacheableHost()) {
  779. PersistentStorage.set('host:' + this._host, this.internalHost);
  780. }
  781. }
  782. },
  783. enumerable: false,
  784. configurable: true
  785. });
  786. RepoInfo.prototype.toString = function () {
  787. var str = this.toURLString();
  788. if (this.persistenceKey) {
  789. str += '<' + this.persistenceKey + '>';
  790. }
  791. return str;
  792. };
  793. RepoInfo.prototype.toURLString = function () {
  794. var protocol = this.secure ? 'https://' : 'http://';
  795. var query = this.includeNamespaceInQueryParams
  796. ? "?ns=".concat(this.namespace)
  797. : '';
  798. return "".concat(protocol).concat(this.host, "/").concat(query);
  799. };
  800. return RepoInfo;
  801. }());
  802. function repoInfoNeedsQueryParam(repoInfo) {
  803. return (repoInfo.host !== repoInfo.internalHost ||
  804. repoInfo.isCustomHost() ||
  805. repoInfo.includeNamespaceInQueryParams);
  806. }
  807. /**
  808. * Returns the websocket URL for this repo
  809. * @param repoInfo - RepoInfo object
  810. * @param type - of connection
  811. * @param params - list
  812. * @returns The URL for this repo
  813. */
  814. function repoInfoConnectionURL(repoInfo, type, params) {
  815. util.assert(typeof type === 'string', 'typeof type must == string');
  816. util.assert(typeof params === 'object', 'typeof params must == object');
  817. var connURL;
  818. if (type === WEBSOCKET) {
  819. connURL =
  820. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  821. }
  822. else if (type === LONG_POLLING) {
  823. connURL =
  824. (repoInfo.secure ? 'https://' : 'http://') +
  825. repoInfo.internalHost +
  826. '/.lp?';
  827. }
  828. else {
  829. throw new Error('Unknown connection type: ' + type);
  830. }
  831. if (repoInfoNeedsQueryParam(repoInfo)) {
  832. params['ns'] = repoInfo.namespace;
  833. }
  834. var pairs = [];
  835. each(params, function (key, value) {
  836. pairs.push(key + '=' + value);
  837. });
  838. return connURL + pairs.join('&');
  839. }
  840. /**
  841. * @license
  842. * Copyright 2017 Google LLC
  843. *
  844. * Licensed under the Apache License, Version 2.0 (the "License");
  845. * you may not use this file except in compliance with the License.
  846. * You may obtain a copy of the License at
  847. *
  848. * http://www.apache.org/licenses/LICENSE-2.0
  849. *
  850. * Unless required by applicable law or agreed to in writing, software
  851. * distributed under the License is distributed on an "AS IS" BASIS,
  852. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  853. * See the License for the specific language governing permissions and
  854. * limitations under the License.
  855. */
  856. /**
  857. * Tracks a collection of stats.
  858. */
  859. var StatsCollection = /** @class */ (function () {
  860. function StatsCollection() {
  861. this.counters_ = {};
  862. }
  863. StatsCollection.prototype.incrementCounter = function (name, amount) {
  864. if (amount === void 0) { amount = 1; }
  865. if (!util.contains(this.counters_, name)) {
  866. this.counters_[name] = 0;
  867. }
  868. this.counters_[name] += amount;
  869. };
  870. StatsCollection.prototype.get = function () {
  871. return util.deepCopy(this.counters_);
  872. };
  873. return StatsCollection;
  874. }());
  875. /**
  876. * @license
  877. * Copyright 2017 Google LLC
  878. *
  879. * Licensed under the Apache License, Version 2.0 (the "License");
  880. * you may not use this file except in compliance with the License.
  881. * You may obtain a copy of the License at
  882. *
  883. * http://www.apache.org/licenses/LICENSE-2.0
  884. *
  885. * Unless required by applicable law or agreed to in writing, software
  886. * distributed under the License is distributed on an "AS IS" BASIS,
  887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  888. * See the License for the specific language governing permissions and
  889. * limitations under the License.
  890. */
  891. var collections = {};
  892. var reporters = {};
  893. function statsManagerGetCollection(repoInfo) {
  894. var hashString = repoInfo.toString();
  895. if (!collections[hashString]) {
  896. collections[hashString] = new StatsCollection();
  897. }
  898. return collections[hashString];
  899. }
  900. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  901. var hashString = repoInfo.toString();
  902. if (!reporters[hashString]) {
  903. reporters[hashString] = creatorFunction();
  904. }
  905. return reporters[hashString];
  906. }
  907. /**
  908. * @license
  909. * Copyright 2019 Google LLC
  910. *
  911. * Licensed under the Apache License, Version 2.0 (the "License");
  912. * you may not use this file except in compliance with the License.
  913. * You may obtain a copy of the License at
  914. *
  915. * http://www.apache.org/licenses/LICENSE-2.0
  916. *
  917. * Unless required by applicable law or agreed to in writing, software
  918. * distributed under the License is distributed on an "AS IS" BASIS,
  919. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  920. * See the License for the specific language governing permissions and
  921. * limitations under the License.
  922. */
  923. /** The semver (www.semver.org) version of the SDK. */
  924. var SDK_VERSION = '';
  925. /**
  926. * SDK_VERSION should be set before any database instance is created
  927. * @internal
  928. */
  929. function setSDKVersion(version) {
  930. SDK_VERSION = version;
  931. }
  932. /**
  933. * @license
  934. * Copyright 2017 Google LLC
  935. *
  936. * Licensed under the Apache License, Version 2.0 (the "License");
  937. * you may not use this file except in compliance with the License.
  938. * You may obtain a copy of the License at
  939. *
  940. * http://www.apache.org/licenses/LICENSE-2.0
  941. *
  942. * Unless required by applicable law or agreed to in writing, software
  943. * distributed under the License is distributed on an "AS IS" BASIS,
  944. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  945. * See the License for the specific language governing permissions and
  946. * limitations under the License.
  947. */
  948. var WEBSOCKET_MAX_FRAME_SIZE = 16384;
  949. var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  950. var WebSocketImpl = null;
  951. if (typeof MozWebSocket !== 'undefined') {
  952. WebSocketImpl = MozWebSocket;
  953. }
  954. else if (typeof WebSocket !== 'undefined') {
  955. WebSocketImpl = WebSocket;
  956. }
  957. function setWebSocketImpl(impl) {
  958. WebSocketImpl = impl;
  959. }
  960. /**
  961. * Create a new websocket connection with the given callbacks.
  962. */
  963. var WebSocketConnection = /** @class */ (function () {
  964. /**
  965. * @param connId identifier for this transport
  966. * @param repoInfo The info for the websocket endpoint.
  967. * @param applicationId The Firebase App ID for this project.
  968. * @param appCheckToken The App Check Token for this client.
  969. * @param authToken The Auth Token for this client.
  970. * @param transportSessionId Optional transportSessionId if this is connecting
  971. * to an existing transport session
  972. * @param lastSessionId Optional lastSessionId if there was a previous
  973. * connection
  974. */
  975. function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  976. this.connId = connId;
  977. this.applicationId = applicationId;
  978. this.appCheckToken = appCheckToken;
  979. this.authToken = authToken;
  980. this.keepaliveTimer = null;
  981. this.frames = null;
  982. this.totalFrames = 0;
  983. this.bytesSent = 0;
  984. this.bytesReceived = 0;
  985. this.log_ = logWrapper(this.connId);
  986. this.stats_ = statsManagerGetCollection(repoInfo);
  987. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  988. this.nodeAdmin = repoInfo.nodeAdmin;
  989. }
  990. /**
  991. * @param repoInfo - The info for the websocket endpoint.
  992. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  993. * session
  994. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  995. * @returns connection url
  996. */
  997. WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  998. var urlParams = {};
  999. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1000. if (!util.isNodeSdk() &&
  1001. typeof location !== 'undefined' &&
  1002. location.hostname &&
  1003. FORGE_DOMAIN_RE.test(location.hostname)) {
  1004. urlParams[REFERER_PARAM] = FORGE_REF;
  1005. }
  1006. if (transportSessionId) {
  1007. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1008. }
  1009. if (lastSessionId) {
  1010. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1011. }
  1012. if (appCheckToken) {
  1013. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1014. }
  1015. if (applicationId) {
  1016. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1017. }
  1018. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1019. };
  1020. /**
  1021. * @param onMessage - Callback when messages arrive
  1022. * @param onDisconnect - Callback with connection lost.
  1023. */
  1024. WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
  1025. var _this = this;
  1026. this.onDisconnect = onDisconnect;
  1027. this.onMessage = onMessage;
  1028. this.log_('Websocket connecting to ' + this.connURL);
  1029. this.everConnected_ = false;
  1030. // Assume failure until proven otherwise.
  1031. PersistentStorage.set('previous_websocket_failure', true);
  1032. try {
  1033. var options = void 0;
  1034. if (util.isNodeSdk()) {
  1035. var device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1036. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1037. options = {
  1038. headers: {
  1039. 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
  1040. 'X-Firebase-GMPID': this.applicationId || ''
  1041. }
  1042. };
  1043. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1044. // Note that we send the credentials here even if they aren't admin credentials, which is
  1045. // not a problem.
  1046. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1047. // through the websocket connection once it is established.
  1048. if (this.authToken) {
  1049. options.headers['Authorization'] = "Bearer ".concat(this.authToken);
  1050. }
  1051. if (this.appCheckToken) {
  1052. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1053. }
  1054. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1055. var env = process['env'];
  1056. var proxy = this.connURL.indexOf('wss://') === 0
  1057. ? env['HTTPS_PROXY'] || env['https_proxy']
  1058. : env['HTTP_PROXY'] || env['http_proxy'];
  1059. if (proxy) {
  1060. options['proxy'] = { origin: proxy };
  1061. }
  1062. }
  1063. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1064. }
  1065. catch (e) {
  1066. this.log_('Error instantiating WebSocket.');
  1067. var error = e.message || e.data;
  1068. if (error) {
  1069. this.log_(error);
  1070. }
  1071. this.onClosed_();
  1072. return;
  1073. }
  1074. this.mySock.onopen = function () {
  1075. _this.log_('Websocket connected.');
  1076. _this.everConnected_ = true;
  1077. };
  1078. this.mySock.onclose = function () {
  1079. _this.log_('Websocket connection was disconnected.');
  1080. _this.mySock = null;
  1081. _this.onClosed_();
  1082. };
  1083. this.mySock.onmessage = function (m) {
  1084. _this.handleIncomingFrame(m);
  1085. };
  1086. this.mySock.onerror = function (e) {
  1087. _this.log_('WebSocket error. Closing connection.');
  1088. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1089. var error = e.message || e.data;
  1090. if (error) {
  1091. _this.log_(error);
  1092. }
  1093. _this.onClosed_();
  1094. };
  1095. };
  1096. /**
  1097. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1098. */
  1099. WebSocketConnection.prototype.start = function () { };
  1100. WebSocketConnection.forceDisallow = function () {
  1101. WebSocketConnection.forceDisallow_ = true;
  1102. };
  1103. WebSocketConnection.isAvailable = function () {
  1104. var isOldAndroid = false;
  1105. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1106. var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1107. var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1108. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1109. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1110. isOldAndroid = true;
  1111. }
  1112. }
  1113. }
  1114. return (!isOldAndroid &&
  1115. WebSocketImpl !== null &&
  1116. !WebSocketConnection.forceDisallow_);
  1117. };
  1118. /**
  1119. * Returns true if we previously failed to connect with this transport.
  1120. */
  1121. WebSocketConnection.previouslyFailed = function () {
  1122. // If our persistent storage is actually only in-memory storage,
  1123. // we default to assuming that it previously failed to be safe.
  1124. return (PersistentStorage.isInMemoryStorage ||
  1125. PersistentStorage.get('previous_websocket_failure') === true);
  1126. };
  1127. WebSocketConnection.prototype.markConnectionHealthy = function () {
  1128. PersistentStorage.remove('previous_websocket_failure');
  1129. };
  1130. WebSocketConnection.prototype.appendFrame_ = function (data) {
  1131. this.frames.push(data);
  1132. if (this.frames.length === this.totalFrames) {
  1133. var fullMess = this.frames.join('');
  1134. this.frames = null;
  1135. var jsonMess = util.jsonEval(fullMess);
  1136. //handle the message
  1137. this.onMessage(jsonMess);
  1138. }
  1139. };
  1140. /**
  1141. * @param frameCount - The number of frames we are expecting from the server
  1142. */
  1143. WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
  1144. this.totalFrames = frameCount;
  1145. this.frames = [];
  1146. };
  1147. /**
  1148. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1149. * @returns Any remaining data to be process, or null if there is none
  1150. */
  1151. WebSocketConnection.prototype.extractFrameCount_ = function (data) {
  1152. util.assert(this.frames === null, 'We already have a frame buffer');
  1153. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1154. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1155. if (data.length <= 6) {
  1156. var frameCount = Number(data);
  1157. if (!isNaN(frameCount)) {
  1158. this.handleNewFrameCount_(frameCount);
  1159. return null;
  1160. }
  1161. }
  1162. this.handleNewFrameCount_(1);
  1163. return data;
  1164. };
  1165. /**
  1166. * Process a websocket frame that has arrived from the server.
  1167. * @param mess - The frame data
  1168. */
  1169. WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
  1170. if (this.mySock === null) {
  1171. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1172. }
  1173. var data = mess['data'];
  1174. this.bytesReceived += data.length;
  1175. this.stats_.incrementCounter('bytes_received', data.length);
  1176. this.resetKeepAlive();
  1177. if (this.frames !== null) {
  1178. // we're buffering
  1179. this.appendFrame_(data);
  1180. }
  1181. else {
  1182. // try to parse out a frame count, otherwise, assume 1 and process it
  1183. var remainingData = this.extractFrameCount_(data);
  1184. if (remainingData !== null) {
  1185. this.appendFrame_(remainingData);
  1186. }
  1187. }
  1188. };
  1189. /**
  1190. * Send a message to the server
  1191. * @param data - The JSON object to transmit
  1192. */
  1193. WebSocketConnection.prototype.send = function (data) {
  1194. this.resetKeepAlive();
  1195. var dataStr = util.stringify(data);
  1196. this.bytesSent += dataStr.length;
  1197. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1198. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1199. //up into multiple pieces if it doesn't fit in one request.
  1200. var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1201. //Send the length header
  1202. if (dataSegs.length > 1) {
  1203. this.sendString_(String(dataSegs.length));
  1204. }
  1205. //Send the actual data in segments.
  1206. for (var i = 0; i < dataSegs.length; i++) {
  1207. this.sendString_(dataSegs[i]);
  1208. }
  1209. };
  1210. WebSocketConnection.prototype.shutdown_ = function () {
  1211. this.isClosed_ = true;
  1212. if (this.keepaliveTimer) {
  1213. clearInterval(this.keepaliveTimer);
  1214. this.keepaliveTimer = null;
  1215. }
  1216. if (this.mySock) {
  1217. this.mySock.close();
  1218. this.mySock = null;
  1219. }
  1220. };
  1221. WebSocketConnection.prototype.onClosed_ = function () {
  1222. if (!this.isClosed_) {
  1223. this.log_('WebSocket is closing itself');
  1224. this.shutdown_();
  1225. // since this is an internal close, trigger the close listener
  1226. if (this.onDisconnect) {
  1227. this.onDisconnect(this.everConnected_);
  1228. this.onDisconnect = null;
  1229. }
  1230. }
  1231. };
  1232. /**
  1233. * External-facing close handler.
  1234. * Close the websocket and kill the connection.
  1235. */
  1236. WebSocketConnection.prototype.close = function () {
  1237. if (!this.isClosed_) {
  1238. this.log_('WebSocket is being closed');
  1239. this.shutdown_();
  1240. }
  1241. };
  1242. /**
  1243. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1244. * the last activity.
  1245. */
  1246. WebSocketConnection.prototype.resetKeepAlive = function () {
  1247. var _this = this;
  1248. clearInterval(this.keepaliveTimer);
  1249. this.keepaliveTimer = setInterval(function () {
  1250. //If there has been no websocket activity for a while, send a no-op
  1251. if (_this.mySock) {
  1252. _this.sendString_('0');
  1253. }
  1254. _this.resetKeepAlive();
  1255. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1256. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1257. };
  1258. /**
  1259. * Send a string over the websocket.
  1260. *
  1261. * @param str - String to send.
  1262. */
  1263. WebSocketConnection.prototype.sendString_ = function (str) {
  1264. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1265. // calls for some unknown reason. We treat these as an error and disconnect.
  1266. // See https://app.asana.com/0/58926111402292/68021340250410
  1267. try {
  1268. this.mySock.send(str);
  1269. }
  1270. catch (e) {
  1271. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1272. setTimeout(this.onClosed_.bind(this), 0);
  1273. }
  1274. };
  1275. /**
  1276. * Number of response before we consider the connection "healthy."
  1277. */
  1278. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1279. /**
  1280. * Time to wait for the connection te become healthy before giving up.
  1281. */
  1282. WebSocketConnection.healthyTimeout = 30000;
  1283. return WebSocketConnection;
  1284. }());
  1285. /**
  1286. * @license
  1287. * Copyright 2021 Google LLC
  1288. *
  1289. * Licensed under the Apache License, Version 2.0 (the "License");
  1290. * you may not use this file except in compliance with the License.
  1291. * You may obtain a copy of the License at
  1292. *
  1293. * http://www.apache.org/licenses/LICENSE-2.0
  1294. *
  1295. * Unless required by applicable law or agreed to in writing, software
  1296. * distributed under the License is distributed on an "AS IS" BASIS,
  1297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1298. * See the License for the specific language governing permissions and
  1299. * limitations under the License.
  1300. */
  1301. /**
  1302. * Abstraction around AppCheck's token fetching capabilities.
  1303. */
  1304. var AppCheckTokenProvider = /** @class */ (function () {
  1305. function AppCheckTokenProvider(appName_, appCheckProvider) {
  1306. var _this = this;
  1307. this.appName_ = appName_;
  1308. this.appCheckProvider = appCheckProvider;
  1309. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1310. if (!this.appCheck) {
  1311. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
  1312. }
  1313. }
  1314. AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
  1315. var _this = this;
  1316. if (!this.appCheck) {
  1317. return new Promise(function (resolve, reject) {
  1318. // Support delayed initialization of FirebaseAppCheck. This allows our
  1319. // customers to initialize the RTDB SDK before initializing Firebase
  1320. // AppCheck and ensures that all requests are authenticated if a token
  1321. // becomes available before the timoeout below expires.
  1322. setTimeout(function () {
  1323. if (_this.appCheck) {
  1324. _this.getToken(forceRefresh).then(resolve, reject);
  1325. }
  1326. else {
  1327. resolve(null);
  1328. }
  1329. }, 0);
  1330. });
  1331. }
  1332. return this.appCheck.getToken(forceRefresh);
  1333. };
  1334. AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1335. var _a;
  1336. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
  1337. };
  1338. AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
  1339. warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
  1340. 'are invalid. This usually indicates your app was not initialized correctly.');
  1341. };
  1342. return AppCheckTokenProvider;
  1343. }());
  1344. /**
  1345. * @license
  1346. * Copyright 2017 Google LLC
  1347. *
  1348. * Licensed under the Apache License, Version 2.0 (the "License");
  1349. * you may not use this file except in compliance with the License.
  1350. * You may obtain a copy of the License at
  1351. *
  1352. * http://www.apache.org/licenses/LICENSE-2.0
  1353. *
  1354. * Unless required by applicable law or agreed to in writing, software
  1355. * distributed under the License is distributed on an "AS IS" BASIS,
  1356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1357. * See the License for the specific language governing permissions and
  1358. * limitations under the License.
  1359. */
  1360. /**
  1361. * Abstraction around FirebaseApp's token fetching capabilities.
  1362. */
  1363. var FirebaseAuthTokenProvider = /** @class */ (function () {
  1364. function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
  1365. var _this = this;
  1366. this.appName_ = appName_;
  1367. this.firebaseOptions_ = firebaseOptions_;
  1368. this.authProvider_ = authProvider_;
  1369. this.auth_ = null;
  1370. this.auth_ = authProvider_.getImmediate({ optional: true });
  1371. if (!this.auth_) {
  1372. authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
  1373. }
  1374. }
  1375. FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
  1376. var _this = this;
  1377. if (!this.auth_) {
  1378. return new Promise(function (resolve, reject) {
  1379. // Support delayed initialization of FirebaseAuth. This allows our
  1380. // customers to initialize the RTDB SDK before initializing Firebase
  1381. // Auth and ensures that all requests are authenticated if a token
  1382. // becomes available before the timoeout below expires.
  1383. setTimeout(function () {
  1384. if (_this.auth_) {
  1385. _this.getToken(forceRefresh).then(resolve, reject);
  1386. }
  1387. else {
  1388. resolve(null);
  1389. }
  1390. }, 0);
  1391. });
  1392. }
  1393. return this.auth_.getToken(forceRefresh).catch(function (error) {
  1394. // TODO: Need to figure out all the cases this is raised and whether
  1395. // this makes sense.
  1396. if (error && error.code === 'auth/token-not-initialized') {
  1397. log('Got auth/token-not-initialized error. Treating as null token.');
  1398. return null;
  1399. }
  1400. else {
  1401. return Promise.reject(error);
  1402. }
  1403. });
  1404. };
  1405. FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1406. // TODO: We might want to wrap the listener and call it with no args to
  1407. // avoid a leaky abstraction, but that makes removing the listener harder.
  1408. if (this.auth_) {
  1409. this.auth_.addAuthTokenListener(listener);
  1410. }
  1411. else {
  1412. this.authProvider_
  1413. .get()
  1414. .then(function (auth) { return auth.addAuthTokenListener(listener); });
  1415. }
  1416. };
  1417. FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
  1418. this.authProvider_
  1419. .get()
  1420. .then(function (auth) { return auth.removeAuthTokenListener(listener); });
  1421. };
  1422. FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
  1423. var errorMessage = 'Provided authentication credentials for the app named "' +
  1424. this.appName_ +
  1425. '" are invalid. This usually indicates your app was not ' +
  1426. 'initialized correctly. ';
  1427. if ('credential' in this.firebaseOptions_) {
  1428. errorMessage +=
  1429. 'Make sure the "credential" property provided to initializeApp() ' +
  1430. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1431. 'project.';
  1432. }
  1433. else if ('serviceAccount' in this.firebaseOptions_) {
  1434. errorMessage +=
  1435. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1436. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1437. 'project.';
  1438. }
  1439. else {
  1440. errorMessage +=
  1441. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1442. 'initializeApp() match the values provided for your app at ' +
  1443. 'https://console.firebase.google.com/.';
  1444. }
  1445. warn(errorMessage);
  1446. };
  1447. return FirebaseAuthTokenProvider;
  1448. }());
  1449. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1450. var EmulatorTokenProvider = /** @class */ (function () {
  1451. function EmulatorTokenProvider(accessToken) {
  1452. this.accessToken = accessToken;
  1453. }
  1454. EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
  1455. return Promise.resolve({
  1456. accessToken: this.accessToken
  1457. });
  1458. };
  1459. EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1460. // Invoke the listener immediately to match the behavior in Firebase Auth
  1461. // (see packages/auth/src/auth.js#L1807)
  1462. listener(this.accessToken);
  1463. };
  1464. EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
  1465. EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
  1466. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1467. EmulatorTokenProvider.OWNER = 'owner';
  1468. return EmulatorTokenProvider;
  1469. }());
  1470. /**
  1471. * @license
  1472. * Copyright 2017 Google LLC
  1473. *
  1474. * Licensed under the Apache License, Version 2.0 (the "License");
  1475. * you may not use this file except in compliance with the License.
  1476. * You may obtain a copy of the License at
  1477. *
  1478. * http://www.apache.org/licenses/LICENSE-2.0
  1479. *
  1480. * Unless required by applicable law or agreed to in writing, software
  1481. * distributed under the License is distributed on an "AS IS" BASIS,
  1482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1483. * See the License for the specific language governing permissions and
  1484. * limitations under the License.
  1485. */
  1486. /**
  1487. * This class ensures the packets from the server arrive in order
  1488. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1489. */
  1490. var PacketReceiver = /** @class */ (function () {
  1491. /**
  1492. * @param onMessage_
  1493. */
  1494. function PacketReceiver(onMessage_) {
  1495. this.onMessage_ = onMessage_;
  1496. this.pendingResponses = [];
  1497. this.currentResponseNum = 0;
  1498. this.closeAfterResponse = -1;
  1499. this.onClose = null;
  1500. }
  1501. PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
  1502. this.closeAfterResponse = responseNum;
  1503. this.onClose = callback;
  1504. if (this.closeAfterResponse < this.currentResponseNum) {
  1505. this.onClose();
  1506. this.onClose = null;
  1507. }
  1508. };
  1509. /**
  1510. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1511. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1512. * browsers will respond in the same order as the requests we sent
  1513. */
  1514. PacketReceiver.prototype.handleResponse = function (requestNum, data) {
  1515. var _this = this;
  1516. this.pendingResponses[requestNum] = data;
  1517. var _loop_1 = function () {
  1518. var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
  1519. delete this_1.pendingResponses[this_1.currentResponseNum];
  1520. var _loop_2 = function (i) {
  1521. if (toProcess[i]) {
  1522. exceptionGuard(function () {
  1523. _this.onMessage_(toProcess[i]);
  1524. });
  1525. }
  1526. };
  1527. for (var i = 0; i < toProcess.length; ++i) {
  1528. _loop_2(i);
  1529. }
  1530. if (this_1.currentResponseNum === this_1.closeAfterResponse) {
  1531. if (this_1.onClose) {
  1532. this_1.onClose();
  1533. this_1.onClose = null;
  1534. }
  1535. return "break";
  1536. }
  1537. this_1.currentResponseNum++;
  1538. };
  1539. var this_1 = this;
  1540. while (this.pendingResponses[this.currentResponseNum]) {
  1541. var state_1 = _loop_1();
  1542. if (state_1 === "break")
  1543. break;
  1544. }
  1545. };
  1546. return PacketReceiver;
  1547. }());
  1548. /**
  1549. * @license
  1550. * Copyright 2017 Google LLC
  1551. *
  1552. * Licensed under the Apache License, Version 2.0 (the "License");
  1553. * you may not use this file except in compliance with the License.
  1554. * You may obtain a copy of the License at
  1555. *
  1556. * http://www.apache.org/licenses/LICENSE-2.0
  1557. *
  1558. * Unless required by applicable law or agreed to in writing, software
  1559. * distributed under the License is distributed on an "AS IS" BASIS,
  1560. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1561. * See the License for the specific language governing permissions and
  1562. * limitations under the License.
  1563. */
  1564. // URL query parameters associated with longpolling
  1565. var FIREBASE_LONGPOLL_START_PARAM = 'start';
  1566. var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1567. var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1568. var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1569. var FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1570. var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1571. var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1572. var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1573. var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1574. var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1575. var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1576. var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1577. //Data size constants.
  1578. //TODO: Perf: the maximum length actually differs from browser to browser.
  1579. // We should check what browser we're on and set accordingly.
  1580. var MAX_URL_DATA_SIZE = 1870;
  1581. var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1582. var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1583. /**
  1584. * Keepalive period
  1585. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1586. * length of 30 seconds that we can't exceed.
  1587. */
  1588. var KEEPALIVE_REQUEST_INTERVAL = 25000;
  1589. /**
  1590. * How long to wait before aborting a long-polling connection attempt.
  1591. */
  1592. var LP_CONNECT_TIMEOUT = 30000;
  1593. /**
  1594. * This class manages a single long-polling connection.
  1595. */
  1596. var BrowserPollConnection = /** @class */ (function () {
  1597. /**
  1598. * @param connId An identifier for this connection, used for logging
  1599. * @param repoInfo The info for the endpoint to send data to.
  1600. * @param applicationId The Firebase App ID for this project.
  1601. * @param appCheckToken The AppCheck token for this client.
  1602. * @param authToken The AuthToken to use for this connection.
  1603. * @param transportSessionId Optional transportSessionid if we are
  1604. * reconnecting for an existing transport session
  1605. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1606. * already created a connection previously
  1607. */
  1608. function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1609. var _this = this;
  1610. this.connId = connId;
  1611. this.repoInfo = repoInfo;
  1612. this.applicationId = applicationId;
  1613. this.appCheckToken = appCheckToken;
  1614. this.authToken = authToken;
  1615. this.transportSessionId = transportSessionId;
  1616. this.lastSessionId = lastSessionId;
  1617. this.bytesSent = 0;
  1618. this.bytesReceived = 0;
  1619. this.everConnected_ = false;
  1620. this.log_ = logWrapper(connId);
  1621. this.stats_ = statsManagerGetCollection(repoInfo);
  1622. this.urlFn = function (params) {
  1623. // Always add the token if we have one.
  1624. if (_this.appCheckToken) {
  1625. params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1626. }
  1627. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1628. };
  1629. }
  1630. /**
  1631. * @param onMessage - Callback when messages arrive
  1632. * @param onDisconnect - Callback with connection lost.
  1633. */
  1634. BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
  1635. var _this = this;
  1636. this.curSegmentNum = 0;
  1637. this.onDisconnect_ = onDisconnect;
  1638. this.myPacketOrderer = new PacketReceiver(onMessage);
  1639. this.isClosed_ = false;
  1640. this.connectTimeoutTimer_ = setTimeout(function () {
  1641. _this.log_('Timed out trying to connect.');
  1642. // Make sure we clear the host cache
  1643. _this.onClosed_();
  1644. _this.connectTimeoutTimer_ = null;
  1645. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1646. }, Math.floor(LP_CONNECT_TIMEOUT));
  1647. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1648. executeWhenDOMReady(function () {
  1649. if (_this.isClosed_) {
  1650. return;
  1651. }
  1652. //Set up a callback that gets triggered once a connection is set up.
  1653. _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
  1654. var args = [];
  1655. for (var _i = 0; _i < arguments.length; _i++) {
  1656. args[_i] = arguments[_i];
  1657. }
  1658. var _a = tslib.__read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
  1659. _this.incrementIncomingBytes_(args);
  1660. if (!_this.scriptTagHolder) {
  1661. return; // we closed the connection.
  1662. }
  1663. if (_this.connectTimeoutTimer_) {
  1664. clearTimeout(_this.connectTimeoutTimer_);
  1665. _this.connectTimeoutTimer_ = null;
  1666. }
  1667. _this.everConnected_ = true;
  1668. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1669. _this.id = arg1;
  1670. _this.password = arg2;
  1671. }
  1672. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1673. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1674. if (arg1) {
  1675. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1676. // through our already open polls), so don't send any more.
  1677. _this.scriptTagHolder.sendNewPolls = false;
  1678. // arg1 in this case is the last response number sent by the server. We should try to receive
  1679. // all of the responses up to this one before closing
  1680. _this.myPacketOrderer.closeAfter(arg1, function () {
  1681. _this.onClosed_();
  1682. });
  1683. }
  1684. else {
  1685. _this.onClosed_();
  1686. }
  1687. }
  1688. else {
  1689. throw new Error('Unrecognized command received: ' + command);
  1690. }
  1691. }, function () {
  1692. var args = [];
  1693. for (var _i = 0; _i < arguments.length; _i++) {
  1694. args[_i] = arguments[_i];
  1695. }
  1696. var _a = tslib.__read(args, 2), pN = _a[0], data = _a[1];
  1697. _this.incrementIncomingBytes_(args);
  1698. _this.myPacketOrderer.handleResponse(pN, data);
  1699. }, function () {
  1700. _this.onClosed_();
  1701. }, _this.urlFn);
  1702. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1703. //from cache.
  1704. var urlParams = {};
  1705. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1706. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1707. if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
  1708. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1709. _this.scriptTagHolder.uniqueCallbackIdentifier;
  1710. }
  1711. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1712. if (_this.transportSessionId) {
  1713. urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
  1714. }
  1715. if (_this.lastSessionId) {
  1716. urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
  1717. }
  1718. if (_this.applicationId) {
  1719. urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
  1720. }
  1721. if (_this.appCheckToken) {
  1722. urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1723. }
  1724. if (typeof location !== 'undefined' &&
  1725. location.hostname &&
  1726. FORGE_DOMAIN_RE.test(location.hostname)) {
  1727. urlParams[REFERER_PARAM] = FORGE_REF;
  1728. }
  1729. var connectURL = _this.urlFn(urlParams);
  1730. _this.log_('Connecting via long-poll to ' + connectURL);
  1731. _this.scriptTagHolder.addTag(connectURL, function () {
  1732. /* do nothing */
  1733. });
  1734. });
  1735. };
  1736. /**
  1737. * Call this when a handshake has completed successfully and we want to consider the connection established
  1738. */
  1739. BrowserPollConnection.prototype.start = function () {
  1740. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1741. this.addDisconnectPingFrame(this.id, this.password);
  1742. };
  1743. /**
  1744. * Forces long polling to be considered as a potential transport
  1745. */
  1746. BrowserPollConnection.forceAllow = function () {
  1747. BrowserPollConnection.forceAllow_ = true;
  1748. };
  1749. /**
  1750. * Forces longpolling to not be considered as a potential transport
  1751. */
  1752. BrowserPollConnection.forceDisallow = function () {
  1753. BrowserPollConnection.forceDisallow_ = true;
  1754. };
  1755. // Static method, use string literal so it can be accessed in a generic way
  1756. BrowserPollConnection.isAvailable = function () {
  1757. if (util.isNodeSdk()) {
  1758. return false;
  1759. }
  1760. else if (BrowserPollConnection.forceAllow_) {
  1761. return true;
  1762. }
  1763. else {
  1764. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1765. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1766. return (!BrowserPollConnection.forceDisallow_ &&
  1767. typeof document !== 'undefined' &&
  1768. document.createElement != null &&
  1769. !isChromeExtensionContentScript() &&
  1770. !isWindowsStoreApp());
  1771. }
  1772. };
  1773. /**
  1774. * No-op for polling
  1775. */
  1776. BrowserPollConnection.prototype.markConnectionHealthy = function () { };
  1777. /**
  1778. * Stops polling and cleans up the iframe
  1779. */
  1780. BrowserPollConnection.prototype.shutdown_ = function () {
  1781. this.isClosed_ = true;
  1782. if (this.scriptTagHolder) {
  1783. this.scriptTagHolder.close();
  1784. this.scriptTagHolder = null;
  1785. }
  1786. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1787. if (this.myDisconnFrame) {
  1788. document.body.removeChild(this.myDisconnFrame);
  1789. this.myDisconnFrame = null;
  1790. }
  1791. if (this.connectTimeoutTimer_) {
  1792. clearTimeout(this.connectTimeoutTimer_);
  1793. this.connectTimeoutTimer_ = null;
  1794. }
  1795. };
  1796. /**
  1797. * Triggered when this transport is closed
  1798. */
  1799. BrowserPollConnection.prototype.onClosed_ = function () {
  1800. if (!this.isClosed_) {
  1801. this.log_('Longpoll is closing itself');
  1802. this.shutdown_();
  1803. if (this.onDisconnect_) {
  1804. this.onDisconnect_(this.everConnected_);
  1805. this.onDisconnect_ = null;
  1806. }
  1807. }
  1808. };
  1809. /**
  1810. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1811. * that we've left.
  1812. */
  1813. BrowserPollConnection.prototype.close = function () {
  1814. if (!this.isClosed_) {
  1815. this.log_('Longpoll is being closed.');
  1816. this.shutdown_();
  1817. }
  1818. };
  1819. /**
  1820. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1821. * broken into chunks (since URLs have a small maximum length).
  1822. * @param data - The JSON data to transmit.
  1823. */
  1824. BrowserPollConnection.prototype.send = function (data) {
  1825. var dataStr = util.stringify(data);
  1826. this.bytesSent += dataStr.length;
  1827. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1828. //first, lets get the base64-encoded data
  1829. var base64data = util.base64Encode(dataStr);
  1830. //We can only fit a certain amount in each URL, so we need to split this request
  1831. //up into multiple pieces if it doesn't fit in one request.
  1832. var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1833. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1834. //of segments so that we can reassemble the packet on the server.
  1835. for (var i = 0; i < dataSegs.length; i++) {
  1836. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1837. this.curSegmentNum++;
  1838. }
  1839. };
  1840. /**
  1841. * This is how we notify the server that we're leaving.
  1842. * We aren't able to send requests with DHTML on a window close event, but we can
  1843. * trigger XHR requests in some browsers (everything but Opera basically).
  1844. */
  1845. BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
  1846. if (util.isNodeSdk()) {
  1847. return;
  1848. }
  1849. this.myDisconnFrame = document.createElement('iframe');
  1850. var urlParams = {};
  1851. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1852. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1853. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1854. this.myDisconnFrame.src = this.urlFn(urlParams);
  1855. this.myDisconnFrame.style.display = 'none';
  1856. document.body.appendChild(this.myDisconnFrame);
  1857. };
  1858. /**
  1859. * Used to track the bytes received by this client
  1860. */
  1861. BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
  1862. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1863. var bytesReceived = util.stringify(args).length;
  1864. this.bytesReceived += bytesReceived;
  1865. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1866. };
  1867. return BrowserPollConnection;
  1868. }());
  1869. /*********************************************************************************************
  1870. * A wrapper around an iframe that is used as a long-polling script holder.
  1871. *********************************************************************************************/
  1872. var FirebaseIFrameScriptHolder = /** @class */ (function () {
  1873. /**
  1874. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1875. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1876. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1877. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1878. */
  1879. function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
  1880. this.onDisconnect = onDisconnect;
  1881. this.urlFn = urlFn;
  1882. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1883. //problems in some browsers.
  1884. this.outstandingRequests = new Set();
  1885. //A queue of the pending segments waiting for transmission to the server.
  1886. this.pendingSegs = [];
  1887. //A serial number. We use this for two things:
  1888. // 1) A way to ensure the browser doesn't cache responses to polls
  1889. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1890. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1891. // JSONP code in the order it was added to the iframe.
  1892. this.currentSerial = Math.floor(Math.random() * 100000000);
  1893. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1894. // incoming data from the server that we're waiting for).
  1895. this.sendNewPolls = true;
  1896. if (!util.isNodeSdk()) {
  1897. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1898. //iframes where we put the long-polling script tags. We have two callbacks:
  1899. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1900. // 2) Message Callback - Triggered when new data arrives.
  1901. this.uniqueCallbackIdentifier = LUIDGenerator();
  1902. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1903. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1904. onMessageCB;
  1905. //Create an iframe for us to add script tags to.
  1906. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1907. // Set the iframe's contents.
  1908. var script = '';
  1909. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1910. // for ie9, but ie8 needs to do it again in the document itself.
  1911. if (this.myIFrame.src &&
  1912. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1913. var currentDomain = document.domain;
  1914. script = '<script>document.domain="' + currentDomain + '";</script>';
  1915. }
  1916. var iframeContents = '<html><body>' + script + '</body></html>';
  1917. try {
  1918. this.myIFrame.doc.open();
  1919. this.myIFrame.doc.write(iframeContents);
  1920. this.myIFrame.doc.close();
  1921. }
  1922. catch (e) {
  1923. log('frame writing exception');
  1924. if (e.stack) {
  1925. log(e.stack);
  1926. }
  1927. log(e);
  1928. }
  1929. }
  1930. else {
  1931. this.commandCB = commandCB;
  1932. this.onMessageCB = onMessageCB;
  1933. }
  1934. }
  1935. /**
  1936. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1937. * actually use.
  1938. */
  1939. FirebaseIFrameScriptHolder.createIFrame_ = function () {
  1940. var iframe = document.createElement('iframe');
  1941. iframe.style.display = 'none';
  1942. // This is necessary in order to initialize the document inside the iframe
  1943. if (document.body) {
  1944. document.body.appendChild(iframe);
  1945. try {
  1946. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1947. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1948. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1949. var a = iframe.contentWindow.document;
  1950. if (!a) {
  1951. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1952. log('No IE domain setting required');
  1953. }
  1954. }
  1955. catch (e) {
  1956. var domain = document.domain;
  1957. iframe.src =
  1958. "javascript:void((function(){document.open();document.domain='" +
  1959. domain +
  1960. "';document.close();})())";
  1961. }
  1962. }
  1963. else {
  1964. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1965. // never gets hit.
  1966. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1967. }
  1968. // Get the document of the iframe in a browser-specific way.
  1969. if (iframe.contentDocument) {
  1970. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1971. }
  1972. else if (iframe.contentWindow) {
  1973. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1974. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1975. }
  1976. else if (iframe.document) {
  1977. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1978. iframe.doc = iframe.document; //others?
  1979. }
  1980. return iframe;
  1981. };
  1982. /**
  1983. * Cancel all outstanding queries and remove the frame.
  1984. */
  1985. FirebaseIFrameScriptHolder.prototype.close = function () {
  1986. var _this = this;
  1987. //Mark this iframe as dead, so no new requests are sent.
  1988. this.alive = false;
  1989. if (this.myIFrame) {
  1990. //We have to actually remove all of the html inside this iframe before removing it from the
  1991. //window, or IE will continue loading and executing the script tags we've already added, which
  1992. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1993. this.myIFrame.doc.body.textContent = '';
  1994. setTimeout(function () {
  1995. if (_this.myIFrame !== null) {
  1996. document.body.removeChild(_this.myIFrame);
  1997. _this.myIFrame = null;
  1998. }
  1999. }, Math.floor(0));
  2000. }
  2001. // Protect from being called recursively.
  2002. var onDisconnect = this.onDisconnect;
  2003. if (onDisconnect) {
  2004. this.onDisconnect = null;
  2005. onDisconnect();
  2006. }
  2007. };
  2008. /**
  2009. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  2010. * @param id - The ID of this connection
  2011. * @param pw - The password for this connection
  2012. */
  2013. FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
  2014. this.myID = id;
  2015. this.myPW = pw;
  2016. this.alive = true;
  2017. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  2018. while (this.newRequest_()) { }
  2019. };
  2020. /**
  2021. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  2022. * too many outstanding requests and we are still alive.
  2023. *
  2024. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  2025. * needed.
  2026. */
  2027. FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
  2028. // We keep one outstanding request open all the time to receive data, but if we need to send data
  2029. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  2030. // close the old request.
  2031. if (this.alive &&
  2032. this.sendNewPolls &&
  2033. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  2034. //construct our url
  2035. this.currentSerial++;
  2036. var urlParams = {};
  2037. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  2038. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  2039. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  2040. var theURL = this.urlFn(urlParams);
  2041. //Now add as much data as we can.
  2042. var curDataString = '';
  2043. var i = 0;
  2044. while (this.pendingSegs.length > 0) {
  2045. //first, lets see if the next segment will fit.
  2046. var nextSeg = this.pendingSegs[0];
  2047. if (nextSeg.d.length +
  2048. SEG_HEADER_SIZE +
  2049. curDataString.length <=
  2050. MAX_URL_DATA_SIZE) {
  2051. //great, the segment will fit. Lets append it.
  2052. var theSeg = this.pendingSegs.shift();
  2053. curDataString =
  2054. curDataString +
  2055. '&' +
  2056. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  2057. i +
  2058. '=' +
  2059. theSeg.seg +
  2060. '&' +
  2061. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  2062. i +
  2063. '=' +
  2064. theSeg.ts +
  2065. '&' +
  2066. FIREBASE_LONGPOLL_DATA_PARAM +
  2067. i +
  2068. '=' +
  2069. theSeg.d;
  2070. i++;
  2071. }
  2072. else {
  2073. break;
  2074. }
  2075. }
  2076. theURL = theURL + curDataString;
  2077. this.addLongPollTag_(theURL, this.currentSerial);
  2078. return true;
  2079. }
  2080. else {
  2081. return false;
  2082. }
  2083. };
  2084. /**
  2085. * Queue a packet for transmission to the server.
  2086. * @param segnum - A sequential id for this packet segment used for reassembly
  2087. * @param totalsegs - The total number of segments in this packet
  2088. * @param data - The data for this segment.
  2089. */
  2090. FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
  2091. //add this to the queue of segments to send.
  2092. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2093. //send the data immediately if there isn't already data being transmitted, unless
  2094. //startLongPoll hasn't been called yet.
  2095. if (this.alive) {
  2096. this.newRequest_();
  2097. }
  2098. };
  2099. /**
  2100. * Add a script tag for a regular long-poll request.
  2101. * @param url - The URL of the script tag.
  2102. * @param serial - The serial number of the request.
  2103. */
  2104. FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
  2105. var _this = this;
  2106. //remember that we sent this request.
  2107. this.outstandingRequests.add(serial);
  2108. var doNewRequest = function () {
  2109. _this.outstandingRequests.delete(serial);
  2110. _this.newRequest_();
  2111. };
  2112. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2113. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2114. var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2115. var readyStateCB = function () {
  2116. // Request completed. Cancel the keepalive.
  2117. clearTimeout(keepaliveTimeout);
  2118. // Trigger a new request so we can continue receiving data.
  2119. doNewRequest();
  2120. };
  2121. this.addTag(url, readyStateCB);
  2122. };
  2123. /**
  2124. * Add an arbitrary script tag to the iframe.
  2125. * @param url - The URL for the script tag source.
  2126. * @param loadCB - A callback to be triggered once the script has loaded.
  2127. */
  2128. FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
  2129. var _this = this;
  2130. if (util.isNodeSdk()) {
  2131. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2132. this.doNodeLongPoll(url, loadCB);
  2133. }
  2134. else {
  2135. setTimeout(function () {
  2136. try {
  2137. // if we're already closed, don't add this poll
  2138. if (!_this.sendNewPolls) {
  2139. return;
  2140. }
  2141. var newScript_1 = _this.myIFrame.doc.createElement('script');
  2142. newScript_1.type = 'text/javascript';
  2143. newScript_1.async = true;
  2144. newScript_1.src = url;
  2145. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2146. newScript_1.onload = newScript_1.onreadystatechange =
  2147. function () {
  2148. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2149. var rstate = newScript_1.readyState;
  2150. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2151. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2152. newScript_1.onload = newScript_1.onreadystatechange = null;
  2153. if (newScript_1.parentNode) {
  2154. newScript_1.parentNode.removeChild(newScript_1);
  2155. }
  2156. loadCB();
  2157. }
  2158. };
  2159. newScript_1.onerror = function () {
  2160. log('Long-poll script failed to load: ' + url);
  2161. _this.sendNewPolls = false;
  2162. _this.close();
  2163. };
  2164. _this.myIFrame.doc.body.appendChild(newScript_1);
  2165. }
  2166. catch (e) {
  2167. // TODO: we should make this error visible somehow
  2168. }
  2169. }, Math.floor(1));
  2170. }
  2171. };
  2172. return FirebaseIFrameScriptHolder;
  2173. }());
  2174. /**
  2175. * @license
  2176. * Copyright 2017 Google LLC
  2177. *
  2178. * Licensed under the Apache License, Version 2.0 (the "License");
  2179. * you may not use this file except in compliance with the License.
  2180. * You may obtain a copy of the License at
  2181. *
  2182. * http://www.apache.org/licenses/LICENSE-2.0
  2183. *
  2184. * Unless required by applicable law or agreed to in writing, software
  2185. * distributed under the License is distributed on an "AS IS" BASIS,
  2186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2187. * See the License for the specific language governing permissions and
  2188. * limitations under the License.
  2189. */
  2190. /**
  2191. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2192. * lifecycle.
  2193. *
  2194. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2195. * they are available.
  2196. */
  2197. var TransportManager = /** @class */ (function () {
  2198. /**
  2199. * @param repoInfo - Metadata around the namespace we're connecting to
  2200. */
  2201. function TransportManager(repoInfo) {
  2202. this.initTransports_(repoInfo);
  2203. }
  2204. Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
  2205. get: function () {
  2206. return [BrowserPollConnection, WebSocketConnection];
  2207. },
  2208. enumerable: false,
  2209. configurable: true
  2210. });
  2211. Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
  2212. /**
  2213. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2214. * TransportManager has already set up transports_
  2215. */
  2216. get: function () {
  2217. return this.globalTransportInitialized_;
  2218. },
  2219. enumerable: false,
  2220. configurable: true
  2221. });
  2222. TransportManager.prototype.initTransports_ = function (repoInfo) {
  2223. var e_1, _a;
  2224. var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2225. var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2226. if (repoInfo.webSocketOnly) {
  2227. if (!isWebSocketsAvailable) {
  2228. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2229. }
  2230. isSkipPollConnection = true;
  2231. }
  2232. if (isSkipPollConnection) {
  2233. this.transports_ = [WebSocketConnection];
  2234. }
  2235. else {
  2236. var transports = (this.transports_ = []);
  2237. try {
  2238. for (var _b = tslib.__values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
  2239. var transport = _c.value;
  2240. if (transport && transport['isAvailable']()) {
  2241. transports.push(transport);
  2242. }
  2243. }
  2244. }
  2245. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2246. finally {
  2247. try {
  2248. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  2249. }
  2250. finally { if (e_1) throw e_1.error; }
  2251. }
  2252. TransportManager.globalTransportInitialized_ = true;
  2253. }
  2254. };
  2255. /**
  2256. * @returns The constructor for the initial transport to use
  2257. */
  2258. TransportManager.prototype.initialTransport = function () {
  2259. if (this.transports_.length > 0) {
  2260. return this.transports_[0];
  2261. }
  2262. else {
  2263. throw new Error('No transports available');
  2264. }
  2265. };
  2266. /**
  2267. * @returns The constructor for the next transport, or null
  2268. */
  2269. TransportManager.prototype.upgradeTransport = function () {
  2270. if (this.transports_.length > 1) {
  2271. return this.transports_[1];
  2272. }
  2273. else {
  2274. return null;
  2275. }
  2276. };
  2277. // Keeps track of whether the TransportManager has already chosen a transport to use
  2278. TransportManager.globalTransportInitialized_ = false;
  2279. return TransportManager;
  2280. }());
  2281. /**
  2282. * @license
  2283. * Copyright 2017 Google LLC
  2284. *
  2285. * Licensed under the Apache License, Version 2.0 (the "License");
  2286. * you may not use this file except in compliance with the License.
  2287. * You may obtain a copy of the License at
  2288. *
  2289. * http://www.apache.org/licenses/LICENSE-2.0
  2290. *
  2291. * Unless required by applicable law or agreed to in writing, software
  2292. * distributed under the License is distributed on an "AS IS" BASIS,
  2293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2294. * See the License for the specific language governing permissions and
  2295. * limitations under the License.
  2296. */
  2297. // Abort upgrade attempt if it takes longer than 60s.
  2298. var UPGRADE_TIMEOUT = 60000;
  2299. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2300. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2301. var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2302. // 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)
  2303. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2304. // but we've sent/received enough bytes, we don't cancel the connection.
  2305. var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2306. var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2307. var MESSAGE_TYPE = 't';
  2308. var MESSAGE_DATA = 'd';
  2309. var CONTROL_SHUTDOWN = 's';
  2310. var CONTROL_RESET = 'r';
  2311. var CONTROL_ERROR = 'e';
  2312. var CONTROL_PONG = 'o';
  2313. var SWITCH_ACK = 'a';
  2314. var END_TRANSMISSION = 'n';
  2315. var PING = 'p';
  2316. var SERVER_HELLO = 'h';
  2317. /**
  2318. * Creates a new real-time connection to the server using whichever method works
  2319. * best in the current browser.
  2320. */
  2321. var Connection = /** @class */ (function () {
  2322. /**
  2323. * @param id - an id for this connection
  2324. * @param repoInfo_ - the info for the endpoint to connect to
  2325. * @param applicationId_ - the Firebase App ID for this project
  2326. * @param appCheckToken_ - The App Check Token for this device.
  2327. * @param authToken_ - The auth token for this session.
  2328. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2329. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2330. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2331. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2332. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2333. */
  2334. function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2335. this.id = id;
  2336. this.repoInfo_ = repoInfo_;
  2337. this.applicationId_ = applicationId_;
  2338. this.appCheckToken_ = appCheckToken_;
  2339. this.authToken_ = authToken_;
  2340. this.onMessage_ = onMessage_;
  2341. this.onReady_ = onReady_;
  2342. this.onDisconnect_ = onDisconnect_;
  2343. this.onKill_ = onKill_;
  2344. this.lastSessionId = lastSessionId;
  2345. this.connectionCount = 0;
  2346. this.pendingDataMessages = [];
  2347. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2348. this.log_ = logWrapper('c:' + this.id + ':');
  2349. this.transportManager_ = new TransportManager(repoInfo_);
  2350. this.log_('Connection created');
  2351. this.start_();
  2352. }
  2353. /**
  2354. * Starts a connection attempt
  2355. */
  2356. Connection.prototype.start_ = function () {
  2357. var _this = this;
  2358. var conn = this.transportManager_.initialTransport();
  2359. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2360. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2361. // can consider the transport healthy.
  2362. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2363. var onMessageReceived = this.connReceiver_(this.conn_);
  2364. var onConnectionLost = this.disconnReceiver_(this.conn_);
  2365. this.tx_ = this.conn_;
  2366. this.rx_ = this.conn_;
  2367. this.secondaryConn_ = null;
  2368. this.isHealthy_ = false;
  2369. /*
  2370. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2371. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2372. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2373. * still have the context of your originating frame.
  2374. */
  2375. setTimeout(function () {
  2376. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2377. _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
  2378. }, Math.floor(0));
  2379. var healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2380. if (healthyTimeoutMS > 0) {
  2381. this.healthyTimeout_ = setTimeoutNonBlocking(function () {
  2382. _this.healthyTimeout_ = null;
  2383. if (!_this.isHealthy_) {
  2384. if (_this.conn_ &&
  2385. _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2386. _this.log_('Connection exceeded healthy timeout but has received ' +
  2387. _this.conn_.bytesReceived +
  2388. ' bytes. Marking connection healthy.');
  2389. _this.isHealthy_ = true;
  2390. _this.conn_.markConnectionHealthy();
  2391. }
  2392. else if (_this.conn_ &&
  2393. _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2394. _this.log_('Connection exceeded healthy timeout but has sent ' +
  2395. _this.conn_.bytesSent +
  2396. ' bytes. Leaving connection alive.');
  2397. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2398. // the server.
  2399. }
  2400. else {
  2401. _this.log_('Closing unhealthy connection after timeout.');
  2402. _this.close();
  2403. }
  2404. }
  2405. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2406. }, Math.floor(healthyTimeoutMS));
  2407. }
  2408. };
  2409. Connection.prototype.nextTransportId_ = function () {
  2410. return 'c:' + this.id + ':' + this.connectionCount++;
  2411. };
  2412. Connection.prototype.disconnReceiver_ = function (conn) {
  2413. var _this = this;
  2414. return function (everConnected) {
  2415. if (conn === _this.conn_) {
  2416. _this.onConnectionLost_(everConnected);
  2417. }
  2418. else if (conn === _this.secondaryConn_) {
  2419. _this.log_('Secondary connection lost.');
  2420. _this.onSecondaryConnectionLost_();
  2421. }
  2422. else {
  2423. _this.log_('closing an old connection');
  2424. }
  2425. };
  2426. };
  2427. Connection.prototype.connReceiver_ = function (conn) {
  2428. var _this = this;
  2429. return function (message) {
  2430. if (_this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2431. if (conn === _this.rx_) {
  2432. _this.onPrimaryMessageReceived_(message);
  2433. }
  2434. else if (conn === _this.secondaryConn_) {
  2435. _this.onSecondaryMessageReceived_(message);
  2436. }
  2437. else {
  2438. _this.log_('message on old connection');
  2439. }
  2440. }
  2441. };
  2442. };
  2443. /**
  2444. * @param dataMsg - An arbitrary data message to be sent to the server
  2445. */
  2446. Connection.prototype.sendRequest = function (dataMsg) {
  2447. // wrap in a data message envelope and send it on
  2448. var msg = { t: 'd', d: dataMsg };
  2449. this.sendData_(msg);
  2450. };
  2451. Connection.prototype.tryCleanupConnection = function () {
  2452. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2453. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2454. this.conn_ = this.secondaryConn_;
  2455. this.secondaryConn_ = null;
  2456. // the server will shutdown the old connection
  2457. }
  2458. };
  2459. Connection.prototype.onSecondaryControl_ = function (controlData) {
  2460. if (MESSAGE_TYPE in controlData) {
  2461. var cmd = controlData[MESSAGE_TYPE];
  2462. if (cmd === SWITCH_ACK) {
  2463. this.upgradeIfSecondaryHealthy_();
  2464. }
  2465. else if (cmd === CONTROL_RESET) {
  2466. // Most likely the session wasn't valid. Abandon the switch attempt
  2467. this.log_('Got a reset on secondary, closing it');
  2468. this.secondaryConn_.close();
  2469. // If we were already using this connection for something, than we need to fully close
  2470. if (this.tx_ === this.secondaryConn_ ||
  2471. this.rx_ === this.secondaryConn_) {
  2472. this.close();
  2473. }
  2474. }
  2475. else if (cmd === CONTROL_PONG) {
  2476. this.log_('got pong on secondary.');
  2477. this.secondaryResponsesRequired_--;
  2478. this.upgradeIfSecondaryHealthy_();
  2479. }
  2480. }
  2481. };
  2482. Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
  2483. var layer = requireKey('t', parsedData);
  2484. var data = requireKey('d', parsedData);
  2485. if (layer === 'c') {
  2486. this.onSecondaryControl_(data);
  2487. }
  2488. else if (layer === 'd') {
  2489. // got a data message, but we're still second connection. Need to buffer it up
  2490. this.pendingDataMessages.push(data);
  2491. }
  2492. else {
  2493. throw new Error('Unknown protocol layer: ' + layer);
  2494. }
  2495. };
  2496. Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
  2497. if (this.secondaryResponsesRequired_ <= 0) {
  2498. this.log_('Secondary connection is healthy.');
  2499. this.isHealthy_ = true;
  2500. this.secondaryConn_.markConnectionHealthy();
  2501. this.proceedWithUpgrade_();
  2502. }
  2503. else {
  2504. // Send a ping to make sure the connection is healthy.
  2505. this.log_('sending ping on secondary.');
  2506. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2507. }
  2508. };
  2509. Connection.prototype.proceedWithUpgrade_ = function () {
  2510. // tell this connection to consider itself open
  2511. this.secondaryConn_.start();
  2512. // send ack
  2513. this.log_('sending client ack on secondary');
  2514. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2515. // send end packet on primary transport, switch to sending on this one
  2516. // can receive on this one, buffer responses until end received on primary transport
  2517. this.log_('Ending transmission on primary');
  2518. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2519. this.tx_ = this.secondaryConn_;
  2520. this.tryCleanupConnection();
  2521. };
  2522. Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
  2523. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2524. var layer = requireKey('t', parsedData);
  2525. var data = requireKey('d', parsedData);
  2526. if (layer === 'c') {
  2527. this.onControl_(data);
  2528. }
  2529. else if (layer === 'd') {
  2530. this.onDataMessage_(data);
  2531. }
  2532. };
  2533. Connection.prototype.onDataMessage_ = function (message) {
  2534. this.onPrimaryResponse_();
  2535. // We don't do anything with data messages, just kick them up a level
  2536. this.onMessage_(message);
  2537. };
  2538. Connection.prototype.onPrimaryResponse_ = function () {
  2539. if (!this.isHealthy_) {
  2540. this.primaryResponsesRequired_--;
  2541. if (this.primaryResponsesRequired_ <= 0) {
  2542. this.log_('Primary connection is healthy.');
  2543. this.isHealthy_ = true;
  2544. this.conn_.markConnectionHealthy();
  2545. }
  2546. }
  2547. };
  2548. Connection.prototype.onControl_ = function (controlData) {
  2549. var cmd = requireKey(MESSAGE_TYPE, controlData);
  2550. if (MESSAGE_DATA in controlData) {
  2551. var payload = controlData[MESSAGE_DATA];
  2552. if (cmd === SERVER_HELLO) {
  2553. var handshakePayload = tslib.__assign({}, payload);
  2554. if (this.repoInfo_.isUsingEmulator) {
  2555. // 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.
  2556. handshakePayload.h = this.repoInfo_.host;
  2557. }
  2558. this.onHandshake_(handshakePayload);
  2559. }
  2560. else if (cmd === END_TRANSMISSION) {
  2561. this.log_('recvd end transmission on primary');
  2562. this.rx_ = this.secondaryConn_;
  2563. for (var i = 0; i < this.pendingDataMessages.length; ++i) {
  2564. this.onDataMessage_(this.pendingDataMessages[i]);
  2565. }
  2566. this.pendingDataMessages = [];
  2567. this.tryCleanupConnection();
  2568. }
  2569. else if (cmd === CONTROL_SHUTDOWN) {
  2570. // This was previously the 'onKill' callback passed to the lower-level connection
  2571. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2572. this.onConnectionShutdown_(payload);
  2573. }
  2574. else if (cmd === CONTROL_RESET) {
  2575. // payload in this case is the host we should contact
  2576. this.onReset_(payload);
  2577. }
  2578. else if (cmd === CONTROL_ERROR) {
  2579. error('Server Error: ' + payload);
  2580. }
  2581. else if (cmd === CONTROL_PONG) {
  2582. this.log_('got pong on primary.');
  2583. this.onPrimaryResponse_();
  2584. this.sendPingOnPrimaryIfNecessary_();
  2585. }
  2586. else {
  2587. error('Unknown control packet command: ' + cmd);
  2588. }
  2589. }
  2590. };
  2591. /**
  2592. * @param handshake - The handshake data returned from the server
  2593. */
  2594. Connection.prototype.onHandshake_ = function (handshake) {
  2595. var timestamp = handshake.ts;
  2596. var version = handshake.v;
  2597. var host = handshake.h;
  2598. this.sessionId = handshake.s;
  2599. this.repoInfo_.host = host;
  2600. // if we've already closed the connection, then don't bother trying to progress further
  2601. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2602. this.conn_.start();
  2603. this.onConnectionEstablished_(this.conn_, timestamp);
  2604. if (PROTOCOL_VERSION !== version) {
  2605. warn('Protocol version mismatch detected');
  2606. }
  2607. // TODO: do we want to upgrade? when? maybe a delay?
  2608. this.tryStartUpgrade_();
  2609. }
  2610. };
  2611. Connection.prototype.tryStartUpgrade_ = function () {
  2612. var conn = this.transportManager_.upgradeTransport();
  2613. if (conn) {
  2614. this.startUpgrade_(conn);
  2615. }
  2616. };
  2617. Connection.prototype.startUpgrade_ = function (conn) {
  2618. var _this = this;
  2619. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2620. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2621. // can consider the transport healthy.
  2622. this.secondaryResponsesRequired_ =
  2623. conn['responsesRequiredToBeHealthy'] || 0;
  2624. var onMessage = this.connReceiver_(this.secondaryConn_);
  2625. var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2626. this.secondaryConn_.open(onMessage, onDisconnect);
  2627. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2628. setTimeoutNonBlocking(function () {
  2629. if (_this.secondaryConn_) {
  2630. _this.log_('Timed out trying to upgrade.');
  2631. _this.secondaryConn_.close();
  2632. }
  2633. }, Math.floor(UPGRADE_TIMEOUT));
  2634. };
  2635. Connection.prototype.onReset_ = function (host) {
  2636. this.log_('Reset packet received. New host: ' + host);
  2637. this.repoInfo_.host = host;
  2638. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2639. // We don't currently support resets after the connection has already been established
  2640. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2641. this.close();
  2642. }
  2643. else {
  2644. // Close whatever connections we have open and start again.
  2645. this.closeConnections_();
  2646. this.start_();
  2647. }
  2648. };
  2649. Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
  2650. var _this = this;
  2651. this.log_('Realtime connection established.');
  2652. this.conn_ = conn;
  2653. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2654. if (this.onReady_) {
  2655. this.onReady_(timestamp, this.sessionId);
  2656. this.onReady_ = null;
  2657. }
  2658. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2659. // send some pings.
  2660. if (this.primaryResponsesRequired_ === 0) {
  2661. this.log_('Primary connection is healthy.');
  2662. this.isHealthy_ = true;
  2663. }
  2664. else {
  2665. setTimeoutNonBlocking(function () {
  2666. _this.sendPingOnPrimaryIfNecessary_();
  2667. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2668. }
  2669. };
  2670. Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
  2671. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2672. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2673. this.log_('sending ping on primary.');
  2674. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2675. }
  2676. };
  2677. Connection.prototype.onSecondaryConnectionLost_ = function () {
  2678. var conn = this.secondaryConn_;
  2679. this.secondaryConn_ = null;
  2680. if (this.tx_ === conn || this.rx_ === conn) {
  2681. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2682. this.close();
  2683. }
  2684. };
  2685. /**
  2686. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2687. * we should flush the host cache
  2688. */
  2689. Connection.prototype.onConnectionLost_ = function (everConnected) {
  2690. this.conn_ = null;
  2691. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2692. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2693. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2694. this.log_('Realtime connection failed.');
  2695. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2696. if (this.repoInfo_.isCacheableHost()) {
  2697. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2698. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2699. this.repoInfo_.internalHost = this.repoInfo_.host;
  2700. }
  2701. }
  2702. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2703. this.log_('Realtime connection lost.');
  2704. }
  2705. this.close();
  2706. };
  2707. Connection.prototype.onConnectionShutdown_ = function (reason) {
  2708. this.log_('Connection shutdown command received. Shutting down...');
  2709. if (this.onKill_) {
  2710. this.onKill_(reason);
  2711. this.onKill_ = null;
  2712. }
  2713. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2714. // so clear the callback.
  2715. this.onDisconnect_ = null;
  2716. this.close();
  2717. };
  2718. Connection.prototype.sendData_ = function (data) {
  2719. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2720. throw 'Connection is not connected';
  2721. }
  2722. else {
  2723. this.tx_.send(data);
  2724. }
  2725. };
  2726. /**
  2727. * Cleans up this connection, calling the appropriate callbacks
  2728. */
  2729. Connection.prototype.close = function () {
  2730. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2731. this.log_('Closing realtime connection.');
  2732. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2733. this.closeConnections_();
  2734. if (this.onDisconnect_) {
  2735. this.onDisconnect_();
  2736. this.onDisconnect_ = null;
  2737. }
  2738. }
  2739. };
  2740. Connection.prototype.closeConnections_ = function () {
  2741. this.log_('Shutting down all connections');
  2742. if (this.conn_) {
  2743. this.conn_.close();
  2744. this.conn_ = null;
  2745. }
  2746. if (this.secondaryConn_) {
  2747. this.secondaryConn_.close();
  2748. this.secondaryConn_ = null;
  2749. }
  2750. if (this.healthyTimeout_) {
  2751. clearTimeout(this.healthyTimeout_);
  2752. this.healthyTimeout_ = null;
  2753. }
  2754. };
  2755. return Connection;
  2756. }());
  2757. /**
  2758. * @license
  2759. * Copyright 2017 Google LLC
  2760. *
  2761. * Licensed under the Apache License, Version 2.0 (the "License");
  2762. * you may not use this file except in compliance with the License.
  2763. * You may obtain a copy of the License at
  2764. *
  2765. * http://www.apache.org/licenses/LICENSE-2.0
  2766. *
  2767. * Unless required by applicable law or agreed to in writing, software
  2768. * distributed under the License is distributed on an "AS IS" BASIS,
  2769. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2770. * See the License for the specific language governing permissions and
  2771. * limitations under the License.
  2772. */
  2773. /**
  2774. * Interface defining the set of actions that can be performed against the Firebase server
  2775. * (basically corresponds to our wire protocol).
  2776. *
  2777. * @interface
  2778. */
  2779. var ServerActions = /** @class */ (function () {
  2780. function ServerActions() {
  2781. }
  2782. ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
  2783. ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
  2784. /**
  2785. * Refreshes the auth token for the current connection.
  2786. * @param token - The authentication token
  2787. */
  2788. ServerActions.prototype.refreshAuthToken = function (token) { };
  2789. /**
  2790. * Refreshes the app check token for the current connection.
  2791. * @param token The app check token
  2792. */
  2793. ServerActions.prototype.refreshAppCheckToken = function (token) { };
  2794. ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
  2795. ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
  2796. ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
  2797. ServerActions.prototype.reportStats = function (stats) { };
  2798. return ServerActions;
  2799. }());
  2800. /**
  2801. * @license
  2802. * Copyright 2017 Google LLC
  2803. *
  2804. * Licensed under the Apache License, Version 2.0 (the "License");
  2805. * you may not use this file except in compliance with the License.
  2806. * You may obtain a copy of the License at
  2807. *
  2808. * http://www.apache.org/licenses/LICENSE-2.0
  2809. *
  2810. * Unless required by applicable law or agreed to in writing, software
  2811. * distributed under the License is distributed on an "AS IS" BASIS,
  2812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2813. * See the License for the specific language governing permissions and
  2814. * limitations under the License.
  2815. */
  2816. /**
  2817. * Base class to be used if you want to emit events. Call the constructor with
  2818. * the set of allowed event names.
  2819. */
  2820. var EventEmitter = /** @class */ (function () {
  2821. function EventEmitter(allowedEvents_) {
  2822. this.allowedEvents_ = allowedEvents_;
  2823. this.listeners_ = {};
  2824. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2825. }
  2826. /**
  2827. * To be called by derived classes to trigger events.
  2828. */
  2829. EventEmitter.prototype.trigger = function (eventType) {
  2830. var varArgs = [];
  2831. for (var _i = 1; _i < arguments.length; _i++) {
  2832. varArgs[_i - 1] = arguments[_i];
  2833. }
  2834. if (Array.isArray(this.listeners_[eventType])) {
  2835. // Clone the list, since callbacks could add/remove listeners.
  2836. var listeners = tslib.__spreadArray([], tslib.__read(this.listeners_[eventType]), false);
  2837. for (var i = 0; i < listeners.length; i++) {
  2838. listeners[i].callback.apply(listeners[i].context, varArgs);
  2839. }
  2840. }
  2841. };
  2842. EventEmitter.prototype.on = function (eventType, callback, context) {
  2843. this.validateEventType_(eventType);
  2844. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2845. this.listeners_[eventType].push({ callback: callback, context: context });
  2846. var eventData = this.getInitialEvent(eventType);
  2847. if (eventData) {
  2848. callback.apply(context, eventData);
  2849. }
  2850. };
  2851. EventEmitter.prototype.off = function (eventType, callback, context) {
  2852. this.validateEventType_(eventType);
  2853. var listeners = this.listeners_[eventType] || [];
  2854. for (var i = 0; i < listeners.length; i++) {
  2855. if (listeners[i].callback === callback &&
  2856. (!context || context === listeners[i].context)) {
  2857. listeners.splice(i, 1);
  2858. return;
  2859. }
  2860. }
  2861. };
  2862. EventEmitter.prototype.validateEventType_ = function (eventType) {
  2863. util.assert(this.allowedEvents_.find(function (et) {
  2864. return et === eventType;
  2865. }), 'Unknown event: ' + eventType);
  2866. };
  2867. return EventEmitter;
  2868. }());
  2869. /**
  2870. * @license
  2871. * Copyright 2017 Google LLC
  2872. *
  2873. * Licensed under the Apache License, Version 2.0 (the "License");
  2874. * you may not use this file except in compliance with the License.
  2875. * You may obtain a copy of the License at
  2876. *
  2877. * http://www.apache.org/licenses/LICENSE-2.0
  2878. *
  2879. * Unless required by applicable law or agreed to in writing, software
  2880. * distributed under the License is distributed on an "AS IS" BASIS,
  2881. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2882. * See the License for the specific language governing permissions and
  2883. * limitations under the License.
  2884. */
  2885. /**
  2886. * Monitors online state (as reported by window.online/offline events).
  2887. *
  2888. * The expectation is that this could have many false positives (thinks we are online
  2889. * when we're not), but no false negatives. So we can safely use it to determine when
  2890. * we definitely cannot reach the internet.
  2891. */
  2892. var OnlineMonitor = /** @class */ (function (_super) {
  2893. tslib.__extends(OnlineMonitor, _super);
  2894. function OnlineMonitor() {
  2895. var _this = _super.call(this, ['online']) || this;
  2896. _this.online_ = true;
  2897. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2898. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2899. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2900. // for Cordova.
  2901. if (typeof window !== 'undefined' &&
  2902. typeof window.addEventListener !== 'undefined' &&
  2903. !util.isMobileCordova()) {
  2904. window.addEventListener('online', function () {
  2905. if (!_this.online_) {
  2906. _this.online_ = true;
  2907. _this.trigger('online', true);
  2908. }
  2909. }, false);
  2910. window.addEventListener('offline', function () {
  2911. if (_this.online_) {
  2912. _this.online_ = false;
  2913. _this.trigger('online', false);
  2914. }
  2915. }, false);
  2916. }
  2917. return _this;
  2918. }
  2919. OnlineMonitor.getInstance = function () {
  2920. return new OnlineMonitor();
  2921. };
  2922. OnlineMonitor.prototype.getInitialEvent = function (eventType) {
  2923. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2924. return [this.online_];
  2925. };
  2926. OnlineMonitor.prototype.currentlyOnline = function () {
  2927. return this.online_;
  2928. };
  2929. return OnlineMonitor;
  2930. }(EventEmitter));
  2931. /**
  2932. * @license
  2933. * Copyright 2017 Google LLC
  2934. *
  2935. * Licensed under the Apache License, Version 2.0 (the "License");
  2936. * you may not use this file except in compliance with the License.
  2937. * You may obtain a copy of the License at
  2938. *
  2939. * http://www.apache.org/licenses/LICENSE-2.0
  2940. *
  2941. * Unless required by applicable law or agreed to in writing, software
  2942. * distributed under the License is distributed on an "AS IS" BASIS,
  2943. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2944. * See the License for the specific language governing permissions and
  2945. * limitations under the License.
  2946. */
  2947. /** Maximum key depth. */
  2948. var MAX_PATH_DEPTH = 32;
  2949. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2950. var MAX_PATH_LENGTH_BYTES = 768;
  2951. /**
  2952. * An immutable object representing a parsed path. It's immutable so that you
  2953. * can pass them around to other functions without worrying about them changing
  2954. * it.
  2955. */
  2956. var Path = /** @class */ (function () {
  2957. /**
  2958. * @param pathOrString - Path string to parse, or another path, or the raw
  2959. * tokens array
  2960. */
  2961. function Path(pathOrString, pieceNum) {
  2962. if (pieceNum === void 0) {
  2963. this.pieces_ = pathOrString.split('/');
  2964. // Remove empty pieces.
  2965. var copyTo = 0;
  2966. for (var i = 0; i < this.pieces_.length; i++) {
  2967. if (this.pieces_[i].length > 0) {
  2968. this.pieces_[copyTo] = this.pieces_[i];
  2969. copyTo++;
  2970. }
  2971. }
  2972. this.pieces_.length = copyTo;
  2973. this.pieceNum_ = 0;
  2974. }
  2975. else {
  2976. this.pieces_ = pathOrString;
  2977. this.pieceNum_ = pieceNum;
  2978. }
  2979. }
  2980. Path.prototype.toString = function () {
  2981. var pathString = '';
  2982. for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
  2983. if (this.pieces_[i] !== '') {
  2984. pathString += '/' + this.pieces_[i];
  2985. }
  2986. }
  2987. return pathString || '/';
  2988. };
  2989. return Path;
  2990. }());
  2991. function newEmptyPath() {
  2992. return new Path('');
  2993. }
  2994. function pathGetFront(path) {
  2995. if (path.pieceNum_ >= path.pieces_.length) {
  2996. return null;
  2997. }
  2998. return path.pieces_[path.pieceNum_];
  2999. }
  3000. /**
  3001. * @returns The number of segments in this path
  3002. */
  3003. function pathGetLength(path) {
  3004. return path.pieces_.length - path.pieceNum_;
  3005. }
  3006. function pathPopFront(path) {
  3007. var pieceNum = path.pieceNum_;
  3008. if (pieceNum < path.pieces_.length) {
  3009. pieceNum++;
  3010. }
  3011. return new Path(path.pieces_, pieceNum);
  3012. }
  3013. function pathGetBack(path) {
  3014. if (path.pieceNum_ < path.pieces_.length) {
  3015. return path.pieces_[path.pieces_.length - 1];
  3016. }
  3017. return null;
  3018. }
  3019. function pathToUrlEncodedString(path) {
  3020. var pathString = '';
  3021. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3022. if (path.pieces_[i] !== '') {
  3023. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  3024. }
  3025. }
  3026. return pathString || '/';
  3027. }
  3028. /**
  3029. * Shallow copy of the parts of the path.
  3030. *
  3031. */
  3032. function pathSlice(path, begin) {
  3033. if (begin === void 0) { begin = 0; }
  3034. return path.pieces_.slice(path.pieceNum_ + begin);
  3035. }
  3036. function pathParent(path) {
  3037. if (path.pieceNum_ >= path.pieces_.length) {
  3038. return null;
  3039. }
  3040. var pieces = [];
  3041. for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  3042. pieces.push(path.pieces_[i]);
  3043. }
  3044. return new Path(pieces, 0);
  3045. }
  3046. function pathChild(path, childPathObj) {
  3047. var pieces = [];
  3048. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3049. pieces.push(path.pieces_[i]);
  3050. }
  3051. if (childPathObj instanceof Path) {
  3052. for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  3053. pieces.push(childPathObj.pieces_[i]);
  3054. }
  3055. }
  3056. else {
  3057. var childPieces = childPathObj.split('/');
  3058. for (var i = 0; i < childPieces.length; i++) {
  3059. if (childPieces[i].length > 0) {
  3060. pieces.push(childPieces[i]);
  3061. }
  3062. }
  3063. }
  3064. return new Path(pieces, 0);
  3065. }
  3066. /**
  3067. * @returns True if there are no segments in this path
  3068. */
  3069. function pathIsEmpty(path) {
  3070. return path.pieceNum_ >= path.pieces_.length;
  3071. }
  3072. /**
  3073. * @returns The path from outerPath to innerPath
  3074. */
  3075. function newRelativePath(outerPath, innerPath) {
  3076. var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  3077. if (outer === null) {
  3078. return innerPath;
  3079. }
  3080. else if (outer === inner) {
  3081. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  3082. }
  3083. else {
  3084. throw new Error('INTERNAL ERROR: innerPath (' +
  3085. innerPath +
  3086. ') is not within ' +
  3087. 'outerPath (' +
  3088. outerPath +
  3089. ')');
  3090. }
  3091. }
  3092. /**
  3093. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  3094. */
  3095. function pathCompare(left, right) {
  3096. var leftKeys = pathSlice(left, 0);
  3097. var rightKeys = pathSlice(right, 0);
  3098. for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  3099. var cmp = nameCompare(leftKeys[i], rightKeys[i]);
  3100. if (cmp !== 0) {
  3101. return cmp;
  3102. }
  3103. }
  3104. if (leftKeys.length === rightKeys.length) {
  3105. return 0;
  3106. }
  3107. return leftKeys.length < rightKeys.length ? -1 : 1;
  3108. }
  3109. /**
  3110. * @returns true if paths are the same.
  3111. */
  3112. function pathEquals(path, other) {
  3113. if (pathGetLength(path) !== pathGetLength(other)) {
  3114. return false;
  3115. }
  3116. for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3117. if (path.pieces_[i] !== other.pieces_[j]) {
  3118. return false;
  3119. }
  3120. }
  3121. return true;
  3122. }
  3123. /**
  3124. * @returns True if this path is a parent of (or the same as) other
  3125. */
  3126. function pathContains(path, other) {
  3127. var i = path.pieceNum_;
  3128. var j = other.pieceNum_;
  3129. if (pathGetLength(path) > pathGetLength(other)) {
  3130. return false;
  3131. }
  3132. while (i < path.pieces_.length) {
  3133. if (path.pieces_[i] !== other.pieces_[j]) {
  3134. return false;
  3135. }
  3136. ++i;
  3137. ++j;
  3138. }
  3139. return true;
  3140. }
  3141. /**
  3142. * Dynamic (mutable) path used to count path lengths.
  3143. *
  3144. * This class is used to efficiently check paths for valid
  3145. * length (in UTF8 bytes) and depth (used in path validation).
  3146. *
  3147. * Throws Error exception if path is ever invalid.
  3148. *
  3149. * The definition of a path always begins with '/'.
  3150. */
  3151. var ValidationPath = /** @class */ (function () {
  3152. /**
  3153. * @param path - Initial Path.
  3154. * @param errorPrefix_ - Prefix for any error messages.
  3155. */
  3156. function ValidationPath(path, errorPrefix_) {
  3157. this.errorPrefix_ = errorPrefix_;
  3158. this.parts_ = pathSlice(path, 0);
  3159. /** Initialize to number of '/' chars needed in path. */
  3160. this.byteLength_ = Math.max(1, this.parts_.length);
  3161. for (var i = 0; i < this.parts_.length; i++) {
  3162. this.byteLength_ += util.stringLength(this.parts_[i]);
  3163. }
  3164. validationPathCheckValid(this);
  3165. }
  3166. return ValidationPath;
  3167. }());
  3168. function validationPathPush(validationPath, child) {
  3169. // Count the needed '/'
  3170. if (validationPath.parts_.length > 0) {
  3171. validationPath.byteLength_ += 1;
  3172. }
  3173. validationPath.parts_.push(child);
  3174. validationPath.byteLength_ += util.stringLength(child);
  3175. validationPathCheckValid(validationPath);
  3176. }
  3177. function validationPathPop(validationPath) {
  3178. var last = validationPath.parts_.pop();
  3179. validationPath.byteLength_ -= util.stringLength(last);
  3180. // Un-count the previous '/'
  3181. if (validationPath.parts_.length > 0) {
  3182. validationPath.byteLength_ -= 1;
  3183. }
  3184. }
  3185. function validationPathCheckValid(validationPath) {
  3186. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3187. throw new Error(validationPath.errorPrefix_ +
  3188. 'has a key path longer than ' +
  3189. MAX_PATH_LENGTH_BYTES +
  3190. ' bytes (' +
  3191. validationPath.byteLength_ +
  3192. ').');
  3193. }
  3194. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3195. throw new Error(validationPath.errorPrefix_ +
  3196. 'path specified exceeds the maximum depth that can be written (' +
  3197. MAX_PATH_DEPTH +
  3198. ') or object contains a cycle ' +
  3199. validationPathToErrorString(validationPath));
  3200. }
  3201. }
  3202. /**
  3203. * String for use in error messages - uses '.' notation for path.
  3204. */
  3205. function validationPathToErrorString(validationPath) {
  3206. if (validationPath.parts_.length === 0) {
  3207. return '';
  3208. }
  3209. return "in property '" + validationPath.parts_.join('.') + "'";
  3210. }
  3211. /**
  3212. * @license
  3213. * Copyright 2017 Google LLC
  3214. *
  3215. * Licensed under the Apache License, Version 2.0 (the "License");
  3216. * you may not use this file except in compliance with the License.
  3217. * You may obtain a copy of the License at
  3218. *
  3219. * http://www.apache.org/licenses/LICENSE-2.0
  3220. *
  3221. * Unless required by applicable law or agreed to in writing, software
  3222. * distributed under the License is distributed on an "AS IS" BASIS,
  3223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3224. * See the License for the specific language governing permissions and
  3225. * limitations under the License.
  3226. */
  3227. var VisibilityMonitor = /** @class */ (function (_super) {
  3228. tslib.__extends(VisibilityMonitor, _super);
  3229. function VisibilityMonitor() {
  3230. var _this = _super.call(this, ['visible']) || this;
  3231. var hidden;
  3232. var visibilityChange;
  3233. if (typeof document !== 'undefined' &&
  3234. typeof document.addEventListener !== 'undefined') {
  3235. if (typeof document['hidden'] !== 'undefined') {
  3236. // Opera 12.10 and Firefox 18 and later support
  3237. visibilityChange = 'visibilitychange';
  3238. hidden = 'hidden';
  3239. }
  3240. else if (typeof document['mozHidden'] !== 'undefined') {
  3241. visibilityChange = 'mozvisibilitychange';
  3242. hidden = 'mozHidden';
  3243. }
  3244. else if (typeof document['msHidden'] !== 'undefined') {
  3245. visibilityChange = 'msvisibilitychange';
  3246. hidden = 'msHidden';
  3247. }
  3248. else if (typeof document['webkitHidden'] !== 'undefined') {
  3249. visibilityChange = 'webkitvisibilitychange';
  3250. hidden = 'webkitHidden';
  3251. }
  3252. }
  3253. // Initially, we always assume we are visible. This ensures that in browsers
  3254. // without page visibility support or in cases where we are never visible
  3255. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3256. // reconnects
  3257. _this.visible_ = true;
  3258. if (visibilityChange) {
  3259. document.addEventListener(visibilityChange, function () {
  3260. var visible = !document[hidden];
  3261. if (visible !== _this.visible_) {
  3262. _this.visible_ = visible;
  3263. _this.trigger('visible', visible);
  3264. }
  3265. }, false);
  3266. }
  3267. return _this;
  3268. }
  3269. VisibilityMonitor.getInstance = function () {
  3270. return new VisibilityMonitor();
  3271. };
  3272. VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
  3273. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3274. return [this.visible_];
  3275. };
  3276. return VisibilityMonitor;
  3277. }(EventEmitter));
  3278. /**
  3279. * @license
  3280. * Copyright 2017 Google LLC
  3281. *
  3282. * Licensed under the Apache License, Version 2.0 (the "License");
  3283. * you may not use this file except in compliance with the License.
  3284. * You may obtain a copy of the License at
  3285. *
  3286. * http://www.apache.org/licenses/LICENSE-2.0
  3287. *
  3288. * Unless required by applicable law or agreed to in writing, software
  3289. * distributed under the License is distributed on an "AS IS" BASIS,
  3290. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3291. * See the License for the specific language governing permissions and
  3292. * limitations under the License.
  3293. */
  3294. var RECONNECT_MIN_DELAY = 1000;
  3295. var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3296. var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3297. var RECONNECT_DELAY_MULTIPLIER = 1.3;
  3298. var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3299. var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3300. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3301. var INVALID_TOKEN_THRESHOLD = 3;
  3302. /**
  3303. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3304. *
  3305. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3306. * in quotes to make sure the closure compiler does not minify them.
  3307. */
  3308. var PersistentConnection = /** @class */ (function (_super) {
  3309. tslib.__extends(PersistentConnection, _super);
  3310. /**
  3311. * @param repoInfo_ - Data about the namespace we are connecting to
  3312. * @param applicationId_ - The Firebase App ID for this project
  3313. * @param onDataUpdate_ - A callback for new data from the server
  3314. */
  3315. function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3316. var _this = _super.call(this) || this;
  3317. _this.repoInfo_ = repoInfo_;
  3318. _this.applicationId_ = applicationId_;
  3319. _this.onDataUpdate_ = onDataUpdate_;
  3320. _this.onConnectStatus_ = onConnectStatus_;
  3321. _this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3322. _this.authTokenProvider_ = authTokenProvider_;
  3323. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3324. _this.authOverride_ = authOverride_;
  3325. // Used for diagnostic logging.
  3326. _this.id = PersistentConnection.nextPersistentConnectionId_++;
  3327. _this.log_ = logWrapper('p:' + _this.id + ':');
  3328. _this.interruptReasons_ = {};
  3329. _this.listens = new Map();
  3330. _this.outstandingPuts_ = [];
  3331. _this.outstandingGets_ = [];
  3332. _this.outstandingPutCount_ = 0;
  3333. _this.outstandingGetCount_ = 0;
  3334. _this.onDisconnectRequestQueue_ = [];
  3335. _this.connected_ = false;
  3336. _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3337. _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3338. _this.securityDebugCallback_ = null;
  3339. _this.lastSessionId = null;
  3340. _this.establishConnectionTimer_ = null;
  3341. _this.visible_ = false;
  3342. // Before we get connected, we keep a queue of pending messages to send.
  3343. _this.requestCBHash_ = {};
  3344. _this.requestNumber_ = 0;
  3345. _this.realtime_ = null;
  3346. _this.authToken_ = null;
  3347. _this.appCheckToken_ = null;
  3348. _this.forceTokenRefresh_ = false;
  3349. _this.invalidAuthTokenCount_ = 0;
  3350. _this.invalidAppCheckTokenCount_ = 0;
  3351. _this.firstConnection_ = true;
  3352. _this.lastConnectionAttemptTime_ = null;
  3353. _this.lastConnectionEstablishedTime_ = null;
  3354. if (authOverride_ && !util.isNodeSdk()) {
  3355. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3356. }
  3357. VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
  3358. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3359. OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
  3360. }
  3361. return _this;
  3362. }
  3363. PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
  3364. var curReqNum = ++this.requestNumber_;
  3365. var msg = { r: curReqNum, a: action, b: body };
  3366. this.log_(util.stringify(msg));
  3367. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3368. this.realtime_.sendRequest(msg);
  3369. if (onResponse) {
  3370. this.requestCBHash_[curReqNum] = onResponse;
  3371. }
  3372. };
  3373. PersistentConnection.prototype.get = function (query) {
  3374. this.initConnection_();
  3375. var deferred = new util.Deferred();
  3376. var request = {
  3377. p: query._path.toString(),
  3378. q: query._queryObject
  3379. };
  3380. var outstandingGet = {
  3381. action: 'g',
  3382. request: request,
  3383. onComplete: function (message) {
  3384. var payload = message['d'];
  3385. if (message['s'] === 'ok') {
  3386. deferred.resolve(payload);
  3387. }
  3388. else {
  3389. deferred.reject(payload);
  3390. }
  3391. }
  3392. };
  3393. this.outstandingGets_.push(outstandingGet);
  3394. this.outstandingGetCount_++;
  3395. var index = this.outstandingGets_.length - 1;
  3396. if (this.connected_) {
  3397. this.sendGet_(index);
  3398. }
  3399. return deferred.promise;
  3400. };
  3401. PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  3402. this.initConnection_();
  3403. var queryId = query._queryIdentifier;
  3404. var pathString = query._path.toString();
  3405. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3406. if (!this.listens.has(pathString)) {
  3407. this.listens.set(pathString, new Map());
  3408. }
  3409. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3410. util.assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
  3411. var listenSpec = {
  3412. onComplete: onComplete,
  3413. hashFn: currentHashFn,
  3414. query: query,
  3415. tag: tag
  3416. };
  3417. this.listens.get(pathString).set(queryId, listenSpec);
  3418. if (this.connected_) {
  3419. this.sendListen_(listenSpec);
  3420. }
  3421. };
  3422. PersistentConnection.prototype.sendGet_ = function (index) {
  3423. var _this = this;
  3424. var get = this.outstandingGets_[index];
  3425. this.sendRequest('g', get.request, function (message) {
  3426. delete _this.outstandingGets_[index];
  3427. _this.outstandingGetCount_--;
  3428. if (_this.outstandingGetCount_ === 0) {
  3429. _this.outstandingGets_ = [];
  3430. }
  3431. if (get.onComplete) {
  3432. get.onComplete(message);
  3433. }
  3434. });
  3435. };
  3436. PersistentConnection.prototype.sendListen_ = function (listenSpec) {
  3437. var _this = this;
  3438. var query = listenSpec.query;
  3439. var pathString = query._path.toString();
  3440. var queryId = query._queryIdentifier;
  3441. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3442. var req = { /*path*/ p: pathString };
  3443. var action = 'q';
  3444. // Only bother to send query if it's non-default.
  3445. if (listenSpec.tag) {
  3446. req['q'] = query._queryObject;
  3447. req['t'] = listenSpec.tag;
  3448. }
  3449. req[ /*hash*/'h'] = listenSpec.hashFn();
  3450. this.sendRequest(action, req, function (message) {
  3451. var payload = message[ /*data*/'d'];
  3452. var status = message[ /*status*/'s'];
  3453. // print warnings in any case...
  3454. PersistentConnection.warnOnListenWarnings_(payload, query);
  3455. var currentListenSpec = _this.listens.get(pathString) &&
  3456. _this.listens.get(pathString).get(queryId);
  3457. // only trigger actions if the listen hasn't been removed and readded
  3458. if (currentListenSpec === listenSpec) {
  3459. _this.log_('listen response', message);
  3460. if (status !== 'ok') {
  3461. _this.removeListen_(pathString, queryId);
  3462. }
  3463. if (listenSpec.onComplete) {
  3464. listenSpec.onComplete(status, payload);
  3465. }
  3466. }
  3467. });
  3468. };
  3469. PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
  3470. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  3471. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3472. var warnings = util.safeGet(payload, 'w');
  3473. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3474. var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3475. var indexPath = query._path.toString();
  3476. warn("Using an unspecified index. Your data will be downloaded and " +
  3477. "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
  3478. "".concat(indexPath, " to your security rules for better performance."));
  3479. }
  3480. }
  3481. };
  3482. PersistentConnection.prototype.refreshAuthToken = function (token) {
  3483. this.authToken_ = token;
  3484. this.log_('Auth token refreshed');
  3485. if (this.authToken_) {
  3486. this.tryAuth();
  3487. }
  3488. else {
  3489. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3490. //the credential so we dont become authenticated next time we connect.
  3491. if (this.connected_) {
  3492. this.sendRequest('unauth', {}, function () { });
  3493. }
  3494. }
  3495. this.reduceReconnectDelayIfAdminCredential_(token);
  3496. };
  3497. PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
  3498. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3499. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3500. var isFirebaseSecret = credential && credential.length === 40;
  3501. if (isFirebaseSecret || util.isAdmin(credential)) {
  3502. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3503. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3504. }
  3505. };
  3506. PersistentConnection.prototype.refreshAppCheckToken = function (token) {
  3507. this.appCheckToken_ = token;
  3508. this.log_('App check token refreshed');
  3509. if (this.appCheckToken_) {
  3510. this.tryAppCheck();
  3511. }
  3512. else {
  3513. //If we're connected we want to let the server know to unauthenticate us.
  3514. //If we're not connected, simply delete the credential so we dont become
  3515. // authenticated next time we connect.
  3516. if (this.connected_) {
  3517. this.sendRequest('unappeck', {}, function () { });
  3518. }
  3519. }
  3520. };
  3521. /**
  3522. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3523. * a auth revoked (the connection is closed).
  3524. */
  3525. PersistentConnection.prototype.tryAuth = function () {
  3526. var _this = this;
  3527. if (this.connected_ && this.authToken_) {
  3528. var token_1 = this.authToken_;
  3529. var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';
  3530. var requestData = { cred: token_1 };
  3531. if (this.authOverride_ === null) {
  3532. requestData['noauth'] = true;
  3533. }
  3534. else if (typeof this.authOverride_ === 'object') {
  3535. requestData['authvar'] = this.authOverride_;
  3536. }
  3537. this.sendRequest(authMethod, requestData, function (res) {
  3538. var status = res[ /*status*/'s'];
  3539. var data = res[ /*data*/'d'] || 'error';
  3540. if (_this.authToken_ === token_1) {
  3541. if (status === 'ok') {
  3542. _this.invalidAuthTokenCount_ = 0;
  3543. }
  3544. else {
  3545. // Triggers reconnect and force refresh for auth token
  3546. _this.onAuthRevoked_(status, data);
  3547. }
  3548. }
  3549. });
  3550. }
  3551. };
  3552. /**
  3553. * Attempts to authenticate with the given token. If the authentication
  3554. * attempt fails, it's triggered like the token was revoked (the connection is
  3555. * closed).
  3556. */
  3557. PersistentConnection.prototype.tryAppCheck = function () {
  3558. var _this = this;
  3559. if (this.connected_ && this.appCheckToken_) {
  3560. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
  3561. var status = res[ /*status*/'s'];
  3562. var data = res[ /*data*/'d'] || 'error';
  3563. if (status === 'ok') {
  3564. _this.invalidAppCheckTokenCount_ = 0;
  3565. }
  3566. else {
  3567. _this.onAppCheckRevoked_(status, data);
  3568. }
  3569. });
  3570. }
  3571. };
  3572. /**
  3573. * @inheritDoc
  3574. */
  3575. PersistentConnection.prototype.unlisten = function (query, tag) {
  3576. var pathString = query._path.toString();
  3577. var queryId = query._queryIdentifier;
  3578. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3579. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3580. var listen = this.removeListen_(pathString, queryId);
  3581. if (listen && this.connected_) {
  3582. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3583. }
  3584. };
  3585. PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
  3586. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3587. var req = { /*path*/ p: pathString };
  3588. var action = 'n';
  3589. // Only bother sending queryId if it's non-default.
  3590. if (tag) {
  3591. req['q'] = queryObj;
  3592. req['t'] = tag;
  3593. }
  3594. this.sendRequest(action, req);
  3595. };
  3596. PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
  3597. this.initConnection_();
  3598. if (this.connected_) {
  3599. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3600. }
  3601. else {
  3602. this.onDisconnectRequestQueue_.push({
  3603. pathString: pathString,
  3604. action: 'o',
  3605. data: data,
  3606. onComplete: onComplete
  3607. });
  3608. }
  3609. };
  3610. PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
  3611. this.initConnection_();
  3612. if (this.connected_) {
  3613. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3614. }
  3615. else {
  3616. this.onDisconnectRequestQueue_.push({
  3617. pathString: pathString,
  3618. action: 'om',
  3619. data: data,
  3620. onComplete: onComplete
  3621. });
  3622. }
  3623. };
  3624. PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
  3625. this.initConnection_();
  3626. if (this.connected_) {
  3627. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3628. }
  3629. else {
  3630. this.onDisconnectRequestQueue_.push({
  3631. pathString: pathString,
  3632. action: 'oc',
  3633. data: null,
  3634. onComplete: onComplete
  3635. });
  3636. }
  3637. };
  3638. PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
  3639. var request = { /*path*/ p: pathString, /*data*/ d: data };
  3640. this.log_('onDisconnect ' + action, request);
  3641. this.sendRequest(action, request, function (response) {
  3642. if (onComplete) {
  3643. setTimeout(function () {
  3644. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3645. }, Math.floor(0));
  3646. }
  3647. });
  3648. };
  3649. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  3650. this.putInternal('p', pathString, data, onComplete, hash);
  3651. };
  3652. PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
  3653. this.putInternal('m', pathString, data, onComplete, hash);
  3654. };
  3655. PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
  3656. this.initConnection_();
  3657. var request = {
  3658. /*path*/ p: pathString,
  3659. /*data*/ d: data
  3660. };
  3661. if (hash !== undefined) {
  3662. request[ /*hash*/'h'] = hash;
  3663. }
  3664. // TODO: Only keep track of the most recent put for a given path?
  3665. this.outstandingPuts_.push({
  3666. action: action,
  3667. request: request,
  3668. onComplete: onComplete
  3669. });
  3670. this.outstandingPutCount_++;
  3671. var index = this.outstandingPuts_.length - 1;
  3672. if (this.connected_) {
  3673. this.sendPut_(index);
  3674. }
  3675. else {
  3676. this.log_('Buffering put: ' + pathString);
  3677. }
  3678. };
  3679. PersistentConnection.prototype.sendPut_ = function (index) {
  3680. var _this = this;
  3681. var action = this.outstandingPuts_[index].action;
  3682. var request = this.outstandingPuts_[index].request;
  3683. var onComplete = this.outstandingPuts_[index].onComplete;
  3684. this.outstandingPuts_[index].queued = this.connected_;
  3685. this.sendRequest(action, request, function (message) {
  3686. _this.log_(action + ' response', message);
  3687. delete _this.outstandingPuts_[index];
  3688. _this.outstandingPutCount_--;
  3689. // Clean up array occasionally.
  3690. if (_this.outstandingPutCount_ === 0) {
  3691. _this.outstandingPuts_ = [];
  3692. }
  3693. if (onComplete) {
  3694. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3695. }
  3696. });
  3697. };
  3698. PersistentConnection.prototype.reportStats = function (stats) {
  3699. var _this = this;
  3700. // If we're not connected, we just drop the stats.
  3701. if (this.connected_) {
  3702. var request = { /*counters*/ c: stats };
  3703. this.log_('reportStats', request);
  3704. this.sendRequest(/*stats*/ 's', request, function (result) {
  3705. var status = result[ /*status*/'s'];
  3706. if (status !== 'ok') {
  3707. var errorReason = result[ /* data */'d'];
  3708. _this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3709. }
  3710. });
  3711. }
  3712. };
  3713. PersistentConnection.prototype.onDataMessage_ = function (message) {
  3714. if ('r' in message) {
  3715. // this is a response
  3716. this.log_('from server: ' + util.stringify(message));
  3717. var reqNum = message['r'];
  3718. var onResponse = this.requestCBHash_[reqNum];
  3719. if (onResponse) {
  3720. delete this.requestCBHash_[reqNum];
  3721. onResponse(message[ /*body*/'b']);
  3722. }
  3723. }
  3724. else if ('error' in message) {
  3725. throw 'A server-side error has occurred: ' + message['error'];
  3726. }
  3727. else if ('a' in message) {
  3728. // a and b are action and body, respectively
  3729. this.onDataPush_(message['a'], message['b']);
  3730. }
  3731. };
  3732. PersistentConnection.prototype.onDataPush_ = function (action, body) {
  3733. this.log_('handleServerMessage', action, body);
  3734. if (action === 'd') {
  3735. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3736. /*isMerge*/ false, body['t']);
  3737. }
  3738. else if (action === 'm') {
  3739. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3740. /*isMerge=*/ true, body['t']);
  3741. }
  3742. else if (action === 'c') {
  3743. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3744. }
  3745. else if (action === 'ac') {
  3746. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3747. }
  3748. else if (action === 'apc') {
  3749. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3750. }
  3751. else if (action === 'sd') {
  3752. this.onSecurityDebugPacket_(body);
  3753. }
  3754. else {
  3755. error('Unrecognized action received from server: ' +
  3756. util.stringify(action) +
  3757. '\nAre you using the latest client?');
  3758. }
  3759. };
  3760. PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
  3761. this.log_('connection ready');
  3762. this.connected_ = true;
  3763. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3764. this.handleTimestamp_(timestamp);
  3765. this.lastSessionId = sessionId;
  3766. if (this.firstConnection_) {
  3767. this.sendConnectStats_();
  3768. }
  3769. this.restoreState_();
  3770. this.firstConnection_ = false;
  3771. this.onConnectStatus_(true);
  3772. };
  3773. PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
  3774. var _this = this;
  3775. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3776. if (this.establishConnectionTimer_) {
  3777. clearTimeout(this.establishConnectionTimer_);
  3778. }
  3779. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3780. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3781. this.establishConnectionTimer_ = setTimeout(function () {
  3782. _this.establishConnectionTimer_ = null;
  3783. _this.establishConnection_();
  3784. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3785. }, Math.floor(timeout));
  3786. };
  3787. PersistentConnection.prototype.initConnection_ = function () {
  3788. if (!this.realtime_ && this.firstConnection_) {
  3789. this.scheduleConnect_(0);
  3790. }
  3791. };
  3792. PersistentConnection.prototype.onVisible_ = function (visible) {
  3793. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3794. if (visible &&
  3795. !this.visible_ &&
  3796. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3797. this.log_('Window became visible. Reducing delay.');
  3798. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3799. if (!this.realtime_) {
  3800. this.scheduleConnect_(0);
  3801. }
  3802. }
  3803. this.visible_ = visible;
  3804. };
  3805. PersistentConnection.prototype.onOnline_ = function (online) {
  3806. if (online) {
  3807. this.log_('Browser went online.');
  3808. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3809. if (!this.realtime_) {
  3810. this.scheduleConnect_(0);
  3811. }
  3812. }
  3813. else {
  3814. this.log_('Browser went offline. Killing connection.');
  3815. if (this.realtime_) {
  3816. this.realtime_.close();
  3817. }
  3818. }
  3819. };
  3820. PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
  3821. this.log_('data client disconnected');
  3822. this.connected_ = false;
  3823. this.realtime_ = null;
  3824. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3825. this.cancelSentTransactions_();
  3826. // Clear out the pending requests.
  3827. this.requestCBHash_ = {};
  3828. if (this.shouldReconnect_()) {
  3829. if (!this.visible_) {
  3830. this.log_("Window isn't visible. Delaying reconnect.");
  3831. this.reconnectDelay_ = this.maxReconnectDelay_;
  3832. this.lastConnectionAttemptTime_ = new Date().getTime();
  3833. }
  3834. else if (this.lastConnectionEstablishedTime_) {
  3835. // If we've been connected long enough, reset reconnect delay to minimum.
  3836. var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3837. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3838. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3839. }
  3840. this.lastConnectionEstablishedTime_ = null;
  3841. }
  3842. var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3843. var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3844. reconnectDelay = Math.random() * reconnectDelay;
  3845. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3846. this.scheduleConnect_(reconnectDelay);
  3847. // Adjust reconnect delay for next time.
  3848. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3849. }
  3850. this.onConnectStatus_(false);
  3851. };
  3852. PersistentConnection.prototype.establishConnection_ = function () {
  3853. return tslib.__awaiter(this, void 0, void 0, function () {
  3854. var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
  3855. var _this = this;
  3856. return tslib.__generator(this, function (_b) {
  3857. switch (_b.label) {
  3858. case 0:
  3859. if (!this.shouldReconnect_()) return [3 /*break*/, 4];
  3860. this.log_('Making a connection attempt');
  3861. this.lastConnectionAttemptTime_ = new Date().getTime();
  3862. this.lastConnectionEstablishedTime_ = null;
  3863. onDataMessage = this.onDataMessage_.bind(this);
  3864. onReady = this.onReady_.bind(this);
  3865. onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
  3866. connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3867. lastSessionId = this.lastSessionId;
  3868. canceled_1 = false;
  3869. connection_1 = null;
  3870. closeFn = function () {
  3871. if (connection_1) {
  3872. connection_1.close();
  3873. }
  3874. else {
  3875. canceled_1 = true;
  3876. onDisconnect_1();
  3877. }
  3878. };
  3879. sendRequestFn = function (msg) {
  3880. util.assert(connection_1, "sendRequest call when we're not connected not allowed.");
  3881. connection_1.sendRequest(msg);
  3882. };
  3883. this.realtime_ = {
  3884. close: closeFn,
  3885. sendRequest: sendRequestFn
  3886. };
  3887. forceRefresh = this.forceTokenRefresh_;
  3888. this.forceTokenRefresh_ = false;
  3889. _b.label = 1;
  3890. case 1:
  3891. _b.trys.push([1, 3, , 4]);
  3892. return [4 /*yield*/, Promise.all([
  3893. this.authTokenProvider_.getToken(forceRefresh),
  3894. this.appCheckTokenProvider_.getToken(forceRefresh)
  3895. ])];
  3896. case 2:
  3897. _a = tslib.__read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
  3898. if (!canceled_1) {
  3899. log('getToken() completed. Creating connection.');
  3900. this.authToken_ = authToken && authToken.accessToken;
  3901. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3902. connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
  3903. /* onKill= */ function (reason) {
  3904. warn(reason + ' (' + _this.repoInfo_.toString() + ')');
  3905. _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3906. }, lastSessionId);
  3907. }
  3908. else {
  3909. log('getToken() completed but was canceled');
  3910. }
  3911. return [3 /*break*/, 4];
  3912. case 3:
  3913. error_1 = _b.sent();
  3914. this.log_('Failed to get token: ' + error_1);
  3915. if (!canceled_1) {
  3916. if (this.repoInfo_.nodeAdmin) {
  3917. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3918. // But getToken() may also just have temporarily failed, so we still want to
  3919. // continue retrying.
  3920. warn(error_1);
  3921. }
  3922. closeFn();
  3923. }
  3924. return [3 /*break*/, 4];
  3925. case 4: return [2 /*return*/];
  3926. }
  3927. });
  3928. });
  3929. };
  3930. PersistentConnection.prototype.interrupt = function (reason) {
  3931. log('Interrupting connection for reason: ' + reason);
  3932. this.interruptReasons_[reason] = true;
  3933. if (this.realtime_) {
  3934. this.realtime_.close();
  3935. }
  3936. else {
  3937. if (this.establishConnectionTimer_) {
  3938. clearTimeout(this.establishConnectionTimer_);
  3939. this.establishConnectionTimer_ = null;
  3940. }
  3941. if (this.connected_) {
  3942. this.onRealtimeDisconnect_();
  3943. }
  3944. }
  3945. };
  3946. PersistentConnection.prototype.resume = function (reason) {
  3947. log('Resuming connection for reason: ' + reason);
  3948. delete this.interruptReasons_[reason];
  3949. if (util.isEmpty(this.interruptReasons_)) {
  3950. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3951. if (!this.realtime_) {
  3952. this.scheduleConnect_(0);
  3953. }
  3954. }
  3955. };
  3956. PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
  3957. var delta = timestamp - new Date().getTime();
  3958. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3959. };
  3960. PersistentConnection.prototype.cancelSentTransactions_ = function () {
  3961. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  3962. var put = this.outstandingPuts_[i];
  3963. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3964. if (put.onComplete) {
  3965. put.onComplete('disconnect');
  3966. }
  3967. delete this.outstandingPuts_[i];
  3968. this.outstandingPutCount_--;
  3969. }
  3970. }
  3971. // Clean up array occasionally.
  3972. if (this.outstandingPutCount_ === 0) {
  3973. this.outstandingPuts_ = [];
  3974. }
  3975. };
  3976. PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
  3977. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3978. var queryId;
  3979. if (!query) {
  3980. queryId = 'default';
  3981. }
  3982. else {
  3983. queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
  3984. }
  3985. var listen = this.removeListen_(pathString, queryId);
  3986. if (listen && listen.onComplete) {
  3987. listen.onComplete('permission_denied');
  3988. }
  3989. };
  3990. PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
  3991. var normalizedPathString = new Path(pathString).toString(); // normalize path.
  3992. var listen;
  3993. if (this.listens.has(normalizedPathString)) {
  3994. var map = this.listens.get(normalizedPathString);
  3995. listen = map.get(queryId);
  3996. map.delete(queryId);
  3997. if (map.size === 0) {
  3998. this.listens.delete(normalizedPathString);
  3999. }
  4000. }
  4001. else {
  4002. // all listens for this path has already been removed
  4003. listen = undefined;
  4004. }
  4005. return listen;
  4006. };
  4007. PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
  4008. log('Auth token revoked: ' + statusCode + '/' + explanation);
  4009. this.authToken_ = null;
  4010. this.forceTokenRefresh_ = true;
  4011. this.realtime_.close();
  4012. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4013. // We'll wait a couple times before logging the warning / increasing the
  4014. // retry period since oauth tokens will report as "invalid" if they're
  4015. // just expired. Plus there may be transient issues that resolve themselves.
  4016. this.invalidAuthTokenCount_++;
  4017. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4018. // Set a long reconnect delay because recovery is unlikely
  4019. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  4020. // Notify the auth token provider that the token is invalid, which will log
  4021. // a warning
  4022. this.authTokenProvider_.notifyForInvalidToken();
  4023. }
  4024. }
  4025. };
  4026. PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
  4027. log('App check token revoked: ' + statusCode + '/' + explanation);
  4028. this.appCheckToken_ = null;
  4029. this.forceTokenRefresh_ = true;
  4030. // Note: We don't close the connection as the developer may not have
  4031. // enforcement enabled. The backend closes connections with enforcements.
  4032. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4033. // We'll wait a couple times before logging the warning / increasing the
  4034. // retry period since oauth tokens will report as "invalid" if they're
  4035. // just expired. Plus there may be transient issues that resolve themselves.
  4036. this.invalidAppCheckTokenCount_++;
  4037. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4038. this.appCheckTokenProvider_.notifyForInvalidToken();
  4039. }
  4040. }
  4041. };
  4042. PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
  4043. if (this.securityDebugCallback_) {
  4044. this.securityDebugCallback_(body);
  4045. }
  4046. else {
  4047. if ('msg' in body) {
  4048. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  4049. }
  4050. }
  4051. };
  4052. PersistentConnection.prototype.restoreState_ = function () {
  4053. var e_1, _a, e_2, _b;
  4054. //Re-authenticate ourselves if we have a credential stored.
  4055. this.tryAuth();
  4056. this.tryAppCheck();
  4057. try {
  4058. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  4059. // make sure to send listens before puts.
  4060. for (var _c = tslib.__values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
  4061. var queries = _d.value;
  4062. try {
  4063. for (var _e = (e_2 = void 0, tslib.__values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
  4064. var listenSpec = _f.value;
  4065. this.sendListen_(listenSpec);
  4066. }
  4067. }
  4068. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  4069. finally {
  4070. try {
  4071. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  4072. }
  4073. finally { if (e_2) throw e_2.error; }
  4074. }
  4075. }
  4076. }
  4077. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4078. finally {
  4079. try {
  4080. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  4081. }
  4082. finally { if (e_1) throw e_1.error; }
  4083. }
  4084. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  4085. if (this.outstandingPuts_[i]) {
  4086. this.sendPut_(i);
  4087. }
  4088. }
  4089. while (this.onDisconnectRequestQueue_.length) {
  4090. var request = this.onDisconnectRequestQueue_.shift();
  4091. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  4092. }
  4093. for (var i = 0; i < this.outstandingGets_.length; i++) {
  4094. if (this.outstandingGets_[i]) {
  4095. this.sendGet_(i);
  4096. }
  4097. }
  4098. };
  4099. /**
  4100. * Sends client stats for first connection
  4101. */
  4102. PersistentConnection.prototype.sendConnectStats_ = function () {
  4103. var stats = {};
  4104. var clientName = 'js';
  4105. if (util.isNodeSdk()) {
  4106. if (this.repoInfo_.nodeAdmin) {
  4107. clientName = 'admin_node';
  4108. }
  4109. else {
  4110. clientName = 'node';
  4111. }
  4112. }
  4113. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  4114. if (util.isMobileCordova()) {
  4115. stats['framework.cordova'] = 1;
  4116. }
  4117. else if (util.isReactNative()) {
  4118. stats['framework.reactnative'] = 1;
  4119. }
  4120. this.reportStats(stats);
  4121. };
  4122. PersistentConnection.prototype.shouldReconnect_ = function () {
  4123. var online = OnlineMonitor.getInstance().currentlyOnline();
  4124. return util.isEmpty(this.interruptReasons_) && online;
  4125. };
  4126. PersistentConnection.nextPersistentConnectionId_ = 0;
  4127. /**
  4128. * Counter for number of connections created. Mainly used for tagging in the logs
  4129. */
  4130. PersistentConnection.nextConnectionId_ = 0;
  4131. return PersistentConnection;
  4132. }(ServerActions));
  4133. /**
  4134. * @license
  4135. * Copyright 2017 Google LLC
  4136. *
  4137. * Licensed under the Apache License, Version 2.0 (the "License");
  4138. * you may not use this file except in compliance with the License.
  4139. * You may obtain a copy of the License at
  4140. *
  4141. * http://www.apache.org/licenses/LICENSE-2.0
  4142. *
  4143. * Unless required by applicable law or agreed to in writing, software
  4144. * distributed under the License is distributed on an "AS IS" BASIS,
  4145. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4146. * See the License for the specific language governing permissions and
  4147. * limitations under the License.
  4148. */
  4149. var NamedNode = /** @class */ (function () {
  4150. function NamedNode(name, node) {
  4151. this.name = name;
  4152. this.node = node;
  4153. }
  4154. NamedNode.Wrap = function (name, node) {
  4155. return new NamedNode(name, node);
  4156. };
  4157. return NamedNode;
  4158. }());
  4159. /**
  4160. * @license
  4161. * Copyright 2017 Google LLC
  4162. *
  4163. * Licensed under the Apache License, Version 2.0 (the "License");
  4164. * you may not use this file except in compliance with the License.
  4165. * You may obtain a copy of the License at
  4166. *
  4167. * http://www.apache.org/licenses/LICENSE-2.0
  4168. *
  4169. * Unless required by applicable law or agreed to in writing, software
  4170. * distributed under the License is distributed on an "AS IS" BASIS,
  4171. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4172. * See the License for the specific language governing permissions and
  4173. * limitations under the License.
  4174. */
  4175. var Index = /** @class */ (function () {
  4176. function Index() {
  4177. }
  4178. /**
  4179. * @returns A standalone comparison function for
  4180. * this index
  4181. */
  4182. Index.prototype.getCompare = function () {
  4183. return this.compare.bind(this);
  4184. };
  4185. /**
  4186. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4187. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4188. *
  4189. *
  4190. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4191. */
  4192. Index.prototype.indexedValueChanged = function (oldNode, newNode) {
  4193. var oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4194. var newWrapped = new NamedNode(MIN_NAME, newNode);
  4195. return this.compare(oldWrapped, newWrapped) !== 0;
  4196. };
  4197. /**
  4198. * @returns a node wrapper that will sort equal to or less than
  4199. * any other node wrapper, using this index
  4200. */
  4201. Index.prototype.minPost = function () {
  4202. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4203. return NamedNode.MIN;
  4204. };
  4205. return Index;
  4206. }());
  4207. /**
  4208. * @license
  4209. * Copyright 2017 Google LLC
  4210. *
  4211. * Licensed under the Apache License, Version 2.0 (the "License");
  4212. * you may not use this file except in compliance with the License.
  4213. * You may obtain a copy of the License at
  4214. *
  4215. * http://www.apache.org/licenses/LICENSE-2.0
  4216. *
  4217. * Unless required by applicable law or agreed to in writing, software
  4218. * distributed under the License is distributed on an "AS IS" BASIS,
  4219. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4220. * See the License for the specific language governing permissions and
  4221. * limitations under the License.
  4222. */
  4223. var __EMPTY_NODE;
  4224. var KeyIndex = /** @class */ (function (_super) {
  4225. tslib.__extends(KeyIndex, _super);
  4226. function KeyIndex() {
  4227. return _super !== null && _super.apply(this, arguments) || this;
  4228. }
  4229. Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
  4230. get: function () {
  4231. return __EMPTY_NODE;
  4232. },
  4233. set: function (val) {
  4234. __EMPTY_NODE = val;
  4235. },
  4236. enumerable: false,
  4237. configurable: true
  4238. });
  4239. KeyIndex.prototype.compare = function (a, b) {
  4240. return nameCompare(a.name, b.name);
  4241. };
  4242. KeyIndex.prototype.isDefinedOn = function (node) {
  4243. // We could probably return true here (since every node has a key), but it's never called
  4244. // so just leaving unimplemented for now.
  4245. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4246. };
  4247. KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  4248. return false; // The key for a node never changes.
  4249. };
  4250. KeyIndex.prototype.minPost = function () {
  4251. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4252. return NamedNode.MIN;
  4253. };
  4254. KeyIndex.prototype.maxPost = function () {
  4255. // TODO: This should really be created once and cached in a static property, but
  4256. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4257. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4258. };
  4259. KeyIndex.prototype.makePost = function (indexValue, name) {
  4260. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4261. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4262. return new NamedNode(indexValue, __EMPTY_NODE);
  4263. };
  4264. /**
  4265. * @returns String representation for inclusion in a query spec
  4266. */
  4267. KeyIndex.prototype.toString = function () {
  4268. return '.key';
  4269. };
  4270. return KeyIndex;
  4271. }(Index));
  4272. var KEY_INDEX = new KeyIndex();
  4273. /**
  4274. * @license
  4275. * Copyright 2017 Google LLC
  4276. *
  4277. * Licensed under the Apache License, Version 2.0 (the "License");
  4278. * you may not use this file except in compliance with the License.
  4279. * You may obtain a copy of the License at
  4280. *
  4281. * http://www.apache.org/licenses/LICENSE-2.0
  4282. *
  4283. * Unless required by applicable law or agreed to in writing, software
  4284. * distributed under the License is distributed on an "AS IS" BASIS,
  4285. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4286. * See the License for the specific language governing permissions and
  4287. * limitations under the License.
  4288. */
  4289. /**
  4290. * An iterator over an LLRBNode.
  4291. */
  4292. var SortedMapIterator = /** @class */ (function () {
  4293. /**
  4294. * @param node - Node to iterate.
  4295. * @param isReverse_ - Whether or not to iterate in reverse
  4296. */
  4297. function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
  4298. if (resultGenerator_ === void 0) { resultGenerator_ = null; }
  4299. this.isReverse_ = isReverse_;
  4300. this.resultGenerator_ = resultGenerator_;
  4301. this.nodeStack_ = [];
  4302. var cmp = 1;
  4303. while (!node.isEmpty()) {
  4304. node = node;
  4305. cmp = startKey ? comparator(node.key, startKey) : 1;
  4306. // flip the comparison if we're going in reverse
  4307. if (isReverse_) {
  4308. cmp *= -1;
  4309. }
  4310. if (cmp < 0) {
  4311. // This node is less than our start key. ignore it
  4312. if (this.isReverse_) {
  4313. node = node.left;
  4314. }
  4315. else {
  4316. node = node.right;
  4317. }
  4318. }
  4319. else if (cmp === 0) {
  4320. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4321. this.nodeStack_.push(node);
  4322. break;
  4323. }
  4324. else {
  4325. // This node is greater than our start key, add it to the stack and move to the next one
  4326. this.nodeStack_.push(node);
  4327. if (this.isReverse_) {
  4328. node = node.right;
  4329. }
  4330. else {
  4331. node = node.left;
  4332. }
  4333. }
  4334. }
  4335. }
  4336. SortedMapIterator.prototype.getNext = function () {
  4337. if (this.nodeStack_.length === 0) {
  4338. return null;
  4339. }
  4340. var node = this.nodeStack_.pop();
  4341. var result;
  4342. if (this.resultGenerator_) {
  4343. result = this.resultGenerator_(node.key, node.value);
  4344. }
  4345. else {
  4346. result = { key: node.key, value: node.value };
  4347. }
  4348. if (this.isReverse_) {
  4349. node = node.left;
  4350. while (!node.isEmpty()) {
  4351. this.nodeStack_.push(node);
  4352. node = node.right;
  4353. }
  4354. }
  4355. else {
  4356. node = node.right;
  4357. while (!node.isEmpty()) {
  4358. this.nodeStack_.push(node);
  4359. node = node.left;
  4360. }
  4361. }
  4362. return result;
  4363. };
  4364. SortedMapIterator.prototype.hasNext = function () {
  4365. return this.nodeStack_.length > 0;
  4366. };
  4367. SortedMapIterator.prototype.peek = function () {
  4368. if (this.nodeStack_.length === 0) {
  4369. return null;
  4370. }
  4371. var node = this.nodeStack_[this.nodeStack_.length - 1];
  4372. if (this.resultGenerator_) {
  4373. return this.resultGenerator_(node.key, node.value);
  4374. }
  4375. else {
  4376. return { key: node.key, value: node.value };
  4377. }
  4378. };
  4379. return SortedMapIterator;
  4380. }());
  4381. /**
  4382. * Represents a node in a Left-leaning Red-Black tree.
  4383. */
  4384. var LLRBNode = /** @class */ (function () {
  4385. /**
  4386. * @param key - Key associated with this node.
  4387. * @param value - Value associated with this node.
  4388. * @param color - Whether this node is red.
  4389. * @param left - Left child.
  4390. * @param right - Right child.
  4391. */
  4392. function LLRBNode(key, value, color, left, right) {
  4393. this.key = key;
  4394. this.value = value;
  4395. this.color = color != null ? color : LLRBNode.RED;
  4396. this.left =
  4397. left != null ? left : SortedMap.EMPTY_NODE;
  4398. this.right =
  4399. right != null ? right : SortedMap.EMPTY_NODE;
  4400. }
  4401. /**
  4402. * Returns a copy of the current node, optionally replacing pieces of it.
  4403. *
  4404. * @param key - New key for the node, or null.
  4405. * @param value - New value for the node, or null.
  4406. * @param color - New color for the node, or null.
  4407. * @param left - New left child for the node, or null.
  4408. * @param right - New right child for the node, or null.
  4409. * @returns The node copy.
  4410. */
  4411. LLRBNode.prototype.copy = function (key, value, color, left, right) {
  4412. 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);
  4413. };
  4414. /**
  4415. * @returns The total number of nodes in the tree.
  4416. */
  4417. LLRBNode.prototype.count = function () {
  4418. return this.left.count() + 1 + this.right.count();
  4419. };
  4420. /**
  4421. * @returns True if the tree is empty.
  4422. */
  4423. LLRBNode.prototype.isEmpty = function () {
  4424. return false;
  4425. };
  4426. /**
  4427. * Traverses the tree in key order and calls the specified action function
  4428. * for each node.
  4429. *
  4430. * @param action - Callback function to be called for each
  4431. * node. If it returns true, traversal is aborted.
  4432. * @returns The first truthy value returned by action, or the last falsey
  4433. * value returned by action
  4434. */
  4435. LLRBNode.prototype.inorderTraversal = function (action) {
  4436. return (this.left.inorderTraversal(action) ||
  4437. !!action(this.key, this.value) ||
  4438. this.right.inorderTraversal(action));
  4439. };
  4440. /**
  4441. * Traverses the tree in reverse key order and calls the specified action function
  4442. * for each node.
  4443. *
  4444. * @param action - Callback function to be called for each
  4445. * node. If it returns true, traversal is aborted.
  4446. * @returns True if traversal was aborted.
  4447. */
  4448. LLRBNode.prototype.reverseTraversal = function (action) {
  4449. return (this.right.reverseTraversal(action) ||
  4450. action(this.key, this.value) ||
  4451. this.left.reverseTraversal(action));
  4452. };
  4453. /**
  4454. * @returns The minimum node in the tree.
  4455. */
  4456. LLRBNode.prototype.min_ = function () {
  4457. if (this.left.isEmpty()) {
  4458. return this;
  4459. }
  4460. else {
  4461. return this.left.min_();
  4462. }
  4463. };
  4464. /**
  4465. * @returns The maximum key in the tree.
  4466. */
  4467. LLRBNode.prototype.minKey = function () {
  4468. return this.min_().key;
  4469. };
  4470. /**
  4471. * @returns The maximum key in the tree.
  4472. */
  4473. LLRBNode.prototype.maxKey = function () {
  4474. if (this.right.isEmpty()) {
  4475. return this.key;
  4476. }
  4477. else {
  4478. return this.right.maxKey();
  4479. }
  4480. };
  4481. /**
  4482. * @param key - Key to insert.
  4483. * @param value - Value to insert.
  4484. * @param comparator - Comparator.
  4485. * @returns New tree, with the key/value added.
  4486. */
  4487. LLRBNode.prototype.insert = function (key, value, comparator) {
  4488. var n = this;
  4489. var cmp = comparator(key, n.key);
  4490. if (cmp < 0) {
  4491. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4492. }
  4493. else if (cmp === 0) {
  4494. n = n.copy(null, value, null, null, null);
  4495. }
  4496. else {
  4497. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4498. }
  4499. return n.fixUp_();
  4500. };
  4501. /**
  4502. * @returns New tree, with the minimum key removed.
  4503. */
  4504. LLRBNode.prototype.removeMin_ = function () {
  4505. if (this.left.isEmpty()) {
  4506. return SortedMap.EMPTY_NODE;
  4507. }
  4508. var n = this;
  4509. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4510. n = n.moveRedLeft_();
  4511. }
  4512. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4513. return n.fixUp_();
  4514. };
  4515. /**
  4516. * @param key - The key of the item to remove.
  4517. * @param comparator - Comparator.
  4518. * @returns New tree, with the specified item removed.
  4519. */
  4520. LLRBNode.prototype.remove = function (key, comparator) {
  4521. var n, smallest;
  4522. n = this;
  4523. if (comparator(key, n.key) < 0) {
  4524. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4525. n = n.moveRedLeft_();
  4526. }
  4527. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4528. }
  4529. else {
  4530. if (n.left.isRed_()) {
  4531. n = n.rotateRight_();
  4532. }
  4533. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4534. n = n.moveRedRight_();
  4535. }
  4536. if (comparator(key, n.key) === 0) {
  4537. if (n.right.isEmpty()) {
  4538. return SortedMap.EMPTY_NODE;
  4539. }
  4540. else {
  4541. smallest = n.right.min_();
  4542. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4543. }
  4544. }
  4545. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4546. }
  4547. return n.fixUp_();
  4548. };
  4549. /**
  4550. * @returns Whether this is a RED node.
  4551. */
  4552. LLRBNode.prototype.isRed_ = function () {
  4553. return this.color;
  4554. };
  4555. /**
  4556. * @returns New tree after performing any needed rotations.
  4557. */
  4558. LLRBNode.prototype.fixUp_ = function () {
  4559. var n = this;
  4560. if (n.right.isRed_() && !n.left.isRed_()) {
  4561. n = n.rotateLeft_();
  4562. }
  4563. if (n.left.isRed_() && n.left.left.isRed_()) {
  4564. n = n.rotateRight_();
  4565. }
  4566. if (n.left.isRed_() && n.right.isRed_()) {
  4567. n = n.colorFlip_();
  4568. }
  4569. return n;
  4570. };
  4571. /**
  4572. * @returns New tree, after moveRedLeft.
  4573. */
  4574. LLRBNode.prototype.moveRedLeft_ = function () {
  4575. var n = this.colorFlip_();
  4576. if (n.right.left.isRed_()) {
  4577. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4578. n = n.rotateLeft_();
  4579. n = n.colorFlip_();
  4580. }
  4581. return n;
  4582. };
  4583. /**
  4584. * @returns New tree, after moveRedRight.
  4585. */
  4586. LLRBNode.prototype.moveRedRight_ = function () {
  4587. var n = this.colorFlip_();
  4588. if (n.left.left.isRed_()) {
  4589. n = n.rotateRight_();
  4590. n = n.colorFlip_();
  4591. }
  4592. return n;
  4593. };
  4594. /**
  4595. * @returns New tree, after rotateLeft.
  4596. */
  4597. LLRBNode.prototype.rotateLeft_ = function () {
  4598. var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4599. return this.right.copy(null, null, this.color, nl, null);
  4600. };
  4601. /**
  4602. * @returns New tree, after rotateRight.
  4603. */
  4604. LLRBNode.prototype.rotateRight_ = function () {
  4605. var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4606. return this.left.copy(null, null, this.color, null, nr);
  4607. };
  4608. /**
  4609. * @returns Newt ree, after colorFlip.
  4610. */
  4611. LLRBNode.prototype.colorFlip_ = function () {
  4612. var left = this.left.copy(null, null, !this.left.color, null, null);
  4613. var right = this.right.copy(null, null, !this.right.color, null, null);
  4614. return this.copy(null, null, !this.color, left, right);
  4615. };
  4616. /**
  4617. * For testing.
  4618. *
  4619. * @returns True if all is well.
  4620. */
  4621. LLRBNode.prototype.checkMaxDepth_ = function () {
  4622. var blackDepth = this.check_();
  4623. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4624. };
  4625. LLRBNode.prototype.check_ = function () {
  4626. if (this.isRed_() && this.left.isRed_()) {
  4627. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4628. }
  4629. if (this.right.isRed_()) {
  4630. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4631. }
  4632. var blackDepth = this.left.check_();
  4633. if (blackDepth !== this.right.check_()) {
  4634. throw new Error('Black depths differ');
  4635. }
  4636. else {
  4637. return blackDepth + (this.isRed_() ? 0 : 1);
  4638. }
  4639. };
  4640. LLRBNode.RED = true;
  4641. LLRBNode.BLACK = false;
  4642. return LLRBNode;
  4643. }());
  4644. /**
  4645. * Represents an empty node (a leaf node in the Red-Black Tree).
  4646. */
  4647. var LLRBEmptyNode = /** @class */ (function () {
  4648. function LLRBEmptyNode() {
  4649. }
  4650. /**
  4651. * Returns a copy of the current node.
  4652. *
  4653. * @returns The node copy.
  4654. */
  4655. LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
  4656. return this;
  4657. };
  4658. /**
  4659. * Returns a copy of the tree, with the specified key/value added.
  4660. *
  4661. * @param key - Key to be added.
  4662. * @param value - Value to be added.
  4663. * @param comparator - Comparator.
  4664. * @returns New tree, with item added.
  4665. */
  4666. LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
  4667. return new LLRBNode(key, value, null);
  4668. };
  4669. /**
  4670. * Returns a copy of the tree, with the specified key removed.
  4671. *
  4672. * @param key - The key to remove.
  4673. * @param comparator - Comparator.
  4674. * @returns New tree, with item removed.
  4675. */
  4676. LLRBEmptyNode.prototype.remove = function (key, comparator) {
  4677. return this;
  4678. };
  4679. /**
  4680. * @returns The total number of nodes in the tree.
  4681. */
  4682. LLRBEmptyNode.prototype.count = function () {
  4683. return 0;
  4684. };
  4685. /**
  4686. * @returns True if the tree is empty.
  4687. */
  4688. LLRBEmptyNode.prototype.isEmpty = function () {
  4689. return true;
  4690. };
  4691. /**
  4692. * Traverses the tree in key order and calls the specified action function
  4693. * for each node.
  4694. *
  4695. * @param action - Callback function to be called for each
  4696. * node. If it returns true, traversal is aborted.
  4697. * @returns True if traversal was aborted.
  4698. */
  4699. LLRBEmptyNode.prototype.inorderTraversal = function (action) {
  4700. return false;
  4701. };
  4702. /**
  4703. * Traverses the tree in reverse key order and calls the specified action function
  4704. * for each node.
  4705. *
  4706. * @param action - Callback function to be called for each
  4707. * node. If it returns true, traversal is aborted.
  4708. * @returns True if traversal was aborted.
  4709. */
  4710. LLRBEmptyNode.prototype.reverseTraversal = function (action) {
  4711. return false;
  4712. };
  4713. LLRBEmptyNode.prototype.minKey = function () {
  4714. return null;
  4715. };
  4716. LLRBEmptyNode.prototype.maxKey = function () {
  4717. return null;
  4718. };
  4719. LLRBEmptyNode.prototype.check_ = function () {
  4720. return 0;
  4721. };
  4722. /**
  4723. * @returns Whether this node is red.
  4724. */
  4725. LLRBEmptyNode.prototype.isRed_ = function () {
  4726. return false;
  4727. };
  4728. return LLRBEmptyNode;
  4729. }());
  4730. /**
  4731. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4732. * tree.
  4733. */
  4734. var SortedMap = /** @class */ (function () {
  4735. /**
  4736. * @param comparator_ - Key comparator.
  4737. * @param root_ - Optional root node for the map.
  4738. */
  4739. function SortedMap(comparator_, root_) {
  4740. if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
  4741. this.comparator_ = comparator_;
  4742. this.root_ = root_;
  4743. }
  4744. /**
  4745. * Returns a copy of the map, with the specified key/value added or replaced.
  4746. * (TODO: We should perhaps rename this method to 'put')
  4747. *
  4748. * @param key - Key to be added.
  4749. * @param value - Value to be added.
  4750. * @returns New map, with item added.
  4751. */
  4752. SortedMap.prototype.insert = function (key, value) {
  4753. return new SortedMap(this.comparator_, this.root_
  4754. .insert(key, value, this.comparator_)
  4755. .copy(null, null, LLRBNode.BLACK, null, null));
  4756. };
  4757. /**
  4758. * Returns a copy of the map, with the specified key removed.
  4759. *
  4760. * @param key - The key to remove.
  4761. * @returns New map, with item removed.
  4762. */
  4763. SortedMap.prototype.remove = function (key) {
  4764. return new SortedMap(this.comparator_, this.root_
  4765. .remove(key, this.comparator_)
  4766. .copy(null, null, LLRBNode.BLACK, null, null));
  4767. };
  4768. /**
  4769. * Returns the value of the node with the given key, or null.
  4770. *
  4771. * @param key - The key to look up.
  4772. * @returns The value of the node with the given key, or null if the
  4773. * key doesn't exist.
  4774. */
  4775. SortedMap.prototype.get = function (key) {
  4776. var cmp;
  4777. var node = this.root_;
  4778. while (!node.isEmpty()) {
  4779. cmp = this.comparator_(key, node.key);
  4780. if (cmp === 0) {
  4781. return node.value;
  4782. }
  4783. else if (cmp < 0) {
  4784. node = node.left;
  4785. }
  4786. else if (cmp > 0) {
  4787. node = node.right;
  4788. }
  4789. }
  4790. return null;
  4791. };
  4792. /**
  4793. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4794. * @param key - The key to find the predecessor of
  4795. * @returns The predecessor key.
  4796. */
  4797. SortedMap.prototype.getPredecessorKey = function (key) {
  4798. var cmp, node = this.root_, rightParent = null;
  4799. while (!node.isEmpty()) {
  4800. cmp = this.comparator_(key, node.key);
  4801. if (cmp === 0) {
  4802. if (!node.left.isEmpty()) {
  4803. node = node.left;
  4804. while (!node.right.isEmpty()) {
  4805. node = node.right;
  4806. }
  4807. return node.key;
  4808. }
  4809. else if (rightParent) {
  4810. return rightParent.key;
  4811. }
  4812. else {
  4813. return null; // first item.
  4814. }
  4815. }
  4816. else if (cmp < 0) {
  4817. node = node.left;
  4818. }
  4819. else if (cmp > 0) {
  4820. rightParent = node;
  4821. node = node.right;
  4822. }
  4823. }
  4824. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4825. };
  4826. /**
  4827. * @returns True if the map is empty.
  4828. */
  4829. SortedMap.prototype.isEmpty = function () {
  4830. return this.root_.isEmpty();
  4831. };
  4832. /**
  4833. * @returns The total number of nodes in the map.
  4834. */
  4835. SortedMap.prototype.count = function () {
  4836. return this.root_.count();
  4837. };
  4838. /**
  4839. * @returns The minimum key in the map.
  4840. */
  4841. SortedMap.prototype.minKey = function () {
  4842. return this.root_.minKey();
  4843. };
  4844. /**
  4845. * @returns The maximum key in the map.
  4846. */
  4847. SortedMap.prototype.maxKey = function () {
  4848. return this.root_.maxKey();
  4849. };
  4850. /**
  4851. * Traverses the map in key order and calls the specified action function
  4852. * for each key/value pair.
  4853. *
  4854. * @param action - Callback function to be called
  4855. * for each key/value pair. If action returns true, traversal is aborted.
  4856. * @returns The first truthy value returned by action, or the last falsey
  4857. * value returned by action
  4858. */
  4859. SortedMap.prototype.inorderTraversal = function (action) {
  4860. return this.root_.inorderTraversal(action);
  4861. };
  4862. /**
  4863. * Traverses the map in reverse key order and calls the specified action function
  4864. * for each key/value pair.
  4865. *
  4866. * @param action - Callback function to be called
  4867. * for each key/value pair. If action returns true, traversal is aborted.
  4868. * @returns True if the traversal was aborted.
  4869. */
  4870. SortedMap.prototype.reverseTraversal = function (action) {
  4871. return this.root_.reverseTraversal(action);
  4872. };
  4873. /**
  4874. * Returns an iterator over the SortedMap.
  4875. * @returns The iterator.
  4876. */
  4877. SortedMap.prototype.getIterator = function (resultGenerator) {
  4878. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4879. };
  4880. SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
  4881. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4882. };
  4883. SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
  4884. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4885. };
  4886. SortedMap.prototype.getReverseIterator = function (resultGenerator) {
  4887. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4888. };
  4889. /**
  4890. * Always use the same empty node, to reduce memory.
  4891. */
  4892. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4893. return SortedMap;
  4894. }());
  4895. /**
  4896. * @license
  4897. * Copyright 2017 Google LLC
  4898. *
  4899. * Licensed under the Apache License, Version 2.0 (the "License");
  4900. * you may not use this file except in compliance with the License.
  4901. * You may obtain a copy of the License at
  4902. *
  4903. * http://www.apache.org/licenses/LICENSE-2.0
  4904. *
  4905. * Unless required by applicable law or agreed to in writing, software
  4906. * distributed under the License is distributed on an "AS IS" BASIS,
  4907. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4908. * See the License for the specific language governing permissions and
  4909. * limitations under the License.
  4910. */
  4911. function NAME_ONLY_COMPARATOR(left, right) {
  4912. return nameCompare(left.name, right.name);
  4913. }
  4914. function NAME_COMPARATOR(left, right) {
  4915. return nameCompare(left, right);
  4916. }
  4917. /**
  4918. * @license
  4919. * Copyright 2017 Google LLC
  4920. *
  4921. * Licensed under the Apache License, Version 2.0 (the "License");
  4922. * you may not use this file except in compliance with the License.
  4923. * You may obtain a copy of the License at
  4924. *
  4925. * http://www.apache.org/licenses/LICENSE-2.0
  4926. *
  4927. * Unless required by applicable law or agreed to in writing, software
  4928. * distributed under the License is distributed on an "AS IS" BASIS,
  4929. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4930. * See the License for the specific language governing permissions and
  4931. * limitations under the License.
  4932. */
  4933. var MAX_NODE$2;
  4934. function setMaxNode$1(val) {
  4935. MAX_NODE$2 = val;
  4936. }
  4937. var priorityHashText = function (priority) {
  4938. if (typeof priority === 'number') {
  4939. return 'number:' + doubleToIEEE754String(priority);
  4940. }
  4941. else {
  4942. return 'string:' + priority;
  4943. }
  4944. };
  4945. /**
  4946. * Validates that a priority snapshot Node is valid.
  4947. */
  4948. var validatePriorityNode = function (priorityNode) {
  4949. if (priorityNode.isLeafNode()) {
  4950. var val = priorityNode.val();
  4951. util.assert(typeof val === 'string' ||
  4952. typeof val === 'number' ||
  4953. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  4954. }
  4955. else {
  4956. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4957. }
  4958. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4959. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4960. };
  4961. /**
  4962. * @license
  4963. * Copyright 2017 Google LLC
  4964. *
  4965. * Licensed under the Apache License, Version 2.0 (the "License");
  4966. * you may not use this file except in compliance with the License.
  4967. * You may obtain a copy of the License at
  4968. *
  4969. * http://www.apache.org/licenses/LICENSE-2.0
  4970. *
  4971. * Unless required by applicable law or agreed to in writing, software
  4972. * distributed under the License is distributed on an "AS IS" BASIS,
  4973. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4974. * See the License for the specific language governing permissions and
  4975. * limitations under the License.
  4976. */
  4977. var __childrenNodeConstructor;
  4978. /**
  4979. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4980. * implements Node and stores the value of the node (a string,
  4981. * number, or boolean) accessible via getValue().
  4982. */
  4983. var LeafNode = /** @class */ (function () {
  4984. /**
  4985. * @param value_ - The value to store in this leaf node. The object type is
  4986. * possible in the event of a deferred value
  4987. * @param priorityNode_ - The priority of this node.
  4988. */
  4989. function LeafNode(value_, priorityNode_) {
  4990. if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
  4991. this.value_ = value_;
  4992. this.priorityNode_ = priorityNode_;
  4993. this.lazyHash_ = null;
  4994. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4995. validatePriorityNode(this.priorityNode_);
  4996. }
  4997. Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
  4998. get: function () {
  4999. return __childrenNodeConstructor;
  5000. },
  5001. set: function (val) {
  5002. __childrenNodeConstructor = val;
  5003. },
  5004. enumerable: false,
  5005. configurable: true
  5006. });
  5007. /** @inheritDoc */
  5008. LeafNode.prototype.isLeafNode = function () {
  5009. return true;
  5010. };
  5011. /** @inheritDoc */
  5012. LeafNode.prototype.getPriority = function () {
  5013. return this.priorityNode_;
  5014. };
  5015. /** @inheritDoc */
  5016. LeafNode.prototype.updatePriority = function (newPriorityNode) {
  5017. return new LeafNode(this.value_, newPriorityNode);
  5018. };
  5019. /** @inheritDoc */
  5020. LeafNode.prototype.getImmediateChild = function (childName) {
  5021. // Hack to treat priority as a regular child
  5022. if (childName === '.priority') {
  5023. return this.priorityNode_;
  5024. }
  5025. else {
  5026. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5027. }
  5028. };
  5029. /** @inheritDoc */
  5030. LeafNode.prototype.getChild = function (path) {
  5031. if (pathIsEmpty(path)) {
  5032. return this;
  5033. }
  5034. else if (pathGetFront(path) === '.priority') {
  5035. return this.priorityNode_;
  5036. }
  5037. else {
  5038. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5039. }
  5040. };
  5041. LeafNode.prototype.hasChild = function () {
  5042. return false;
  5043. };
  5044. /** @inheritDoc */
  5045. LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
  5046. return null;
  5047. };
  5048. /** @inheritDoc */
  5049. LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5050. if (childName === '.priority') {
  5051. return this.updatePriority(newChildNode);
  5052. }
  5053. else if (newChildNode.isEmpty() && childName !== '.priority') {
  5054. return this;
  5055. }
  5056. else {
  5057. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  5058. }
  5059. };
  5060. /** @inheritDoc */
  5061. LeafNode.prototype.updateChild = function (path, newChildNode) {
  5062. var front = pathGetFront(path);
  5063. if (front === null) {
  5064. return newChildNode;
  5065. }
  5066. else if (newChildNode.isEmpty() && front !== '.priority') {
  5067. return this;
  5068. }
  5069. else {
  5070. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5071. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  5072. }
  5073. };
  5074. /** @inheritDoc */
  5075. LeafNode.prototype.isEmpty = function () {
  5076. return false;
  5077. };
  5078. /** @inheritDoc */
  5079. LeafNode.prototype.numChildren = function () {
  5080. return 0;
  5081. };
  5082. /** @inheritDoc */
  5083. LeafNode.prototype.forEachChild = function (index, action) {
  5084. return false;
  5085. };
  5086. LeafNode.prototype.val = function (exportFormat) {
  5087. if (exportFormat && !this.getPriority().isEmpty()) {
  5088. return {
  5089. '.value': this.getValue(),
  5090. '.priority': this.getPriority().val()
  5091. };
  5092. }
  5093. else {
  5094. return this.getValue();
  5095. }
  5096. };
  5097. /** @inheritDoc */
  5098. LeafNode.prototype.hash = function () {
  5099. if (this.lazyHash_ === null) {
  5100. var toHash = '';
  5101. if (!this.priorityNode_.isEmpty()) {
  5102. toHash +=
  5103. 'priority:' +
  5104. priorityHashText(this.priorityNode_.val()) +
  5105. ':';
  5106. }
  5107. var type = typeof this.value_;
  5108. toHash += type + ':';
  5109. if (type === 'number') {
  5110. toHash += doubleToIEEE754String(this.value_);
  5111. }
  5112. else {
  5113. toHash += this.value_;
  5114. }
  5115. this.lazyHash_ = sha1(toHash);
  5116. }
  5117. return this.lazyHash_;
  5118. };
  5119. /**
  5120. * Returns the value of the leaf node.
  5121. * @returns The value of the node.
  5122. */
  5123. LeafNode.prototype.getValue = function () {
  5124. return this.value_;
  5125. };
  5126. LeafNode.prototype.compareTo = function (other) {
  5127. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  5128. return 1;
  5129. }
  5130. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  5131. return -1;
  5132. }
  5133. else {
  5134. util.assert(other.isLeafNode(), 'Unknown node type');
  5135. return this.compareToLeafNode_(other);
  5136. }
  5137. };
  5138. /**
  5139. * Comparison specifically for two leaf nodes
  5140. */
  5141. LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
  5142. var otherLeafType = typeof otherLeaf.value_;
  5143. var thisLeafType = typeof this.value_;
  5144. var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  5145. var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  5146. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  5147. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  5148. if (otherIndex === thisIndex) {
  5149. // Same type, compare values
  5150. if (thisLeafType === 'object') {
  5151. // Deferred value nodes are all equal, but we should also never get to this point...
  5152. return 0;
  5153. }
  5154. else {
  5155. // Note that this works because true > false, all others are number or string comparisons
  5156. if (this.value_ < otherLeaf.value_) {
  5157. return -1;
  5158. }
  5159. else if (this.value_ === otherLeaf.value_) {
  5160. return 0;
  5161. }
  5162. else {
  5163. return 1;
  5164. }
  5165. }
  5166. }
  5167. else {
  5168. return thisIndex - otherIndex;
  5169. }
  5170. };
  5171. LeafNode.prototype.withIndex = function () {
  5172. return this;
  5173. };
  5174. LeafNode.prototype.isIndexed = function () {
  5175. return true;
  5176. };
  5177. LeafNode.prototype.equals = function (other) {
  5178. if (other === this) {
  5179. return true;
  5180. }
  5181. else if (other.isLeafNode()) {
  5182. var otherLeaf = other;
  5183. return (this.value_ === otherLeaf.value_ &&
  5184. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5185. }
  5186. else {
  5187. return false;
  5188. }
  5189. };
  5190. /**
  5191. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5192. * the same type, the comparison falls back to their value
  5193. */
  5194. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5195. return LeafNode;
  5196. }());
  5197. /**
  5198. * @license
  5199. * Copyright 2017 Google LLC
  5200. *
  5201. * Licensed under the Apache License, Version 2.0 (the "License");
  5202. * you may not use this file except in compliance with the License.
  5203. * You may obtain a copy of the License at
  5204. *
  5205. * http://www.apache.org/licenses/LICENSE-2.0
  5206. *
  5207. * Unless required by applicable law or agreed to in writing, software
  5208. * distributed under the License is distributed on an "AS IS" BASIS,
  5209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5210. * See the License for the specific language governing permissions and
  5211. * limitations under the License.
  5212. */
  5213. var nodeFromJSON$1;
  5214. var MAX_NODE$1;
  5215. function setNodeFromJSON(val) {
  5216. nodeFromJSON$1 = val;
  5217. }
  5218. function setMaxNode(val) {
  5219. MAX_NODE$1 = val;
  5220. }
  5221. var PriorityIndex = /** @class */ (function (_super) {
  5222. tslib.__extends(PriorityIndex, _super);
  5223. function PriorityIndex() {
  5224. return _super !== null && _super.apply(this, arguments) || this;
  5225. }
  5226. PriorityIndex.prototype.compare = function (a, b) {
  5227. var aPriority = a.node.getPriority();
  5228. var bPriority = b.node.getPriority();
  5229. var indexCmp = aPriority.compareTo(bPriority);
  5230. if (indexCmp === 0) {
  5231. return nameCompare(a.name, b.name);
  5232. }
  5233. else {
  5234. return indexCmp;
  5235. }
  5236. };
  5237. PriorityIndex.prototype.isDefinedOn = function (node) {
  5238. return !node.getPriority().isEmpty();
  5239. };
  5240. PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  5241. return !oldNode.getPriority().equals(newNode.getPriority());
  5242. };
  5243. PriorityIndex.prototype.minPost = function () {
  5244. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5245. return NamedNode.MIN;
  5246. };
  5247. PriorityIndex.prototype.maxPost = function () {
  5248. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5249. };
  5250. PriorityIndex.prototype.makePost = function (indexValue, name) {
  5251. var priorityNode = nodeFromJSON$1(indexValue);
  5252. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5253. };
  5254. /**
  5255. * @returns String representation for inclusion in a query spec
  5256. */
  5257. PriorityIndex.prototype.toString = function () {
  5258. return '.priority';
  5259. };
  5260. return PriorityIndex;
  5261. }(Index));
  5262. var PRIORITY_INDEX = new PriorityIndex();
  5263. /**
  5264. * @license
  5265. * Copyright 2017 Google LLC
  5266. *
  5267. * Licensed under the Apache License, Version 2.0 (the "License");
  5268. * you may not use this file except in compliance with the License.
  5269. * You may obtain a copy of the License at
  5270. *
  5271. * http://www.apache.org/licenses/LICENSE-2.0
  5272. *
  5273. * Unless required by applicable law or agreed to in writing, software
  5274. * distributed under the License is distributed on an "AS IS" BASIS,
  5275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5276. * See the License for the specific language governing permissions and
  5277. * limitations under the License.
  5278. */
  5279. var LOG_2 = Math.log(2);
  5280. var Base12Num = /** @class */ (function () {
  5281. function Base12Num(length) {
  5282. var logBase2 = function (num) {
  5283. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5284. return parseInt((Math.log(num) / LOG_2), 10);
  5285. };
  5286. var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
  5287. this.count = logBase2(length + 1);
  5288. this.current_ = this.count - 1;
  5289. var mask = bitMask(this.count);
  5290. this.bits_ = (length + 1) & mask;
  5291. }
  5292. Base12Num.prototype.nextBitIsOne = function () {
  5293. //noinspection JSBitwiseOperatorUsage
  5294. var result = !(this.bits_ & (0x1 << this.current_));
  5295. this.current_--;
  5296. return result;
  5297. };
  5298. return Base12Num;
  5299. }());
  5300. /**
  5301. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5302. * function
  5303. *
  5304. * Uses the algorithm described in the paper linked here:
  5305. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5306. *
  5307. * @param childList - Unsorted list of children
  5308. * @param cmp - The comparison method to be used
  5309. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5310. * type is not NamedNode
  5311. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5312. */
  5313. var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5314. childList.sort(cmp);
  5315. var buildBalancedTree = function (low, high) {
  5316. var length = high - low;
  5317. var namedNode;
  5318. var key;
  5319. if (length === 0) {
  5320. return null;
  5321. }
  5322. else if (length === 1) {
  5323. namedNode = childList[low];
  5324. key = keyFn ? keyFn(namedNode) : namedNode;
  5325. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5326. }
  5327. else {
  5328. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5329. var middle = parseInt((length / 2), 10) + low;
  5330. var left = buildBalancedTree(low, middle);
  5331. var right = buildBalancedTree(middle + 1, high);
  5332. namedNode = childList[middle];
  5333. key = keyFn ? keyFn(namedNode) : namedNode;
  5334. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5335. }
  5336. };
  5337. var buildFrom12Array = function (base12) {
  5338. var node = null;
  5339. var root = null;
  5340. var index = childList.length;
  5341. var buildPennant = function (chunkSize, color) {
  5342. var low = index - chunkSize;
  5343. var high = index;
  5344. index -= chunkSize;
  5345. var childTree = buildBalancedTree(low + 1, high);
  5346. var namedNode = childList[low];
  5347. var key = keyFn ? keyFn(namedNode) : namedNode;
  5348. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5349. };
  5350. var attachPennant = function (pennant) {
  5351. if (node) {
  5352. node.left = pennant;
  5353. node = pennant;
  5354. }
  5355. else {
  5356. root = pennant;
  5357. node = pennant;
  5358. }
  5359. };
  5360. for (var i = 0; i < base12.count; ++i) {
  5361. var isOne = base12.nextBitIsOne();
  5362. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5363. var chunkSize = Math.pow(2, base12.count - (i + 1));
  5364. if (isOne) {
  5365. buildPennant(chunkSize, LLRBNode.BLACK);
  5366. }
  5367. else {
  5368. // current == 2
  5369. buildPennant(chunkSize, LLRBNode.BLACK);
  5370. buildPennant(chunkSize, LLRBNode.RED);
  5371. }
  5372. }
  5373. return root;
  5374. };
  5375. var base12 = new Base12Num(childList.length);
  5376. var root = buildFrom12Array(base12);
  5377. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5378. return new SortedMap(mapSortFn || cmp, root);
  5379. };
  5380. /**
  5381. * @license
  5382. * Copyright 2017 Google LLC
  5383. *
  5384. * Licensed under the Apache License, Version 2.0 (the "License");
  5385. * you may not use this file except in compliance with the License.
  5386. * You may obtain a copy of the License at
  5387. *
  5388. * http://www.apache.org/licenses/LICENSE-2.0
  5389. *
  5390. * Unless required by applicable law or agreed to in writing, software
  5391. * distributed under the License is distributed on an "AS IS" BASIS,
  5392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5393. * See the License for the specific language governing permissions and
  5394. * limitations under the License.
  5395. */
  5396. var _defaultIndexMap;
  5397. var fallbackObject = {};
  5398. var IndexMap = /** @class */ (function () {
  5399. function IndexMap(indexes_, indexSet_) {
  5400. this.indexes_ = indexes_;
  5401. this.indexSet_ = indexSet_;
  5402. }
  5403. Object.defineProperty(IndexMap, "Default", {
  5404. /**
  5405. * The default IndexMap for nodes without a priority
  5406. */
  5407. get: function () {
  5408. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5409. _defaultIndexMap =
  5410. _defaultIndexMap ||
  5411. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5412. return _defaultIndexMap;
  5413. },
  5414. enumerable: false,
  5415. configurable: true
  5416. });
  5417. IndexMap.prototype.get = function (indexKey) {
  5418. var sortedMap = util.safeGet(this.indexes_, indexKey);
  5419. if (!sortedMap) {
  5420. throw new Error('No index defined for ' + indexKey);
  5421. }
  5422. if (sortedMap instanceof SortedMap) {
  5423. return sortedMap;
  5424. }
  5425. else {
  5426. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5427. // regular child map
  5428. return null;
  5429. }
  5430. };
  5431. IndexMap.prototype.hasIndex = function (indexDefinition) {
  5432. return util.contains(this.indexSet_, indexDefinition.toString());
  5433. };
  5434. IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
  5435. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5436. var childList = [];
  5437. var sawIndexedValue = false;
  5438. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5439. var next = iter.getNext();
  5440. while (next) {
  5441. sawIndexedValue =
  5442. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5443. childList.push(next);
  5444. next = iter.getNext();
  5445. }
  5446. var newIndex;
  5447. if (sawIndexedValue) {
  5448. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5449. }
  5450. else {
  5451. newIndex = fallbackObject;
  5452. }
  5453. var indexName = indexDefinition.toString();
  5454. var newIndexSet = tslib.__assign({}, this.indexSet_);
  5455. newIndexSet[indexName] = indexDefinition;
  5456. var newIndexes = tslib.__assign({}, this.indexes_);
  5457. newIndexes[indexName] = newIndex;
  5458. return new IndexMap(newIndexes, newIndexSet);
  5459. };
  5460. /**
  5461. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5462. */
  5463. IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
  5464. var _this = this;
  5465. var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) {
  5466. var index = util.safeGet(_this.indexSet_, indexName);
  5467. util.assert(index, 'Missing index implementation for ' + indexName);
  5468. if (indexedChildren === fallbackObject) {
  5469. // Check to see if we need to index everything
  5470. if (index.isDefinedOn(namedNode.node)) {
  5471. // We need to build this index
  5472. var childList = [];
  5473. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5474. var next = iter.getNext();
  5475. while (next) {
  5476. if (next.name !== namedNode.name) {
  5477. childList.push(next);
  5478. }
  5479. next = iter.getNext();
  5480. }
  5481. childList.push(namedNode);
  5482. return buildChildSet(childList, index.getCompare());
  5483. }
  5484. else {
  5485. // No change, this remains a fallback
  5486. return fallbackObject;
  5487. }
  5488. }
  5489. else {
  5490. var existingSnap = existingChildren.get(namedNode.name);
  5491. var newChildren = indexedChildren;
  5492. if (existingSnap) {
  5493. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5494. }
  5495. return newChildren.insert(namedNode, namedNode.node);
  5496. }
  5497. });
  5498. return new IndexMap(newIndexes, this.indexSet_);
  5499. };
  5500. /**
  5501. * Create a new IndexMap instance with the given value removed
  5502. */
  5503. IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
  5504. var newIndexes = util.map(this.indexes_, function (indexedChildren) {
  5505. if (indexedChildren === fallbackObject) {
  5506. // This is the fallback. Just return it, nothing to do in this case
  5507. return indexedChildren;
  5508. }
  5509. else {
  5510. var existingSnap = existingChildren.get(namedNode.name);
  5511. if (existingSnap) {
  5512. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5513. }
  5514. else {
  5515. // No record of this child
  5516. return indexedChildren;
  5517. }
  5518. }
  5519. });
  5520. return new IndexMap(newIndexes, this.indexSet_);
  5521. };
  5522. return IndexMap;
  5523. }());
  5524. /**
  5525. * @license
  5526. * Copyright 2017 Google LLC
  5527. *
  5528. * Licensed under the Apache License, Version 2.0 (the "License");
  5529. * you may not use this file except in compliance with the License.
  5530. * You may obtain a copy of the License at
  5531. *
  5532. * http://www.apache.org/licenses/LICENSE-2.0
  5533. *
  5534. * Unless required by applicable law or agreed to in writing, software
  5535. * distributed under the License is distributed on an "AS IS" BASIS,
  5536. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5537. * See the License for the specific language governing permissions and
  5538. * limitations under the License.
  5539. */
  5540. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5541. var EMPTY_NODE;
  5542. /**
  5543. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5544. * (i.e. nodes with children). It implements Node and stores the
  5545. * list of children in the children property, sorted by child name.
  5546. */
  5547. var ChildrenNode = /** @class */ (function () {
  5548. /**
  5549. * @param children_ - List of children of this node..
  5550. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5551. */
  5552. function ChildrenNode(children_, priorityNode_, indexMap_) {
  5553. this.children_ = children_;
  5554. this.priorityNode_ = priorityNode_;
  5555. this.indexMap_ = indexMap_;
  5556. this.lazyHash_ = null;
  5557. /**
  5558. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5559. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5560. * class instead of an empty ChildrenNode.
  5561. */
  5562. if (this.priorityNode_) {
  5563. validatePriorityNode(this.priorityNode_);
  5564. }
  5565. if (this.children_.isEmpty()) {
  5566. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5567. }
  5568. }
  5569. Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
  5570. get: function () {
  5571. return (EMPTY_NODE ||
  5572. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5573. },
  5574. enumerable: false,
  5575. configurable: true
  5576. });
  5577. /** @inheritDoc */
  5578. ChildrenNode.prototype.isLeafNode = function () {
  5579. return false;
  5580. };
  5581. /** @inheritDoc */
  5582. ChildrenNode.prototype.getPriority = function () {
  5583. return this.priorityNode_ || EMPTY_NODE;
  5584. };
  5585. /** @inheritDoc */
  5586. ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
  5587. if (this.children_.isEmpty()) {
  5588. // Don't allow priorities on empty nodes
  5589. return this;
  5590. }
  5591. else {
  5592. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5593. }
  5594. };
  5595. /** @inheritDoc */
  5596. ChildrenNode.prototype.getImmediateChild = function (childName) {
  5597. // Hack to treat priority as a regular child
  5598. if (childName === '.priority') {
  5599. return this.getPriority();
  5600. }
  5601. else {
  5602. var child = this.children_.get(childName);
  5603. return child === null ? EMPTY_NODE : child;
  5604. }
  5605. };
  5606. /** @inheritDoc */
  5607. ChildrenNode.prototype.getChild = function (path) {
  5608. var front = pathGetFront(path);
  5609. if (front === null) {
  5610. return this;
  5611. }
  5612. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5613. };
  5614. /** @inheritDoc */
  5615. ChildrenNode.prototype.hasChild = function (childName) {
  5616. return this.children_.get(childName) !== null;
  5617. };
  5618. /** @inheritDoc */
  5619. ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5620. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  5621. if (childName === '.priority') {
  5622. return this.updatePriority(newChildNode);
  5623. }
  5624. else {
  5625. var namedNode = new NamedNode(childName, newChildNode);
  5626. var newChildren = void 0, newIndexMap = void 0;
  5627. if (newChildNode.isEmpty()) {
  5628. newChildren = this.children_.remove(childName);
  5629. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5630. }
  5631. else {
  5632. newChildren = this.children_.insert(childName, newChildNode);
  5633. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5634. }
  5635. var newPriority = newChildren.isEmpty()
  5636. ? EMPTY_NODE
  5637. : this.priorityNode_;
  5638. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5639. }
  5640. };
  5641. /** @inheritDoc */
  5642. ChildrenNode.prototype.updateChild = function (path, newChildNode) {
  5643. var front = pathGetFront(path);
  5644. if (front === null) {
  5645. return newChildNode;
  5646. }
  5647. else {
  5648. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5649. var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5650. return this.updateImmediateChild(front, newImmediateChild);
  5651. }
  5652. };
  5653. /** @inheritDoc */
  5654. ChildrenNode.prototype.isEmpty = function () {
  5655. return this.children_.isEmpty();
  5656. };
  5657. /** @inheritDoc */
  5658. ChildrenNode.prototype.numChildren = function () {
  5659. return this.children_.count();
  5660. };
  5661. /** @inheritDoc */
  5662. ChildrenNode.prototype.val = function (exportFormat) {
  5663. if (this.isEmpty()) {
  5664. return null;
  5665. }
  5666. var obj = {};
  5667. var numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5668. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5669. obj[key] = childNode.val(exportFormat);
  5670. numKeys++;
  5671. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5672. maxKey = Math.max(maxKey, Number(key));
  5673. }
  5674. else {
  5675. allIntegerKeys = false;
  5676. }
  5677. });
  5678. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5679. // convert to array.
  5680. var array = [];
  5681. // eslint-disable-next-line guard-for-in
  5682. for (var key in obj) {
  5683. array[key] = obj[key];
  5684. }
  5685. return array;
  5686. }
  5687. else {
  5688. if (exportFormat && !this.getPriority().isEmpty()) {
  5689. obj['.priority'] = this.getPriority().val();
  5690. }
  5691. return obj;
  5692. }
  5693. };
  5694. /** @inheritDoc */
  5695. ChildrenNode.prototype.hash = function () {
  5696. if (this.lazyHash_ === null) {
  5697. var toHash_1 = '';
  5698. if (!this.getPriority().isEmpty()) {
  5699. toHash_1 +=
  5700. 'priority:' +
  5701. priorityHashText(this.getPriority().val()) +
  5702. ':';
  5703. }
  5704. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5705. var childHash = childNode.hash();
  5706. if (childHash !== '') {
  5707. toHash_1 += ':' + key + ':' + childHash;
  5708. }
  5709. });
  5710. this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
  5711. }
  5712. return this.lazyHash_;
  5713. };
  5714. /** @inheritDoc */
  5715. ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
  5716. var idx = this.resolveIndex_(index);
  5717. if (idx) {
  5718. var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5719. return predecessor ? predecessor.name : null;
  5720. }
  5721. else {
  5722. return this.children_.getPredecessorKey(childName);
  5723. }
  5724. };
  5725. ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
  5726. var idx = this.resolveIndex_(indexDefinition);
  5727. if (idx) {
  5728. var minKey = idx.minKey();
  5729. return minKey && minKey.name;
  5730. }
  5731. else {
  5732. return this.children_.minKey();
  5733. }
  5734. };
  5735. ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
  5736. var minKey = this.getFirstChildName(indexDefinition);
  5737. if (minKey) {
  5738. return new NamedNode(minKey, this.children_.get(minKey));
  5739. }
  5740. else {
  5741. return null;
  5742. }
  5743. };
  5744. /**
  5745. * Given an index, return the key name of the largest value we have, according to that index
  5746. */
  5747. ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
  5748. var idx = this.resolveIndex_(indexDefinition);
  5749. if (idx) {
  5750. var maxKey = idx.maxKey();
  5751. return maxKey && maxKey.name;
  5752. }
  5753. else {
  5754. return this.children_.maxKey();
  5755. }
  5756. };
  5757. ChildrenNode.prototype.getLastChild = function (indexDefinition) {
  5758. var maxKey = this.getLastChildName(indexDefinition);
  5759. if (maxKey) {
  5760. return new NamedNode(maxKey, this.children_.get(maxKey));
  5761. }
  5762. else {
  5763. return null;
  5764. }
  5765. };
  5766. ChildrenNode.prototype.forEachChild = function (index, action) {
  5767. var idx = this.resolveIndex_(index);
  5768. if (idx) {
  5769. return idx.inorderTraversal(function (wrappedNode) {
  5770. return action(wrappedNode.name, wrappedNode.node);
  5771. });
  5772. }
  5773. else {
  5774. return this.children_.inorderTraversal(action);
  5775. }
  5776. };
  5777. ChildrenNode.prototype.getIterator = function (indexDefinition) {
  5778. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5779. };
  5780. ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
  5781. var idx = this.resolveIndex_(indexDefinition);
  5782. if (idx) {
  5783. return idx.getIteratorFrom(startPost, function (key) { return key; });
  5784. }
  5785. else {
  5786. var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5787. var next = iterator.peek();
  5788. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5789. iterator.getNext();
  5790. next = iterator.peek();
  5791. }
  5792. return iterator;
  5793. }
  5794. };
  5795. ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
  5796. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5797. };
  5798. ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
  5799. var idx = this.resolveIndex_(indexDefinition);
  5800. if (idx) {
  5801. return idx.getReverseIteratorFrom(endPost, function (key) {
  5802. return key;
  5803. });
  5804. }
  5805. else {
  5806. var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5807. var next = iterator.peek();
  5808. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5809. iterator.getNext();
  5810. next = iterator.peek();
  5811. }
  5812. return iterator;
  5813. }
  5814. };
  5815. ChildrenNode.prototype.compareTo = function (other) {
  5816. if (this.isEmpty()) {
  5817. if (other.isEmpty()) {
  5818. return 0;
  5819. }
  5820. else {
  5821. return -1;
  5822. }
  5823. }
  5824. else if (other.isLeafNode() || other.isEmpty()) {
  5825. return 1;
  5826. }
  5827. else if (other === MAX_NODE) {
  5828. return -1;
  5829. }
  5830. else {
  5831. // Must be another node with children.
  5832. return 0;
  5833. }
  5834. };
  5835. ChildrenNode.prototype.withIndex = function (indexDefinition) {
  5836. if (indexDefinition === KEY_INDEX ||
  5837. this.indexMap_.hasIndex(indexDefinition)) {
  5838. return this;
  5839. }
  5840. else {
  5841. var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5842. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5843. }
  5844. };
  5845. ChildrenNode.prototype.isIndexed = function (index) {
  5846. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5847. };
  5848. ChildrenNode.prototype.equals = function (other) {
  5849. if (other === this) {
  5850. return true;
  5851. }
  5852. else if (other.isLeafNode()) {
  5853. return false;
  5854. }
  5855. else {
  5856. var otherChildrenNode = other;
  5857. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5858. return false;
  5859. }
  5860. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5861. var thisIter = this.getIterator(PRIORITY_INDEX);
  5862. var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5863. var thisCurrent = thisIter.getNext();
  5864. var otherCurrent = otherIter.getNext();
  5865. while (thisCurrent && otherCurrent) {
  5866. if (thisCurrent.name !== otherCurrent.name ||
  5867. !thisCurrent.node.equals(otherCurrent.node)) {
  5868. return false;
  5869. }
  5870. thisCurrent = thisIter.getNext();
  5871. otherCurrent = otherIter.getNext();
  5872. }
  5873. return thisCurrent === null && otherCurrent === null;
  5874. }
  5875. else {
  5876. return false;
  5877. }
  5878. }
  5879. };
  5880. /**
  5881. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5882. * instead.
  5883. *
  5884. */
  5885. ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
  5886. if (indexDefinition === KEY_INDEX) {
  5887. return null;
  5888. }
  5889. else {
  5890. return this.indexMap_.get(indexDefinition.toString());
  5891. }
  5892. };
  5893. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5894. return ChildrenNode;
  5895. }());
  5896. var MaxNode = /** @class */ (function (_super) {
  5897. tslib.__extends(MaxNode, _super);
  5898. function MaxNode() {
  5899. return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
  5900. }
  5901. MaxNode.prototype.compareTo = function (other) {
  5902. if (other === this) {
  5903. return 0;
  5904. }
  5905. else {
  5906. return 1;
  5907. }
  5908. };
  5909. MaxNode.prototype.equals = function (other) {
  5910. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5911. return other === this;
  5912. };
  5913. MaxNode.prototype.getPriority = function () {
  5914. return this;
  5915. };
  5916. MaxNode.prototype.getImmediateChild = function (childName) {
  5917. return ChildrenNode.EMPTY_NODE;
  5918. };
  5919. MaxNode.prototype.isEmpty = function () {
  5920. return false;
  5921. };
  5922. return MaxNode;
  5923. }(ChildrenNode));
  5924. /**
  5925. * Marker that will sort higher than any other snapshot.
  5926. */
  5927. var MAX_NODE = new MaxNode();
  5928. Object.defineProperties(NamedNode, {
  5929. MIN: {
  5930. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5931. },
  5932. MAX: {
  5933. value: new NamedNode(MAX_NAME, MAX_NODE)
  5934. }
  5935. });
  5936. /**
  5937. * Reference Extensions
  5938. */
  5939. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5940. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5941. setMaxNode$1(MAX_NODE);
  5942. setMaxNode(MAX_NODE);
  5943. /**
  5944. * @license
  5945. * Copyright 2017 Google LLC
  5946. *
  5947. * Licensed under the Apache License, Version 2.0 (the "License");
  5948. * you may not use this file except in compliance with the License.
  5949. * You may obtain a copy of the License at
  5950. *
  5951. * http://www.apache.org/licenses/LICENSE-2.0
  5952. *
  5953. * Unless required by applicable law or agreed to in writing, software
  5954. * distributed under the License is distributed on an "AS IS" BASIS,
  5955. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5956. * See the License for the specific language governing permissions and
  5957. * limitations under the License.
  5958. */
  5959. var USE_HINZE = true;
  5960. /**
  5961. * Constructs a snapshot node representing the passed JSON and returns it.
  5962. * @param json - JSON to create a node for.
  5963. * @param priority - Optional priority to use. This will be ignored if the
  5964. * passed JSON contains a .priority property.
  5965. */
  5966. function nodeFromJSON(json, priority) {
  5967. if (priority === void 0) { priority = null; }
  5968. if (json === null) {
  5969. return ChildrenNode.EMPTY_NODE;
  5970. }
  5971. if (typeof json === 'object' && '.priority' in json) {
  5972. priority = json['.priority'];
  5973. }
  5974. util.assert(priority === null ||
  5975. typeof priority === 'string' ||
  5976. typeof priority === 'number' ||
  5977. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5978. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5979. json = json['.value'];
  5980. }
  5981. // Valid leaf nodes include non-objects or server-value wrapper objects
  5982. if (typeof json !== 'object' || '.sv' in json) {
  5983. var jsonLeaf = json;
  5984. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5985. }
  5986. if (!(json instanceof Array) && USE_HINZE) {
  5987. var children_1 = [];
  5988. var childrenHavePriority_1 = false;
  5989. var hinzeJsonObj = json;
  5990. each(hinzeJsonObj, function (key, child) {
  5991. if (key.substring(0, 1) !== '.') {
  5992. // Ignore metadata nodes
  5993. var childNode = nodeFromJSON(child);
  5994. if (!childNode.isEmpty()) {
  5995. childrenHavePriority_1 =
  5996. childrenHavePriority_1 || !childNode.getPriority().isEmpty();
  5997. children_1.push(new NamedNode(key, childNode));
  5998. }
  5999. }
  6000. });
  6001. if (children_1.length === 0) {
  6002. return ChildrenNode.EMPTY_NODE;
  6003. }
  6004. var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
  6005. if (childrenHavePriority_1) {
  6006. var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
  6007. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  6008. }
  6009. else {
  6010. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  6011. }
  6012. }
  6013. else {
  6014. var node_1 = ChildrenNode.EMPTY_NODE;
  6015. each(json, function (key, childData) {
  6016. if (util.contains(json, key)) {
  6017. if (key.substring(0, 1) !== '.') {
  6018. // ignore metadata nodes.
  6019. var childNode = nodeFromJSON(childData);
  6020. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  6021. node_1 = node_1.updateImmediateChild(key, childNode);
  6022. }
  6023. }
  6024. }
  6025. });
  6026. return node_1.updatePriority(nodeFromJSON(priority));
  6027. }
  6028. }
  6029. setNodeFromJSON(nodeFromJSON);
  6030. /**
  6031. * @license
  6032. * Copyright 2017 Google LLC
  6033. *
  6034. * Licensed under the Apache License, Version 2.0 (the "License");
  6035. * you may not use this file except in compliance with the License.
  6036. * You may obtain a copy of the License at
  6037. *
  6038. * http://www.apache.org/licenses/LICENSE-2.0
  6039. *
  6040. * Unless required by applicable law or agreed to in writing, software
  6041. * distributed under the License is distributed on an "AS IS" BASIS,
  6042. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6043. * See the License for the specific language governing permissions and
  6044. * limitations under the License.
  6045. */
  6046. var PathIndex = /** @class */ (function (_super) {
  6047. tslib.__extends(PathIndex, _super);
  6048. function PathIndex(indexPath_) {
  6049. var _this = _super.call(this) || this;
  6050. _this.indexPath_ = indexPath_;
  6051. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  6052. return _this;
  6053. }
  6054. PathIndex.prototype.extractChild = function (snap) {
  6055. return snap.getChild(this.indexPath_);
  6056. };
  6057. PathIndex.prototype.isDefinedOn = function (node) {
  6058. return !node.getChild(this.indexPath_).isEmpty();
  6059. };
  6060. PathIndex.prototype.compare = function (a, b) {
  6061. var aChild = this.extractChild(a.node);
  6062. var bChild = this.extractChild(b.node);
  6063. var indexCmp = aChild.compareTo(bChild);
  6064. if (indexCmp === 0) {
  6065. return nameCompare(a.name, b.name);
  6066. }
  6067. else {
  6068. return indexCmp;
  6069. }
  6070. };
  6071. PathIndex.prototype.makePost = function (indexValue, name) {
  6072. var valueNode = nodeFromJSON(indexValue);
  6073. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  6074. return new NamedNode(name, node);
  6075. };
  6076. PathIndex.prototype.maxPost = function () {
  6077. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  6078. return new NamedNode(MAX_NAME, node);
  6079. };
  6080. PathIndex.prototype.toString = function () {
  6081. return pathSlice(this.indexPath_, 0).join('/');
  6082. };
  6083. return PathIndex;
  6084. }(Index));
  6085. /**
  6086. * @license
  6087. * Copyright 2017 Google LLC
  6088. *
  6089. * Licensed under the Apache License, Version 2.0 (the "License");
  6090. * you may not use this file except in compliance with the License.
  6091. * You may obtain a copy of the License at
  6092. *
  6093. * http://www.apache.org/licenses/LICENSE-2.0
  6094. *
  6095. * Unless required by applicable law or agreed to in writing, software
  6096. * distributed under the License is distributed on an "AS IS" BASIS,
  6097. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6098. * See the License for the specific language governing permissions and
  6099. * limitations under the License.
  6100. */
  6101. var ValueIndex = /** @class */ (function (_super) {
  6102. tslib.__extends(ValueIndex, _super);
  6103. function ValueIndex() {
  6104. return _super !== null && _super.apply(this, arguments) || this;
  6105. }
  6106. ValueIndex.prototype.compare = function (a, b) {
  6107. var indexCmp = a.node.compareTo(b.node);
  6108. if (indexCmp === 0) {
  6109. return nameCompare(a.name, b.name);
  6110. }
  6111. else {
  6112. return indexCmp;
  6113. }
  6114. };
  6115. ValueIndex.prototype.isDefinedOn = function (node) {
  6116. return true;
  6117. };
  6118. ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  6119. return !oldNode.equals(newNode);
  6120. };
  6121. ValueIndex.prototype.minPost = function () {
  6122. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6123. return NamedNode.MIN;
  6124. };
  6125. ValueIndex.prototype.maxPost = function () {
  6126. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6127. return NamedNode.MAX;
  6128. };
  6129. ValueIndex.prototype.makePost = function (indexValue, name) {
  6130. var valueNode = nodeFromJSON(indexValue);
  6131. return new NamedNode(name, valueNode);
  6132. };
  6133. /**
  6134. * @returns String representation for inclusion in a query spec
  6135. */
  6136. ValueIndex.prototype.toString = function () {
  6137. return '.value';
  6138. };
  6139. return ValueIndex;
  6140. }(Index));
  6141. var VALUE_INDEX = new ValueIndex();
  6142. /**
  6143. * @license
  6144. * Copyright 2017 Google LLC
  6145. *
  6146. * Licensed under the Apache License, Version 2.0 (the "License");
  6147. * you may not use this file except in compliance with the License.
  6148. * You may obtain a copy of the License at
  6149. *
  6150. * http://www.apache.org/licenses/LICENSE-2.0
  6151. *
  6152. * Unless required by applicable law or agreed to in writing, software
  6153. * distributed under the License is distributed on an "AS IS" BASIS,
  6154. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6155. * See the License for the specific language governing permissions and
  6156. * limitations under the License.
  6157. */
  6158. function changeValue(snapshotNode) {
  6159. return { type: "value" /* ChangeType.VALUE */, snapshotNode: snapshotNode };
  6160. }
  6161. function changeChildAdded(childName, snapshotNode) {
  6162. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode: snapshotNode, childName: childName };
  6163. }
  6164. function changeChildRemoved(childName, snapshotNode) {
  6165. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode: snapshotNode, childName: childName };
  6166. }
  6167. function changeChildChanged(childName, snapshotNode, oldSnap) {
  6168. return {
  6169. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  6170. snapshotNode: snapshotNode,
  6171. childName: childName,
  6172. oldSnap: oldSnap
  6173. };
  6174. }
  6175. function changeChildMoved(childName, snapshotNode) {
  6176. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode: snapshotNode, childName: childName };
  6177. }
  6178. /**
  6179. * @license
  6180. * Copyright 2017 Google LLC
  6181. *
  6182. * Licensed under the Apache License, Version 2.0 (the "License");
  6183. * you may not use this file except in compliance with the License.
  6184. * You may obtain a copy of the License at
  6185. *
  6186. * http://www.apache.org/licenses/LICENSE-2.0
  6187. *
  6188. * Unless required by applicable law or agreed to in writing, software
  6189. * distributed under the License is distributed on an "AS IS" BASIS,
  6190. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6191. * See the License for the specific language governing permissions and
  6192. * limitations under the License.
  6193. */
  6194. /**
  6195. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  6196. */
  6197. var IndexedFilter = /** @class */ (function () {
  6198. function IndexedFilter(index_) {
  6199. this.index_ = index_;
  6200. }
  6201. IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6202. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  6203. var oldChild = snap.getImmediateChild(key);
  6204. // Check if anything actually changed.
  6205. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  6206. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  6207. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  6208. // to avoid treating these cases as "nothing changed."
  6209. if (oldChild.isEmpty() === newChild.isEmpty()) {
  6210. // Nothing changed.
  6211. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  6212. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  6213. return snap;
  6214. }
  6215. }
  6216. if (optChangeAccumulator != null) {
  6217. if (newChild.isEmpty()) {
  6218. if (snap.hasChild(key)) {
  6219. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6220. }
  6221. else {
  6222. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6223. }
  6224. }
  6225. else if (oldChild.isEmpty()) {
  6226. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6227. }
  6228. else {
  6229. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6230. }
  6231. }
  6232. if (snap.isLeafNode() && newChild.isEmpty()) {
  6233. return snap;
  6234. }
  6235. else {
  6236. // Make sure the node is indexed
  6237. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6238. }
  6239. };
  6240. IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6241. if (optChangeAccumulator != null) {
  6242. if (!oldSnap.isLeafNode()) {
  6243. oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6244. if (!newSnap.hasChild(key)) {
  6245. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6246. }
  6247. });
  6248. }
  6249. if (!newSnap.isLeafNode()) {
  6250. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6251. if (oldSnap.hasChild(key)) {
  6252. var oldChild = oldSnap.getImmediateChild(key);
  6253. if (!oldChild.equals(childNode)) {
  6254. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6255. }
  6256. }
  6257. else {
  6258. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6259. }
  6260. });
  6261. }
  6262. }
  6263. return newSnap.withIndex(this.index_);
  6264. };
  6265. IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6266. if (oldSnap.isEmpty()) {
  6267. return ChildrenNode.EMPTY_NODE;
  6268. }
  6269. else {
  6270. return oldSnap.updatePriority(newPriority);
  6271. }
  6272. };
  6273. IndexedFilter.prototype.filtersNodes = function () {
  6274. return false;
  6275. };
  6276. IndexedFilter.prototype.getIndexedFilter = function () {
  6277. return this;
  6278. };
  6279. IndexedFilter.prototype.getIndex = function () {
  6280. return this.index_;
  6281. };
  6282. return IndexedFilter;
  6283. }());
  6284. /**
  6285. * @license
  6286. * Copyright 2017 Google LLC
  6287. *
  6288. * Licensed under the Apache License, Version 2.0 (the "License");
  6289. * you may not use this file except in compliance with the License.
  6290. * You may obtain a copy of the License at
  6291. *
  6292. * http://www.apache.org/licenses/LICENSE-2.0
  6293. *
  6294. * Unless required by applicable law or agreed to in writing, software
  6295. * distributed under the License is distributed on an "AS IS" BASIS,
  6296. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6297. * See the License for the specific language governing permissions and
  6298. * limitations under the License.
  6299. */
  6300. /**
  6301. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6302. */
  6303. var RangedFilter = /** @class */ (function () {
  6304. function RangedFilter(params) {
  6305. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6306. this.index_ = params.getIndex();
  6307. this.startPost_ = RangedFilter.getStartPost_(params);
  6308. this.endPost_ = RangedFilter.getEndPost_(params);
  6309. this.startIsInclusive_ = !params.startAfterSet_;
  6310. this.endIsInclusive_ = !params.endBeforeSet_;
  6311. }
  6312. RangedFilter.prototype.getStartPost = function () {
  6313. return this.startPost_;
  6314. };
  6315. RangedFilter.prototype.getEndPost = function () {
  6316. return this.endPost_;
  6317. };
  6318. RangedFilter.prototype.matches = function (node) {
  6319. var isWithinStart = this.startIsInclusive_
  6320. ? this.index_.compare(this.getStartPost(), node) <= 0
  6321. : this.index_.compare(this.getStartPost(), node) < 0;
  6322. var isWithinEnd = this.endIsInclusive_
  6323. ? this.index_.compare(node, this.getEndPost()) <= 0
  6324. : this.index_.compare(node, this.getEndPost()) < 0;
  6325. return isWithinStart && isWithinEnd;
  6326. };
  6327. RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6328. if (!this.matches(new NamedNode(key, newChild))) {
  6329. newChild = ChildrenNode.EMPTY_NODE;
  6330. }
  6331. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6332. };
  6333. RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6334. if (newSnap.isLeafNode()) {
  6335. // Make sure we have a children node with the correct index, not a leaf node;
  6336. newSnap = ChildrenNode.EMPTY_NODE;
  6337. }
  6338. var filtered = newSnap.withIndex(this.index_);
  6339. // Don't support priorities on queries
  6340. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6341. var self = this;
  6342. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6343. if (!self.matches(new NamedNode(key, childNode))) {
  6344. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6345. }
  6346. });
  6347. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6348. };
  6349. RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6350. // Don't support priorities on queries
  6351. return oldSnap;
  6352. };
  6353. RangedFilter.prototype.filtersNodes = function () {
  6354. return true;
  6355. };
  6356. RangedFilter.prototype.getIndexedFilter = function () {
  6357. return this.indexedFilter_;
  6358. };
  6359. RangedFilter.prototype.getIndex = function () {
  6360. return this.index_;
  6361. };
  6362. RangedFilter.getStartPost_ = function (params) {
  6363. if (params.hasStart()) {
  6364. var startName = params.getIndexStartName();
  6365. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6366. }
  6367. else {
  6368. return params.getIndex().minPost();
  6369. }
  6370. };
  6371. RangedFilter.getEndPost_ = function (params) {
  6372. if (params.hasEnd()) {
  6373. var endName = params.getIndexEndName();
  6374. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6375. }
  6376. else {
  6377. return params.getIndex().maxPost();
  6378. }
  6379. };
  6380. return RangedFilter;
  6381. }());
  6382. /**
  6383. * @license
  6384. * Copyright 2017 Google LLC
  6385. *
  6386. * Licensed under the Apache License, Version 2.0 (the "License");
  6387. * you may not use this file except in compliance with the License.
  6388. * You may obtain a copy of the License at
  6389. *
  6390. * http://www.apache.org/licenses/LICENSE-2.0
  6391. *
  6392. * Unless required by applicable law or agreed to in writing, software
  6393. * distributed under the License is distributed on an "AS IS" BASIS,
  6394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6395. * See the License for the specific language governing permissions and
  6396. * limitations under the License.
  6397. */
  6398. /**
  6399. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6400. */
  6401. var LimitedFilter = /** @class */ (function () {
  6402. function LimitedFilter(params) {
  6403. var _this = this;
  6404. this.withinDirectionalStart = function (node) {
  6405. return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
  6406. };
  6407. this.withinDirectionalEnd = function (node) {
  6408. return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
  6409. };
  6410. this.withinStartPost = function (node) {
  6411. var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
  6412. return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6413. };
  6414. this.withinEndPost = function (node) {
  6415. var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
  6416. return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6417. };
  6418. this.rangedFilter_ = new RangedFilter(params);
  6419. this.index_ = params.getIndex();
  6420. this.limit_ = params.getLimit();
  6421. this.reverse_ = !params.isViewFromLeft();
  6422. this.startIsInclusive_ = !params.startAfterSet_;
  6423. this.endIsInclusive_ = !params.endBeforeSet_;
  6424. }
  6425. LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6426. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6427. newChild = ChildrenNode.EMPTY_NODE;
  6428. }
  6429. if (snap.getImmediateChild(key).equals(newChild)) {
  6430. // No change
  6431. return snap;
  6432. }
  6433. else if (snap.numChildren() < this.limit_) {
  6434. return this.rangedFilter_
  6435. .getIndexedFilter()
  6436. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6437. }
  6438. else {
  6439. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6440. }
  6441. };
  6442. LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6443. var filtered;
  6444. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6445. // Make sure we have a children node with the correct index, not a leaf node;
  6446. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6447. }
  6448. else {
  6449. if (this.limit_ * 2 < newSnap.numChildren() &&
  6450. newSnap.isIndexed(this.index_)) {
  6451. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6452. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6453. // anchor to the startPost, endPost, or last element as appropriate
  6454. var iterator = void 0;
  6455. if (this.reverse_) {
  6456. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6457. }
  6458. else {
  6459. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6460. }
  6461. var count = 0;
  6462. while (iterator.hasNext() && count < this.limit_) {
  6463. var next = iterator.getNext();
  6464. if (!this.withinDirectionalStart(next)) {
  6465. // if we have not reached the start, skip to the next element
  6466. continue;
  6467. }
  6468. else if (!this.withinDirectionalEnd(next)) {
  6469. // if we have reached the end, stop adding elements
  6470. break;
  6471. }
  6472. else {
  6473. filtered = filtered.updateImmediateChild(next.name, next.node);
  6474. count++;
  6475. }
  6476. }
  6477. }
  6478. else {
  6479. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6480. filtered = newSnap.withIndex(this.index_);
  6481. // Don't support priorities on queries
  6482. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6483. var iterator = void 0;
  6484. if (this.reverse_) {
  6485. iterator = filtered.getReverseIterator(this.index_);
  6486. }
  6487. else {
  6488. iterator = filtered.getIterator(this.index_);
  6489. }
  6490. var count = 0;
  6491. while (iterator.hasNext()) {
  6492. var next = iterator.getNext();
  6493. var inRange = count < this.limit_ &&
  6494. this.withinDirectionalStart(next) &&
  6495. this.withinDirectionalEnd(next);
  6496. if (inRange) {
  6497. count++;
  6498. }
  6499. else {
  6500. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6501. }
  6502. }
  6503. }
  6504. }
  6505. return this.rangedFilter_
  6506. .getIndexedFilter()
  6507. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6508. };
  6509. LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6510. // Don't support priorities on queries
  6511. return oldSnap;
  6512. };
  6513. LimitedFilter.prototype.filtersNodes = function () {
  6514. return true;
  6515. };
  6516. LimitedFilter.prototype.getIndexedFilter = function () {
  6517. return this.rangedFilter_.getIndexedFilter();
  6518. };
  6519. LimitedFilter.prototype.getIndex = function () {
  6520. return this.index_;
  6521. };
  6522. LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
  6523. // TODO: rename all cache stuff etc to general snap terminology
  6524. var cmp;
  6525. if (this.reverse_) {
  6526. var indexCmp_1 = this.index_.getCompare();
  6527. cmp = function (a, b) { return indexCmp_1(b, a); };
  6528. }
  6529. else {
  6530. cmp = this.index_.getCompare();
  6531. }
  6532. var oldEventCache = snap;
  6533. util.assert(oldEventCache.numChildren() === this.limit_, '');
  6534. var newChildNamedNode = new NamedNode(childKey, childSnap);
  6535. var windowBoundary = this.reverse_
  6536. ? oldEventCache.getFirstChild(this.index_)
  6537. : oldEventCache.getLastChild(this.index_);
  6538. var inRange = this.rangedFilter_.matches(newChildNamedNode);
  6539. if (oldEventCache.hasChild(childKey)) {
  6540. var oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6541. var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6542. while (nextChild != null &&
  6543. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6544. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6545. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6546. // the limited filter...
  6547. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6548. }
  6549. var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6550. var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6551. if (remainsInWindow) {
  6552. if (changeAccumulator != null) {
  6553. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6554. }
  6555. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6556. }
  6557. else {
  6558. if (changeAccumulator != null) {
  6559. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6560. }
  6561. var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6562. var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6563. if (nextChildInRange) {
  6564. if (changeAccumulator != null) {
  6565. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6566. }
  6567. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6568. }
  6569. else {
  6570. return newEventCache;
  6571. }
  6572. }
  6573. }
  6574. else if (childSnap.isEmpty()) {
  6575. // we're deleting a node, but it was not in the window, so ignore it
  6576. return snap;
  6577. }
  6578. else if (inRange) {
  6579. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6580. if (changeAccumulator != null) {
  6581. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6582. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6583. }
  6584. return oldEventCache
  6585. .updateImmediateChild(childKey, childSnap)
  6586. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6587. }
  6588. else {
  6589. return snap;
  6590. }
  6591. }
  6592. else {
  6593. return snap;
  6594. }
  6595. };
  6596. return LimitedFilter;
  6597. }());
  6598. /**
  6599. * @license
  6600. * Copyright 2017 Google LLC
  6601. *
  6602. * Licensed under the Apache License, Version 2.0 (the "License");
  6603. * you may not use this file except in compliance with the License.
  6604. * You may obtain a copy of the License at
  6605. *
  6606. * http://www.apache.org/licenses/LICENSE-2.0
  6607. *
  6608. * Unless required by applicable law or agreed to in writing, software
  6609. * distributed under the License is distributed on an "AS IS" BASIS,
  6610. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6611. * See the License for the specific language governing permissions and
  6612. * limitations under the License.
  6613. */
  6614. /**
  6615. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6616. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6617. * user-facing API level, so it is not done here.
  6618. *
  6619. * @internal
  6620. */
  6621. var QueryParams = /** @class */ (function () {
  6622. function QueryParams() {
  6623. this.limitSet_ = false;
  6624. this.startSet_ = false;
  6625. this.startNameSet_ = false;
  6626. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6627. this.endSet_ = false;
  6628. this.endNameSet_ = false;
  6629. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6630. this.limit_ = 0;
  6631. this.viewFrom_ = '';
  6632. this.indexStartValue_ = null;
  6633. this.indexStartName_ = '';
  6634. this.indexEndValue_ = null;
  6635. this.indexEndName_ = '';
  6636. this.index_ = PRIORITY_INDEX;
  6637. }
  6638. QueryParams.prototype.hasStart = function () {
  6639. return this.startSet_;
  6640. };
  6641. /**
  6642. * @returns True if it would return from left.
  6643. */
  6644. QueryParams.prototype.isViewFromLeft = function () {
  6645. if (this.viewFrom_ === '') {
  6646. // limit(), rather than limitToFirst or limitToLast was called.
  6647. // This means that only one of startSet_ and endSet_ is true. Use them
  6648. // to calculate which side of the view to anchor to. If neither is set,
  6649. // anchor to the end.
  6650. return this.startSet_;
  6651. }
  6652. else {
  6653. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6654. }
  6655. };
  6656. /**
  6657. * Only valid to call if hasStart() returns true
  6658. */
  6659. QueryParams.prototype.getIndexStartValue = function () {
  6660. util.assert(this.startSet_, 'Only valid if start has been set');
  6661. return this.indexStartValue_;
  6662. };
  6663. /**
  6664. * Only valid to call if hasStart() returns true.
  6665. * Returns the starting key name for the range defined by these query parameters
  6666. */
  6667. QueryParams.prototype.getIndexStartName = function () {
  6668. util.assert(this.startSet_, 'Only valid if start has been set');
  6669. if (this.startNameSet_) {
  6670. return this.indexStartName_;
  6671. }
  6672. else {
  6673. return MIN_NAME;
  6674. }
  6675. };
  6676. QueryParams.prototype.hasEnd = function () {
  6677. return this.endSet_;
  6678. };
  6679. /**
  6680. * Only valid to call if hasEnd() returns true.
  6681. */
  6682. QueryParams.prototype.getIndexEndValue = function () {
  6683. util.assert(this.endSet_, 'Only valid if end has been set');
  6684. return this.indexEndValue_;
  6685. };
  6686. /**
  6687. * Only valid to call if hasEnd() returns true.
  6688. * Returns the end key name for the range defined by these query parameters
  6689. */
  6690. QueryParams.prototype.getIndexEndName = function () {
  6691. util.assert(this.endSet_, 'Only valid if end has been set');
  6692. if (this.endNameSet_) {
  6693. return this.indexEndName_;
  6694. }
  6695. else {
  6696. return MAX_NAME;
  6697. }
  6698. };
  6699. QueryParams.prototype.hasLimit = function () {
  6700. return this.limitSet_;
  6701. };
  6702. /**
  6703. * @returns True if a limit has been set and it has been explicitly anchored
  6704. */
  6705. QueryParams.prototype.hasAnchoredLimit = function () {
  6706. return this.limitSet_ && this.viewFrom_ !== '';
  6707. };
  6708. /**
  6709. * Only valid to call if hasLimit() returns true
  6710. */
  6711. QueryParams.prototype.getLimit = function () {
  6712. util.assert(this.limitSet_, 'Only valid if limit has been set');
  6713. return this.limit_;
  6714. };
  6715. QueryParams.prototype.getIndex = function () {
  6716. return this.index_;
  6717. };
  6718. QueryParams.prototype.loadsAllData = function () {
  6719. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6720. };
  6721. QueryParams.prototype.isDefault = function () {
  6722. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6723. };
  6724. QueryParams.prototype.copy = function () {
  6725. var copy = new QueryParams();
  6726. copy.limitSet_ = this.limitSet_;
  6727. copy.limit_ = this.limit_;
  6728. copy.startSet_ = this.startSet_;
  6729. copy.startAfterSet_ = this.startAfterSet_;
  6730. copy.indexStartValue_ = this.indexStartValue_;
  6731. copy.startNameSet_ = this.startNameSet_;
  6732. copy.indexStartName_ = this.indexStartName_;
  6733. copy.endSet_ = this.endSet_;
  6734. copy.endBeforeSet_ = this.endBeforeSet_;
  6735. copy.indexEndValue_ = this.indexEndValue_;
  6736. copy.endNameSet_ = this.endNameSet_;
  6737. copy.indexEndName_ = this.indexEndName_;
  6738. copy.index_ = this.index_;
  6739. copy.viewFrom_ = this.viewFrom_;
  6740. return copy;
  6741. };
  6742. return QueryParams;
  6743. }());
  6744. function queryParamsGetNodeFilter(queryParams) {
  6745. if (queryParams.loadsAllData()) {
  6746. return new IndexedFilter(queryParams.getIndex());
  6747. }
  6748. else if (queryParams.hasLimit()) {
  6749. return new LimitedFilter(queryParams);
  6750. }
  6751. else {
  6752. return new RangedFilter(queryParams);
  6753. }
  6754. }
  6755. function queryParamsLimitToFirst(queryParams, newLimit) {
  6756. var newParams = queryParams.copy();
  6757. newParams.limitSet_ = true;
  6758. newParams.limit_ = newLimit;
  6759. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6760. return newParams;
  6761. }
  6762. function queryParamsLimitToLast(queryParams, newLimit) {
  6763. var newParams = queryParams.copy();
  6764. newParams.limitSet_ = true;
  6765. newParams.limit_ = newLimit;
  6766. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6767. return newParams;
  6768. }
  6769. function queryParamsStartAt(queryParams, indexValue, key) {
  6770. var newParams = queryParams.copy();
  6771. newParams.startSet_ = true;
  6772. if (indexValue === undefined) {
  6773. indexValue = null;
  6774. }
  6775. newParams.indexStartValue_ = indexValue;
  6776. if (key != null) {
  6777. newParams.startNameSet_ = true;
  6778. newParams.indexStartName_ = key;
  6779. }
  6780. else {
  6781. newParams.startNameSet_ = false;
  6782. newParams.indexStartName_ = '';
  6783. }
  6784. return newParams;
  6785. }
  6786. function queryParamsStartAfter(queryParams, indexValue, key) {
  6787. var params;
  6788. if (queryParams.index_ === KEY_INDEX || !!key) {
  6789. params = queryParamsStartAt(queryParams, indexValue, key);
  6790. }
  6791. else {
  6792. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6793. }
  6794. params.startAfterSet_ = true;
  6795. return params;
  6796. }
  6797. function queryParamsEndAt(queryParams, indexValue, key) {
  6798. var newParams = queryParams.copy();
  6799. newParams.endSet_ = true;
  6800. if (indexValue === undefined) {
  6801. indexValue = null;
  6802. }
  6803. newParams.indexEndValue_ = indexValue;
  6804. if (key !== undefined) {
  6805. newParams.endNameSet_ = true;
  6806. newParams.indexEndName_ = key;
  6807. }
  6808. else {
  6809. newParams.endNameSet_ = false;
  6810. newParams.indexEndName_ = '';
  6811. }
  6812. return newParams;
  6813. }
  6814. function queryParamsEndBefore(queryParams, indexValue, key) {
  6815. var params;
  6816. if (queryParams.index_ === KEY_INDEX || !!key) {
  6817. params = queryParamsEndAt(queryParams, indexValue, key);
  6818. }
  6819. else {
  6820. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6821. }
  6822. params.endBeforeSet_ = true;
  6823. return params;
  6824. }
  6825. function queryParamsOrderBy(queryParams, index) {
  6826. var newParams = queryParams.copy();
  6827. newParams.index_ = index;
  6828. return newParams;
  6829. }
  6830. /**
  6831. * Returns a set of REST query string parameters representing this query.
  6832. *
  6833. * @returns query string parameters
  6834. */
  6835. function queryParamsToRestQueryStringParameters(queryParams) {
  6836. var qs = {};
  6837. if (queryParams.isDefault()) {
  6838. return qs;
  6839. }
  6840. var orderBy;
  6841. if (queryParams.index_ === PRIORITY_INDEX) {
  6842. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6843. }
  6844. else if (queryParams.index_ === VALUE_INDEX) {
  6845. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6846. }
  6847. else if (queryParams.index_ === KEY_INDEX) {
  6848. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6849. }
  6850. else {
  6851. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6852. orderBy = queryParams.index_.toString();
  6853. }
  6854. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  6855. if (queryParams.startSet_) {
  6856. var startParam = queryParams.startAfterSet_
  6857. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6858. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6859. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  6860. if (queryParams.startNameSet_) {
  6861. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  6862. }
  6863. }
  6864. if (queryParams.endSet_) {
  6865. var endParam = queryParams.endBeforeSet_
  6866. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6867. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6868. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  6869. if (queryParams.endNameSet_) {
  6870. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  6871. }
  6872. }
  6873. if (queryParams.limitSet_) {
  6874. if (queryParams.isViewFromLeft()) {
  6875. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6876. }
  6877. else {
  6878. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6879. }
  6880. }
  6881. return qs;
  6882. }
  6883. function queryParamsGetQueryObject(queryParams) {
  6884. var obj = {};
  6885. if (queryParams.startSet_) {
  6886. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6887. queryParams.indexStartValue_;
  6888. if (queryParams.startNameSet_) {
  6889. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6890. queryParams.indexStartName_;
  6891. }
  6892. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6893. !queryParams.startAfterSet_;
  6894. }
  6895. if (queryParams.endSet_) {
  6896. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6897. if (queryParams.endNameSet_) {
  6898. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6899. }
  6900. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6901. !queryParams.endBeforeSet_;
  6902. }
  6903. if (queryParams.limitSet_) {
  6904. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6905. var viewFrom = queryParams.viewFrom_;
  6906. if (viewFrom === '') {
  6907. if (queryParams.isViewFromLeft()) {
  6908. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6909. }
  6910. else {
  6911. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6912. }
  6913. }
  6914. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6915. }
  6916. // For now, priority index is the default, so we only specify if it's some other index
  6917. if (queryParams.index_ !== PRIORITY_INDEX) {
  6918. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6919. }
  6920. return obj;
  6921. }
  6922. /**
  6923. * @license
  6924. * Copyright 2017 Google LLC
  6925. *
  6926. * Licensed under the Apache License, Version 2.0 (the "License");
  6927. * you may not use this file except in compliance with the License.
  6928. * You may obtain a copy of the License at
  6929. *
  6930. * http://www.apache.org/licenses/LICENSE-2.0
  6931. *
  6932. * Unless required by applicable law or agreed to in writing, software
  6933. * distributed under the License is distributed on an "AS IS" BASIS,
  6934. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6935. * See the License for the specific language governing permissions and
  6936. * limitations under the License.
  6937. */
  6938. /**
  6939. * An implementation of ServerActions that communicates with the server via REST requests.
  6940. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6941. * persistent connection (using WebSockets or long-polling)
  6942. */
  6943. var ReadonlyRestClient = /** @class */ (function (_super) {
  6944. tslib.__extends(ReadonlyRestClient, _super);
  6945. /**
  6946. * @param repoInfo_ - Data about the namespace we are connecting to
  6947. * @param onDataUpdate_ - A callback for new data from the server
  6948. */
  6949. function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6950. var _this = _super.call(this) || this;
  6951. _this.repoInfo_ = repoInfo_;
  6952. _this.onDataUpdate_ = onDataUpdate_;
  6953. _this.authTokenProvider_ = authTokenProvider_;
  6954. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6955. /** @private {function(...[*])} */
  6956. _this.log_ = logWrapper('p:rest:');
  6957. /**
  6958. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6959. * that's been removed. :-/
  6960. */
  6961. _this.listens_ = {};
  6962. return _this;
  6963. }
  6964. ReadonlyRestClient.prototype.reportStats = function (stats) {
  6965. throw new Error('Method not implemented.');
  6966. };
  6967. ReadonlyRestClient.getListenId_ = function (query, tag) {
  6968. if (tag !== undefined) {
  6969. return 'tag$' + tag;
  6970. }
  6971. else {
  6972. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6973. return query._path.toString();
  6974. }
  6975. };
  6976. /** @inheritDoc */
  6977. ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  6978. var _this = this;
  6979. var pathString = query._path.toString();
  6980. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6981. // Mark this listener so we can tell if it's removed.
  6982. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  6983. var thisListen = {};
  6984. this.listens_[listenId] = thisListen;
  6985. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6986. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  6987. var data = result;
  6988. if (error === 404) {
  6989. data = null;
  6990. error = null;
  6991. }
  6992. if (error === null) {
  6993. _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6994. }
  6995. if (util.safeGet(_this.listens_, listenId) === thisListen) {
  6996. var status_1;
  6997. if (!error) {
  6998. status_1 = 'ok';
  6999. }
  7000. else if (error === 401) {
  7001. status_1 = 'permission_denied';
  7002. }
  7003. else {
  7004. status_1 = 'rest_error:' + error;
  7005. }
  7006. onComplete(status_1, null);
  7007. }
  7008. });
  7009. };
  7010. /** @inheritDoc */
  7011. ReadonlyRestClient.prototype.unlisten = function (query, tag) {
  7012. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  7013. delete this.listens_[listenId];
  7014. };
  7015. ReadonlyRestClient.prototype.get = function (query) {
  7016. var _this = this;
  7017. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  7018. var pathString = query._path.toString();
  7019. var deferred = new util.Deferred();
  7020. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  7021. var data = result;
  7022. if (error === 404) {
  7023. data = null;
  7024. error = null;
  7025. }
  7026. if (error === null) {
  7027. _this.onDataUpdate_(pathString, data,
  7028. /*isMerge=*/ false,
  7029. /*tag=*/ null);
  7030. deferred.resolve(data);
  7031. }
  7032. else {
  7033. deferred.reject(new Error(data));
  7034. }
  7035. });
  7036. return deferred.promise;
  7037. };
  7038. /** @inheritDoc */
  7039. ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
  7040. // no-op since we just always call getToken.
  7041. };
  7042. /**
  7043. * Performs a REST request to the given path, with the provided query string parameters,
  7044. * and any auth credentials we have.
  7045. */
  7046. ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
  7047. var _this = this;
  7048. if (queryStringParameters === void 0) { queryStringParameters = {}; }
  7049. queryStringParameters['format'] = 'export';
  7050. return Promise.all([
  7051. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  7052. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  7053. ]).then(function (_a) {
  7054. var _b = tslib.__read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
  7055. if (authToken && authToken.accessToken) {
  7056. queryStringParameters['auth'] = authToken.accessToken;
  7057. }
  7058. if (appCheckToken && appCheckToken.token) {
  7059. queryStringParameters['ac'] = appCheckToken.token;
  7060. }
  7061. var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
  7062. _this.repoInfo_.host +
  7063. pathString +
  7064. '?' +
  7065. 'ns=' +
  7066. _this.repoInfo_.namespace +
  7067. util.querystring(queryStringParameters);
  7068. _this.log_('Sending REST request for ' + url);
  7069. var xhr = new XMLHttpRequest();
  7070. xhr.onreadystatechange = function () {
  7071. if (callback && xhr.readyState === 4) {
  7072. _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  7073. var res = null;
  7074. if (xhr.status >= 200 && xhr.status < 300) {
  7075. try {
  7076. res = util.jsonEval(xhr.responseText);
  7077. }
  7078. catch (e) {
  7079. warn('Failed to parse JSON response for ' +
  7080. url +
  7081. ': ' +
  7082. xhr.responseText);
  7083. }
  7084. callback(null, res);
  7085. }
  7086. else {
  7087. // 401 and 404 are expected.
  7088. if (xhr.status !== 401 && xhr.status !== 404) {
  7089. warn('Got unsuccessful REST response for ' +
  7090. url +
  7091. ' Status: ' +
  7092. xhr.status);
  7093. }
  7094. callback(xhr.status);
  7095. }
  7096. callback = null;
  7097. }
  7098. };
  7099. xhr.open('GET', url, /*asynchronous=*/ true);
  7100. xhr.send();
  7101. });
  7102. };
  7103. return ReadonlyRestClient;
  7104. }(ServerActions));
  7105. /**
  7106. * @license
  7107. * Copyright 2017 Google LLC
  7108. *
  7109. * Licensed under the Apache License, Version 2.0 (the "License");
  7110. * you may not use this file except in compliance with the License.
  7111. * You may obtain a copy of the License at
  7112. *
  7113. * http://www.apache.org/licenses/LICENSE-2.0
  7114. *
  7115. * Unless required by applicable law or agreed to in writing, software
  7116. * distributed under the License is distributed on an "AS IS" BASIS,
  7117. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7118. * See the License for the specific language governing permissions and
  7119. * limitations under the License.
  7120. */
  7121. /**
  7122. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  7123. */
  7124. var SnapshotHolder = /** @class */ (function () {
  7125. function SnapshotHolder() {
  7126. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  7127. }
  7128. SnapshotHolder.prototype.getNode = function (path) {
  7129. return this.rootNode_.getChild(path);
  7130. };
  7131. SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
  7132. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  7133. };
  7134. return SnapshotHolder;
  7135. }());
  7136. /**
  7137. * @license
  7138. * Copyright 2017 Google LLC
  7139. *
  7140. * Licensed under the Apache License, Version 2.0 (the "License");
  7141. * you may not use this file except in compliance with the License.
  7142. * You may obtain a copy of the License at
  7143. *
  7144. * http://www.apache.org/licenses/LICENSE-2.0
  7145. *
  7146. * Unless required by applicable law or agreed to in writing, software
  7147. * distributed under the License is distributed on an "AS IS" BASIS,
  7148. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7149. * See the License for the specific language governing permissions and
  7150. * limitations under the License.
  7151. */
  7152. function newSparseSnapshotTree() {
  7153. return {
  7154. value: null,
  7155. children: new Map()
  7156. };
  7157. }
  7158. /**
  7159. * Stores the given node at the specified path. If there is already a node
  7160. * at a shallower path, it merges the new data into that snapshot node.
  7161. *
  7162. * @param path - Path to look up snapshot for.
  7163. * @param data - The new data, or null.
  7164. */
  7165. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  7166. if (pathIsEmpty(path)) {
  7167. sparseSnapshotTree.value = data;
  7168. sparseSnapshotTree.children.clear();
  7169. }
  7170. else if (sparseSnapshotTree.value !== null) {
  7171. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  7172. }
  7173. else {
  7174. var childKey = pathGetFront(path);
  7175. if (!sparseSnapshotTree.children.has(childKey)) {
  7176. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  7177. }
  7178. var child = sparseSnapshotTree.children.get(childKey);
  7179. path = pathPopFront(path);
  7180. sparseSnapshotTreeRemember(child, path, data);
  7181. }
  7182. }
  7183. /**
  7184. * Purge the data at path from the cache.
  7185. *
  7186. * @param path - Path to look up snapshot for.
  7187. * @returns True if this node should now be removed.
  7188. */
  7189. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  7190. if (pathIsEmpty(path)) {
  7191. sparseSnapshotTree.value = null;
  7192. sparseSnapshotTree.children.clear();
  7193. return true;
  7194. }
  7195. else {
  7196. if (sparseSnapshotTree.value !== null) {
  7197. if (sparseSnapshotTree.value.isLeafNode()) {
  7198. // We're trying to forget a node that doesn't exist
  7199. return false;
  7200. }
  7201. else {
  7202. var value = sparseSnapshotTree.value;
  7203. sparseSnapshotTree.value = null;
  7204. value.forEachChild(PRIORITY_INDEX, function (key, tree) {
  7205. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  7206. });
  7207. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  7208. }
  7209. }
  7210. else if (sparseSnapshotTree.children.size > 0) {
  7211. var childKey = pathGetFront(path);
  7212. path = pathPopFront(path);
  7213. if (sparseSnapshotTree.children.has(childKey)) {
  7214. var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  7215. if (safeToRemove) {
  7216. sparseSnapshotTree.children.delete(childKey);
  7217. }
  7218. }
  7219. return sparseSnapshotTree.children.size === 0;
  7220. }
  7221. else {
  7222. return true;
  7223. }
  7224. }
  7225. }
  7226. /**
  7227. * Recursively iterates through all of the stored tree and calls the
  7228. * callback on each one.
  7229. *
  7230. * @param prefixPath - Path to look up node for.
  7231. * @param func - The function to invoke for each tree.
  7232. */
  7233. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7234. if (sparseSnapshotTree.value !== null) {
  7235. func(prefixPath, sparseSnapshotTree.value);
  7236. }
  7237. else {
  7238. sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
  7239. var path = new Path(prefixPath.toString() + '/' + key);
  7240. sparseSnapshotTreeForEachTree(tree, path, func);
  7241. });
  7242. }
  7243. }
  7244. /**
  7245. * Iterates through each immediate child and triggers the callback.
  7246. * Only seems to be used in tests.
  7247. *
  7248. * @param func - The function to invoke for each child.
  7249. */
  7250. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7251. sparseSnapshotTree.children.forEach(function (tree, key) {
  7252. func(key, tree);
  7253. });
  7254. }
  7255. /**
  7256. * @license
  7257. * Copyright 2017 Google LLC
  7258. *
  7259. * Licensed under the Apache License, Version 2.0 (the "License");
  7260. * you may not use this file except in compliance with the License.
  7261. * You may obtain a copy of the License at
  7262. *
  7263. * http://www.apache.org/licenses/LICENSE-2.0
  7264. *
  7265. * Unless required by applicable law or agreed to in writing, software
  7266. * distributed under the License is distributed on an "AS IS" BASIS,
  7267. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7268. * See the License for the specific language governing permissions and
  7269. * limitations under the License.
  7270. */
  7271. /**
  7272. * Returns the delta from the previous call to get stats.
  7273. *
  7274. * @param collection_ - The collection to "listen" to.
  7275. */
  7276. var StatsListener = /** @class */ (function () {
  7277. function StatsListener(collection_) {
  7278. this.collection_ = collection_;
  7279. this.last_ = null;
  7280. }
  7281. StatsListener.prototype.get = function () {
  7282. var newStats = this.collection_.get();
  7283. var delta = tslib.__assign({}, newStats);
  7284. if (this.last_) {
  7285. each(this.last_, function (stat, value) {
  7286. delta[stat] = delta[stat] - value;
  7287. });
  7288. }
  7289. this.last_ = newStats;
  7290. return delta;
  7291. };
  7292. return StatsListener;
  7293. }());
  7294. /**
  7295. * @license
  7296. * Copyright 2017 Google LLC
  7297. *
  7298. * Licensed under the Apache License, Version 2.0 (the "License");
  7299. * you may not use this file except in compliance with the License.
  7300. * You may obtain a copy of the License at
  7301. *
  7302. * http://www.apache.org/licenses/LICENSE-2.0
  7303. *
  7304. * Unless required by applicable law or agreed to in writing, software
  7305. * distributed under the License is distributed on an "AS IS" BASIS,
  7306. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7307. * See the License for the specific language governing permissions and
  7308. * limitations under the License.
  7309. */
  7310. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7311. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7312. // seconds to try to ensure the Firebase connection is established / settled.
  7313. var FIRST_STATS_MIN_TIME = 10 * 1000;
  7314. var FIRST_STATS_MAX_TIME = 30 * 1000;
  7315. // We'll continue to report stats on average every 5 minutes.
  7316. var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7317. var StatsReporter = /** @class */ (function () {
  7318. function StatsReporter(collection, server_) {
  7319. this.server_ = server_;
  7320. this.statsToReport_ = {};
  7321. this.statsListener_ = new StatsListener(collection);
  7322. var timeout = FIRST_STATS_MIN_TIME +
  7323. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7324. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7325. }
  7326. StatsReporter.prototype.reportStats_ = function () {
  7327. var _this = this;
  7328. var stats = this.statsListener_.get();
  7329. var reportedStats = {};
  7330. var haveStatsToReport = false;
  7331. each(stats, function (stat, value) {
  7332. if (value > 0 && util.contains(_this.statsToReport_, stat)) {
  7333. reportedStats[stat] = value;
  7334. haveStatsToReport = true;
  7335. }
  7336. });
  7337. if (haveStatsToReport) {
  7338. this.server_.reportStats(reportedStats);
  7339. }
  7340. // queue our next run.
  7341. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7342. };
  7343. return StatsReporter;
  7344. }());
  7345. /**
  7346. * @license
  7347. * Copyright 2017 Google LLC
  7348. *
  7349. * Licensed under the Apache License, Version 2.0 (the "License");
  7350. * you may not use this file except in compliance with the License.
  7351. * You may obtain a copy of the License at
  7352. *
  7353. * http://www.apache.org/licenses/LICENSE-2.0
  7354. *
  7355. * Unless required by applicable law or agreed to in writing, software
  7356. * distributed under the License is distributed on an "AS IS" BASIS,
  7357. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7358. * See the License for the specific language governing permissions and
  7359. * limitations under the License.
  7360. */
  7361. /**
  7362. *
  7363. * @enum
  7364. */
  7365. var OperationType;
  7366. (function (OperationType) {
  7367. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7368. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7369. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7370. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7371. })(OperationType || (OperationType = {}));
  7372. function newOperationSourceUser() {
  7373. return {
  7374. fromUser: true,
  7375. fromServer: false,
  7376. queryId: null,
  7377. tagged: false
  7378. };
  7379. }
  7380. function newOperationSourceServer() {
  7381. return {
  7382. fromUser: false,
  7383. fromServer: true,
  7384. queryId: null,
  7385. tagged: false
  7386. };
  7387. }
  7388. function newOperationSourceServerTaggedQuery(queryId) {
  7389. return {
  7390. fromUser: false,
  7391. fromServer: true,
  7392. queryId: queryId,
  7393. tagged: true
  7394. };
  7395. }
  7396. /**
  7397. * @license
  7398. * Copyright 2017 Google LLC
  7399. *
  7400. * Licensed under the Apache License, Version 2.0 (the "License");
  7401. * you may not use this file except in compliance with the License.
  7402. * You may obtain a copy of the License at
  7403. *
  7404. * http://www.apache.org/licenses/LICENSE-2.0
  7405. *
  7406. * Unless required by applicable law or agreed to in writing, software
  7407. * distributed under the License is distributed on an "AS IS" BASIS,
  7408. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7409. * See the License for the specific language governing permissions and
  7410. * limitations under the License.
  7411. */
  7412. var AckUserWrite = /** @class */ (function () {
  7413. /**
  7414. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7415. */
  7416. function AckUserWrite(
  7417. /** @inheritDoc */ path,
  7418. /** @inheritDoc */ affectedTree,
  7419. /** @inheritDoc */ revert) {
  7420. this.path = path;
  7421. this.affectedTree = affectedTree;
  7422. this.revert = revert;
  7423. /** @inheritDoc */
  7424. this.type = OperationType.ACK_USER_WRITE;
  7425. /** @inheritDoc */
  7426. this.source = newOperationSourceUser();
  7427. }
  7428. AckUserWrite.prototype.operationForChild = function (childName) {
  7429. if (!pathIsEmpty(this.path)) {
  7430. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7431. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7432. }
  7433. else if (this.affectedTree.value != null) {
  7434. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7435. // All child locations are affected as well; just return same operation.
  7436. return this;
  7437. }
  7438. else {
  7439. var childTree = this.affectedTree.subtree(new Path(childName));
  7440. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7441. }
  7442. };
  7443. return AckUserWrite;
  7444. }());
  7445. /**
  7446. * @license
  7447. * Copyright 2017 Google LLC
  7448. *
  7449. * Licensed under the Apache License, Version 2.0 (the "License");
  7450. * you may not use this file except in compliance with the License.
  7451. * You may obtain a copy of the License at
  7452. *
  7453. * http://www.apache.org/licenses/LICENSE-2.0
  7454. *
  7455. * Unless required by applicable law or agreed to in writing, software
  7456. * distributed under the License is distributed on an "AS IS" BASIS,
  7457. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7458. * See the License for the specific language governing permissions and
  7459. * limitations under the License.
  7460. */
  7461. var ListenComplete = /** @class */ (function () {
  7462. function ListenComplete(source, path) {
  7463. this.source = source;
  7464. this.path = path;
  7465. /** @inheritDoc */
  7466. this.type = OperationType.LISTEN_COMPLETE;
  7467. }
  7468. ListenComplete.prototype.operationForChild = function (childName) {
  7469. if (pathIsEmpty(this.path)) {
  7470. return new ListenComplete(this.source, newEmptyPath());
  7471. }
  7472. else {
  7473. return new ListenComplete(this.source, pathPopFront(this.path));
  7474. }
  7475. };
  7476. return ListenComplete;
  7477. }());
  7478. /**
  7479. * @license
  7480. * Copyright 2017 Google LLC
  7481. *
  7482. * Licensed under the Apache License, Version 2.0 (the "License");
  7483. * you may not use this file except in compliance with the License.
  7484. * You may obtain a copy of the License at
  7485. *
  7486. * http://www.apache.org/licenses/LICENSE-2.0
  7487. *
  7488. * Unless required by applicable law or agreed to in writing, software
  7489. * distributed under the License is distributed on an "AS IS" BASIS,
  7490. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7491. * See the License for the specific language governing permissions and
  7492. * limitations under the License.
  7493. */
  7494. var Overwrite = /** @class */ (function () {
  7495. function Overwrite(source, path, snap) {
  7496. this.source = source;
  7497. this.path = path;
  7498. this.snap = snap;
  7499. /** @inheritDoc */
  7500. this.type = OperationType.OVERWRITE;
  7501. }
  7502. Overwrite.prototype.operationForChild = function (childName) {
  7503. if (pathIsEmpty(this.path)) {
  7504. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7505. }
  7506. else {
  7507. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7508. }
  7509. };
  7510. return Overwrite;
  7511. }());
  7512. /**
  7513. * @license
  7514. * Copyright 2017 Google LLC
  7515. *
  7516. * Licensed under the Apache License, Version 2.0 (the "License");
  7517. * you may not use this file except in compliance with the License.
  7518. * You may obtain a copy of the License at
  7519. *
  7520. * http://www.apache.org/licenses/LICENSE-2.0
  7521. *
  7522. * Unless required by applicable law or agreed to in writing, software
  7523. * distributed under the License is distributed on an "AS IS" BASIS,
  7524. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7525. * See the License for the specific language governing permissions and
  7526. * limitations under the License.
  7527. */
  7528. var Merge = /** @class */ (function () {
  7529. function Merge(
  7530. /** @inheritDoc */ source,
  7531. /** @inheritDoc */ path,
  7532. /** @inheritDoc */ children) {
  7533. this.source = source;
  7534. this.path = path;
  7535. this.children = children;
  7536. /** @inheritDoc */
  7537. this.type = OperationType.MERGE;
  7538. }
  7539. Merge.prototype.operationForChild = function (childName) {
  7540. if (pathIsEmpty(this.path)) {
  7541. var childTree = this.children.subtree(new Path(childName));
  7542. if (childTree.isEmpty()) {
  7543. // This child is unaffected
  7544. return null;
  7545. }
  7546. else if (childTree.value) {
  7547. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7548. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7549. }
  7550. else {
  7551. // This is a merge at a deeper level
  7552. return new Merge(this.source, newEmptyPath(), childTree);
  7553. }
  7554. }
  7555. else {
  7556. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7557. return new Merge(this.source, pathPopFront(this.path), this.children);
  7558. }
  7559. };
  7560. Merge.prototype.toString = function () {
  7561. return ('Operation(' +
  7562. this.path +
  7563. ': ' +
  7564. this.source.toString() +
  7565. ' merge: ' +
  7566. this.children.toString() +
  7567. ')');
  7568. };
  7569. return Merge;
  7570. }());
  7571. /**
  7572. * @license
  7573. * Copyright 2017 Google LLC
  7574. *
  7575. * Licensed under the Apache License, Version 2.0 (the "License");
  7576. * you may not use this file except in compliance with the License.
  7577. * You may obtain a copy of the License at
  7578. *
  7579. * http://www.apache.org/licenses/LICENSE-2.0
  7580. *
  7581. * Unless required by applicable law or agreed to in writing, software
  7582. * distributed under the License is distributed on an "AS IS" BASIS,
  7583. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7584. * See the License for the specific language governing permissions and
  7585. * limitations under the License.
  7586. */
  7587. /**
  7588. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7589. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7590. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7591. * whether a node potentially had children removed due to a filter.
  7592. */
  7593. var CacheNode = /** @class */ (function () {
  7594. function CacheNode(node_, fullyInitialized_, filtered_) {
  7595. this.node_ = node_;
  7596. this.fullyInitialized_ = fullyInitialized_;
  7597. this.filtered_ = filtered_;
  7598. }
  7599. /**
  7600. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7601. */
  7602. CacheNode.prototype.isFullyInitialized = function () {
  7603. return this.fullyInitialized_;
  7604. };
  7605. /**
  7606. * Returns whether this node is potentially missing children due to a filter applied to the node
  7607. */
  7608. CacheNode.prototype.isFiltered = function () {
  7609. return this.filtered_;
  7610. };
  7611. CacheNode.prototype.isCompleteForPath = function (path) {
  7612. if (pathIsEmpty(path)) {
  7613. return this.isFullyInitialized() && !this.filtered_;
  7614. }
  7615. var childKey = pathGetFront(path);
  7616. return this.isCompleteForChild(childKey);
  7617. };
  7618. CacheNode.prototype.isCompleteForChild = function (key) {
  7619. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7620. };
  7621. CacheNode.prototype.getNode = function () {
  7622. return this.node_;
  7623. };
  7624. return CacheNode;
  7625. }());
  7626. /**
  7627. * @license
  7628. * Copyright 2017 Google LLC
  7629. *
  7630. * Licensed under the Apache License, Version 2.0 (the "License");
  7631. * you may not use this file except in compliance with the License.
  7632. * You may obtain a copy of the License at
  7633. *
  7634. * http://www.apache.org/licenses/LICENSE-2.0
  7635. *
  7636. * Unless required by applicable law or agreed to in writing, software
  7637. * distributed under the License is distributed on an "AS IS" BASIS,
  7638. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7639. * See the License for the specific language governing permissions and
  7640. * limitations under the License.
  7641. */
  7642. /**
  7643. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7644. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7645. * for details.
  7646. *
  7647. */
  7648. var EventGenerator = /** @class */ (function () {
  7649. function EventGenerator(query_) {
  7650. this.query_ = query_;
  7651. this.index_ = this.query_._queryParams.getIndex();
  7652. }
  7653. return EventGenerator;
  7654. }());
  7655. /**
  7656. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7657. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7658. *
  7659. * Notes:
  7660. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7661. * our index.
  7662. * - prevName will be calculated based on the index ordering.
  7663. */
  7664. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7665. var events = [];
  7666. var moves = [];
  7667. changes.forEach(function (change) {
  7668. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7669. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7670. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7671. }
  7672. });
  7673. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7674. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7675. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7676. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7677. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7678. return events;
  7679. }
  7680. /**
  7681. * Given changes of a single change type, generate the corresponding events.
  7682. */
  7683. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7684. var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
  7685. filteredChanges.sort(function (a, b) {
  7686. return eventGeneratorCompareChanges(eventGenerator, a, b);
  7687. });
  7688. filteredChanges.forEach(function (change) {
  7689. var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7690. registrations.forEach(function (registration) {
  7691. if (registration.respondsTo(change.type)) {
  7692. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7693. }
  7694. });
  7695. });
  7696. }
  7697. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7698. if (change.type === 'value' || change.type === 'child_removed') {
  7699. return change;
  7700. }
  7701. else {
  7702. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7703. return change;
  7704. }
  7705. }
  7706. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7707. if (a.childName == null || b.childName == null) {
  7708. throw util.assertionError('Should only compare child_ events.');
  7709. }
  7710. var aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7711. var bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7712. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7713. }
  7714. /**
  7715. * @license
  7716. * Copyright 2017 Google LLC
  7717. *
  7718. * Licensed under the Apache License, Version 2.0 (the "License");
  7719. * you may not use this file except in compliance with the License.
  7720. * You may obtain a copy of the License at
  7721. *
  7722. * http://www.apache.org/licenses/LICENSE-2.0
  7723. *
  7724. * Unless required by applicable law or agreed to in writing, software
  7725. * distributed under the License is distributed on an "AS IS" BASIS,
  7726. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7727. * See the License for the specific language governing permissions and
  7728. * limitations under the License.
  7729. */
  7730. function newViewCache(eventCache, serverCache) {
  7731. return { eventCache: eventCache, serverCache: serverCache };
  7732. }
  7733. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7734. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7735. }
  7736. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7737. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7738. }
  7739. function viewCacheGetCompleteEventSnap(viewCache) {
  7740. return viewCache.eventCache.isFullyInitialized()
  7741. ? viewCache.eventCache.getNode()
  7742. : null;
  7743. }
  7744. function viewCacheGetCompleteServerSnap(viewCache) {
  7745. return viewCache.serverCache.isFullyInitialized()
  7746. ? viewCache.serverCache.getNode()
  7747. : null;
  7748. }
  7749. /**
  7750. * @license
  7751. * Copyright 2017 Google LLC
  7752. *
  7753. * Licensed under the Apache License, Version 2.0 (the "License");
  7754. * you may not use this file except in compliance with the License.
  7755. * You may obtain a copy of the License at
  7756. *
  7757. * http://www.apache.org/licenses/LICENSE-2.0
  7758. *
  7759. * Unless required by applicable law or agreed to in writing, software
  7760. * distributed under the License is distributed on an "AS IS" BASIS,
  7761. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7762. * See the License for the specific language governing permissions and
  7763. * limitations under the License.
  7764. */
  7765. var emptyChildrenSingleton;
  7766. /**
  7767. * Singleton empty children collection.
  7768. *
  7769. */
  7770. var EmptyChildren = function () {
  7771. if (!emptyChildrenSingleton) {
  7772. emptyChildrenSingleton = new SortedMap(stringCompare);
  7773. }
  7774. return emptyChildrenSingleton;
  7775. };
  7776. /**
  7777. * A tree with immutable elements.
  7778. */
  7779. var ImmutableTree = /** @class */ (function () {
  7780. function ImmutableTree(value, children) {
  7781. if (children === void 0) { children = EmptyChildren(); }
  7782. this.value = value;
  7783. this.children = children;
  7784. }
  7785. ImmutableTree.fromObject = function (obj) {
  7786. var tree = new ImmutableTree(null);
  7787. each(obj, function (childPath, childSnap) {
  7788. tree = tree.set(new Path(childPath), childSnap);
  7789. });
  7790. return tree;
  7791. };
  7792. /**
  7793. * True if the value is empty and there are no children
  7794. */
  7795. ImmutableTree.prototype.isEmpty = function () {
  7796. return this.value === null && this.children.isEmpty();
  7797. };
  7798. /**
  7799. * Given a path and predicate, return the first node and the path to that node
  7800. * where the predicate returns true.
  7801. *
  7802. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7803. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7804. *
  7805. * @param relativePath - The remainder of the path
  7806. * @param predicate - The predicate to satisfy to return a node
  7807. */
  7808. ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
  7809. if (this.value != null && predicate(this.value)) {
  7810. return { path: newEmptyPath(), value: this.value };
  7811. }
  7812. else {
  7813. if (pathIsEmpty(relativePath)) {
  7814. return null;
  7815. }
  7816. else {
  7817. var front = pathGetFront(relativePath);
  7818. var child = this.children.get(front);
  7819. if (child !== null) {
  7820. var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7821. if (childExistingPathAndValue != null) {
  7822. var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7823. return { path: fullPath, value: childExistingPathAndValue.value };
  7824. }
  7825. else {
  7826. return null;
  7827. }
  7828. }
  7829. else {
  7830. return null;
  7831. }
  7832. }
  7833. }
  7834. };
  7835. /**
  7836. * Find, if it exists, the shortest subpath of the given path that points a defined
  7837. * value in the tree
  7838. */
  7839. ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
  7840. return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
  7841. };
  7842. /**
  7843. * @returns The subtree at the given path
  7844. */
  7845. ImmutableTree.prototype.subtree = function (relativePath) {
  7846. if (pathIsEmpty(relativePath)) {
  7847. return this;
  7848. }
  7849. else {
  7850. var front = pathGetFront(relativePath);
  7851. var childTree = this.children.get(front);
  7852. if (childTree !== null) {
  7853. return childTree.subtree(pathPopFront(relativePath));
  7854. }
  7855. else {
  7856. return new ImmutableTree(null);
  7857. }
  7858. }
  7859. };
  7860. /**
  7861. * Sets a value at the specified path.
  7862. *
  7863. * @param relativePath - Path to set value at.
  7864. * @param toSet - Value to set.
  7865. * @returns Resulting tree.
  7866. */
  7867. ImmutableTree.prototype.set = function (relativePath, toSet) {
  7868. if (pathIsEmpty(relativePath)) {
  7869. return new ImmutableTree(toSet, this.children);
  7870. }
  7871. else {
  7872. var front = pathGetFront(relativePath);
  7873. var child = this.children.get(front) || new ImmutableTree(null);
  7874. var newChild = child.set(pathPopFront(relativePath), toSet);
  7875. var newChildren = this.children.insert(front, newChild);
  7876. return new ImmutableTree(this.value, newChildren);
  7877. }
  7878. };
  7879. /**
  7880. * Removes the value at the specified path.
  7881. *
  7882. * @param relativePath - Path to value to remove.
  7883. * @returns Resulting tree.
  7884. */
  7885. ImmutableTree.prototype.remove = function (relativePath) {
  7886. if (pathIsEmpty(relativePath)) {
  7887. if (this.children.isEmpty()) {
  7888. return new ImmutableTree(null);
  7889. }
  7890. else {
  7891. return new ImmutableTree(null, this.children);
  7892. }
  7893. }
  7894. else {
  7895. var front = pathGetFront(relativePath);
  7896. var child = this.children.get(front);
  7897. if (child) {
  7898. var newChild = child.remove(pathPopFront(relativePath));
  7899. var newChildren = void 0;
  7900. if (newChild.isEmpty()) {
  7901. newChildren = this.children.remove(front);
  7902. }
  7903. else {
  7904. newChildren = this.children.insert(front, newChild);
  7905. }
  7906. if (this.value === null && newChildren.isEmpty()) {
  7907. return new ImmutableTree(null);
  7908. }
  7909. else {
  7910. return new ImmutableTree(this.value, newChildren);
  7911. }
  7912. }
  7913. else {
  7914. return this;
  7915. }
  7916. }
  7917. };
  7918. /**
  7919. * Gets a value from the tree.
  7920. *
  7921. * @param relativePath - Path to get value for.
  7922. * @returns Value at path, or null.
  7923. */
  7924. ImmutableTree.prototype.get = function (relativePath) {
  7925. if (pathIsEmpty(relativePath)) {
  7926. return this.value;
  7927. }
  7928. else {
  7929. var front = pathGetFront(relativePath);
  7930. var child = this.children.get(front);
  7931. if (child) {
  7932. return child.get(pathPopFront(relativePath));
  7933. }
  7934. else {
  7935. return null;
  7936. }
  7937. }
  7938. };
  7939. /**
  7940. * Replace the subtree at the specified path with the given new tree.
  7941. *
  7942. * @param relativePath - Path to replace subtree for.
  7943. * @param newTree - New tree.
  7944. * @returns Resulting tree.
  7945. */
  7946. ImmutableTree.prototype.setTree = function (relativePath, newTree) {
  7947. if (pathIsEmpty(relativePath)) {
  7948. return newTree;
  7949. }
  7950. else {
  7951. var front = pathGetFront(relativePath);
  7952. var child = this.children.get(front) || new ImmutableTree(null);
  7953. var newChild = child.setTree(pathPopFront(relativePath), newTree);
  7954. var newChildren = void 0;
  7955. if (newChild.isEmpty()) {
  7956. newChildren = this.children.remove(front);
  7957. }
  7958. else {
  7959. newChildren = this.children.insert(front, newChild);
  7960. }
  7961. return new ImmutableTree(this.value, newChildren);
  7962. }
  7963. };
  7964. /**
  7965. * Performs a depth first fold on this tree. Transforms a tree into a single
  7966. * value, given a function that operates on the path to a node, an optional
  7967. * current value, and a map of child names to folded subtrees
  7968. */
  7969. ImmutableTree.prototype.fold = function (fn) {
  7970. return this.fold_(newEmptyPath(), fn);
  7971. };
  7972. /**
  7973. * Recursive helper for public-facing fold() method
  7974. */
  7975. ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
  7976. var accum = {};
  7977. this.children.inorderTraversal(function (childKey, childTree) {
  7978. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7979. });
  7980. return fn(pathSoFar, this.value, accum);
  7981. };
  7982. /**
  7983. * Find the first matching value on the given path. Return the result of applying f to it.
  7984. */
  7985. ImmutableTree.prototype.findOnPath = function (path, f) {
  7986. return this.findOnPath_(path, newEmptyPath(), f);
  7987. };
  7988. ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
  7989. var result = this.value ? f(pathSoFar, this.value) : false;
  7990. if (result) {
  7991. return result;
  7992. }
  7993. else {
  7994. if (pathIsEmpty(pathToFollow)) {
  7995. return null;
  7996. }
  7997. else {
  7998. var front = pathGetFront(pathToFollow);
  7999. var nextChild = this.children.get(front);
  8000. if (nextChild) {
  8001. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  8002. }
  8003. else {
  8004. return null;
  8005. }
  8006. }
  8007. }
  8008. };
  8009. ImmutableTree.prototype.foreachOnPath = function (path, f) {
  8010. return this.foreachOnPath_(path, newEmptyPath(), f);
  8011. };
  8012. ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
  8013. if (pathIsEmpty(pathToFollow)) {
  8014. return this;
  8015. }
  8016. else {
  8017. if (this.value) {
  8018. f(currentRelativePath, this.value);
  8019. }
  8020. var front = pathGetFront(pathToFollow);
  8021. var nextChild = this.children.get(front);
  8022. if (nextChild) {
  8023. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  8024. }
  8025. else {
  8026. return new ImmutableTree(null);
  8027. }
  8028. }
  8029. };
  8030. /**
  8031. * Calls the given function for each node in the tree that has a value.
  8032. *
  8033. * @param f - A function to be called with the path from the root of the tree to
  8034. * a node, and the value at that node. Called in depth-first order.
  8035. */
  8036. ImmutableTree.prototype.foreach = function (f) {
  8037. this.foreach_(newEmptyPath(), f);
  8038. };
  8039. ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
  8040. this.children.inorderTraversal(function (childName, childTree) {
  8041. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  8042. });
  8043. if (this.value) {
  8044. f(currentRelativePath, this.value);
  8045. }
  8046. };
  8047. ImmutableTree.prototype.foreachChild = function (f) {
  8048. this.children.inorderTraversal(function (childName, childTree) {
  8049. if (childTree.value) {
  8050. f(childName, childTree.value);
  8051. }
  8052. });
  8053. };
  8054. return ImmutableTree;
  8055. }());
  8056. /**
  8057. * @license
  8058. * Copyright 2017 Google LLC
  8059. *
  8060. * Licensed under the Apache License, Version 2.0 (the "License");
  8061. * you may not use this file except in compliance with the License.
  8062. * You may obtain a copy of the License at
  8063. *
  8064. * http://www.apache.org/licenses/LICENSE-2.0
  8065. *
  8066. * Unless required by applicable law or agreed to in writing, software
  8067. * distributed under the License is distributed on an "AS IS" BASIS,
  8068. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8069. * See the License for the specific language governing permissions and
  8070. * limitations under the License.
  8071. */
  8072. /**
  8073. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  8074. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  8075. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  8076. * to reflect the write added.
  8077. */
  8078. var CompoundWrite = /** @class */ (function () {
  8079. function CompoundWrite(writeTree_) {
  8080. this.writeTree_ = writeTree_;
  8081. }
  8082. CompoundWrite.empty = function () {
  8083. return new CompoundWrite(new ImmutableTree(null));
  8084. };
  8085. return CompoundWrite;
  8086. }());
  8087. function compoundWriteAddWrite(compoundWrite, path, node) {
  8088. if (pathIsEmpty(path)) {
  8089. return new CompoundWrite(new ImmutableTree(node));
  8090. }
  8091. else {
  8092. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8093. if (rootmost != null) {
  8094. var rootMostPath = rootmost.path;
  8095. var value = rootmost.value;
  8096. var relativePath = newRelativePath(rootMostPath, path);
  8097. value = value.updateChild(relativePath, node);
  8098. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  8099. }
  8100. else {
  8101. var subtree = new ImmutableTree(node);
  8102. var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  8103. return new CompoundWrite(newWriteTree);
  8104. }
  8105. }
  8106. }
  8107. function compoundWriteAddWrites(compoundWrite, path, updates) {
  8108. var newWrite = compoundWrite;
  8109. each(updates, function (childKey, node) {
  8110. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  8111. });
  8112. return newWrite;
  8113. }
  8114. /**
  8115. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  8116. * location, which must be removed by calling this method with that path.
  8117. *
  8118. * @param compoundWrite - The CompoundWrite to remove.
  8119. * @param path - The path at which a write and all deeper writes should be removed
  8120. * @returns The new CompoundWrite with the removed path
  8121. */
  8122. function compoundWriteRemoveWrite(compoundWrite, path) {
  8123. if (pathIsEmpty(path)) {
  8124. return CompoundWrite.empty();
  8125. }
  8126. else {
  8127. var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  8128. return new CompoundWrite(newWriteTree);
  8129. }
  8130. }
  8131. /**
  8132. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  8133. * considered "complete".
  8134. *
  8135. * @param compoundWrite - The CompoundWrite to check.
  8136. * @param path - The path to check for
  8137. * @returns Whether there is a complete write at that path
  8138. */
  8139. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  8140. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  8141. }
  8142. /**
  8143. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  8144. * writes from deeper paths, but will return child nodes from a more shallow path.
  8145. *
  8146. * @param compoundWrite - The CompoundWrite to get the node from.
  8147. * @param path - The path to get a complete write
  8148. * @returns The node if complete at that path, or null otherwise.
  8149. */
  8150. function compoundWriteGetCompleteNode(compoundWrite, path) {
  8151. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8152. if (rootmost != null) {
  8153. return compoundWrite.writeTree_
  8154. .get(rootmost.path)
  8155. .getChild(newRelativePath(rootmost.path, path));
  8156. }
  8157. else {
  8158. return null;
  8159. }
  8160. }
  8161. /**
  8162. * Returns all children that are guaranteed to be a complete overwrite.
  8163. *
  8164. * @param compoundWrite - The CompoundWrite to get children from.
  8165. * @returns A list of all complete children.
  8166. */
  8167. function compoundWriteGetCompleteChildren(compoundWrite) {
  8168. var children = [];
  8169. var node = compoundWrite.writeTree_.value;
  8170. if (node != null) {
  8171. // If it's a leaf node, it has no children; so nothing to do.
  8172. if (!node.isLeafNode()) {
  8173. node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8174. children.push(new NamedNode(childName, childNode));
  8175. });
  8176. }
  8177. }
  8178. else {
  8179. compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
  8180. if (childTree.value != null) {
  8181. children.push(new NamedNode(childName, childTree.value));
  8182. }
  8183. });
  8184. }
  8185. return children;
  8186. }
  8187. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  8188. if (pathIsEmpty(path)) {
  8189. return compoundWrite;
  8190. }
  8191. else {
  8192. var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  8193. if (shadowingNode != null) {
  8194. return new CompoundWrite(new ImmutableTree(shadowingNode));
  8195. }
  8196. else {
  8197. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  8198. }
  8199. }
  8200. }
  8201. /**
  8202. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  8203. * @returns Whether this CompoundWrite is empty
  8204. */
  8205. function compoundWriteIsEmpty(compoundWrite) {
  8206. return compoundWrite.writeTree_.isEmpty();
  8207. }
  8208. /**
  8209. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  8210. * node
  8211. * @param node - The node to apply this CompoundWrite to
  8212. * @returns The node with all writes applied
  8213. */
  8214. function compoundWriteApply(compoundWrite, node) {
  8215. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  8216. }
  8217. function applySubtreeWrite(relativePath, writeTree, node) {
  8218. if (writeTree.value != null) {
  8219. // Since there a write is always a leaf, we're done here
  8220. return node.updateChild(relativePath, writeTree.value);
  8221. }
  8222. else {
  8223. var priorityWrite_1 = null;
  8224. writeTree.children.inorderTraversal(function (childKey, childTree) {
  8225. if (childKey === '.priority') {
  8226. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  8227. // to apply priorities to empty nodes that are later filled
  8228. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  8229. priorityWrite_1 = childTree.value;
  8230. }
  8231. else {
  8232. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  8233. }
  8234. });
  8235. // If there was a priority write, we only apply it if the node is not empty
  8236. if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
  8237. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
  8238. }
  8239. return node;
  8240. }
  8241. }
  8242. /**
  8243. * @license
  8244. * Copyright 2017 Google LLC
  8245. *
  8246. * Licensed under the Apache License, Version 2.0 (the "License");
  8247. * you may not use this file except in compliance with the License.
  8248. * You may obtain a copy of the License at
  8249. *
  8250. * http://www.apache.org/licenses/LICENSE-2.0
  8251. *
  8252. * Unless required by applicable law or agreed to in writing, software
  8253. * distributed under the License is distributed on an "AS IS" BASIS,
  8254. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8255. * See the License for the specific language governing permissions and
  8256. * limitations under the License.
  8257. */
  8258. /**
  8259. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8260. *
  8261. */
  8262. function writeTreeChildWrites(writeTree, path) {
  8263. return newWriteTreeRef(path, writeTree);
  8264. }
  8265. /**
  8266. * Record a new overwrite from user code.
  8267. *
  8268. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8269. */
  8270. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8271. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8272. if (visible === undefined) {
  8273. visible = true;
  8274. }
  8275. writeTree.allWrites.push({
  8276. path: path,
  8277. snap: snap,
  8278. writeId: writeId,
  8279. visible: visible
  8280. });
  8281. if (visible) {
  8282. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8283. }
  8284. writeTree.lastWriteId = writeId;
  8285. }
  8286. /**
  8287. * Record a new merge from user code.
  8288. */
  8289. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8290. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8291. writeTree.allWrites.push({
  8292. path: path,
  8293. children: changedChildren,
  8294. writeId: writeId,
  8295. visible: true
  8296. });
  8297. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8298. writeTree.lastWriteId = writeId;
  8299. }
  8300. function writeTreeGetWrite(writeTree, writeId) {
  8301. for (var i = 0; i < writeTree.allWrites.length; i++) {
  8302. var record = writeTree.allWrites[i];
  8303. if (record.writeId === writeId) {
  8304. return record;
  8305. }
  8306. }
  8307. return null;
  8308. }
  8309. /**
  8310. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8311. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8312. *
  8313. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8314. * events as a result).
  8315. */
  8316. function writeTreeRemoveWrite(writeTree, writeId) {
  8317. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8318. // out of order.
  8319. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8320. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8321. var idx = writeTree.allWrites.findIndex(function (s) {
  8322. return s.writeId === writeId;
  8323. });
  8324. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8325. var writeToRemove = writeTree.allWrites[idx];
  8326. writeTree.allWrites.splice(idx, 1);
  8327. var removedWriteWasVisible = writeToRemove.visible;
  8328. var removedWriteOverlapsWithOtherWrites = false;
  8329. var i = writeTree.allWrites.length - 1;
  8330. while (removedWriteWasVisible && i >= 0) {
  8331. var currentWrite = writeTree.allWrites[i];
  8332. if (currentWrite.visible) {
  8333. if (i >= idx &&
  8334. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8335. // The removed write was completely shadowed by a subsequent write.
  8336. removedWriteWasVisible = false;
  8337. }
  8338. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8339. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8340. removedWriteOverlapsWithOtherWrites = true;
  8341. }
  8342. }
  8343. i--;
  8344. }
  8345. if (!removedWriteWasVisible) {
  8346. return false;
  8347. }
  8348. else if (removedWriteOverlapsWithOtherWrites) {
  8349. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8350. writeTreeResetTree_(writeTree);
  8351. return true;
  8352. }
  8353. else {
  8354. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8355. if (writeToRemove.snap) {
  8356. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8357. }
  8358. else {
  8359. var children = writeToRemove.children;
  8360. each(children, function (childName) {
  8361. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8362. });
  8363. }
  8364. return true;
  8365. }
  8366. }
  8367. function writeTreeRecordContainsPath_(writeRecord, path) {
  8368. if (writeRecord.snap) {
  8369. return pathContains(writeRecord.path, path);
  8370. }
  8371. else {
  8372. for (var childName in writeRecord.children) {
  8373. if (writeRecord.children.hasOwnProperty(childName) &&
  8374. pathContains(pathChild(writeRecord.path, childName), path)) {
  8375. return true;
  8376. }
  8377. }
  8378. return false;
  8379. }
  8380. }
  8381. /**
  8382. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8383. */
  8384. function writeTreeResetTree_(writeTree) {
  8385. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8386. if (writeTree.allWrites.length > 0) {
  8387. writeTree.lastWriteId =
  8388. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8389. }
  8390. else {
  8391. writeTree.lastWriteId = -1;
  8392. }
  8393. }
  8394. /**
  8395. * The default filter used when constructing the tree. Keep everything that's visible.
  8396. */
  8397. function writeTreeDefaultFilter_(write) {
  8398. return write.visible;
  8399. }
  8400. /**
  8401. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8402. * event data at that path.
  8403. */
  8404. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8405. var compoundWrite = CompoundWrite.empty();
  8406. for (var i = 0; i < writes.length; ++i) {
  8407. var write = writes[i];
  8408. // Theory, a later set will either:
  8409. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8410. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8411. if (filter(write)) {
  8412. var writePath = write.path;
  8413. var relativePath = void 0;
  8414. if (write.snap) {
  8415. if (pathContains(treeRoot, writePath)) {
  8416. relativePath = newRelativePath(treeRoot, writePath);
  8417. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8418. }
  8419. else if (pathContains(writePath, treeRoot)) {
  8420. relativePath = newRelativePath(writePath, treeRoot);
  8421. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8422. }
  8423. else ;
  8424. }
  8425. else if (write.children) {
  8426. if (pathContains(treeRoot, writePath)) {
  8427. relativePath = newRelativePath(treeRoot, writePath);
  8428. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8429. }
  8430. else if (pathContains(writePath, treeRoot)) {
  8431. relativePath = newRelativePath(writePath, treeRoot);
  8432. if (pathIsEmpty(relativePath)) {
  8433. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8434. }
  8435. else {
  8436. var child = util.safeGet(write.children, pathGetFront(relativePath));
  8437. if (child) {
  8438. // There exists a child in this node that matches the root path
  8439. var deepNode = child.getChild(pathPopFront(relativePath));
  8440. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8441. }
  8442. }
  8443. }
  8444. else ;
  8445. }
  8446. else {
  8447. throw util.assertionError('WriteRecord should have .snap or .children');
  8448. }
  8449. }
  8450. }
  8451. return compoundWrite;
  8452. }
  8453. /**
  8454. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8455. * writes), attempt to calculate a complete snapshot for the given path
  8456. *
  8457. * @param writeIdsToExclude - An optional set to be excluded
  8458. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8459. */
  8460. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8461. if (!writeIdsToExclude && !includeHiddenWrites) {
  8462. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8463. if (shadowingNode != null) {
  8464. return shadowingNode;
  8465. }
  8466. else {
  8467. var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8468. if (compoundWriteIsEmpty(subMerge)) {
  8469. return completeServerCache;
  8470. }
  8471. else if (completeServerCache == null &&
  8472. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8473. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8474. return null;
  8475. }
  8476. else {
  8477. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8478. return compoundWriteApply(subMerge, layeredCache);
  8479. }
  8480. }
  8481. }
  8482. else {
  8483. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8484. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8485. return completeServerCache;
  8486. }
  8487. else {
  8488. // If the server cache is null, and we don't have a complete cache, we need to return null
  8489. if (!includeHiddenWrites &&
  8490. completeServerCache == null &&
  8491. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8492. return null;
  8493. }
  8494. else {
  8495. var filter = function (write) {
  8496. return ((write.visible || includeHiddenWrites) &&
  8497. (!writeIdsToExclude ||
  8498. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8499. (pathContains(write.path, treePath) ||
  8500. pathContains(treePath, write.path)));
  8501. };
  8502. var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8503. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8504. return compoundWriteApply(mergeAtPath, layeredCache);
  8505. }
  8506. }
  8507. }
  8508. }
  8509. /**
  8510. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8511. * Used when creating new views, to pre-fill their complete event children snapshot.
  8512. */
  8513. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8514. var completeChildren = ChildrenNode.EMPTY_NODE;
  8515. var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8516. if (topLevelSet) {
  8517. if (!topLevelSet.isLeafNode()) {
  8518. // we're shadowing everything. Return the children.
  8519. topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
  8520. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8521. });
  8522. }
  8523. return completeChildren;
  8524. }
  8525. else if (completeServerChildren) {
  8526. // Layer any children we have on top of this
  8527. // We know we don't have a top-level set, so just enumerate existing children
  8528. var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8529. completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8530. var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
  8531. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8532. });
  8533. // Add any complete children we have from the set
  8534. compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
  8535. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8536. });
  8537. return completeChildren;
  8538. }
  8539. else {
  8540. // We don't have anything to layer on top of. Layer on any children we have
  8541. // Note that we can return an empty snap if we have a defined delete
  8542. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8543. compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
  8544. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8545. });
  8546. return completeChildren;
  8547. }
  8548. }
  8549. /**
  8550. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8551. * applied to the event cache.
  8552. *
  8553. * Possibilities:
  8554. *
  8555. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8556. *
  8557. * 2. Some write is completely shadowing. No events to be raised
  8558. *
  8559. * 3. Is partially shadowed. Events
  8560. *
  8561. * Either existingEventSnap or existingServerSnap must exist
  8562. */
  8563. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8564. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8565. var path = pathChild(treePath, childPath);
  8566. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8567. // At this point we can probably guarantee that we're in case 2, meaning no events
  8568. // May need to check visibility while doing the findRootMostValueAndPath call
  8569. return null;
  8570. }
  8571. else {
  8572. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8573. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8574. if (compoundWriteIsEmpty(childMerge)) {
  8575. // We're not shadowing at all. Case 1
  8576. return existingServerSnap.getChild(childPath);
  8577. }
  8578. else {
  8579. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8580. // However this is tricky to find out, since user updates don't necessary change the server
  8581. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8582. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8583. // only check if the updates change the serverNode.
  8584. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8585. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8586. }
  8587. }
  8588. }
  8589. /**
  8590. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8591. * complete child for this ChildKey.
  8592. */
  8593. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8594. var path = pathChild(treePath, childKey);
  8595. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8596. if (shadowingNode != null) {
  8597. return shadowingNode;
  8598. }
  8599. else {
  8600. if (existingServerSnap.isCompleteForChild(childKey)) {
  8601. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8602. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8603. }
  8604. else {
  8605. return null;
  8606. }
  8607. }
  8608. }
  8609. /**
  8610. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8611. * a higher path, this will return the child of that write relative to the write and this path.
  8612. * Returns null if there is no write at this path.
  8613. */
  8614. function writeTreeShadowingWrite(writeTree, path) {
  8615. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8616. }
  8617. /**
  8618. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8619. * the window, but may now be in the window.
  8620. */
  8621. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8622. var toIterate;
  8623. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8624. var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8625. if (shadowingNode != null) {
  8626. toIterate = shadowingNode;
  8627. }
  8628. else if (completeServerData != null) {
  8629. toIterate = compoundWriteApply(merge, completeServerData);
  8630. }
  8631. else {
  8632. // no children to iterate on
  8633. return [];
  8634. }
  8635. toIterate = toIterate.withIndex(index);
  8636. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8637. var nodes = [];
  8638. var cmp = index.getCompare();
  8639. var iter = reverse
  8640. ? toIterate.getReverseIteratorFrom(startPost, index)
  8641. : toIterate.getIteratorFrom(startPost, index);
  8642. var next = iter.getNext();
  8643. while (next && nodes.length < count) {
  8644. if (cmp(next, startPost) !== 0) {
  8645. nodes.push(next);
  8646. }
  8647. next = iter.getNext();
  8648. }
  8649. return nodes;
  8650. }
  8651. else {
  8652. return [];
  8653. }
  8654. }
  8655. function newWriteTree() {
  8656. return {
  8657. visibleWrites: CompoundWrite.empty(),
  8658. allWrites: [],
  8659. lastWriteId: -1
  8660. };
  8661. }
  8662. /**
  8663. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8664. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8665. * can lead to a more expensive calculation.
  8666. *
  8667. * @param writeIdsToExclude - Optional writes to exclude.
  8668. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8669. */
  8670. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8671. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8672. }
  8673. /**
  8674. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8675. * mix of the given server data and write data.
  8676. *
  8677. */
  8678. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8679. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8680. }
  8681. /**
  8682. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8683. * if anything, needs to be applied to the event cache.
  8684. *
  8685. * Possibilities:
  8686. *
  8687. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8688. *
  8689. * 2. Some write is completely shadowing. No events to be raised
  8690. *
  8691. * 3. Is partially shadowed. Events should be raised
  8692. *
  8693. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8694. *
  8695. *
  8696. */
  8697. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8698. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8699. }
  8700. /**
  8701. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8702. * a higher path, this will return the child of that write relative to the write and this path.
  8703. * Returns null if there is no write at this path.
  8704. *
  8705. */
  8706. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8707. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8708. }
  8709. /**
  8710. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8711. * the window, but may now be in the window
  8712. */
  8713. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8714. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8715. }
  8716. /**
  8717. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8718. * complete child for this ChildKey.
  8719. */
  8720. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8721. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8722. }
  8723. /**
  8724. * Return a WriteTreeRef for a child.
  8725. */
  8726. function writeTreeRefChild(writeTreeRef, childName) {
  8727. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8728. }
  8729. function newWriteTreeRef(path, writeTree) {
  8730. return {
  8731. treePath: path,
  8732. writeTree: writeTree
  8733. };
  8734. }
  8735. /**
  8736. * @license
  8737. * Copyright 2017 Google LLC
  8738. *
  8739. * Licensed under the Apache License, Version 2.0 (the "License");
  8740. * you may not use this file except in compliance with the License.
  8741. * You may obtain a copy of the License at
  8742. *
  8743. * http://www.apache.org/licenses/LICENSE-2.0
  8744. *
  8745. * Unless required by applicable law or agreed to in writing, software
  8746. * distributed under the License is distributed on an "AS IS" BASIS,
  8747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8748. * See the License for the specific language governing permissions and
  8749. * limitations under the License.
  8750. */
  8751. var ChildChangeAccumulator = /** @class */ (function () {
  8752. function ChildChangeAccumulator() {
  8753. this.changeMap = new Map();
  8754. }
  8755. ChildChangeAccumulator.prototype.trackChildChange = function (change) {
  8756. var type = change.type;
  8757. var childKey = change.childName;
  8758. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8759. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8760. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8761. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8762. var oldChange = this.changeMap.get(childKey);
  8763. if (oldChange) {
  8764. var oldType = oldChange.type;
  8765. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8766. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8767. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8768. }
  8769. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8770. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8771. this.changeMap.delete(childKey);
  8772. }
  8773. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8774. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8775. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8776. }
  8777. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8778. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8779. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8780. }
  8781. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8782. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8783. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8784. }
  8785. else {
  8786. throw util.assertionError('Illegal combination of changes: ' +
  8787. change +
  8788. ' occurred after ' +
  8789. oldChange);
  8790. }
  8791. }
  8792. else {
  8793. this.changeMap.set(childKey, change);
  8794. }
  8795. };
  8796. ChildChangeAccumulator.prototype.getChanges = function () {
  8797. return Array.from(this.changeMap.values());
  8798. };
  8799. return ChildChangeAccumulator;
  8800. }());
  8801. /**
  8802. * @license
  8803. * Copyright 2017 Google LLC
  8804. *
  8805. * Licensed under the Apache License, Version 2.0 (the "License");
  8806. * you may not use this file except in compliance with the License.
  8807. * You may obtain a copy of the License at
  8808. *
  8809. * http://www.apache.org/licenses/LICENSE-2.0
  8810. *
  8811. * Unless required by applicable law or agreed to in writing, software
  8812. * distributed under the License is distributed on an "AS IS" BASIS,
  8813. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8814. * See the License for the specific language governing permissions and
  8815. * limitations under the License.
  8816. */
  8817. /**
  8818. * An implementation of CompleteChildSource that never returns any additional children
  8819. */
  8820. // eslint-disable-next-line @typescript-eslint/naming-convention
  8821. var NoCompleteChildSource_ = /** @class */ (function () {
  8822. function NoCompleteChildSource_() {
  8823. }
  8824. NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
  8825. return null;
  8826. };
  8827. NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
  8828. return null;
  8829. };
  8830. return NoCompleteChildSource_;
  8831. }());
  8832. /**
  8833. * Singleton instance.
  8834. */
  8835. var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8836. /**
  8837. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8838. * old event caches available to calculate complete children.
  8839. */
  8840. var WriteTreeCompleteChildSource = /** @class */ (function () {
  8841. function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
  8842. if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
  8843. this.writes_ = writes_;
  8844. this.viewCache_ = viewCache_;
  8845. this.optCompleteServerCache_ = optCompleteServerCache_;
  8846. }
  8847. WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
  8848. var node = this.viewCache_.eventCache;
  8849. if (node.isCompleteForChild(childKey)) {
  8850. return node.getNode().getImmediateChild(childKey);
  8851. }
  8852. else {
  8853. var serverNode = this.optCompleteServerCache_ != null
  8854. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8855. : this.viewCache_.serverCache;
  8856. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8857. }
  8858. };
  8859. WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
  8860. var completeServerData = this.optCompleteServerCache_ != null
  8861. ? this.optCompleteServerCache_
  8862. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8863. var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8864. if (nodes.length === 0) {
  8865. return null;
  8866. }
  8867. else {
  8868. return nodes[0];
  8869. }
  8870. };
  8871. return WriteTreeCompleteChildSource;
  8872. }());
  8873. /**
  8874. * @license
  8875. * Copyright 2017 Google LLC
  8876. *
  8877. * Licensed under the Apache License, Version 2.0 (the "License");
  8878. * you may not use this file except in compliance with the License.
  8879. * You may obtain a copy of the License at
  8880. *
  8881. * http://www.apache.org/licenses/LICENSE-2.0
  8882. *
  8883. * Unless required by applicable law or agreed to in writing, software
  8884. * distributed under the License is distributed on an "AS IS" BASIS,
  8885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8886. * See the License for the specific language governing permissions and
  8887. * limitations under the License.
  8888. */
  8889. function newViewProcessor(filter) {
  8890. return { filter: filter };
  8891. }
  8892. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8893. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8894. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8895. }
  8896. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8897. var accumulator = new ChildChangeAccumulator();
  8898. var newViewCache, filterServerNode;
  8899. if (operation.type === OperationType.OVERWRITE) {
  8900. var overwrite = operation;
  8901. if (overwrite.source.fromUser) {
  8902. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8903. }
  8904. else {
  8905. util.assert(overwrite.source.fromServer, 'Unknown source.');
  8906. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8907. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8908. // again
  8909. filterServerNode =
  8910. overwrite.source.tagged ||
  8911. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8912. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8913. }
  8914. }
  8915. else if (operation.type === OperationType.MERGE) {
  8916. var merge = operation;
  8917. if (merge.source.fromUser) {
  8918. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8919. }
  8920. else {
  8921. util.assert(merge.source.fromServer, 'Unknown source.');
  8922. // We filter the node if it's a tagged update or the node has been previously filtered
  8923. filterServerNode =
  8924. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8925. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8926. }
  8927. }
  8928. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8929. var ackUserWrite = operation;
  8930. if (!ackUserWrite.revert) {
  8931. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8932. }
  8933. else {
  8934. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8935. }
  8936. }
  8937. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8938. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8939. }
  8940. else {
  8941. throw util.assertionError('Unknown operation type: ' + operation.type);
  8942. }
  8943. var changes = accumulator.getChanges();
  8944. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8945. return { viewCache: newViewCache, changes: changes };
  8946. }
  8947. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8948. var eventSnap = newViewCache.eventCache;
  8949. if (eventSnap.isFullyInitialized()) {
  8950. var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8951. var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8952. if (accumulator.length > 0 ||
  8953. !oldViewCache.eventCache.isFullyInitialized() ||
  8954. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8955. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8956. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8957. }
  8958. }
  8959. }
  8960. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8961. var oldEventSnap = viewCache.eventCache;
  8962. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8963. // we have a shadowing write, ignore changes
  8964. return viewCache;
  8965. }
  8966. else {
  8967. var newEventCache = void 0, serverNode = void 0;
  8968. if (pathIsEmpty(changePath)) {
  8969. // TODO: figure out how this plays with "sliding ack windows"
  8970. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8971. if (viewCache.serverCache.isFiltered()) {
  8972. // We need to special case this, because we need to only apply writes to complete children, or
  8973. // we might end up raising events for incomplete children. If the server data is filtered deep
  8974. // writes cannot be guaranteed to be complete
  8975. var serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8976. var completeChildren = serverCache instanceof ChildrenNode
  8977. ? serverCache
  8978. : ChildrenNode.EMPTY_NODE;
  8979. var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8980. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8981. }
  8982. else {
  8983. var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8984. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8985. }
  8986. }
  8987. else {
  8988. var childKey = pathGetFront(changePath);
  8989. if (childKey === '.priority') {
  8990. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8991. var oldEventNode = oldEventSnap.getNode();
  8992. serverNode = viewCache.serverCache.getNode();
  8993. // we might have overwrites for this priority
  8994. var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8995. if (updatedPriority != null) {
  8996. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8997. }
  8998. else {
  8999. // priority didn't change, keep old node
  9000. newEventCache = oldEventSnap.getNode();
  9001. }
  9002. }
  9003. else {
  9004. var childChangePath = pathPopFront(changePath);
  9005. // update child
  9006. var newEventChild = void 0;
  9007. if (oldEventSnap.isCompleteForChild(childKey)) {
  9008. serverNode = viewCache.serverCache.getNode();
  9009. var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  9010. if (eventChildUpdate != null) {
  9011. newEventChild = oldEventSnap
  9012. .getNode()
  9013. .getImmediateChild(childKey)
  9014. .updateChild(childChangePath, eventChildUpdate);
  9015. }
  9016. else {
  9017. // Nothing changed, just keep the old child
  9018. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9019. }
  9020. }
  9021. else {
  9022. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9023. }
  9024. if (newEventChild != null) {
  9025. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  9026. }
  9027. else {
  9028. // no complete child available or no change
  9029. newEventCache = oldEventSnap.getNode();
  9030. }
  9031. }
  9032. }
  9033. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  9034. }
  9035. }
  9036. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  9037. var oldServerSnap = oldViewCache.serverCache;
  9038. var newServerCache;
  9039. var serverFilter = filterServerNode
  9040. ? viewProcessor.filter
  9041. : viewProcessor.filter.getIndexedFilter();
  9042. if (pathIsEmpty(changePath)) {
  9043. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  9044. }
  9045. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  9046. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  9047. var newServerNode = oldServerSnap
  9048. .getNode()
  9049. .updateChild(changePath, changedSnap);
  9050. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  9051. }
  9052. else {
  9053. var childKey = pathGetFront(changePath);
  9054. if (!oldServerSnap.isCompleteForPath(changePath) &&
  9055. pathGetLength(changePath) > 1) {
  9056. // We don't update incomplete nodes with updates intended for other listeners
  9057. return oldViewCache;
  9058. }
  9059. var childChangePath = pathPopFront(changePath);
  9060. var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  9061. var newChildNode = childNode.updateChild(childChangePath, changedSnap);
  9062. if (childKey === '.priority') {
  9063. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  9064. }
  9065. else {
  9066. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  9067. }
  9068. }
  9069. var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  9070. var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  9071. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  9072. }
  9073. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  9074. var oldEventSnap = oldViewCache.eventCache;
  9075. var newViewCache, newEventCache;
  9076. var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  9077. if (pathIsEmpty(changePath)) {
  9078. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  9079. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  9080. }
  9081. else {
  9082. var childKey = pathGetFront(changePath);
  9083. if (childKey === '.priority') {
  9084. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  9085. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  9086. }
  9087. else {
  9088. var childChangePath = pathPopFront(changePath);
  9089. var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9090. var newChild = void 0;
  9091. if (pathIsEmpty(childChangePath)) {
  9092. // Child overwrite, we can replace the child
  9093. newChild = changedSnap;
  9094. }
  9095. else {
  9096. var childNode = source.getCompleteChild(childKey);
  9097. if (childNode != null) {
  9098. if (pathGetBack(childChangePath) === '.priority' &&
  9099. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  9100. // This is a priority update on an empty node. If this node exists on the server, the
  9101. // server will send down the priority in the update, so ignore for now
  9102. newChild = childNode;
  9103. }
  9104. else {
  9105. newChild = childNode.updateChild(childChangePath, changedSnap);
  9106. }
  9107. }
  9108. else {
  9109. // There is no complete child node available
  9110. newChild = ChildrenNode.EMPTY_NODE;
  9111. }
  9112. }
  9113. if (!oldChild.equals(newChild)) {
  9114. var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  9115. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  9116. }
  9117. else {
  9118. newViewCache = oldViewCache;
  9119. }
  9120. }
  9121. }
  9122. return newViewCache;
  9123. }
  9124. function viewProcessorCacheHasChild(viewCache, childKey) {
  9125. return viewCache.eventCache.isCompleteForChild(childKey);
  9126. }
  9127. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  9128. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9129. // window leaving room for new items. It's important we process these changes first, so we
  9130. // iterate the changes twice, first processing any that affect items currently in view.
  9131. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9132. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9133. // not the other.
  9134. var curViewCache = viewCache;
  9135. changedChildren.foreach(function (relativePath, childNode) {
  9136. var writePath = pathChild(path, relativePath);
  9137. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9138. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9139. }
  9140. });
  9141. changedChildren.foreach(function (relativePath, childNode) {
  9142. var writePath = pathChild(path, relativePath);
  9143. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9144. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9145. }
  9146. });
  9147. return curViewCache;
  9148. }
  9149. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  9150. merge.foreach(function (relativePath, childNode) {
  9151. node = node.updateChild(relativePath, childNode);
  9152. });
  9153. return node;
  9154. }
  9155. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  9156. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  9157. // wait for the complete data update coming soon.
  9158. if (viewCache.serverCache.getNode().isEmpty() &&
  9159. !viewCache.serverCache.isFullyInitialized()) {
  9160. return viewCache;
  9161. }
  9162. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9163. // window leaving room for new items. It's important we process these changes first, so we
  9164. // iterate the changes twice, first processing any that affect items currently in view.
  9165. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9166. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9167. // not the other.
  9168. var curViewCache = viewCache;
  9169. var viewMergeTree;
  9170. if (pathIsEmpty(path)) {
  9171. viewMergeTree = changedChildren;
  9172. }
  9173. else {
  9174. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  9175. }
  9176. var serverNode = viewCache.serverCache.getNode();
  9177. viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
  9178. if (serverNode.hasChild(childKey)) {
  9179. var serverChild = viewCache.serverCache
  9180. .getNode()
  9181. .getImmediateChild(childKey);
  9182. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  9183. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9184. }
  9185. });
  9186. viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
  9187. var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  9188. childMergeTree.value === null;
  9189. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  9190. var serverChild = viewCache.serverCache
  9191. .getNode()
  9192. .getImmediateChild(childKey);
  9193. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  9194. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9195. }
  9196. });
  9197. return curViewCache;
  9198. }
  9199. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  9200. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  9201. return viewCache;
  9202. }
  9203. // Only filter server node if it is currently filtered
  9204. var filterServerNode = viewCache.serverCache.isFiltered();
  9205. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  9206. // now that it won't be shadowed.
  9207. var serverCache = viewCache.serverCache;
  9208. if (affectedTree.value != null) {
  9209. // This is an overwrite.
  9210. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  9211. serverCache.isCompleteForPath(ackPath)) {
  9212. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  9213. }
  9214. else if (pathIsEmpty(ackPath)) {
  9215. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  9216. // should just re-apply whatever we have in our cache as a merge.
  9217. var changedChildren_1 = new ImmutableTree(null);
  9218. serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
  9219. changedChildren_1 = changedChildren_1.set(new Path(name), node);
  9220. });
  9221. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
  9222. }
  9223. else {
  9224. return viewCache;
  9225. }
  9226. }
  9227. else {
  9228. // This is a merge.
  9229. var changedChildren_2 = new ImmutableTree(null);
  9230. affectedTree.foreach(function (mergePath, value) {
  9231. var serverCachePath = pathChild(ackPath, mergePath);
  9232. if (serverCache.isCompleteForPath(serverCachePath)) {
  9233. changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  9234. }
  9235. });
  9236. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
  9237. }
  9238. }
  9239. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  9240. var oldServerNode = viewCache.serverCache;
  9241. var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  9242. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  9243. }
  9244. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  9245. var complete;
  9246. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  9247. return viewCache;
  9248. }
  9249. else {
  9250. var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  9251. var oldEventCache = viewCache.eventCache.getNode();
  9252. var newEventCache = void 0;
  9253. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9254. var newNode = void 0;
  9255. if (viewCache.serverCache.isFullyInitialized()) {
  9256. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9257. }
  9258. else {
  9259. var serverChildren = viewCache.serverCache.getNode();
  9260. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9261. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9262. }
  9263. newNode = newNode;
  9264. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9265. }
  9266. else {
  9267. var childKey = pathGetFront(path);
  9268. var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9269. if (newChild == null &&
  9270. viewCache.serverCache.isCompleteForChild(childKey)) {
  9271. newChild = oldEventCache.getImmediateChild(childKey);
  9272. }
  9273. if (newChild != null) {
  9274. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9275. }
  9276. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9277. // No complete child available, delete the existing one, if any
  9278. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9279. }
  9280. else {
  9281. newEventCache = oldEventCache;
  9282. }
  9283. if (newEventCache.isEmpty() &&
  9284. viewCache.serverCache.isFullyInitialized()) {
  9285. // We might have reverted all child writes. Maybe the old event was a leaf node
  9286. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9287. if (complete.isLeafNode()) {
  9288. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9289. }
  9290. }
  9291. }
  9292. complete =
  9293. viewCache.serverCache.isFullyInitialized() ||
  9294. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9295. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9296. }
  9297. }
  9298. /**
  9299. * @license
  9300. * Copyright 2017 Google LLC
  9301. *
  9302. * Licensed under the Apache License, Version 2.0 (the "License");
  9303. * you may not use this file except in compliance with the License.
  9304. * You may obtain a copy of the License at
  9305. *
  9306. * http://www.apache.org/licenses/LICENSE-2.0
  9307. *
  9308. * Unless required by applicable law or agreed to in writing, software
  9309. * distributed under the License is distributed on an "AS IS" BASIS,
  9310. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9311. * See the License for the specific language governing permissions and
  9312. * limitations under the License.
  9313. */
  9314. /**
  9315. * A view represents a specific location and query that has 1 or more event registrations.
  9316. *
  9317. * It does several things:
  9318. * - Maintains the list of event registrations for this location/query.
  9319. * - Maintains a cache of the data visible for this location/query.
  9320. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9321. * registrations returns the set of events to be raised.
  9322. */
  9323. var View = /** @class */ (function () {
  9324. function View(query_, initialViewCache) {
  9325. this.query_ = query_;
  9326. this.eventRegistrations_ = [];
  9327. var params = this.query_._queryParams;
  9328. var indexFilter = new IndexedFilter(params.getIndex());
  9329. var filter = queryParamsGetNodeFilter(params);
  9330. this.processor_ = newViewProcessor(filter);
  9331. var initialServerCache = initialViewCache.serverCache;
  9332. var initialEventCache = initialViewCache.eventCache;
  9333. // Don't filter server node with other filter than index, wait for tagged listen
  9334. var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9335. var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9336. var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9337. var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9338. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9339. this.eventGenerator_ = new EventGenerator(this.query_);
  9340. }
  9341. Object.defineProperty(View.prototype, "query", {
  9342. get: function () {
  9343. return this.query_;
  9344. },
  9345. enumerable: false,
  9346. configurable: true
  9347. });
  9348. return View;
  9349. }());
  9350. function viewGetServerCache(view) {
  9351. return view.viewCache_.serverCache.getNode();
  9352. }
  9353. function viewGetCompleteNode(view) {
  9354. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9355. }
  9356. function viewGetCompleteServerCache(view, path) {
  9357. var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9358. if (cache) {
  9359. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9360. // we need to see if it contains the child we're interested in.
  9361. if (view.query._queryParams.loadsAllData() ||
  9362. (!pathIsEmpty(path) &&
  9363. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9364. return cache.getChild(path);
  9365. }
  9366. }
  9367. return null;
  9368. }
  9369. function viewIsEmpty(view) {
  9370. return view.eventRegistrations_.length === 0;
  9371. }
  9372. function viewAddEventRegistration(view, eventRegistration) {
  9373. view.eventRegistrations_.push(eventRegistration);
  9374. }
  9375. /**
  9376. * @param eventRegistration - If null, remove all callbacks.
  9377. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9378. * @returns Cancel events, if cancelError was provided.
  9379. */
  9380. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9381. var cancelEvents = [];
  9382. if (cancelError) {
  9383. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9384. var path_1 = view.query._path;
  9385. view.eventRegistrations_.forEach(function (registration) {
  9386. var maybeEvent = registration.createCancelEvent(cancelError, path_1);
  9387. if (maybeEvent) {
  9388. cancelEvents.push(maybeEvent);
  9389. }
  9390. });
  9391. }
  9392. if (eventRegistration) {
  9393. var remaining = [];
  9394. for (var i = 0; i < view.eventRegistrations_.length; ++i) {
  9395. var existing = view.eventRegistrations_[i];
  9396. if (!existing.matches(eventRegistration)) {
  9397. remaining.push(existing);
  9398. }
  9399. else if (eventRegistration.hasAnyCallback()) {
  9400. // We're removing just this one
  9401. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9402. break;
  9403. }
  9404. }
  9405. view.eventRegistrations_ = remaining;
  9406. }
  9407. else {
  9408. view.eventRegistrations_ = [];
  9409. }
  9410. return cancelEvents;
  9411. }
  9412. /**
  9413. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9414. */
  9415. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9416. if (operation.type === OperationType.MERGE &&
  9417. operation.source.queryId !== null) {
  9418. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9419. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9420. }
  9421. var oldViewCache = view.viewCache_;
  9422. var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9423. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9424. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  9425. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9426. view.viewCache_ = result.viewCache;
  9427. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9428. }
  9429. function viewGetInitialEvents(view, registration) {
  9430. var eventSnap = view.viewCache_.eventCache;
  9431. var initialChanges = [];
  9432. if (!eventSnap.getNode().isLeafNode()) {
  9433. var eventNode = eventSnap.getNode();
  9434. eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  9435. initialChanges.push(changeChildAdded(key, childNode));
  9436. });
  9437. }
  9438. if (eventSnap.isFullyInitialized()) {
  9439. initialChanges.push(changeValue(eventSnap.getNode()));
  9440. }
  9441. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9442. }
  9443. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9444. var registrations = eventRegistration
  9445. ? [eventRegistration]
  9446. : view.eventRegistrations_;
  9447. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9448. }
  9449. /**
  9450. * @license
  9451. * Copyright 2017 Google LLC
  9452. *
  9453. * Licensed under the Apache License, Version 2.0 (the "License");
  9454. * you may not use this file except in compliance with the License.
  9455. * You may obtain a copy of the License at
  9456. *
  9457. * http://www.apache.org/licenses/LICENSE-2.0
  9458. *
  9459. * Unless required by applicable law or agreed to in writing, software
  9460. * distributed under the License is distributed on an "AS IS" BASIS,
  9461. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9462. * See the License for the specific language governing permissions and
  9463. * limitations under the License.
  9464. */
  9465. var referenceConstructor$1;
  9466. /**
  9467. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9468. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9469. * and user writes (set, transaction, update).
  9470. *
  9471. * It's responsible for:
  9472. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9473. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9474. * applyUserOverwrite, etc.)
  9475. */
  9476. var SyncPoint = /** @class */ (function () {
  9477. function SyncPoint() {
  9478. /**
  9479. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9480. * queryId and the value is the View for that query.
  9481. *
  9482. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9483. */
  9484. this.views = new Map();
  9485. }
  9486. return SyncPoint;
  9487. }());
  9488. function syncPointSetReferenceConstructor(val) {
  9489. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9490. referenceConstructor$1 = val;
  9491. }
  9492. function syncPointGetReferenceConstructor() {
  9493. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9494. return referenceConstructor$1;
  9495. }
  9496. function syncPointIsEmpty(syncPoint) {
  9497. return syncPoint.views.size === 0;
  9498. }
  9499. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9500. var e_1, _a;
  9501. var queryId = operation.source.queryId;
  9502. if (queryId !== null) {
  9503. var view = syncPoint.views.get(queryId);
  9504. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9505. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9506. }
  9507. else {
  9508. var events = [];
  9509. try {
  9510. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9511. var view = _c.value;
  9512. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9513. }
  9514. }
  9515. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  9516. finally {
  9517. try {
  9518. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9519. }
  9520. finally { if (e_1) throw e_1.error; }
  9521. }
  9522. return events;
  9523. }
  9524. }
  9525. /**
  9526. * Get a view for the specified query.
  9527. *
  9528. * @param query - The query to return a view for
  9529. * @param writesCache
  9530. * @param serverCache
  9531. * @param serverCacheComplete
  9532. * @returns Events to raise.
  9533. */
  9534. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9535. var queryId = query._queryIdentifier;
  9536. var view = syncPoint.views.get(queryId);
  9537. if (!view) {
  9538. // TODO: make writesCache take flag for complete server node
  9539. var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9540. var eventCacheComplete = false;
  9541. if (eventCache) {
  9542. eventCacheComplete = true;
  9543. }
  9544. else if (serverCache instanceof ChildrenNode) {
  9545. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9546. eventCacheComplete = false;
  9547. }
  9548. else {
  9549. eventCache = ChildrenNode.EMPTY_NODE;
  9550. eventCacheComplete = false;
  9551. }
  9552. var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9553. return new View(query, viewCache);
  9554. }
  9555. return view;
  9556. }
  9557. /**
  9558. * Add an event callback for the specified query.
  9559. *
  9560. * @param query
  9561. * @param eventRegistration
  9562. * @param writesCache
  9563. * @param serverCache - Complete server cache, if we have it.
  9564. * @param serverCacheComplete
  9565. * @returns Events to raise.
  9566. */
  9567. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9568. var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9569. if (!syncPoint.views.has(query._queryIdentifier)) {
  9570. syncPoint.views.set(query._queryIdentifier, view);
  9571. }
  9572. // This is guaranteed to exist now, we just created anything that was missing
  9573. viewAddEventRegistration(view, eventRegistration);
  9574. return viewGetInitialEvents(view, eventRegistration);
  9575. }
  9576. /**
  9577. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9578. *
  9579. * If query is the default query, we'll check all views for the specified eventRegistration.
  9580. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9581. *
  9582. * @param eventRegistration - If null, remove all callbacks.
  9583. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9584. * @returns removed queries and any cancel events
  9585. */
  9586. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9587. var e_2, _a;
  9588. var queryId = query._queryIdentifier;
  9589. var removed = [];
  9590. var cancelEvents = [];
  9591. var hadCompleteView = syncPointHasCompleteView(syncPoint);
  9592. if (queryId === 'default') {
  9593. try {
  9594. // When you do ref.off(...), we search all views for the registration to remove.
  9595. for (var _b = tslib.__values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9596. var _d = tslib.__read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
  9597. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9598. if (viewIsEmpty(view)) {
  9599. syncPoint.views.delete(viewQueryId);
  9600. // We'll deal with complete views later.
  9601. if (!view.query._queryParams.loadsAllData()) {
  9602. removed.push(view.query);
  9603. }
  9604. }
  9605. }
  9606. }
  9607. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  9608. finally {
  9609. try {
  9610. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9611. }
  9612. finally { if (e_2) throw e_2.error; }
  9613. }
  9614. }
  9615. else {
  9616. // remove the callback from the specific view.
  9617. var view = syncPoint.views.get(queryId);
  9618. if (view) {
  9619. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9620. if (viewIsEmpty(view)) {
  9621. syncPoint.views.delete(queryId);
  9622. // We'll deal with complete views later.
  9623. if (!view.query._queryParams.loadsAllData()) {
  9624. removed.push(view.query);
  9625. }
  9626. }
  9627. }
  9628. }
  9629. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9630. // We removed our last complete view.
  9631. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9632. }
  9633. return { removed: removed, events: cancelEvents };
  9634. }
  9635. function syncPointGetQueryViews(syncPoint) {
  9636. var e_3, _a;
  9637. var result = [];
  9638. try {
  9639. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9640. var view = _c.value;
  9641. if (!view.query._queryParams.loadsAllData()) {
  9642. result.push(view);
  9643. }
  9644. }
  9645. }
  9646. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  9647. finally {
  9648. try {
  9649. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9650. }
  9651. finally { if (e_3) throw e_3.error; }
  9652. }
  9653. return result;
  9654. }
  9655. /**
  9656. * @param path - The path to the desired complete snapshot
  9657. * @returns A complete cache, if it exists
  9658. */
  9659. function syncPointGetCompleteServerCache(syncPoint, path) {
  9660. var e_4, _a;
  9661. var serverCache = null;
  9662. try {
  9663. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9664. var view = _c.value;
  9665. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9666. }
  9667. }
  9668. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  9669. finally {
  9670. try {
  9671. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9672. }
  9673. finally { if (e_4) throw e_4.error; }
  9674. }
  9675. return serverCache;
  9676. }
  9677. function syncPointViewForQuery(syncPoint, query) {
  9678. var params = query._queryParams;
  9679. if (params.loadsAllData()) {
  9680. return syncPointGetCompleteView(syncPoint);
  9681. }
  9682. else {
  9683. var queryId = query._queryIdentifier;
  9684. return syncPoint.views.get(queryId);
  9685. }
  9686. }
  9687. function syncPointViewExistsForQuery(syncPoint, query) {
  9688. return syncPointViewForQuery(syncPoint, query) != null;
  9689. }
  9690. function syncPointHasCompleteView(syncPoint) {
  9691. return syncPointGetCompleteView(syncPoint) != null;
  9692. }
  9693. function syncPointGetCompleteView(syncPoint) {
  9694. var e_5, _a;
  9695. try {
  9696. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9697. var view = _c.value;
  9698. if (view.query._queryParams.loadsAllData()) {
  9699. return view;
  9700. }
  9701. }
  9702. }
  9703. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  9704. finally {
  9705. try {
  9706. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9707. }
  9708. finally { if (e_5) throw e_5.error; }
  9709. }
  9710. return null;
  9711. }
  9712. /**
  9713. * @license
  9714. * Copyright 2017 Google LLC
  9715. *
  9716. * Licensed under the Apache License, Version 2.0 (the "License");
  9717. * you may not use this file except in compliance with the License.
  9718. * You may obtain a copy of the License at
  9719. *
  9720. * http://www.apache.org/licenses/LICENSE-2.0
  9721. *
  9722. * Unless required by applicable law or agreed to in writing, software
  9723. * distributed under the License is distributed on an "AS IS" BASIS,
  9724. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9725. * See the License for the specific language governing permissions and
  9726. * limitations under the License.
  9727. */
  9728. var referenceConstructor;
  9729. function syncTreeSetReferenceConstructor(val) {
  9730. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9731. referenceConstructor = val;
  9732. }
  9733. function syncTreeGetReferenceConstructor() {
  9734. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  9735. return referenceConstructor;
  9736. }
  9737. /**
  9738. * Static tracker for next query tag.
  9739. */
  9740. var syncTreeNextQueryTag_ = 1;
  9741. /**
  9742. * SyncTree is the central class for managing event callback registration, data caching, views
  9743. * (query processing), and event generation. There are typically two SyncTree instances for
  9744. * each Repo, one for the normal Firebase data, and one for the .info data.
  9745. *
  9746. * It has a number of responsibilities, including:
  9747. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9748. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9749. * (applyUserOverwrite(), applyUserMerge()).
  9750. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9751. * applyServerMerge()).
  9752. * - Generating user-facing events for server and user changes (all of the apply* methods
  9753. * return the set of events that need to be raised as a result).
  9754. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9755. * to the correct set of paths and queries to satisfy the current set of user event
  9756. * callbacks (listens are started/stopped using the provided listenProvider).
  9757. *
  9758. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9759. * events are returned to the caller rather than raised synchronously.
  9760. *
  9761. */
  9762. var SyncTree = /** @class */ (function () {
  9763. /**
  9764. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9765. * to server data.
  9766. */
  9767. function SyncTree(listenProvider_) {
  9768. this.listenProvider_ = listenProvider_;
  9769. /**
  9770. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9771. */
  9772. this.syncPointTree_ = new ImmutableTree(null);
  9773. /**
  9774. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9775. */
  9776. this.pendingWriteTree_ = newWriteTree();
  9777. this.tagToQueryMap = new Map();
  9778. this.queryToTagMap = new Map();
  9779. }
  9780. return SyncTree;
  9781. }());
  9782. /**
  9783. * Apply the data changes for a user-generated set() or transaction() call.
  9784. *
  9785. * @returns Events to raise.
  9786. */
  9787. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9788. // Record pending write.
  9789. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9790. if (!visible) {
  9791. return [];
  9792. }
  9793. else {
  9794. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9795. }
  9796. }
  9797. /**
  9798. * Apply the data from a user-generated update() call
  9799. *
  9800. * @returns Events to raise.
  9801. */
  9802. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9803. // Record pending merge.
  9804. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9805. var changeTree = ImmutableTree.fromObject(changedChildren);
  9806. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9807. }
  9808. /**
  9809. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9810. *
  9811. * @param revert - True if the given write failed and needs to be reverted
  9812. * @returns Events to raise.
  9813. */
  9814. function syncTreeAckUserWrite(syncTree, writeId, revert) {
  9815. if (revert === void 0) { revert = false; }
  9816. var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9817. var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9818. if (!needToReevaluate) {
  9819. return [];
  9820. }
  9821. else {
  9822. var affectedTree_1 = new ImmutableTree(null);
  9823. if (write.snap != null) {
  9824. // overwrite
  9825. affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
  9826. }
  9827. else {
  9828. each(write.children, function (pathString) {
  9829. affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
  9830. });
  9831. }
  9832. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
  9833. }
  9834. }
  9835. /**
  9836. * Apply new server data for the specified path..
  9837. *
  9838. * @returns Events to raise.
  9839. */
  9840. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9841. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9842. }
  9843. /**
  9844. * Apply new server data to be merged in at the specified path.
  9845. *
  9846. * @returns Events to raise.
  9847. */
  9848. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9849. var changeTree = ImmutableTree.fromObject(changedChildren);
  9850. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9851. }
  9852. /**
  9853. * Apply a listen complete for a query
  9854. *
  9855. * @returns Events to raise.
  9856. */
  9857. function syncTreeApplyListenComplete(syncTree, path) {
  9858. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9859. }
  9860. /**
  9861. * Apply a listen complete for a tagged query
  9862. *
  9863. * @returns Events to raise.
  9864. */
  9865. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9866. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9867. if (queryKey) {
  9868. var r = syncTreeParseQueryKey_(queryKey);
  9869. var queryPath = r.path, queryId = r.queryId;
  9870. var relativePath = newRelativePath(queryPath, path);
  9871. var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9872. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9873. }
  9874. else {
  9875. // We've already removed the query. No big deal, ignore the update
  9876. return [];
  9877. }
  9878. }
  9879. /**
  9880. * Remove event callback(s).
  9881. *
  9882. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9883. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9884. *
  9885. * @param eventRegistration - If null, all callbacks are removed.
  9886. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9887. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9888. * deduping needs to take place. This flag allows toggling of that behavior
  9889. * @returns Cancel events, if cancelError was provided.
  9890. */
  9891. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
  9892. if (skipListenerDedup === void 0) { skipListenerDedup = false; }
  9893. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9894. var path = query._path;
  9895. var maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9896. var cancelEvents = [];
  9897. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9898. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9899. // not loadsAllData().
  9900. if (maybeSyncPoint &&
  9901. (query._queryIdentifier === 'default' ||
  9902. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9903. var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9904. if (syncPointIsEmpty(maybeSyncPoint)) {
  9905. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9906. }
  9907. var removed = removedAndEvents.removed;
  9908. cancelEvents = removedAndEvents.events;
  9909. if (!skipListenerDedup) {
  9910. /**
  9911. * We may have just removed one of many listeners and can short-circuit this whole process
  9912. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9913. * properly set up.
  9914. */
  9915. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9916. // queryId === 'default'
  9917. var removingDefault = -1 !==
  9918. removed.findIndex(function (query) {
  9919. return query._queryParams.loadsAllData();
  9920. });
  9921. var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
  9922. return syncPointHasCompleteView(parentSyncPoint);
  9923. });
  9924. if (removingDefault && !covered) {
  9925. var subtree = syncTree.syncPointTree_.subtree(path);
  9926. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9927. // removal
  9928. if (!subtree.isEmpty()) {
  9929. // We need to fold over our subtree and collect the listeners to send
  9930. var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9931. // Ok, we've collected all the listens we need. Set them up.
  9932. for (var i = 0; i < newViews.length; ++i) {
  9933. var view = newViews[i], newQuery = view.query;
  9934. var listener = syncTreeCreateListenerForView_(syncTree, view);
  9935. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9936. }
  9937. }
  9938. // Otherwise there's nothing below us, so nothing we need to start listening on
  9939. }
  9940. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9941. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9942. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9943. if (!covered && removed.length > 0 && !cancelError) {
  9944. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9945. // default. Otherwise, we need to iterate through and cancel each individual query
  9946. if (removingDefault) {
  9947. // We don't tag default listeners
  9948. var defaultTag = null;
  9949. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9950. }
  9951. else {
  9952. removed.forEach(function (queryToRemove) {
  9953. var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9954. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9955. });
  9956. }
  9957. }
  9958. }
  9959. // Now, clear all of the tags we're tracking for the removed listens
  9960. syncTreeRemoveTags_(syncTree, removed);
  9961. }
  9962. return cancelEvents;
  9963. }
  9964. /**
  9965. * Apply new server data for the specified tagged query.
  9966. *
  9967. * @returns Events to raise.
  9968. */
  9969. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9970. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9971. if (queryKey != null) {
  9972. var r = syncTreeParseQueryKey_(queryKey);
  9973. var queryPath = r.path, queryId = r.queryId;
  9974. var relativePath = newRelativePath(queryPath, path);
  9975. var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9976. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9977. }
  9978. else {
  9979. // Query must have been removed already
  9980. return [];
  9981. }
  9982. }
  9983. /**
  9984. * Apply server data to be merged in for the specified tagged query.
  9985. *
  9986. * @returns Events to raise.
  9987. */
  9988. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9989. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9990. if (queryKey) {
  9991. var r = syncTreeParseQueryKey_(queryKey);
  9992. var queryPath = r.path, queryId = r.queryId;
  9993. var relativePath = newRelativePath(queryPath, path);
  9994. var changeTree = ImmutableTree.fromObject(changedChildren);
  9995. var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9996. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9997. }
  9998. else {
  9999. // We've already removed the query. No big deal, ignore the update
  10000. return [];
  10001. }
  10002. }
  10003. /**
  10004. * Add an event callback for the specified query.
  10005. *
  10006. * @returns Events to raise.
  10007. */
  10008. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
  10009. if (skipSetupListener === void 0) { skipSetupListener = false; }
  10010. var path = query._path;
  10011. var serverCache = null;
  10012. var foundAncestorDefaultView = false;
  10013. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10014. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10015. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10016. var relativePath = newRelativePath(pathToSyncPoint, path);
  10017. serverCache =
  10018. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10019. foundAncestorDefaultView =
  10020. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  10021. });
  10022. var syncPoint = syncTree.syncPointTree_.get(path);
  10023. if (!syncPoint) {
  10024. syncPoint = new SyncPoint();
  10025. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10026. }
  10027. else {
  10028. foundAncestorDefaultView =
  10029. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  10030. serverCache =
  10031. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10032. }
  10033. var serverCacheComplete;
  10034. if (serverCache != null) {
  10035. serverCacheComplete = true;
  10036. }
  10037. else {
  10038. serverCacheComplete = false;
  10039. serverCache = ChildrenNode.EMPTY_NODE;
  10040. var subtree = syncTree.syncPointTree_.subtree(path);
  10041. subtree.foreachChild(function (childName, childSyncPoint) {
  10042. var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  10043. if (completeCache) {
  10044. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  10045. }
  10046. });
  10047. }
  10048. var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  10049. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  10050. // We need to track a tag for this query
  10051. var queryKey = syncTreeMakeQueryKey_(query);
  10052. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  10053. var tag = syncTreeGetNextQueryTag_();
  10054. syncTree.queryToTagMap.set(queryKey, tag);
  10055. syncTree.tagToQueryMap.set(tag, queryKey);
  10056. }
  10057. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  10058. var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  10059. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  10060. var view = syncPointViewForQuery(syncPoint, query);
  10061. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  10062. }
  10063. return events;
  10064. }
  10065. /**
  10066. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  10067. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  10068. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  10069. * <incremented total> as the write is applied locally and then acknowledged at the server.
  10070. *
  10071. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  10072. *
  10073. * @param path - The path to the data we want
  10074. * @param writeIdsToExclude - A specific set to be excluded
  10075. */
  10076. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  10077. var includeHiddenSets = true;
  10078. var writeTree = syncTree.pendingWriteTree_;
  10079. var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
  10080. var relativePath = newRelativePath(pathSoFar, path);
  10081. var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  10082. if (serverCache) {
  10083. return serverCache;
  10084. }
  10085. });
  10086. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  10087. }
  10088. function syncTreeGetServerValue(syncTree, query) {
  10089. var path = query._path;
  10090. var serverCache = null;
  10091. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10092. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10093. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10094. var relativePath = newRelativePath(pathToSyncPoint, path);
  10095. serverCache =
  10096. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10097. });
  10098. var syncPoint = syncTree.syncPointTree_.get(path);
  10099. if (!syncPoint) {
  10100. syncPoint = new SyncPoint();
  10101. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10102. }
  10103. else {
  10104. serverCache =
  10105. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10106. }
  10107. var serverCacheComplete = serverCache != null;
  10108. var serverCacheNode = serverCacheComplete
  10109. ? new CacheNode(serverCache, true, false)
  10110. : null;
  10111. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  10112. var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  10113. return viewGetCompleteNode(view);
  10114. }
  10115. /**
  10116. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  10117. *
  10118. * NOTES:
  10119. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  10120. *
  10121. * - We call applyOperation() on each SyncPoint passing three things:
  10122. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  10123. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  10124. * 3. A snapshot Node with cached server data, if we have it.
  10125. *
  10126. * - We concatenate all of the events returned by each SyncPoint and return the result.
  10127. */
  10128. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  10129. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  10130. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  10131. }
  10132. /**
  10133. * Recursive helper for applyOperationToSyncPoints_
  10134. */
  10135. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  10136. if (pathIsEmpty(operation.path)) {
  10137. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  10138. }
  10139. else {
  10140. var syncPoint = syncPointTree.get(newEmptyPath());
  10141. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10142. if (serverCache == null && syncPoint != null) {
  10143. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10144. }
  10145. var events = [];
  10146. var childName = pathGetFront(operation.path);
  10147. var childOperation = operation.operationForChild(childName);
  10148. var childTree = syncPointTree.children.get(childName);
  10149. if (childTree && childOperation) {
  10150. var childServerCache = serverCache
  10151. ? serverCache.getImmediateChild(childName)
  10152. : null;
  10153. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10154. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10155. }
  10156. if (syncPoint) {
  10157. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10158. }
  10159. return events;
  10160. }
  10161. }
  10162. /**
  10163. * Recursive helper for applyOperationToSyncPoints_
  10164. */
  10165. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  10166. var syncPoint = syncPointTree.get(newEmptyPath());
  10167. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10168. if (serverCache == null && syncPoint != null) {
  10169. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10170. }
  10171. var events = [];
  10172. syncPointTree.children.inorderTraversal(function (childName, childTree) {
  10173. var childServerCache = serverCache
  10174. ? serverCache.getImmediateChild(childName)
  10175. : null;
  10176. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10177. var childOperation = operation.operationForChild(childName);
  10178. if (childOperation) {
  10179. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10180. }
  10181. });
  10182. if (syncPoint) {
  10183. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10184. }
  10185. return events;
  10186. }
  10187. function syncTreeCreateListenerForView_(syncTree, view) {
  10188. var query = view.query;
  10189. var tag = syncTreeTagForQuery(syncTree, query);
  10190. return {
  10191. hashFn: function () {
  10192. var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  10193. return cache.hash();
  10194. },
  10195. onComplete: function (status) {
  10196. if (status === 'ok') {
  10197. if (tag) {
  10198. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  10199. }
  10200. else {
  10201. return syncTreeApplyListenComplete(syncTree, query._path);
  10202. }
  10203. }
  10204. else {
  10205. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  10206. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  10207. var error = errorForServerCode(status, query);
  10208. return syncTreeRemoveEventRegistration(syncTree, query,
  10209. /*eventRegistration*/ null, error);
  10210. }
  10211. }
  10212. };
  10213. }
  10214. /**
  10215. * Return the tag associated with the given query.
  10216. */
  10217. function syncTreeTagForQuery(syncTree, query) {
  10218. var queryKey = syncTreeMakeQueryKey_(query);
  10219. return syncTree.queryToTagMap.get(queryKey);
  10220. }
  10221. /**
  10222. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  10223. */
  10224. function syncTreeMakeQueryKey_(query) {
  10225. return query._path.toString() + '$' + query._queryIdentifier;
  10226. }
  10227. /**
  10228. * Return the query associated with the given tag, if we have one
  10229. */
  10230. function syncTreeQueryKeyForTag_(syncTree, tag) {
  10231. return syncTree.tagToQueryMap.get(tag);
  10232. }
  10233. /**
  10234. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  10235. */
  10236. function syncTreeParseQueryKey_(queryKey) {
  10237. var splitIndex = queryKey.indexOf('$');
  10238. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  10239. return {
  10240. queryId: queryKey.substr(splitIndex + 1),
  10241. path: new Path(queryKey.substr(0, splitIndex))
  10242. };
  10243. }
  10244. /**
  10245. * A helper method to apply tagged operations
  10246. */
  10247. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  10248. var syncPoint = syncTree.syncPointTree_.get(queryPath);
  10249. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  10250. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  10251. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  10252. }
  10253. /**
  10254. * This collapses multiple unfiltered views into a single view, since we only need a single
  10255. * listener for them.
  10256. */
  10257. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  10258. return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10259. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  10260. var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  10261. return [completeView];
  10262. }
  10263. else {
  10264. // No complete view here, flatten any deeper listens into an array
  10265. var views_1 = [];
  10266. if (maybeChildSyncPoint) {
  10267. views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
  10268. }
  10269. each(childMap, function (_key, childViews) {
  10270. views_1 = views_1.concat(childViews);
  10271. });
  10272. return views_1;
  10273. }
  10274. });
  10275. }
  10276. /**
  10277. * Normalizes a query to a query we send the server for listening
  10278. *
  10279. * @returns The normalized query
  10280. */
  10281. function syncTreeQueryForListening_(query) {
  10282. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  10283. // We treat queries that load all data as default queries
  10284. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  10285. // from Query
  10286. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  10287. }
  10288. else {
  10289. return query;
  10290. }
  10291. }
  10292. function syncTreeRemoveTags_(syncTree, queries) {
  10293. for (var j = 0; j < queries.length; ++j) {
  10294. var removedQuery = queries[j];
  10295. if (!removedQuery._queryParams.loadsAllData()) {
  10296. // We should have a tag for this
  10297. var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  10298. var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  10299. syncTree.queryToTagMap.delete(removedQueryKey);
  10300. syncTree.tagToQueryMap.delete(removedQueryTag);
  10301. }
  10302. }
  10303. }
  10304. /**
  10305. * Static accessor for query tags.
  10306. */
  10307. function syncTreeGetNextQueryTag_() {
  10308. return syncTreeNextQueryTag_++;
  10309. }
  10310. /**
  10311. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  10312. *
  10313. * @returns This method can return events to support synchronous data sources
  10314. */
  10315. function syncTreeSetupListener_(syncTree, query, view) {
  10316. var path = query._path;
  10317. var tag = syncTreeTagForQuery(syncTree, query);
  10318. var listener = syncTreeCreateListenerForView_(syncTree, view);
  10319. var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10320. var subtree = syncTree.syncPointTree_.subtree(path);
  10321. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10322. // may need to shadow other listens as well.
  10323. if (tag) {
  10324. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10325. }
  10326. else {
  10327. // Shadow everything at or below this location, this is a default listener.
  10328. var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10329. if (!pathIsEmpty(relativePath) &&
  10330. maybeChildSyncPoint &&
  10331. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10332. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10333. }
  10334. else {
  10335. // No default listener here, flatten any deeper queries into an array
  10336. var queries_1 = [];
  10337. if (maybeChildSyncPoint) {
  10338. queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
  10339. }
  10340. each(childMap, function (_key, childQueries) {
  10341. queries_1 = queries_1.concat(childQueries);
  10342. });
  10343. return queries_1;
  10344. }
  10345. });
  10346. for (var i = 0; i < queriesToStop.length; ++i) {
  10347. var queryToStop = queriesToStop[i];
  10348. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10349. }
  10350. }
  10351. return events;
  10352. }
  10353. /**
  10354. * @license
  10355. * Copyright 2017 Google LLC
  10356. *
  10357. * Licensed under the Apache License, Version 2.0 (the "License");
  10358. * you may not use this file except in compliance with the License.
  10359. * You may obtain a copy of the License at
  10360. *
  10361. * http://www.apache.org/licenses/LICENSE-2.0
  10362. *
  10363. * Unless required by applicable law or agreed to in writing, software
  10364. * distributed under the License is distributed on an "AS IS" BASIS,
  10365. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10366. * See the License for the specific language governing permissions and
  10367. * limitations under the License.
  10368. */
  10369. var ExistingValueProvider = /** @class */ (function () {
  10370. function ExistingValueProvider(node_) {
  10371. this.node_ = node_;
  10372. }
  10373. ExistingValueProvider.prototype.getImmediateChild = function (childName) {
  10374. var child = this.node_.getImmediateChild(childName);
  10375. return new ExistingValueProvider(child);
  10376. };
  10377. ExistingValueProvider.prototype.node = function () {
  10378. return this.node_;
  10379. };
  10380. return ExistingValueProvider;
  10381. }());
  10382. var DeferredValueProvider = /** @class */ (function () {
  10383. function DeferredValueProvider(syncTree, path) {
  10384. this.syncTree_ = syncTree;
  10385. this.path_ = path;
  10386. }
  10387. DeferredValueProvider.prototype.getImmediateChild = function (childName) {
  10388. var childPath = pathChild(this.path_, childName);
  10389. return new DeferredValueProvider(this.syncTree_, childPath);
  10390. };
  10391. DeferredValueProvider.prototype.node = function () {
  10392. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10393. };
  10394. return DeferredValueProvider;
  10395. }());
  10396. /**
  10397. * Generate placeholders for deferred values.
  10398. */
  10399. var generateWithValues = function (values) {
  10400. values = values || {};
  10401. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10402. return values;
  10403. };
  10404. /**
  10405. * Value to use when firing local events. When writing server values, fire
  10406. * local events with an approximate value, otherwise return value as-is.
  10407. */
  10408. var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10409. if (!value || typeof value !== 'object') {
  10410. return value;
  10411. }
  10412. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10413. if (typeof value['.sv'] === 'string') {
  10414. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10415. }
  10416. else if (typeof value['.sv'] === 'object') {
  10417. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10418. }
  10419. else {
  10420. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10421. }
  10422. };
  10423. var resolveScalarDeferredValue = function (op, existing, serverValues) {
  10424. switch (op) {
  10425. case 'timestamp':
  10426. return serverValues['timestamp'];
  10427. default:
  10428. util.assert(false, 'Unexpected server value: ' + op);
  10429. }
  10430. };
  10431. var resolveComplexDeferredValue = function (op, existing, unused) {
  10432. if (!op.hasOwnProperty('increment')) {
  10433. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10434. }
  10435. var delta = op['increment'];
  10436. if (typeof delta !== 'number') {
  10437. util.assert(false, 'Unexpected increment value: ' + delta);
  10438. }
  10439. var existingNode = existing.node();
  10440. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10441. // Incrementing a non-number sets the value to the incremented amount
  10442. if (!existingNode.isLeafNode()) {
  10443. return delta;
  10444. }
  10445. var leaf = existingNode;
  10446. var existingVal = leaf.getValue();
  10447. if (typeof existingVal !== 'number') {
  10448. return delta;
  10449. }
  10450. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10451. return existingVal + delta;
  10452. };
  10453. /**
  10454. * Recursively replace all deferred values and priorities in the tree with the
  10455. * specified generated replacement values.
  10456. * @param path - path to which write is relative
  10457. * @param node - new data written at path
  10458. * @param syncTree - current data
  10459. */
  10460. var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10461. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10462. };
  10463. /**
  10464. * Recursively replace all deferred values and priorities in the node with the
  10465. * specified generated replacement values. If there are no server values in the node,
  10466. * it'll be returned as-is.
  10467. */
  10468. var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10469. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10470. };
  10471. function resolveDeferredValue(node, existingVal, serverValues) {
  10472. var rawPri = node.getPriority().val();
  10473. var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10474. var newNode;
  10475. if (node.isLeafNode()) {
  10476. var leafNode = node;
  10477. var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10478. if (value !== leafNode.getValue() ||
  10479. priority !== leafNode.getPriority().val()) {
  10480. return new LeafNode(value, nodeFromJSON(priority));
  10481. }
  10482. else {
  10483. return node;
  10484. }
  10485. }
  10486. else {
  10487. var childrenNode = node;
  10488. newNode = childrenNode;
  10489. if (priority !== childrenNode.getPriority().val()) {
  10490. newNode = newNode.updatePriority(new LeafNode(priority));
  10491. }
  10492. childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  10493. var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10494. if (newChildNode !== childNode) {
  10495. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10496. }
  10497. });
  10498. return newNode;
  10499. }
  10500. }
  10501. /**
  10502. * @license
  10503. * Copyright 2017 Google LLC
  10504. *
  10505. * Licensed under the Apache License, Version 2.0 (the "License");
  10506. * you may not use this file except in compliance with the License.
  10507. * You may obtain a copy of the License at
  10508. *
  10509. * http://www.apache.org/licenses/LICENSE-2.0
  10510. *
  10511. * Unless required by applicable law or agreed to in writing, software
  10512. * distributed under the License is distributed on an "AS IS" BASIS,
  10513. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10514. * See the License for the specific language governing permissions and
  10515. * limitations under the License.
  10516. */
  10517. /**
  10518. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10519. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10520. * children.
  10521. */
  10522. var Tree = /** @class */ (function () {
  10523. /**
  10524. * @param name - Optional name of the node.
  10525. * @param parent - Optional parent node.
  10526. * @param node - Optional node to wrap.
  10527. */
  10528. function Tree(name, parent, node) {
  10529. if (name === void 0) { name = ''; }
  10530. if (parent === void 0) { parent = null; }
  10531. if (node === void 0) { node = { children: {}, childCount: 0 }; }
  10532. this.name = name;
  10533. this.parent = parent;
  10534. this.node = node;
  10535. }
  10536. return Tree;
  10537. }());
  10538. /**
  10539. * Returns a sub-Tree for the given path.
  10540. *
  10541. * @param pathObj - Path to look up.
  10542. * @returns Tree for path.
  10543. */
  10544. function treeSubTree(tree, pathObj) {
  10545. // TODO: Require pathObj to be Path?
  10546. var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10547. var child = tree, next = pathGetFront(path);
  10548. while (next !== null) {
  10549. var childNode = util.safeGet(child.node.children, next) || {
  10550. children: {},
  10551. childCount: 0
  10552. };
  10553. child = new Tree(next, child, childNode);
  10554. path = pathPopFront(path);
  10555. next = pathGetFront(path);
  10556. }
  10557. return child;
  10558. }
  10559. /**
  10560. * Returns the data associated with this tree node.
  10561. *
  10562. * @returns The data or null if no data exists.
  10563. */
  10564. function treeGetValue(tree) {
  10565. return tree.node.value;
  10566. }
  10567. /**
  10568. * Sets data to this tree node.
  10569. *
  10570. * @param value - Value to set.
  10571. */
  10572. function treeSetValue(tree, value) {
  10573. tree.node.value = value;
  10574. treeUpdateParents(tree);
  10575. }
  10576. /**
  10577. * @returns Whether the tree has any children.
  10578. */
  10579. function treeHasChildren(tree) {
  10580. return tree.node.childCount > 0;
  10581. }
  10582. /**
  10583. * @returns Whethe rthe tree is empty (no value or children).
  10584. */
  10585. function treeIsEmpty(tree) {
  10586. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10587. }
  10588. /**
  10589. * Calls action for each child of this tree node.
  10590. *
  10591. * @param action - Action to be called for each child.
  10592. */
  10593. function treeForEachChild(tree, action) {
  10594. each(tree.node.children, function (child, childTree) {
  10595. action(new Tree(child, tree, childTree));
  10596. });
  10597. }
  10598. /**
  10599. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10600. *
  10601. * @param action - Action to be called for each child.
  10602. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10603. * false.
  10604. * @param childrenFirst - Whether to call action on children before calling it on
  10605. * parent.
  10606. */
  10607. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10608. if (includeSelf && !childrenFirst) {
  10609. action(tree);
  10610. }
  10611. treeForEachChild(tree, function (child) {
  10612. treeForEachDescendant(child, action, true, childrenFirst);
  10613. });
  10614. if (includeSelf && childrenFirst) {
  10615. action(tree);
  10616. }
  10617. }
  10618. /**
  10619. * Calls action on each ancestor node.
  10620. *
  10621. * @param action - Action to be called on each parent; return
  10622. * true to abort.
  10623. * @param includeSelf - Whether to call action on this node as well.
  10624. * @returns true if the action callback returned true.
  10625. */
  10626. function treeForEachAncestor(tree, action, includeSelf) {
  10627. var node = includeSelf ? tree : tree.parent;
  10628. while (node !== null) {
  10629. if (action(node)) {
  10630. return true;
  10631. }
  10632. node = node.parent;
  10633. }
  10634. return false;
  10635. }
  10636. /**
  10637. * @returns The path of this tree node, as a Path.
  10638. */
  10639. function treeGetPath(tree) {
  10640. return new Path(tree.parent === null
  10641. ? tree.name
  10642. : treeGetPath(tree.parent) + '/' + tree.name);
  10643. }
  10644. /**
  10645. * Adds or removes this child from its parent based on whether it's empty or not.
  10646. */
  10647. function treeUpdateParents(tree) {
  10648. if (tree.parent !== null) {
  10649. treeUpdateChild(tree.parent, tree.name, tree);
  10650. }
  10651. }
  10652. /**
  10653. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10654. *
  10655. * @param childName - The name of the child to update.
  10656. * @param child - The child to update.
  10657. */
  10658. function treeUpdateChild(tree, childName, child) {
  10659. var childEmpty = treeIsEmpty(child);
  10660. var childExists = util.contains(tree.node.children, childName);
  10661. if (childEmpty && childExists) {
  10662. delete tree.node.children[childName];
  10663. tree.node.childCount--;
  10664. treeUpdateParents(tree);
  10665. }
  10666. else if (!childEmpty && !childExists) {
  10667. tree.node.children[childName] = child.node;
  10668. tree.node.childCount++;
  10669. treeUpdateParents(tree);
  10670. }
  10671. }
  10672. /**
  10673. * @license
  10674. * Copyright 2017 Google LLC
  10675. *
  10676. * Licensed under the Apache License, Version 2.0 (the "License");
  10677. * you may not use this file except in compliance with the License.
  10678. * You may obtain a copy of the License at
  10679. *
  10680. * http://www.apache.org/licenses/LICENSE-2.0
  10681. *
  10682. * Unless required by applicable law or agreed to in writing, software
  10683. * distributed under the License is distributed on an "AS IS" BASIS,
  10684. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10685. * See the License for the specific language governing permissions and
  10686. * limitations under the License.
  10687. */
  10688. /**
  10689. * True for invalid Firebase keys
  10690. */
  10691. var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10692. /**
  10693. * True for invalid Firebase paths.
  10694. * Allows '/' in paths.
  10695. */
  10696. var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10697. /**
  10698. * Maximum number of characters to allow in leaf value
  10699. */
  10700. var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10701. var isValidKey = function (key) {
  10702. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10703. };
  10704. var isValidPathString = function (pathString) {
  10705. return (typeof pathString === 'string' &&
  10706. pathString.length !== 0 &&
  10707. !INVALID_PATH_REGEX_.test(pathString));
  10708. };
  10709. var isValidRootPathString = function (pathString) {
  10710. if (pathString) {
  10711. // Allow '/.info/' at the beginning.
  10712. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10713. }
  10714. return isValidPathString(pathString);
  10715. };
  10716. var isValidPriority = function (priority) {
  10717. return (priority === null ||
  10718. typeof priority === 'string' ||
  10719. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10720. (priority &&
  10721. typeof priority === 'object' &&
  10722. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10723. util.contains(priority, '.sv')));
  10724. };
  10725. /**
  10726. * Pre-validate a datum passed as an argument to Firebase function.
  10727. */
  10728. var validateFirebaseDataArg = function (fnName, value, path, optional) {
  10729. if (optional && value === undefined) {
  10730. return;
  10731. }
  10732. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  10733. };
  10734. /**
  10735. * Validate a data object client-side before sending to server.
  10736. */
  10737. var validateFirebaseData = function (errorPrefix, data, path_) {
  10738. var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10739. if (data === undefined) {
  10740. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10741. }
  10742. if (typeof data === 'function') {
  10743. throw new Error(errorPrefix +
  10744. 'contains a function ' +
  10745. validationPathToErrorString(path) +
  10746. ' with contents = ' +
  10747. data.toString());
  10748. }
  10749. if (isInvalidJSONNumber(data)) {
  10750. throw new Error(errorPrefix +
  10751. 'contains ' +
  10752. data.toString() +
  10753. ' ' +
  10754. validationPathToErrorString(path));
  10755. }
  10756. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10757. if (typeof data === 'string' &&
  10758. data.length > MAX_LEAF_SIZE_ / 3 &&
  10759. util.stringLength(data) > MAX_LEAF_SIZE_) {
  10760. throw new Error(errorPrefix +
  10761. 'contains a string greater than ' +
  10762. MAX_LEAF_SIZE_ +
  10763. ' utf8 bytes ' +
  10764. validationPathToErrorString(path) +
  10765. " ('" +
  10766. data.substring(0, 50) +
  10767. "...')");
  10768. }
  10769. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10770. // to save extra walking of large objects.
  10771. if (data && typeof data === 'object') {
  10772. var hasDotValue_1 = false;
  10773. var hasActualChild_1 = false;
  10774. each(data, function (key, value) {
  10775. if (key === '.value') {
  10776. hasDotValue_1 = true;
  10777. }
  10778. else if (key !== '.priority' && key !== '.sv') {
  10779. hasActualChild_1 = true;
  10780. if (!isValidKey(key)) {
  10781. throw new Error(errorPrefix +
  10782. ' contains an invalid key (' +
  10783. key +
  10784. ') ' +
  10785. validationPathToErrorString(path) +
  10786. '. Keys must be non-empty strings ' +
  10787. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10788. }
  10789. }
  10790. validationPathPush(path, key);
  10791. validateFirebaseData(errorPrefix, value, path);
  10792. validationPathPop(path);
  10793. });
  10794. if (hasDotValue_1 && hasActualChild_1) {
  10795. throw new Error(errorPrefix +
  10796. ' contains ".value" child ' +
  10797. validationPathToErrorString(path) +
  10798. ' in addition to actual children.');
  10799. }
  10800. }
  10801. };
  10802. /**
  10803. * Pre-validate paths passed in the firebase function.
  10804. */
  10805. var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10806. var i, curPath;
  10807. for (i = 0; i < mergePaths.length; i++) {
  10808. curPath = mergePaths[i];
  10809. var keys = pathSlice(curPath);
  10810. for (var j = 0; j < keys.length; j++) {
  10811. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10812. else if (!isValidKey(keys[j])) {
  10813. throw new Error(errorPrefix +
  10814. 'contains an invalid key (' +
  10815. keys[j] +
  10816. ') in path ' +
  10817. curPath.toString() +
  10818. '. Keys must be non-empty strings ' +
  10819. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10820. }
  10821. }
  10822. }
  10823. // Check that update keys are not descendants of each other.
  10824. // We rely on the property that sorting guarantees that ancestors come
  10825. // right before descendants.
  10826. mergePaths.sort(pathCompare);
  10827. var prevPath = null;
  10828. for (i = 0; i < mergePaths.length; i++) {
  10829. curPath = mergePaths[i];
  10830. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10831. throw new Error(errorPrefix +
  10832. 'contains a path ' +
  10833. prevPath.toString() +
  10834. ' that is ancestor of another path ' +
  10835. curPath.toString());
  10836. }
  10837. prevPath = curPath;
  10838. }
  10839. };
  10840. /**
  10841. * pre-validate an object passed as an argument to firebase function (
  10842. * must be an object - e.g. for firebase.update()).
  10843. */
  10844. var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10845. if (optional && data === undefined) {
  10846. return;
  10847. }
  10848. var errorPrefix = util.errorPrefix(fnName, 'values');
  10849. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10850. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  10851. }
  10852. var mergePaths = [];
  10853. each(data, function (key, value) {
  10854. var curPath = new Path(key);
  10855. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  10856. if (pathGetBack(curPath) === '.priority') {
  10857. if (!isValidPriority(value)) {
  10858. throw new Error(errorPrefix +
  10859. "contains an invalid value for '" +
  10860. curPath.toString() +
  10861. "', which must be a valid " +
  10862. 'Firebase priority (a string, finite number, server value, or null).');
  10863. }
  10864. }
  10865. mergePaths.push(curPath);
  10866. });
  10867. validateFirebaseMergePaths(errorPrefix, mergePaths);
  10868. };
  10869. var validatePriority = function (fnName, priority, optional) {
  10870. if (optional && priority === undefined) {
  10871. return;
  10872. }
  10873. if (isInvalidJSONNumber(priority)) {
  10874. throw new Error(util.errorPrefix(fnName, 'priority') +
  10875. 'is ' +
  10876. priority.toString() +
  10877. ', but must be a valid Firebase priority (a string, finite number, ' +
  10878. 'server value, or null).');
  10879. }
  10880. // Special case to allow importing data with a .sv.
  10881. if (!isValidPriority(priority)) {
  10882. throw new Error(util.errorPrefix(fnName, 'priority') +
  10883. 'must be a valid Firebase priority ' +
  10884. '(a string, finite number, server value, or null).');
  10885. }
  10886. };
  10887. var validateKey = function (fnName, argumentName, key, optional) {
  10888. if (optional && key === undefined) {
  10889. return;
  10890. }
  10891. if (!isValidKey(key)) {
  10892. throw new Error(util.errorPrefix(fnName, argumentName) +
  10893. 'was an invalid key = "' +
  10894. key +
  10895. '". Firebase keys must be non-empty strings and ' +
  10896. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10897. }
  10898. };
  10899. /**
  10900. * @internal
  10901. */
  10902. var validatePathString = function (fnName, argumentName, pathString, optional) {
  10903. if (optional && pathString === undefined) {
  10904. return;
  10905. }
  10906. if (!isValidPathString(pathString)) {
  10907. throw new Error(util.errorPrefix(fnName, argumentName) +
  10908. 'was an invalid path = "' +
  10909. pathString +
  10910. '". Paths must be non-empty strings and ' +
  10911. 'can\'t contain ".", "#", "$", "[", or "]"');
  10912. }
  10913. };
  10914. var validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10915. if (pathString) {
  10916. // Allow '/.info/' at the beginning.
  10917. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10918. }
  10919. validatePathString(fnName, argumentName, pathString, optional);
  10920. };
  10921. /**
  10922. * @internal
  10923. */
  10924. var validateWritablePath = function (fnName, path) {
  10925. if (pathGetFront(path) === '.info') {
  10926. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10927. }
  10928. };
  10929. var validateUrl = function (fnName, parsedUrl) {
  10930. // TODO = Validate server better.
  10931. var pathString = parsedUrl.path.toString();
  10932. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10933. parsedUrl.repoInfo.host.length === 0 ||
  10934. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10935. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10936. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10937. throw new Error(util.errorPrefix(fnName, 'url') +
  10938. 'must be a valid firebase URL and ' +
  10939. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10940. }
  10941. };
  10942. /**
  10943. * @license
  10944. * Copyright 2017 Google LLC
  10945. *
  10946. * Licensed under the Apache License, Version 2.0 (the "License");
  10947. * you may not use this file except in compliance with the License.
  10948. * You may obtain a copy of the License at
  10949. *
  10950. * http://www.apache.org/licenses/LICENSE-2.0
  10951. *
  10952. * Unless required by applicable law or agreed to in writing, software
  10953. * distributed under the License is distributed on an "AS IS" BASIS,
  10954. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10955. * See the License for the specific language governing permissions and
  10956. * limitations under the License.
  10957. */
  10958. /**
  10959. * The event queue serves a few purposes:
  10960. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10961. * events being queued.
  10962. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10963. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10964. * left off, ensuring that the events are still raised synchronously and in order.
  10965. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10966. * events are raised synchronously.
  10967. *
  10968. * NOTE: This can all go away if/when we move to async events.
  10969. *
  10970. */
  10971. var EventQueue = /** @class */ (function () {
  10972. function EventQueue() {
  10973. this.eventLists_ = [];
  10974. /**
  10975. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10976. */
  10977. this.recursionDepth_ = 0;
  10978. }
  10979. return EventQueue;
  10980. }());
  10981. /**
  10982. * @param eventDataList - The new events to queue.
  10983. */
  10984. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10985. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10986. var currList = null;
  10987. for (var i = 0; i < eventDataList.length; i++) {
  10988. var data = eventDataList[i];
  10989. var path = data.getPath();
  10990. if (currList !== null && !pathEquals(path, currList.path)) {
  10991. eventQueue.eventLists_.push(currList);
  10992. currList = null;
  10993. }
  10994. if (currList === null) {
  10995. currList = { events: [], path: path };
  10996. }
  10997. currList.events.push(data);
  10998. }
  10999. if (currList) {
  11000. eventQueue.eventLists_.push(currList);
  11001. }
  11002. }
  11003. /**
  11004. * Queues the specified events and synchronously raises all events (including previously queued ones)
  11005. * for the specified path.
  11006. *
  11007. * It is assumed that the new events are all for the specified path.
  11008. *
  11009. * @param path - The path to raise events for.
  11010. * @param eventDataList - The new events to raise.
  11011. */
  11012. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  11013. eventQueueQueueEvents(eventQueue, eventDataList);
  11014. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11015. return pathEquals(eventPath, path);
  11016. });
  11017. }
  11018. /**
  11019. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  11020. * locations related to the specified change path (i.e. all ancestors and descendants).
  11021. *
  11022. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  11023. *
  11024. * @param changedPath - The path to raise events for.
  11025. * @param eventDataList - The events to raise
  11026. */
  11027. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  11028. eventQueueQueueEvents(eventQueue, eventDataList);
  11029. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11030. return pathContains(eventPath, changedPath) ||
  11031. pathContains(changedPath, eventPath);
  11032. });
  11033. }
  11034. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  11035. eventQueue.recursionDepth_++;
  11036. var sentAll = true;
  11037. for (var i = 0; i < eventQueue.eventLists_.length; i++) {
  11038. var eventList = eventQueue.eventLists_[i];
  11039. if (eventList) {
  11040. var eventPath = eventList.path;
  11041. if (predicate(eventPath)) {
  11042. eventListRaise(eventQueue.eventLists_[i]);
  11043. eventQueue.eventLists_[i] = null;
  11044. }
  11045. else {
  11046. sentAll = false;
  11047. }
  11048. }
  11049. }
  11050. if (sentAll) {
  11051. eventQueue.eventLists_ = [];
  11052. }
  11053. eventQueue.recursionDepth_--;
  11054. }
  11055. /**
  11056. * Iterates through the list and raises each event
  11057. */
  11058. function eventListRaise(eventList) {
  11059. for (var i = 0; i < eventList.events.length; i++) {
  11060. var eventData = eventList.events[i];
  11061. if (eventData !== null) {
  11062. eventList.events[i] = null;
  11063. var eventFn = eventData.getEventRunner();
  11064. if (logger) {
  11065. log('event: ' + eventData.toString());
  11066. }
  11067. exceptionGuard(eventFn);
  11068. }
  11069. }
  11070. }
  11071. /**
  11072. * @license
  11073. * Copyright 2017 Google LLC
  11074. *
  11075. * Licensed under the Apache License, Version 2.0 (the "License");
  11076. * you may not use this file except in compliance with the License.
  11077. * You may obtain a copy of the License at
  11078. *
  11079. * http://www.apache.org/licenses/LICENSE-2.0
  11080. *
  11081. * Unless required by applicable law or agreed to in writing, software
  11082. * distributed under the License is distributed on an "AS IS" BASIS,
  11083. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11084. * See the License for the specific language governing permissions and
  11085. * limitations under the License.
  11086. */
  11087. var INTERRUPT_REASON = 'repo_interrupt';
  11088. /**
  11089. * If a transaction does not succeed after 25 retries, we abort it. Among other
  11090. * things this ensure that if there's ever a bug causing a mismatch between
  11091. * client / server hashes for some data, we won't retry indefinitely.
  11092. */
  11093. var MAX_TRANSACTION_RETRIES = 25;
  11094. /**
  11095. * A connection to a single data repository.
  11096. */
  11097. var Repo = /** @class */ (function () {
  11098. function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  11099. this.repoInfo_ = repoInfo_;
  11100. this.forceRestClient_ = forceRestClient_;
  11101. this.authTokenProvider_ = authTokenProvider_;
  11102. this.appCheckProvider_ = appCheckProvider_;
  11103. this.dataUpdateCount = 0;
  11104. this.statsListener_ = null;
  11105. this.eventQueue_ = new EventQueue();
  11106. this.nextWriteId_ = 1;
  11107. this.interceptServerDataCallback_ = null;
  11108. /** A list of data pieces and paths to be set when this client disconnects. */
  11109. this.onDisconnect_ = newSparseSnapshotTree();
  11110. /** Stores queues of outstanding transactions for Firebase locations. */
  11111. this.transactionQueueTree_ = new Tree();
  11112. // TODO: This should be @private but it's used by test_access.js and internal.js
  11113. this.persistentConnection_ = null;
  11114. // This key is intentionally not updated if RepoInfo is later changed or replaced
  11115. this.key = this.repoInfo_.toURLString();
  11116. }
  11117. /**
  11118. * @returns The URL corresponding to the root of this Firebase.
  11119. */
  11120. Repo.prototype.toString = function () {
  11121. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  11122. };
  11123. return Repo;
  11124. }());
  11125. function repoStart(repo, appId, authOverride) {
  11126. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  11127. if (repo.forceRestClient_ || beingCrawled()) {
  11128. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
  11129. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11130. }, repo.authTokenProvider_, repo.appCheckProvider_);
  11131. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  11132. setTimeout(function () { return repoOnConnectStatus(repo, /* connectStatus= */ true); }, 0);
  11133. }
  11134. else {
  11135. // Validate authOverride
  11136. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  11137. if (typeof authOverride !== 'object') {
  11138. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  11139. }
  11140. try {
  11141. util.stringify(authOverride);
  11142. }
  11143. catch (e) {
  11144. throw new Error('Invalid authOverride provided: ' + e);
  11145. }
  11146. }
  11147. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
  11148. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11149. }, function (connectStatus) {
  11150. repoOnConnectStatus(repo, connectStatus);
  11151. }, function (updates) {
  11152. repoOnServerInfoUpdate(repo, updates);
  11153. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  11154. repo.server_ = repo.persistentConnection_;
  11155. }
  11156. repo.authTokenProvider_.addTokenChangeListener(function (token) {
  11157. repo.server_.refreshAuthToken(token);
  11158. });
  11159. repo.appCheckProvider_.addTokenChangeListener(function (result) {
  11160. repo.server_.refreshAppCheckToken(result.token);
  11161. });
  11162. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  11163. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  11164. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
  11165. // Used for .info.
  11166. repo.infoData_ = new SnapshotHolder();
  11167. repo.infoSyncTree_ = new SyncTree({
  11168. startListening: function (query, tag, currentHashFn, onComplete) {
  11169. var infoEvents = [];
  11170. var node = repo.infoData_.getNode(query._path);
  11171. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  11172. // on initial data...
  11173. if (!node.isEmpty()) {
  11174. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  11175. setTimeout(function () {
  11176. onComplete('ok');
  11177. }, 0);
  11178. }
  11179. return infoEvents;
  11180. },
  11181. stopListening: function () { }
  11182. });
  11183. repoUpdateInfo(repo, 'connected', false);
  11184. repo.serverSyncTree_ = new SyncTree({
  11185. startListening: function (query, tag, currentHashFn, onComplete) {
  11186. repo.server_.listen(query, currentHashFn, tag, function (status, data) {
  11187. var events = onComplete(status, data);
  11188. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11189. });
  11190. // No synchronous events for network-backed sync trees
  11191. return [];
  11192. },
  11193. stopListening: function (query, tag) {
  11194. repo.server_.unlisten(query, tag);
  11195. }
  11196. });
  11197. }
  11198. /**
  11199. * @returns The time in milliseconds, taking the server offset into account if we have one.
  11200. */
  11201. function repoServerTime(repo) {
  11202. var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  11203. var offset = offsetNode.val() || 0;
  11204. return new Date().getTime() + offset;
  11205. }
  11206. /**
  11207. * Generate ServerValues using some variables from the repo object.
  11208. */
  11209. function repoGenerateServerValues(repo) {
  11210. return generateWithValues({
  11211. timestamp: repoServerTime(repo)
  11212. });
  11213. }
  11214. /**
  11215. * Called by realtime when we get new messages from the server.
  11216. */
  11217. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  11218. // For testing.
  11219. repo.dataUpdateCount++;
  11220. var path = new Path(pathString);
  11221. data = repo.interceptServerDataCallback_
  11222. ? repo.interceptServerDataCallback_(pathString, data)
  11223. : data;
  11224. var events = [];
  11225. if (tag) {
  11226. if (isMerge) {
  11227. var taggedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11228. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  11229. }
  11230. else {
  11231. var taggedSnap = nodeFromJSON(data);
  11232. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  11233. }
  11234. }
  11235. else if (isMerge) {
  11236. var changedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11237. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  11238. }
  11239. else {
  11240. var snap = nodeFromJSON(data);
  11241. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  11242. }
  11243. var affectedPath = path;
  11244. if (events.length > 0) {
  11245. // Since we have a listener outstanding for each transaction, receiving any events
  11246. // is a proxy for some change having occurred.
  11247. affectedPath = repoRerunTransactions(repo, path);
  11248. }
  11249. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  11250. }
  11251. function repoOnConnectStatus(repo, connectStatus) {
  11252. repoUpdateInfo(repo, 'connected', connectStatus);
  11253. if (connectStatus === false) {
  11254. repoRunOnDisconnectEvents(repo);
  11255. }
  11256. }
  11257. function repoOnServerInfoUpdate(repo, updates) {
  11258. each(updates, function (key, value) {
  11259. repoUpdateInfo(repo, key, value);
  11260. });
  11261. }
  11262. function repoUpdateInfo(repo, pathString, value) {
  11263. var path = new Path('/.info/' + pathString);
  11264. var newNode = nodeFromJSON(value);
  11265. repo.infoData_.updateSnapshot(path, newNode);
  11266. var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  11267. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11268. }
  11269. function repoGetNextWriteId(repo) {
  11270. return repo.nextWriteId_++;
  11271. }
  11272. /**
  11273. * The purpose of `getValue` is to return the latest known value
  11274. * satisfying `query`.
  11275. *
  11276. * This method will first check for in-memory cached values
  11277. * belonging to active listeners. If they are found, such values
  11278. * are considered to be the most up-to-date.
  11279. *
  11280. * If the client is not connected, this method will wait until the
  11281. * repo has established a connection and then request the value for `query`.
  11282. * If the client is not able to retrieve the query result for another reason,
  11283. * it reports an error.
  11284. *
  11285. * @param query - The query to surface a value for.
  11286. */
  11287. function repoGetValue(repo, query, eventRegistration) {
  11288. // Only active queries are cached. There is no persisted cache.
  11289. var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  11290. if (cached != null) {
  11291. return Promise.resolve(cached);
  11292. }
  11293. return repo.server_.get(query).then(function (payload) {
  11294. var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  11295. /**
  11296. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  11297. * Add an event registration,
  11298. * Update data at the path,
  11299. * Raise any events,
  11300. * Cleanup the SyncTree
  11301. */
  11302. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  11303. var events;
  11304. if (query._queryParams.loadsAllData()) {
  11305. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  11306. }
  11307. else {
  11308. var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  11309. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  11310. }
  11311. /*
  11312. * We need to raise events in the scenario where `get()` is called at a parent path, and
  11313. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  11314. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  11315. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  11316. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  11317. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  11318. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  11319. * ensure the corresponding child events will get fired.
  11320. */
  11321. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11322. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  11323. return node;
  11324. }, function (err) {
  11325. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  11326. return Promise.reject(new Error(err));
  11327. });
  11328. }
  11329. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  11330. repoLog(repo, 'set', {
  11331. path: path.toString(),
  11332. value: newVal,
  11333. priority: newPriority
  11334. });
  11335. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11336. // (b) store unresolved paths on JSON parse
  11337. var serverValues = repoGenerateServerValues(repo);
  11338. var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11339. var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11340. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11341. var writeId = repoGetNextWriteId(repo);
  11342. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11343. eventQueueQueueEvents(repo.eventQueue_, events);
  11344. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {
  11345. var success = status === 'ok';
  11346. if (!success) {
  11347. warn('set at ' + path + ' failed: ' + status);
  11348. }
  11349. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11350. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11351. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11352. });
  11353. var affectedPath = repoAbortTransactions(repo, path);
  11354. repoRerunTransactions(repo, affectedPath);
  11355. // We queued the events above, so just flush the queue here
  11356. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11357. }
  11358. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11359. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11360. // Start with our existing data and merge each child into it.
  11361. var empty = true;
  11362. var serverValues = repoGenerateServerValues(repo);
  11363. var changedChildren = {};
  11364. each(childrenToMerge, function (changedKey, changedValue) {
  11365. empty = false;
  11366. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11367. });
  11368. if (!empty) {
  11369. var writeId_1 = repoGetNextWriteId(repo);
  11370. var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
  11371. eventQueueQueueEvents(repo.eventQueue_, events);
  11372. repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
  11373. var success = status === 'ok';
  11374. if (!success) {
  11375. warn('update at ' + path + ' failed: ' + status);
  11376. }
  11377. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
  11378. var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11379. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11380. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11381. });
  11382. each(childrenToMerge, function (changedPath) {
  11383. var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11384. repoRerunTransactions(repo, affectedPath);
  11385. });
  11386. // We queued the events above, so just flush the queue here
  11387. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11388. }
  11389. else {
  11390. log("update() called with empty data. Don't do anything.");
  11391. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11392. }
  11393. }
  11394. /**
  11395. * Applies all of the changes stored up in the onDisconnect_ tree.
  11396. */
  11397. function repoRunOnDisconnectEvents(repo) {
  11398. repoLog(repo, 'onDisconnectEvents');
  11399. var serverValues = repoGenerateServerValues(repo);
  11400. var resolvedOnDisconnectTree = newSparseSnapshotTree();
  11401. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
  11402. var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11403. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11404. });
  11405. var events = [];
  11406. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
  11407. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11408. var affectedPath = repoAbortTransactions(repo, path);
  11409. repoRerunTransactions(repo, affectedPath);
  11410. });
  11411. repo.onDisconnect_ = newSparseSnapshotTree();
  11412. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11413. }
  11414. function repoOnDisconnectCancel(repo, path, onComplete) {
  11415. repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
  11416. if (status === 'ok') {
  11417. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11418. }
  11419. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11420. });
  11421. }
  11422. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11423. var newNode = nodeFromJSON(value);
  11424. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11425. if (status === 'ok') {
  11426. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11427. }
  11428. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11429. });
  11430. }
  11431. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11432. var newNode = nodeFromJSON(value, priority);
  11433. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11434. if (status === 'ok') {
  11435. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11436. }
  11437. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11438. });
  11439. }
  11440. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11441. if (util.isEmpty(childrenToMerge)) {
  11442. log("onDisconnect().update() called with empty data. Don't do anything.");
  11443. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11444. return;
  11445. }
  11446. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
  11447. if (status === 'ok') {
  11448. each(childrenToMerge, function (childName, childNode) {
  11449. var newChildNode = nodeFromJSON(childNode);
  11450. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11451. });
  11452. }
  11453. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11454. });
  11455. }
  11456. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11457. var events;
  11458. if (pathGetFront(query._path) === '.info') {
  11459. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11460. }
  11461. else {
  11462. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11463. }
  11464. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11465. }
  11466. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11467. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11468. // a little bit by handling the return values anyways.
  11469. var events;
  11470. if (pathGetFront(query._path) === '.info') {
  11471. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11472. }
  11473. else {
  11474. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11475. }
  11476. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11477. }
  11478. function repoInterrupt(repo) {
  11479. if (repo.persistentConnection_) {
  11480. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11481. }
  11482. }
  11483. function repoResume(repo) {
  11484. if (repo.persistentConnection_) {
  11485. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11486. }
  11487. }
  11488. function repoLog(repo) {
  11489. var varArgs = [];
  11490. for (var _i = 1; _i < arguments.length; _i++) {
  11491. varArgs[_i - 1] = arguments[_i];
  11492. }
  11493. var prefix = '';
  11494. if (repo.persistentConnection_) {
  11495. prefix = repo.persistentConnection_.id + ':';
  11496. }
  11497. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  11498. }
  11499. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11500. if (callback) {
  11501. exceptionGuard(function () {
  11502. if (status === 'ok') {
  11503. callback(null);
  11504. }
  11505. else {
  11506. var code = (status || 'error').toUpperCase();
  11507. var message = code;
  11508. if (errorReason) {
  11509. message += ': ' + errorReason;
  11510. }
  11511. var error = new Error(message);
  11512. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11513. error.code = code;
  11514. callback(error);
  11515. }
  11516. });
  11517. }
  11518. }
  11519. /**
  11520. * Creates a new transaction, adds it to the transactions we're tracking, and
  11521. * sends it to the server if possible.
  11522. *
  11523. * @param path - Path at which to do transaction.
  11524. * @param transactionUpdate - Update callback.
  11525. * @param onComplete - Completion callback.
  11526. * @param unwatcher - Function that will be called when the transaction no longer
  11527. * need data updates for `path`.
  11528. * @param applyLocally - Whether or not to make intermediate results visible
  11529. */
  11530. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11531. repoLog(repo, 'transaction on ' + path);
  11532. // Initialize transaction.
  11533. var transaction = {
  11534. path: path,
  11535. update: transactionUpdate,
  11536. onComplete: onComplete,
  11537. // One of TransactionStatus enums.
  11538. status: null,
  11539. // Used when combining transactions at different locations to figure out
  11540. // which one goes first.
  11541. order: LUIDGenerator(),
  11542. // Whether to raise local events for this transaction.
  11543. applyLocally: applyLocally,
  11544. // Count of how many times we've retried the transaction.
  11545. retryCount: 0,
  11546. // Function to call to clean up our .on() listener.
  11547. unwatcher: unwatcher,
  11548. // Stores why a transaction was aborted.
  11549. abortReason: null,
  11550. currentWriteId: null,
  11551. currentInputSnapshot: null,
  11552. currentOutputSnapshotRaw: null,
  11553. currentOutputSnapshotResolved: null
  11554. };
  11555. // Run transaction initially.
  11556. var currentState = repoGetLatestState(repo, path, undefined);
  11557. transaction.currentInputSnapshot = currentState;
  11558. var newVal = transaction.update(currentState.val());
  11559. if (newVal === undefined) {
  11560. // Abort transaction.
  11561. transaction.unwatcher();
  11562. transaction.currentOutputSnapshotRaw = null;
  11563. transaction.currentOutputSnapshotResolved = null;
  11564. if (transaction.onComplete) {
  11565. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11566. }
  11567. }
  11568. else {
  11569. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11570. // Mark as run and add to our queue.
  11571. transaction.status = 0 /* TransactionStatus.RUN */;
  11572. var queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11573. var nodeQueue = treeGetValue(queueNode) || [];
  11574. nodeQueue.push(transaction);
  11575. treeSetValue(queueNode, nodeQueue);
  11576. // Update visibleData and raise events
  11577. // Note: We intentionally raise events after updating all of our
  11578. // transaction state, since the user could start new transactions from the
  11579. // event callbacks.
  11580. var priorityForNode = void 0;
  11581. if (typeof newVal === 'object' &&
  11582. newVal !== null &&
  11583. util.contains(newVal, '.priority')) {
  11584. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11585. priorityForNode = util.safeGet(newVal, '.priority');
  11586. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11587. 'Priority must be a valid string, finite number, server value, or null.');
  11588. }
  11589. else {
  11590. var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11591. ChildrenNode.EMPTY_NODE;
  11592. priorityForNode = currentNode.getPriority().val();
  11593. }
  11594. var serverValues = repoGenerateServerValues(repo);
  11595. var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11596. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11597. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11598. transaction.currentOutputSnapshotResolved = newNode;
  11599. transaction.currentWriteId = repoGetNextWriteId(repo);
  11600. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11601. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11602. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11603. }
  11604. }
  11605. /**
  11606. * @param excludeSets - A specific set to exclude
  11607. */
  11608. function repoGetLatestState(repo, path, excludeSets) {
  11609. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11610. ChildrenNode.EMPTY_NODE);
  11611. }
  11612. /**
  11613. * Sends any already-run transactions that aren't waiting for outstanding
  11614. * transactions to complete.
  11615. *
  11616. * Externally it's called with no arguments, but it calls itself recursively
  11617. * with a particular transactionQueueTree node to recurse through the tree.
  11618. *
  11619. * @param node - transactionQueueTree node to start at.
  11620. */
  11621. function repoSendReadyTransactions(repo, node) {
  11622. if (node === void 0) { node = repo.transactionQueueTree_; }
  11623. // Before recursing, make sure any completed transactions are removed.
  11624. if (!node) {
  11625. repoPruneCompletedTransactionsBelowNode(repo, node);
  11626. }
  11627. if (treeGetValue(node)) {
  11628. var queue = repoBuildTransactionQueue(repo, node);
  11629. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  11630. var allRun = queue.every(function (transaction) { return transaction.status === 0 /* TransactionStatus.RUN */; });
  11631. // If they're all run (and not sent), we can send them. Else, we must wait.
  11632. if (allRun) {
  11633. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11634. }
  11635. }
  11636. else if (treeHasChildren(node)) {
  11637. treeForEachChild(node, function (childNode) {
  11638. repoSendReadyTransactions(repo, childNode);
  11639. });
  11640. }
  11641. }
  11642. /**
  11643. * Given a list of run transactions, send them to the server and then handle
  11644. * the result (success or failure).
  11645. *
  11646. * @param path - The location of the queue.
  11647. * @param queue - Queue of transactions under the specified location.
  11648. */
  11649. function repoSendTransactionQueue(repo, path, queue) {
  11650. // Mark transactions as sent and increment retry count!
  11651. var setsToIgnore = queue.map(function (txn) {
  11652. return txn.currentWriteId;
  11653. });
  11654. var latestState = repoGetLatestState(repo, path, setsToIgnore);
  11655. var snapToSend = latestState;
  11656. var latestHash = latestState.hash();
  11657. for (var i = 0; i < queue.length; i++) {
  11658. var txn = queue[i];
  11659. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11660. txn.status = 1 /* TransactionStatus.SENT */;
  11661. txn.retryCount++;
  11662. var relativePath = newRelativePath(path, txn.path);
  11663. // If we've gotten to this point, the output snapshot must be defined.
  11664. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11665. }
  11666. var dataToSend = snapToSend.val(true);
  11667. var pathToSend = path;
  11668. // Send the put.
  11669. repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
  11670. repoLog(repo, 'transaction put response', {
  11671. path: pathToSend.toString(),
  11672. status: status
  11673. });
  11674. var events = [];
  11675. if (status === 'ok') {
  11676. // Queue up the callbacks and fire them after cleaning up all of our
  11677. // transaction state, since the callback could trigger more
  11678. // transactions or sets.
  11679. var callbacks = [];
  11680. var _loop_1 = function (i) {
  11681. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11682. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11683. if (queue[i].onComplete) {
  11684. // We never unset the output snapshot, and given that this
  11685. // transaction is complete, it should be set
  11686. callbacks.push(function () {
  11687. return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
  11688. });
  11689. }
  11690. queue[i].unwatcher();
  11691. };
  11692. for (var i = 0; i < queue.length; i++) {
  11693. _loop_1(i);
  11694. }
  11695. // Now remove the completed transactions.
  11696. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11697. // There may be pending transactions that we can now send.
  11698. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11699. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11700. // Finally, trigger onComplete callbacks.
  11701. for (var i = 0; i < callbacks.length; i++) {
  11702. exceptionGuard(callbacks[i]);
  11703. }
  11704. }
  11705. else {
  11706. // transactions are no longer sent. Update their status appropriately.
  11707. if (status === 'datastale') {
  11708. for (var i = 0; i < queue.length; i++) {
  11709. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11710. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11711. }
  11712. else {
  11713. queue[i].status = 0 /* TransactionStatus.RUN */;
  11714. }
  11715. }
  11716. }
  11717. else {
  11718. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11719. for (var i = 0; i < queue.length; i++) {
  11720. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11721. queue[i].abortReason = status;
  11722. }
  11723. }
  11724. repoRerunTransactions(repo, path);
  11725. }
  11726. }, latestHash);
  11727. }
  11728. /**
  11729. * Finds all transactions dependent on the data at changedPath and reruns them.
  11730. *
  11731. * Should be called any time cached data changes.
  11732. *
  11733. * Return the highest path that was affected by rerunning transactions. This
  11734. * is the path at which events need to be raised for.
  11735. *
  11736. * @param changedPath - The path in mergedData that changed.
  11737. * @returns The rootmost path that was affected by rerunning transactions.
  11738. */
  11739. function repoRerunTransactions(repo, changedPath) {
  11740. var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11741. var path = treeGetPath(rootMostTransactionNode);
  11742. var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11743. repoRerunTransactionQueue(repo, queue, path);
  11744. return path;
  11745. }
  11746. /**
  11747. * Does all the work of rerunning transactions (as well as cleans up aborted
  11748. * transactions and whatnot).
  11749. *
  11750. * @param queue - The queue of transactions to run.
  11751. * @param path - The path the queue is for.
  11752. */
  11753. function repoRerunTransactionQueue(repo, queue, path) {
  11754. if (queue.length === 0) {
  11755. return; // Nothing to do!
  11756. }
  11757. // Queue up the callbacks and fire them after cleaning up all of our
  11758. // transaction state, since the callback could trigger more transactions or
  11759. // sets.
  11760. var callbacks = [];
  11761. var events = [];
  11762. // Ignore all of the sets we're going to re-run.
  11763. var txnsToRerun = queue.filter(function (q) {
  11764. return q.status === 0 /* TransactionStatus.RUN */;
  11765. });
  11766. var setsToIgnore = txnsToRerun.map(function (q) {
  11767. return q.currentWriteId;
  11768. });
  11769. var _loop_2 = function (i) {
  11770. var transaction = queue[i];
  11771. var relativePath = newRelativePath(path, transaction.path);
  11772. var abortTransaction = false, abortReason;
  11773. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11774. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11775. abortTransaction = true;
  11776. abortReason = transaction.abortReason;
  11777. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11778. }
  11779. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11780. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11781. abortTransaction = true;
  11782. abortReason = 'maxretry';
  11783. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11784. }
  11785. else {
  11786. // This code reruns a transaction
  11787. var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11788. transaction.currentInputSnapshot = currentNode;
  11789. var newData = queue[i].update(currentNode.val());
  11790. if (newData !== undefined) {
  11791. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11792. var newDataNode = nodeFromJSON(newData);
  11793. var hasExplicitPriority = typeof newData === 'object' &&
  11794. newData != null &&
  11795. util.contains(newData, '.priority');
  11796. if (!hasExplicitPriority) {
  11797. // Keep the old priority if there wasn't a priority explicitly specified.
  11798. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11799. }
  11800. var oldWriteId = transaction.currentWriteId;
  11801. var serverValues = repoGenerateServerValues(repo);
  11802. var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11803. transaction.currentOutputSnapshotRaw = newDataNode;
  11804. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11805. transaction.currentWriteId = repoGetNextWriteId(repo);
  11806. // Mutates setsToIgnore in place
  11807. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11808. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11809. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11810. }
  11811. else {
  11812. abortTransaction = true;
  11813. abortReason = 'nodata';
  11814. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11815. }
  11816. }
  11817. }
  11818. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11819. events = [];
  11820. if (abortTransaction) {
  11821. // Abort.
  11822. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11823. // Removing a listener can trigger pruning which can muck with
  11824. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11825. // until we're done.
  11826. (function (unwatcher) {
  11827. setTimeout(unwatcher, Math.floor(0));
  11828. })(queue[i].unwatcher);
  11829. if (queue[i].onComplete) {
  11830. if (abortReason === 'nodata') {
  11831. callbacks.push(function () {
  11832. return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
  11833. });
  11834. }
  11835. else {
  11836. callbacks.push(function () {
  11837. return queue[i].onComplete(new Error(abortReason), false, null);
  11838. });
  11839. }
  11840. }
  11841. }
  11842. };
  11843. for (var i = 0; i < queue.length; i++) {
  11844. _loop_2(i);
  11845. }
  11846. // Clean up completed transactions.
  11847. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11848. // Now fire callbacks, now that we're in a good, known state.
  11849. for (var i = 0; i < callbacks.length; i++) {
  11850. exceptionGuard(callbacks[i]);
  11851. }
  11852. // Try to send the transaction result to the server.
  11853. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11854. }
  11855. /**
  11856. * Returns the rootmost ancestor node of the specified path that has a pending
  11857. * transaction on it, or just returns the node for the given path if there are
  11858. * no pending transactions on any ancestor.
  11859. *
  11860. * @param path - The location to start at.
  11861. * @returns The rootmost node with a transaction.
  11862. */
  11863. function repoGetAncestorTransactionNode(repo, path) {
  11864. var front;
  11865. // Start at the root and walk deeper into the tree towards path until we
  11866. // find a node with pending transactions.
  11867. var transactionNode = repo.transactionQueueTree_;
  11868. front = pathGetFront(path);
  11869. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11870. transactionNode = treeSubTree(transactionNode, front);
  11871. path = pathPopFront(path);
  11872. front = pathGetFront(path);
  11873. }
  11874. return transactionNode;
  11875. }
  11876. /**
  11877. * Builds the queue of all transactions at or below the specified
  11878. * transactionNode.
  11879. *
  11880. * @param transactionNode
  11881. * @returns The generated queue.
  11882. */
  11883. function repoBuildTransactionQueue(repo, transactionNode) {
  11884. // Walk any child transaction queues and aggregate them into a single queue.
  11885. var transactionQueue = [];
  11886. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11887. // Sort them by the order the transactions were created.
  11888. transactionQueue.sort(function (a, b) { return a.order - b.order; });
  11889. return transactionQueue;
  11890. }
  11891. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11892. var nodeQueue = treeGetValue(node);
  11893. if (nodeQueue) {
  11894. for (var i = 0; i < nodeQueue.length; i++) {
  11895. queue.push(nodeQueue[i]);
  11896. }
  11897. }
  11898. treeForEachChild(node, function (child) {
  11899. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11900. });
  11901. }
  11902. /**
  11903. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11904. */
  11905. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11906. var queue = treeGetValue(node);
  11907. if (queue) {
  11908. var to = 0;
  11909. for (var from = 0; from < queue.length; from++) {
  11910. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11911. queue[to] = queue[from];
  11912. to++;
  11913. }
  11914. }
  11915. queue.length = to;
  11916. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11917. }
  11918. treeForEachChild(node, function (childNode) {
  11919. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11920. });
  11921. }
  11922. /**
  11923. * Aborts all transactions on ancestors or descendants of the specified path.
  11924. * Called when doing a set() or update() since we consider them incompatible
  11925. * with transactions.
  11926. *
  11927. * @param path - Path for which we want to abort related transactions.
  11928. */
  11929. function repoAbortTransactions(repo, path) {
  11930. var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11931. var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11932. treeForEachAncestor(transactionNode, function (node) {
  11933. repoAbortTransactionsOnNode(repo, node);
  11934. });
  11935. repoAbortTransactionsOnNode(repo, transactionNode);
  11936. treeForEachDescendant(transactionNode, function (node) {
  11937. repoAbortTransactionsOnNode(repo, node);
  11938. });
  11939. return affectedPath;
  11940. }
  11941. /**
  11942. * Abort transactions stored in this transaction queue node.
  11943. *
  11944. * @param node - Node to abort transactions for.
  11945. */
  11946. function repoAbortTransactionsOnNode(repo, node) {
  11947. var queue = treeGetValue(node);
  11948. if (queue) {
  11949. // Queue up the callbacks and fire them after cleaning up all of our
  11950. // transaction state, since the callback could trigger more transactions
  11951. // or sets.
  11952. var callbacks = [];
  11953. // Go through queue. Any already-sent transactions must be marked for
  11954. // abort, while the unsent ones can be immediately aborted and removed.
  11955. var events = [];
  11956. var lastSent = -1;
  11957. for (var i = 0; i < queue.length; i++) {
  11958. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11959. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11960. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11961. lastSent = i;
  11962. // Mark transaction for abort when it comes back.
  11963. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11964. queue[i].abortReason = 'set';
  11965. }
  11966. else {
  11967. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11968. // We can abort it immediately.
  11969. queue[i].unwatcher();
  11970. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11971. if (queue[i].onComplete) {
  11972. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11973. }
  11974. }
  11975. }
  11976. if (lastSent === -1) {
  11977. // We're not waiting for any sent transactions. We can clear the queue.
  11978. treeSetValue(node, undefined);
  11979. }
  11980. else {
  11981. // Remove the transactions we aborted.
  11982. queue.length = lastSent + 1;
  11983. }
  11984. // Now fire the callbacks.
  11985. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11986. for (var i = 0; i < callbacks.length; i++) {
  11987. exceptionGuard(callbacks[i]);
  11988. }
  11989. }
  11990. }
  11991. /**
  11992. * @license
  11993. * Copyright 2017 Google LLC
  11994. *
  11995. * Licensed under the Apache License, Version 2.0 (the "License");
  11996. * you may not use this file except in compliance with the License.
  11997. * You may obtain a copy of the License at
  11998. *
  11999. * http://www.apache.org/licenses/LICENSE-2.0
  12000. *
  12001. * Unless required by applicable law or agreed to in writing, software
  12002. * distributed under the License is distributed on an "AS IS" BASIS,
  12003. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12004. * See the License for the specific language governing permissions and
  12005. * limitations under the License.
  12006. */
  12007. function decodePath(pathString) {
  12008. var pathStringDecoded = '';
  12009. var pieces = pathString.split('/');
  12010. for (var i = 0; i < pieces.length; i++) {
  12011. if (pieces[i].length > 0) {
  12012. var piece = pieces[i];
  12013. try {
  12014. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  12015. }
  12016. catch (e) { }
  12017. pathStringDecoded += '/' + piece;
  12018. }
  12019. }
  12020. return pathStringDecoded;
  12021. }
  12022. /**
  12023. * @returns key value hash
  12024. */
  12025. function decodeQuery(queryString) {
  12026. var e_1, _a;
  12027. var results = {};
  12028. if (queryString.charAt(0) === '?') {
  12029. queryString = queryString.substring(1);
  12030. }
  12031. try {
  12032. for (var _b = tslib.__values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
  12033. var segment = _c.value;
  12034. if (segment.length === 0) {
  12035. continue;
  12036. }
  12037. var kv = segment.split('=');
  12038. if (kv.length === 2) {
  12039. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  12040. }
  12041. else {
  12042. warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
  12043. }
  12044. }
  12045. }
  12046. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  12047. finally {
  12048. try {
  12049. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12050. }
  12051. finally { if (e_1) throw e_1.error; }
  12052. }
  12053. return results;
  12054. }
  12055. var parseRepoInfo = function (dataURL, nodeAdmin) {
  12056. var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  12057. if (parsedUrl.domain === 'firebase.com') {
  12058. fatal(parsedUrl.host +
  12059. ' is no longer supported. ' +
  12060. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  12061. }
  12062. // Catch common error of uninitialized namespace value.
  12063. if ((!namespace || namespace === 'undefined') &&
  12064. parsedUrl.domain !== 'localhost') {
  12065. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  12066. }
  12067. if (!parsedUrl.secure) {
  12068. warnIfPageIsSecure();
  12069. }
  12070. var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  12071. return {
  12072. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  12073. /*persistenceKey=*/ '',
  12074. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  12075. path: new Path(parsedUrl.pathString)
  12076. };
  12077. };
  12078. var parseDatabaseURL = function (dataURL) {
  12079. // Default to empty strings in the event of a malformed string.
  12080. var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  12081. // Always default to SSL, unless otherwise specified.
  12082. var secure = true, scheme = 'https', port = 443;
  12083. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  12084. if (typeof dataURL === 'string') {
  12085. // Parse scheme.
  12086. var colonInd = dataURL.indexOf('//');
  12087. if (colonInd >= 0) {
  12088. scheme = dataURL.substring(0, colonInd - 1);
  12089. dataURL = dataURL.substring(colonInd + 2);
  12090. }
  12091. // Parse host, path, and query string.
  12092. var slashInd = dataURL.indexOf('/');
  12093. if (slashInd === -1) {
  12094. slashInd = dataURL.length;
  12095. }
  12096. var questionMarkInd = dataURL.indexOf('?');
  12097. if (questionMarkInd === -1) {
  12098. questionMarkInd = dataURL.length;
  12099. }
  12100. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  12101. if (slashInd < questionMarkInd) {
  12102. // For pathString, questionMarkInd will always come after slashInd
  12103. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  12104. }
  12105. var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  12106. // If we have a port, use scheme for determining if it's secure.
  12107. colonInd = host.indexOf(':');
  12108. if (colonInd >= 0) {
  12109. secure = scheme === 'https' || scheme === 'wss';
  12110. port = parseInt(host.substring(colonInd + 1), 10);
  12111. }
  12112. else {
  12113. colonInd = host.length;
  12114. }
  12115. var hostWithoutPort = host.slice(0, colonInd);
  12116. if (hostWithoutPort.toLowerCase() === 'localhost') {
  12117. domain = 'localhost';
  12118. }
  12119. else if (hostWithoutPort.split('.').length <= 2) {
  12120. domain = hostWithoutPort;
  12121. }
  12122. else {
  12123. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  12124. var dotInd = host.indexOf('.');
  12125. subdomain = host.substring(0, dotInd).toLowerCase();
  12126. domain = host.substring(dotInd + 1);
  12127. // Normalize namespaces to lowercase to share storage / connection.
  12128. namespace = subdomain;
  12129. }
  12130. // Always treat the value of the `ns` as the namespace name if it is present.
  12131. if ('ns' in queryParams) {
  12132. namespace = queryParams['ns'];
  12133. }
  12134. }
  12135. return {
  12136. host: host,
  12137. port: port,
  12138. domain: domain,
  12139. subdomain: subdomain,
  12140. secure: secure,
  12141. scheme: scheme,
  12142. pathString: pathString,
  12143. namespace: namespace
  12144. };
  12145. };
  12146. /**
  12147. * @license
  12148. * Copyright 2017 Google LLC
  12149. *
  12150. * Licensed under the Apache License, Version 2.0 (the "License");
  12151. * you may not use this file except in compliance with the License.
  12152. * You may obtain a copy of the License at
  12153. *
  12154. * http://www.apache.org/licenses/LICENSE-2.0
  12155. *
  12156. * Unless required by applicable law or agreed to in writing, software
  12157. * distributed under the License is distributed on an "AS IS" BASIS,
  12158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12159. * See the License for the specific language governing permissions and
  12160. * limitations under the License.
  12161. */
  12162. // Modeled after base64 web-safe chars, but ordered by ASCII.
  12163. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  12164. /**
  12165. * Fancy ID generator that creates 20-character string identifiers with the
  12166. * following properties:
  12167. *
  12168. * 1. They're based on timestamp so that they sort *after* any existing ids.
  12169. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  12170. * collide with other clients' IDs.
  12171. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  12172. * that will sort properly).
  12173. * 4. They're monotonically increasing. Even if you generate more than one in
  12174. * the same timestamp, the latter ones will sort after the former ones. We do
  12175. * this by using the previous random bits but "incrementing" them by 1 (only
  12176. * in the case of a timestamp collision).
  12177. */
  12178. var nextPushId = (function () {
  12179. // Timestamp of last push, used to prevent local collisions if you push twice
  12180. // in one ms.
  12181. var lastPushTime = 0;
  12182. // We generate 72-bits of randomness which get turned into 12 characters and
  12183. // appended to the timestamp to prevent collisions with other clients. We
  12184. // store the last characters we generated because in the event of a collision,
  12185. // we'll use those same characters except "incremented" by one.
  12186. var lastRandChars = [];
  12187. return function (now) {
  12188. var duplicateTime = now === lastPushTime;
  12189. lastPushTime = now;
  12190. var i;
  12191. var timeStampChars = new Array(8);
  12192. for (i = 7; i >= 0; i--) {
  12193. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  12194. // NOTE: Can't use << here because javascript will convert to int and lose
  12195. // the upper bits.
  12196. now = Math.floor(now / 64);
  12197. }
  12198. util.assert(now === 0, 'Cannot push at time == 0');
  12199. var id = timeStampChars.join('');
  12200. if (!duplicateTime) {
  12201. for (i = 0; i < 12; i++) {
  12202. lastRandChars[i] = Math.floor(Math.random() * 64);
  12203. }
  12204. }
  12205. else {
  12206. // If the timestamp hasn't changed since last push, use the same random
  12207. // number, except incremented by 1.
  12208. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  12209. lastRandChars[i] = 0;
  12210. }
  12211. lastRandChars[i]++;
  12212. }
  12213. for (i = 0; i < 12; i++) {
  12214. id += PUSH_CHARS.charAt(lastRandChars[i]);
  12215. }
  12216. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  12217. return id;
  12218. };
  12219. })();
  12220. /**
  12221. * @license
  12222. * Copyright 2017 Google LLC
  12223. *
  12224. * Licensed under the Apache License, Version 2.0 (the "License");
  12225. * you may not use this file except in compliance with the License.
  12226. * You may obtain a copy of the License at
  12227. *
  12228. * http://www.apache.org/licenses/LICENSE-2.0
  12229. *
  12230. * Unless required by applicable law or agreed to in writing, software
  12231. * distributed under the License is distributed on an "AS IS" BASIS,
  12232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12233. * See the License for the specific language governing permissions and
  12234. * limitations under the License.
  12235. */
  12236. /**
  12237. * Encapsulates the data needed to raise an event
  12238. */
  12239. var DataEvent = /** @class */ (function () {
  12240. /**
  12241. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  12242. * @param eventRegistration - The function to call to with the event data. User provided
  12243. * @param snapshot - The data backing the event
  12244. * @param prevName - Optional, the name of the previous child for child_* events.
  12245. */
  12246. function DataEvent(eventType, eventRegistration, snapshot, prevName) {
  12247. this.eventType = eventType;
  12248. this.eventRegistration = eventRegistration;
  12249. this.snapshot = snapshot;
  12250. this.prevName = prevName;
  12251. }
  12252. DataEvent.prototype.getPath = function () {
  12253. var ref = this.snapshot.ref;
  12254. if (this.eventType === 'value') {
  12255. return ref._path;
  12256. }
  12257. else {
  12258. return ref.parent._path;
  12259. }
  12260. };
  12261. DataEvent.prototype.getEventType = function () {
  12262. return this.eventType;
  12263. };
  12264. DataEvent.prototype.getEventRunner = function () {
  12265. return this.eventRegistration.getEventRunner(this);
  12266. };
  12267. DataEvent.prototype.toString = function () {
  12268. return (this.getPath().toString() +
  12269. ':' +
  12270. this.eventType +
  12271. ':' +
  12272. util.stringify(this.snapshot.exportVal()));
  12273. };
  12274. return DataEvent;
  12275. }());
  12276. var CancelEvent = /** @class */ (function () {
  12277. function CancelEvent(eventRegistration, error, path) {
  12278. this.eventRegistration = eventRegistration;
  12279. this.error = error;
  12280. this.path = path;
  12281. }
  12282. CancelEvent.prototype.getPath = function () {
  12283. return this.path;
  12284. };
  12285. CancelEvent.prototype.getEventType = function () {
  12286. return 'cancel';
  12287. };
  12288. CancelEvent.prototype.getEventRunner = function () {
  12289. return this.eventRegistration.getEventRunner(this);
  12290. };
  12291. CancelEvent.prototype.toString = function () {
  12292. return this.path.toString() + ':cancel';
  12293. };
  12294. return CancelEvent;
  12295. }());
  12296. /**
  12297. * @license
  12298. * Copyright 2017 Google LLC
  12299. *
  12300. * Licensed under the Apache License, Version 2.0 (the "License");
  12301. * you may not use this file except in compliance with the License.
  12302. * You may obtain a copy of the License at
  12303. *
  12304. * http://www.apache.org/licenses/LICENSE-2.0
  12305. *
  12306. * Unless required by applicable law or agreed to in writing, software
  12307. * distributed under the License is distributed on an "AS IS" BASIS,
  12308. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12309. * See the License for the specific language governing permissions and
  12310. * limitations under the License.
  12311. */
  12312. /**
  12313. * A wrapper class that converts events from the database@exp SDK to the legacy
  12314. * Database SDK. Events are not converted directly as event registration relies
  12315. * on reference comparison of the original user callback (see `matches()`) and
  12316. * relies on equality of the legacy SDK's `context` object.
  12317. */
  12318. var CallbackContext = /** @class */ (function () {
  12319. function CallbackContext(snapshotCallback, cancelCallback) {
  12320. this.snapshotCallback = snapshotCallback;
  12321. this.cancelCallback = cancelCallback;
  12322. }
  12323. CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
  12324. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  12325. };
  12326. CallbackContext.prototype.onCancel = function (error) {
  12327. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  12328. return this.cancelCallback.call(null, error);
  12329. };
  12330. Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
  12331. get: function () {
  12332. return !!this.cancelCallback;
  12333. },
  12334. enumerable: false,
  12335. configurable: true
  12336. });
  12337. CallbackContext.prototype.matches = function (other) {
  12338. return (this.snapshotCallback === other.snapshotCallback ||
  12339. (this.snapshotCallback.userCallback !== undefined &&
  12340. this.snapshotCallback.userCallback ===
  12341. other.snapshotCallback.userCallback &&
  12342. this.snapshotCallback.context === other.snapshotCallback.context));
  12343. };
  12344. return CallbackContext;
  12345. }());
  12346. /**
  12347. * @license
  12348. * Copyright 2021 Google LLC
  12349. *
  12350. * Licensed under the Apache License, Version 2.0 (the "License");
  12351. * you may not use this file except in compliance with the License.
  12352. * You may obtain a copy of the License at
  12353. *
  12354. * http://www.apache.org/licenses/LICENSE-2.0
  12355. *
  12356. * Unless required by applicable law or agreed to in writing, software
  12357. * distributed under the License is distributed on an "AS IS" BASIS,
  12358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12359. * See the License for the specific language governing permissions and
  12360. * limitations under the License.
  12361. */
  12362. /**
  12363. * The `onDisconnect` class allows you to write or clear data when your client
  12364. * disconnects from the Database server. These updates occur whether your
  12365. * client disconnects cleanly or not, so you can rely on them to clean up data
  12366. * even if a connection is dropped or a client crashes.
  12367. *
  12368. * The `onDisconnect` class is most commonly used to manage presence in
  12369. * applications where it is useful to detect how many clients are connected and
  12370. * when other clients disconnect. See
  12371. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12372. * for more information.
  12373. *
  12374. * To avoid problems when a connection is dropped before the requests can be
  12375. * transferred to the Database server, these functions should be called before
  12376. * writing any data.
  12377. *
  12378. * Note that `onDisconnect` operations are only triggered once. If you want an
  12379. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12380. * the `onDisconnect` operations each time you reconnect.
  12381. */
  12382. var OnDisconnect = /** @class */ (function () {
  12383. /** @hideconstructor */
  12384. function OnDisconnect(_repo, _path) {
  12385. this._repo = _repo;
  12386. this._path = _path;
  12387. }
  12388. /**
  12389. * Cancels all previously queued `onDisconnect()` set or update events for this
  12390. * location and all children.
  12391. *
  12392. * If a write has been queued for this location via a `set()` or `update()` at a
  12393. * parent location, the write at this location will be canceled, though writes
  12394. * to sibling locations will still occur.
  12395. *
  12396. * @returns Resolves when synchronization to the server is complete.
  12397. */
  12398. OnDisconnect.prototype.cancel = function () {
  12399. var deferred = new util.Deferred();
  12400. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
  12401. return deferred.promise;
  12402. };
  12403. /**
  12404. * Ensures the data at this location is deleted when the client is disconnected
  12405. * (due to closing the browser, navigating to a new page, or network issues).
  12406. *
  12407. * @returns Resolves when synchronization to the server is complete.
  12408. */
  12409. OnDisconnect.prototype.remove = function () {
  12410. validateWritablePath('OnDisconnect.remove', this._path);
  12411. var deferred = new util.Deferred();
  12412. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
  12413. return deferred.promise;
  12414. };
  12415. /**
  12416. * Ensures the data at this location is set to the specified value when the
  12417. * client is disconnected (due to closing the browser, navigating to a new page,
  12418. * or network issues).
  12419. *
  12420. * `set()` is especially useful for implementing "presence" systems, where a
  12421. * value should be changed or cleared when a user disconnects so that they
  12422. * appear "offline" to other users. See
  12423. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12424. * for more information.
  12425. *
  12426. * Note that `onDisconnect` operations are only triggered once. If you want an
  12427. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12428. * the `onDisconnect` operations each time.
  12429. *
  12430. * @param value - The value to be written to this location on disconnect (can
  12431. * be an object, array, string, number, boolean, or null).
  12432. * @returns Resolves when synchronization to the Database is complete.
  12433. */
  12434. OnDisconnect.prototype.set = function (value) {
  12435. validateWritablePath('OnDisconnect.set', this._path);
  12436. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12437. var deferred = new util.Deferred();
  12438. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
  12439. return deferred.promise;
  12440. };
  12441. /**
  12442. * Ensures the data at this location is set to the specified value and priority
  12443. * when the client is disconnected (due to closing the browser, navigating to a
  12444. * new page, or network issues).
  12445. *
  12446. * @param value - The value to be written to this location on disconnect (can
  12447. * be an object, array, string, number, boolean, or null).
  12448. * @param priority - The priority to be written (string, number, or null).
  12449. * @returns Resolves when synchronization to the Database is complete.
  12450. */
  12451. OnDisconnect.prototype.setWithPriority = function (value, priority) {
  12452. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12453. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12454. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12455. var deferred = new util.Deferred();
  12456. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
  12457. return deferred.promise;
  12458. };
  12459. /**
  12460. * Writes multiple values at this location when the client is disconnected (due
  12461. * to closing the browser, navigating to a new page, or network issues).
  12462. *
  12463. * The `values` argument contains multiple property-value pairs that will be
  12464. * written to the Database together. Each child property can either be a simple
  12465. * property (for example, "name") or a relative path (for example, "name/first")
  12466. * from the current location to the data to update.
  12467. *
  12468. * As opposed to the `set()` method, `update()` can be use to selectively update
  12469. * only the referenced properties at the current location (instead of replacing
  12470. * all the child properties at the current location).
  12471. *
  12472. * @param values - Object containing multiple values.
  12473. * @returns Resolves when synchronization to the Database is complete.
  12474. */
  12475. OnDisconnect.prototype.update = function (values) {
  12476. validateWritablePath('OnDisconnect.update', this._path);
  12477. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12478. var deferred = new util.Deferred();
  12479. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
  12480. return deferred.promise;
  12481. };
  12482. return OnDisconnect;
  12483. }());
  12484. /**
  12485. * @license
  12486. * Copyright 2020 Google LLC
  12487. *
  12488. * Licensed under the Apache License, Version 2.0 (the "License");
  12489. * you may not use this file except in compliance with the License.
  12490. * You may obtain a copy of the License at
  12491. *
  12492. * http://www.apache.org/licenses/LICENSE-2.0
  12493. *
  12494. * Unless required by applicable law or agreed to in writing, software
  12495. * distributed under the License is distributed on an "AS IS" BASIS,
  12496. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12497. * See the License for the specific language governing permissions and
  12498. * limitations under the License.
  12499. */
  12500. /**
  12501. * @internal
  12502. */
  12503. var QueryImpl = /** @class */ (function () {
  12504. /**
  12505. * @hideconstructor
  12506. */
  12507. function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
  12508. this._repo = _repo;
  12509. this._path = _path;
  12510. this._queryParams = _queryParams;
  12511. this._orderByCalled = _orderByCalled;
  12512. }
  12513. Object.defineProperty(QueryImpl.prototype, "key", {
  12514. get: function () {
  12515. if (pathIsEmpty(this._path)) {
  12516. return null;
  12517. }
  12518. else {
  12519. return pathGetBack(this._path);
  12520. }
  12521. },
  12522. enumerable: false,
  12523. configurable: true
  12524. });
  12525. Object.defineProperty(QueryImpl.prototype, "ref", {
  12526. get: function () {
  12527. return new ReferenceImpl(this._repo, this._path);
  12528. },
  12529. enumerable: false,
  12530. configurable: true
  12531. });
  12532. Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
  12533. get: function () {
  12534. var obj = queryParamsGetQueryObject(this._queryParams);
  12535. var id = ObjectToUniqueKey(obj);
  12536. return id === '{}' ? 'default' : id;
  12537. },
  12538. enumerable: false,
  12539. configurable: true
  12540. });
  12541. Object.defineProperty(QueryImpl.prototype, "_queryObject", {
  12542. /**
  12543. * An object representation of the query parameters used by this Query.
  12544. */
  12545. get: function () {
  12546. return queryParamsGetQueryObject(this._queryParams);
  12547. },
  12548. enumerable: false,
  12549. configurable: true
  12550. });
  12551. QueryImpl.prototype.isEqual = function (other) {
  12552. other = util.getModularInstance(other);
  12553. if (!(other instanceof QueryImpl)) {
  12554. return false;
  12555. }
  12556. var sameRepo = this._repo === other._repo;
  12557. var samePath = pathEquals(this._path, other._path);
  12558. var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12559. return sameRepo && samePath && sameQueryIdentifier;
  12560. };
  12561. QueryImpl.prototype.toJSON = function () {
  12562. return this.toString();
  12563. };
  12564. QueryImpl.prototype.toString = function () {
  12565. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12566. };
  12567. return QueryImpl;
  12568. }());
  12569. /**
  12570. * Validates that no other order by call has been made
  12571. */
  12572. function validateNoPreviousOrderByCall(query, fnName) {
  12573. if (query._orderByCalled === true) {
  12574. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12575. }
  12576. }
  12577. /**
  12578. * Validates start/end values for queries.
  12579. */
  12580. function validateQueryEndpoints(params) {
  12581. var startNode = null;
  12582. var endNode = null;
  12583. if (params.hasStart()) {
  12584. startNode = params.getIndexStartValue();
  12585. }
  12586. if (params.hasEnd()) {
  12587. endNode = params.getIndexEndValue();
  12588. }
  12589. if (params.getIndex() === KEY_INDEX) {
  12590. var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12591. 'startAt(), endAt(), or equalTo().';
  12592. var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12593. 'endAt(), endBefore(), or equalTo() must be a string.';
  12594. if (params.hasStart()) {
  12595. var startName = params.getIndexStartName();
  12596. if (startName !== MIN_NAME) {
  12597. throw new Error(tooManyArgsError);
  12598. }
  12599. else if (typeof startNode !== 'string') {
  12600. throw new Error(wrongArgTypeError);
  12601. }
  12602. }
  12603. if (params.hasEnd()) {
  12604. var endName = params.getIndexEndName();
  12605. if (endName !== MAX_NAME) {
  12606. throw new Error(tooManyArgsError);
  12607. }
  12608. else if (typeof endNode !== 'string') {
  12609. throw new Error(wrongArgTypeError);
  12610. }
  12611. }
  12612. }
  12613. else if (params.getIndex() === PRIORITY_INDEX) {
  12614. if ((startNode != null && !isValidPriority(startNode)) ||
  12615. (endNode != null && !isValidPriority(endNode))) {
  12616. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12617. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12618. '(null, a number, or a string).');
  12619. }
  12620. }
  12621. else {
  12622. util.assert(params.getIndex() instanceof PathIndex ||
  12623. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12624. if ((startNode != null && typeof startNode === 'object') ||
  12625. (endNode != null && typeof endNode === 'object')) {
  12626. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12627. 'equalTo() cannot be an object.');
  12628. }
  12629. }
  12630. }
  12631. /**
  12632. * Validates that limit* has been called with the correct combination of parameters
  12633. */
  12634. function validateLimit(params) {
  12635. if (params.hasStart() &&
  12636. params.hasEnd() &&
  12637. params.hasLimit() &&
  12638. !params.hasAnchoredLimit()) {
  12639. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12640. 'limitToFirst() or limitToLast() instead.');
  12641. }
  12642. }
  12643. /**
  12644. * @internal
  12645. */
  12646. var ReferenceImpl = /** @class */ (function (_super) {
  12647. tslib.__extends(ReferenceImpl, _super);
  12648. /** @hideconstructor */
  12649. function ReferenceImpl(repo, path) {
  12650. return _super.call(this, repo, path, new QueryParams(), false) || this;
  12651. }
  12652. Object.defineProperty(ReferenceImpl.prototype, "parent", {
  12653. get: function () {
  12654. var parentPath = pathParent(this._path);
  12655. return parentPath === null
  12656. ? null
  12657. : new ReferenceImpl(this._repo, parentPath);
  12658. },
  12659. enumerable: false,
  12660. configurable: true
  12661. });
  12662. Object.defineProperty(ReferenceImpl.prototype, "root", {
  12663. get: function () {
  12664. var ref = this;
  12665. while (ref.parent !== null) {
  12666. ref = ref.parent;
  12667. }
  12668. return ref;
  12669. },
  12670. enumerable: false,
  12671. configurable: true
  12672. });
  12673. return ReferenceImpl;
  12674. }(QueryImpl));
  12675. /**
  12676. * A `DataSnapshot` contains data from a Database location.
  12677. *
  12678. * Any time you read data from the Database, you receive the data as a
  12679. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12680. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12681. * JavaScript object by calling the `val()` method. Alternatively, you can
  12682. * traverse into the snapshot by calling `child()` to return child snapshots
  12683. * (which you could then call `val()` on).
  12684. *
  12685. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12686. * a Database location. It cannot be modified and will never change (to modify
  12687. * data, you always call the `set()` method on a `Reference` directly).
  12688. */
  12689. var DataSnapshot = /** @class */ (function () {
  12690. /**
  12691. * @param _node - A SnapshotNode to wrap.
  12692. * @param ref - The location this snapshot came from.
  12693. * @param _index - The iteration order for this snapshot
  12694. * @hideconstructor
  12695. */
  12696. function DataSnapshot(_node,
  12697. /**
  12698. * The location of this DataSnapshot.
  12699. */
  12700. ref, _index) {
  12701. this._node = _node;
  12702. this.ref = ref;
  12703. this._index = _index;
  12704. }
  12705. Object.defineProperty(DataSnapshot.prototype, "priority", {
  12706. /**
  12707. * Gets the priority value of the data in this `DataSnapshot`.
  12708. *
  12709. * Applications need not use priority but can order collections by
  12710. * ordinary properties (see
  12711. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12712. * ).
  12713. */
  12714. get: function () {
  12715. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12716. return this._node.getPriority().val();
  12717. },
  12718. enumerable: false,
  12719. configurable: true
  12720. });
  12721. Object.defineProperty(DataSnapshot.prototype, "key", {
  12722. /**
  12723. * The key (last part of the path) of the location of this `DataSnapshot`.
  12724. *
  12725. * The last token in a Database location is considered its key. For example,
  12726. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12727. * `DataSnapshot` will return the key for the location that generated it.
  12728. * However, accessing the key on the root URL of a Database will return
  12729. * `null`.
  12730. */
  12731. get: function () {
  12732. return this.ref.key;
  12733. },
  12734. enumerable: false,
  12735. configurable: true
  12736. });
  12737. Object.defineProperty(DataSnapshot.prototype, "size", {
  12738. /** Returns the number of child properties of this `DataSnapshot`. */
  12739. get: function () {
  12740. return this._node.numChildren();
  12741. },
  12742. enumerable: false,
  12743. configurable: true
  12744. });
  12745. /**
  12746. * Gets another `DataSnapshot` for the location at the specified relative path.
  12747. *
  12748. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12749. * another `DataSnapshot` for the location at the specified relative path. The
  12750. * relative path can either be a simple child name (for example, "ada") or a
  12751. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12752. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12753. * whose value is `null`) is returned.
  12754. *
  12755. * @param path - A relative path to the location of child data.
  12756. */
  12757. DataSnapshot.prototype.child = function (path) {
  12758. var childPath = new Path(path);
  12759. var childRef = child(this.ref, path);
  12760. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12761. };
  12762. /**
  12763. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12764. * efficient than using `snapshot.val() !== null`.
  12765. */
  12766. DataSnapshot.prototype.exists = function () {
  12767. return !this._node.isEmpty();
  12768. };
  12769. /**
  12770. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12771. *
  12772. * The `exportVal()` method is similar to `val()`, except priority information
  12773. * is included (if available), making it suitable for backing up your data.
  12774. *
  12775. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12776. * Array, string, number, boolean, or `null`).
  12777. */
  12778. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12779. DataSnapshot.prototype.exportVal = function () {
  12780. return this._node.val(true);
  12781. };
  12782. /**
  12783. * Enumerates the top-level children in the `DataSnapshot`.
  12784. *
  12785. * Because of the way JavaScript objects work, the ordering of data in the
  12786. * JavaScript object returned by `val()` is not guaranteed to match the
  12787. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12788. * where `forEach()` comes in handy. It guarantees the children of a
  12789. * `DataSnapshot` will be iterated in their query order.
  12790. *
  12791. * If no explicit `orderBy*()` method is used, results are returned
  12792. * ordered by key (unless priorities are used, in which case, results are
  12793. * returned by priority).
  12794. *
  12795. * @param action - A function that will be called for each child DataSnapshot.
  12796. * The callback can return true to cancel further enumeration.
  12797. * @returns true if enumeration was canceled due to your callback returning
  12798. * true.
  12799. */
  12800. DataSnapshot.prototype.forEach = function (action) {
  12801. var _this = this;
  12802. if (this._node.isLeafNode()) {
  12803. return false;
  12804. }
  12805. var childrenNode = this._node;
  12806. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12807. return !!childrenNode.forEachChild(this._index, function (key, node) {
  12808. return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
  12809. });
  12810. };
  12811. /**
  12812. * Returns true if the specified child path has (non-null) data.
  12813. *
  12814. * @param path - A relative path to the location of a potential child.
  12815. * @returns `true` if data exists at the specified child path; else
  12816. * `false`.
  12817. */
  12818. DataSnapshot.prototype.hasChild = function (path) {
  12819. var childPath = new Path(path);
  12820. return !this._node.getChild(childPath).isEmpty();
  12821. };
  12822. /**
  12823. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12824. * properties.
  12825. *
  12826. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12827. * children. If it does, you can enumerate them using `forEach()`. If it
  12828. * doesn't, then either this snapshot contains a primitive value (which can be
  12829. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12830. * `null`).
  12831. *
  12832. * @returns true if this snapshot has any children; else false.
  12833. */
  12834. DataSnapshot.prototype.hasChildren = function () {
  12835. if (this._node.isLeafNode()) {
  12836. return false;
  12837. }
  12838. else {
  12839. return !this._node.isEmpty();
  12840. }
  12841. };
  12842. /**
  12843. * Returns a JSON-serializable representation of this object.
  12844. */
  12845. DataSnapshot.prototype.toJSON = function () {
  12846. return this.exportVal();
  12847. };
  12848. /**
  12849. * Extracts a JavaScript value from a `DataSnapshot`.
  12850. *
  12851. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12852. * scalar type (string, number, or boolean), an array, or an object. It may
  12853. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12854. * data).
  12855. *
  12856. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12857. * Array, string, number, boolean, or `null`).
  12858. */
  12859. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12860. DataSnapshot.prototype.val = function () {
  12861. return this._node.val();
  12862. };
  12863. return DataSnapshot;
  12864. }());
  12865. /**
  12866. *
  12867. * Returns a `Reference` representing the location in the Database
  12868. * corresponding to the provided path. If no path is provided, the `Reference`
  12869. * will point to the root of the Database.
  12870. *
  12871. * @param db - The database instance to obtain a reference for.
  12872. * @param path - Optional path representing the location the returned
  12873. * `Reference` will point. If not provided, the returned `Reference` will
  12874. * point to the root of the Database.
  12875. * @returns If a path is provided, a `Reference`
  12876. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12877. * root of the Database.
  12878. */
  12879. function ref(db, path) {
  12880. db = util.getModularInstance(db);
  12881. db._checkNotDeleted('ref');
  12882. return path !== undefined ? child(db._root, path) : db._root;
  12883. }
  12884. /**
  12885. * Returns a `Reference` representing the location in the Database
  12886. * corresponding to the provided Firebase URL.
  12887. *
  12888. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12889. * has a different domain than the current `Database` instance.
  12890. *
  12891. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12892. * and are not applied to the returned `Reference`.
  12893. *
  12894. * @param db - The database instance to obtain a reference for.
  12895. * @param url - The Firebase URL at which the returned `Reference` will
  12896. * point.
  12897. * @returns A `Reference` pointing to the provided
  12898. * Firebase URL.
  12899. */
  12900. function refFromURL(db, url) {
  12901. db = util.getModularInstance(db);
  12902. db._checkNotDeleted('refFromURL');
  12903. var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12904. validateUrl('refFromURL', parsedURL);
  12905. var repoInfo = parsedURL.repoInfo;
  12906. if (!db._repo.repoInfo_.isCustomHost() &&
  12907. repoInfo.host !== db._repo.repoInfo_.host) {
  12908. fatal('refFromURL' +
  12909. ': Host name does not match the current database: ' +
  12910. '(found ' +
  12911. repoInfo.host +
  12912. ' but expected ' +
  12913. db._repo.repoInfo_.host +
  12914. ')');
  12915. }
  12916. return ref(db, parsedURL.path.toString());
  12917. }
  12918. /**
  12919. * Gets a `Reference` for the location at the specified relative path.
  12920. *
  12921. * The relative path can either be a simple child name (for example, "ada") or
  12922. * a deeper slash-separated path (for example, "ada/name/first").
  12923. *
  12924. * @param parent - The parent location.
  12925. * @param path - A relative path from this location to the desired child
  12926. * location.
  12927. * @returns The specified child location.
  12928. */
  12929. function child(parent, path) {
  12930. parent = util.getModularInstance(parent);
  12931. if (pathGetFront(parent._path) === null) {
  12932. validateRootPathString('child', 'path', path, false);
  12933. }
  12934. else {
  12935. validatePathString('child', 'path', path, false);
  12936. }
  12937. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12938. }
  12939. /**
  12940. * Returns an `OnDisconnect` object - see
  12941. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12942. * for more information on how to use it.
  12943. *
  12944. * @param ref - The reference to add OnDisconnect triggers for.
  12945. */
  12946. function onDisconnect(ref) {
  12947. ref = util.getModularInstance(ref);
  12948. return new OnDisconnect(ref._repo, ref._path);
  12949. }
  12950. /**
  12951. * Generates a new child location using a unique key and returns its
  12952. * `Reference`.
  12953. *
  12954. * This is the most common pattern for adding data to a collection of items.
  12955. *
  12956. * If you provide a value to `push()`, the value is written to the
  12957. * generated location. If you don't pass a value, nothing is written to the
  12958. * database and the child remains empty (but you can use the `Reference`
  12959. * elsewhere).
  12960. *
  12961. * The unique keys generated by `push()` are ordered by the current time, so the
  12962. * resulting list of items is chronologically sorted. The keys are also
  12963. * designed to be unguessable (they contain 72 random bits of entropy).
  12964. *
  12965. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12966. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12967. *
  12968. * @param parent - The parent location.
  12969. * @param value - Optional value to be written at the generated location.
  12970. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12971. * but can be used immediately as the `Reference` to the child location.
  12972. */
  12973. function push(parent, value) {
  12974. parent = util.getModularInstance(parent);
  12975. validateWritablePath('push', parent._path);
  12976. validateFirebaseDataArg('push', value, parent._path, true);
  12977. var now = repoServerTime(parent._repo);
  12978. var name = nextPushId(now);
  12979. // push() returns a ThennableReference whose promise is fulfilled with a
  12980. // regular Reference. We use child() to create handles to two different
  12981. // references. The first is turned into a ThennableReference below by adding
  12982. // then() and catch() methods and is used as the return value of push(). The
  12983. // second remains a regular Reference and is used as the fulfilled value of
  12984. // the first ThennableReference.
  12985. var thennablePushRef = child(parent, name);
  12986. var pushRef = child(parent, name);
  12987. var promise;
  12988. if (value != null) {
  12989. promise = set(pushRef, value).then(function () { return pushRef; });
  12990. }
  12991. else {
  12992. promise = Promise.resolve(pushRef);
  12993. }
  12994. thennablePushRef.then = promise.then.bind(promise);
  12995. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12996. return thennablePushRef;
  12997. }
  12998. /**
  12999. * Removes the data at this Database location.
  13000. *
  13001. * Any data at child locations will also be deleted.
  13002. *
  13003. * The effect of the remove will be visible immediately and the corresponding
  13004. * event 'value' will be triggered. Synchronization of the remove to the
  13005. * Firebase servers will also be started, and the returned Promise will resolve
  13006. * when complete. If provided, the onComplete callback will be called
  13007. * asynchronously after synchronization has finished.
  13008. *
  13009. * @param ref - The location to remove.
  13010. * @returns Resolves when remove on server is complete.
  13011. */
  13012. function remove(ref) {
  13013. validateWritablePath('remove', ref._path);
  13014. return set(ref, null);
  13015. }
  13016. /**
  13017. * Writes data to this Database location.
  13018. *
  13019. * This will overwrite any data at this location and all child locations.
  13020. *
  13021. * The effect of the write will be visible immediately, and the corresponding
  13022. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  13023. * the data to the Firebase servers will also be started, and the returned
  13024. * Promise will resolve when complete. If provided, the `onComplete` callback
  13025. * will be called asynchronously after synchronization has finished.
  13026. *
  13027. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  13028. * all data at this location and all child locations will be deleted.
  13029. *
  13030. * `set()` will remove any priority stored at this location, so if priority is
  13031. * meant to be preserved, you need to use `setWithPriority()` instead.
  13032. *
  13033. * Note that modifying data with `set()` will cancel any pending transactions
  13034. * at that location, so extreme care should be taken if mixing `set()` and
  13035. * `transaction()` to modify the same data.
  13036. *
  13037. * A single `set()` will generate a single "value" event at the location where
  13038. * the `set()` was performed.
  13039. *
  13040. * @param ref - The location to write to.
  13041. * @param value - The value to be written (string, number, boolean, object,
  13042. * array, or null).
  13043. * @returns Resolves when write to server is complete.
  13044. */
  13045. function set(ref, value) {
  13046. ref = util.getModularInstance(ref);
  13047. validateWritablePath('set', ref._path);
  13048. validateFirebaseDataArg('set', value, ref._path, false);
  13049. var deferred = new util.Deferred();
  13050. repoSetWithPriority(ref._repo, ref._path, value,
  13051. /*priority=*/ null, deferred.wrapCallback(function () { }));
  13052. return deferred.promise;
  13053. }
  13054. /**
  13055. * Sets a priority for the data at this Database location.
  13056. *
  13057. * Applications need not use priority but can order collections by
  13058. * ordinary properties (see
  13059. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13060. * ).
  13061. *
  13062. * @param ref - The location to write to.
  13063. * @param priority - The priority to be written (string, number, or null).
  13064. * @returns Resolves when write to server is complete.
  13065. */
  13066. function setPriority(ref, priority) {
  13067. ref = util.getModularInstance(ref);
  13068. validateWritablePath('setPriority', ref._path);
  13069. validatePriority('setPriority', priority, false);
  13070. var deferred = new util.Deferred();
  13071. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
  13072. return deferred.promise;
  13073. }
  13074. /**
  13075. * Writes data the Database location. Like `set()` but also specifies the
  13076. * priority for that data.
  13077. *
  13078. * Applications need not use priority but can order collections by
  13079. * ordinary properties (see
  13080. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13081. * ).
  13082. *
  13083. * @param ref - The location to write to.
  13084. * @param value - The value to be written (string, number, boolean, object,
  13085. * array, or null).
  13086. * @param priority - The priority to be written (string, number, or null).
  13087. * @returns Resolves when write to server is complete.
  13088. */
  13089. function setWithPriority(ref, value, priority) {
  13090. validateWritablePath('setWithPriority', ref._path);
  13091. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  13092. validatePriority('setWithPriority', priority, false);
  13093. if (ref.key === '.length' || ref.key === '.keys') {
  13094. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  13095. }
  13096. var deferred = new util.Deferred();
  13097. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
  13098. return deferred.promise;
  13099. }
  13100. /**
  13101. * Writes multiple values to the Database at once.
  13102. *
  13103. * The `values` argument contains multiple property-value pairs that will be
  13104. * written to the Database together. Each child property can either be a simple
  13105. * property (for example, "name") or a relative path (for example,
  13106. * "name/first") from the current location to the data to update.
  13107. *
  13108. * As opposed to the `set()` method, `update()` can be use to selectively update
  13109. * only the referenced properties at the current location (instead of replacing
  13110. * all the child properties at the current location).
  13111. *
  13112. * The effect of the write will be visible immediately, and the corresponding
  13113. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  13114. * the data to the Firebase servers will also be started, and the returned
  13115. * Promise will resolve when complete. If provided, the `onComplete` callback
  13116. * will be called asynchronously after synchronization has finished.
  13117. *
  13118. * A single `update()` will generate a single "value" event at the location
  13119. * where the `update()` was performed, regardless of how many children were
  13120. * modified.
  13121. *
  13122. * Note that modifying data with `update()` will cancel any pending
  13123. * transactions at that location, so extreme care should be taken if mixing
  13124. * `update()` and `transaction()` to modify the same data.
  13125. *
  13126. * Passing `null` to `update()` will remove the data at this location.
  13127. *
  13128. * See
  13129. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  13130. *
  13131. * @param ref - The location to write to.
  13132. * @param values - Object containing multiple values.
  13133. * @returns Resolves when update on server is complete.
  13134. */
  13135. function update(ref, values) {
  13136. validateFirebaseMergeDataArg('update', values, ref._path, false);
  13137. var deferred = new util.Deferred();
  13138. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
  13139. return deferred.promise;
  13140. }
  13141. /**
  13142. * Gets the most up-to-date result for this query.
  13143. *
  13144. * @param query - The query to run.
  13145. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  13146. * available, or rejects if the client is unable to return a value (e.g., if the
  13147. * server is unreachable and there is nothing cached).
  13148. */
  13149. function get(query) {
  13150. query = util.getModularInstance(query);
  13151. var callbackContext = new CallbackContext(function () { });
  13152. var container = new ValueEventRegistration(callbackContext);
  13153. return repoGetValue(query._repo, query, container).then(function (node) {
  13154. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  13155. });
  13156. }
  13157. /**
  13158. * Represents registration for 'value' events.
  13159. */
  13160. var ValueEventRegistration = /** @class */ (function () {
  13161. function ValueEventRegistration(callbackContext) {
  13162. this.callbackContext = callbackContext;
  13163. }
  13164. ValueEventRegistration.prototype.respondsTo = function (eventType) {
  13165. return eventType === 'value';
  13166. };
  13167. ValueEventRegistration.prototype.createEvent = function (change, query) {
  13168. var index = query._queryParams.getIndex();
  13169. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  13170. };
  13171. ValueEventRegistration.prototype.getEventRunner = function (eventData) {
  13172. var _this = this;
  13173. if (eventData.getEventType() === 'cancel') {
  13174. return function () {
  13175. return _this.callbackContext.onCancel(eventData.error);
  13176. };
  13177. }
  13178. else {
  13179. return function () {
  13180. return _this.callbackContext.onValue(eventData.snapshot, null);
  13181. };
  13182. }
  13183. };
  13184. ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
  13185. if (this.callbackContext.hasCancelCallback) {
  13186. return new CancelEvent(this, error, path);
  13187. }
  13188. else {
  13189. return null;
  13190. }
  13191. };
  13192. ValueEventRegistration.prototype.matches = function (other) {
  13193. if (!(other instanceof ValueEventRegistration)) {
  13194. return false;
  13195. }
  13196. else if (!other.callbackContext || !this.callbackContext) {
  13197. // If no callback specified, we consider it to match any callback.
  13198. return true;
  13199. }
  13200. else {
  13201. return other.callbackContext.matches(this.callbackContext);
  13202. }
  13203. };
  13204. ValueEventRegistration.prototype.hasAnyCallback = function () {
  13205. return this.callbackContext !== null;
  13206. };
  13207. return ValueEventRegistration;
  13208. }());
  13209. /**
  13210. * Represents the registration of a child_x event.
  13211. */
  13212. var ChildEventRegistration = /** @class */ (function () {
  13213. function ChildEventRegistration(eventType, callbackContext) {
  13214. this.eventType = eventType;
  13215. this.callbackContext = callbackContext;
  13216. }
  13217. ChildEventRegistration.prototype.respondsTo = function (eventType) {
  13218. var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  13219. eventToCheck =
  13220. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  13221. return this.eventType === eventToCheck;
  13222. };
  13223. ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
  13224. if (this.callbackContext.hasCancelCallback) {
  13225. return new CancelEvent(this, error, path);
  13226. }
  13227. else {
  13228. return null;
  13229. }
  13230. };
  13231. ChildEventRegistration.prototype.createEvent = function (change, query) {
  13232. util.assert(change.childName != null, 'Child events should have a childName.');
  13233. var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  13234. var index = query._queryParams.getIndex();
  13235. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  13236. };
  13237. ChildEventRegistration.prototype.getEventRunner = function (eventData) {
  13238. var _this = this;
  13239. if (eventData.getEventType() === 'cancel') {
  13240. return function () {
  13241. return _this.callbackContext.onCancel(eventData.error);
  13242. };
  13243. }
  13244. else {
  13245. return function () {
  13246. return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  13247. };
  13248. }
  13249. };
  13250. ChildEventRegistration.prototype.matches = function (other) {
  13251. if (other instanceof ChildEventRegistration) {
  13252. return (this.eventType === other.eventType &&
  13253. (!this.callbackContext ||
  13254. !other.callbackContext ||
  13255. this.callbackContext.matches(other.callbackContext)));
  13256. }
  13257. return false;
  13258. };
  13259. ChildEventRegistration.prototype.hasAnyCallback = function () {
  13260. return !!this.callbackContext;
  13261. };
  13262. return ChildEventRegistration;
  13263. }());
  13264. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  13265. var cancelCallback;
  13266. if (typeof cancelCallbackOrListenOptions === 'object') {
  13267. cancelCallback = undefined;
  13268. options = cancelCallbackOrListenOptions;
  13269. }
  13270. if (typeof cancelCallbackOrListenOptions === 'function') {
  13271. cancelCallback = cancelCallbackOrListenOptions;
  13272. }
  13273. if (options && options.onlyOnce) {
  13274. var userCallback_1 = callback;
  13275. var onceCallback = function (dataSnapshot, previousChildName) {
  13276. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13277. userCallback_1(dataSnapshot, previousChildName);
  13278. };
  13279. onceCallback.userCallback = callback.userCallback;
  13280. onceCallback.context = callback.context;
  13281. callback = onceCallback;
  13282. }
  13283. var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  13284. var container = eventType === 'value'
  13285. ? new ValueEventRegistration(callbackContext)
  13286. : new ChildEventRegistration(eventType, callbackContext);
  13287. repoAddEventCallbackForQuery(query._repo, query, container);
  13288. return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
  13289. }
  13290. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  13291. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  13292. }
  13293. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  13294. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  13295. }
  13296. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  13297. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  13298. }
  13299. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  13300. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  13301. }
  13302. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  13303. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  13304. }
  13305. /**
  13306. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  13307. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  13308. * the respective `on*` callbacks.
  13309. *
  13310. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  13311. * will not automatically remove listeners registered on child nodes, `off()`
  13312. * must also be called on any child listeners to remove the callback.
  13313. *
  13314. * If a callback is not specified, all callbacks for the specified eventType
  13315. * will be removed. Similarly, if no eventType is specified, all callbacks
  13316. * for the `Reference` will be removed.
  13317. *
  13318. * Individual listeners can also be removed by invoking their unsubscribe
  13319. * callbacks.
  13320. *
  13321. * @param query - The query that the listener was registered with.
  13322. * @param eventType - One of the following strings: "value", "child_added",
  13323. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  13324. * for the `Reference` will be removed.
  13325. * @param callback - The callback function that was passed to `on()` or
  13326. * `undefined` to remove all callbacks.
  13327. */
  13328. function off(query, eventType, callback) {
  13329. var container = null;
  13330. var expCallback = callback ? new CallbackContext(callback) : null;
  13331. if (eventType === 'value') {
  13332. container = new ValueEventRegistration(expCallback);
  13333. }
  13334. else if (eventType) {
  13335. container = new ChildEventRegistration(eventType, expCallback);
  13336. }
  13337. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13338. }
  13339. /**
  13340. * A `QueryConstraint` is used to narrow the set of documents returned by a
  13341. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  13342. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  13343. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  13344. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  13345. * {@link orderByValue} or {@link equalTo} and
  13346. * can then be passed to {@link query} to create a new query instance that
  13347. * also contains this `QueryConstraint`.
  13348. */
  13349. var QueryConstraint = /** @class */ (function () {
  13350. function QueryConstraint() {
  13351. }
  13352. return QueryConstraint;
  13353. }());
  13354. var QueryEndAtConstraint = /** @class */ (function (_super) {
  13355. tslib.__extends(QueryEndAtConstraint, _super);
  13356. function QueryEndAtConstraint(_value, _key) {
  13357. var _this = _super.call(this) || this;
  13358. _this._value = _value;
  13359. _this._key = _key;
  13360. return _this;
  13361. }
  13362. QueryEndAtConstraint.prototype._apply = function (query) {
  13363. validateFirebaseDataArg('endAt', this._value, query._path, true);
  13364. var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  13365. validateLimit(newParams);
  13366. validateQueryEndpoints(newParams);
  13367. if (query._queryParams.hasEnd()) {
  13368. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  13369. 'endBefore or equalTo).');
  13370. }
  13371. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13372. };
  13373. return QueryEndAtConstraint;
  13374. }(QueryConstraint));
  13375. /**
  13376. * Creates a `QueryConstraint` with the specified ending point.
  13377. *
  13378. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13379. * allows you to choose arbitrary starting and ending points for your queries.
  13380. *
  13381. * The ending point is inclusive, so children with exactly the specified value
  13382. * will be included in the query. The optional key argument can be used to
  13383. * further limit the range of the query. If it is specified, then children that
  13384. * have exactly the specified value must also have a key name less than or equal
  13385. * to the specified key.
  13386. *
  13387. * You can read more about `endAt()` in
  13388. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13389. *
  13390. * @param value - The value to end at. The argument type depends on which
  13391. * `orderBy*()` function was used in this query. Specify a value that matches
  13392. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13393. * value must be a string.
  13394. * @param key - The child key to end at, among the children with the previously
  13395. * specified priority. This argument is only allowed if ordering by child,
  13396. * value, or priority.
  13397. */
  13398. function endAt(value, key) {
  13399. validateKey('endAt', 'key', key, true);
  13400. return new QueryEndAtConstraint(value, key);
  13401. }
  13402. var QueryEndBeforeConstraint = /** @class */ (function (_super) {
  13403. tslib.__extends(QueryEndBeforeConstraint, _super);
  13404. function QueryEndBeforeConstraint(_value, _key) {
  13405. var _this = _super.call(this) || this;
  13406. _this._value = _value;
  13407. _this._key = _key;
  13408. return _this;
  13409. }
  13410. QueryEndBeforeConstraint.prototype._apply = function (query) {
  13411. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  13412. var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  13413. validateLimit(newParams);
  13414. validateQueryEndpoints(newParams);
  13415. if (query._queryParams.hasEnd()) {
  13416. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  13417. 'endBefore or equalTo).');
  13418. }
  13419. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13420. };
  13421. return QueryEndBeforeConstraint;
  13422. }(QueryConstraint));
  13423. /**
  13424. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  13425. *
  13426. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13427. * allows you to choose arbitrary starting and ending points for your queries.
  13428. *
  13429. * The ending point is exclusive. If only a value is provided, children
  13430. * with a value less than the specified value will be included in the query.
  13431. * If a key is specified, then children must have a value less than or equal
  13432. * to the specified value and a key name less than the specified key.
  13433. *
  13434. * @param value - The value to end before. The argument type depends on which
  13435. * `orderBy*()` function was used in this query. Specify a value that matches
  13436. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13437. * value must be a string.
  13438. * @param key - The child key to end before, among the children with the
  13439. * previously specified priority. This argument is only allowed if ordering by
  13440. * child, value, or priority.
  13441. */
  13442. function endBefore(value, key) {
  13443. validateKey('endBefore', 'key', key, true);
  13444. return new QueryEndBeforeConstraint(value, key);
  13445. }
  13446. var QueryStartAtConstraint = /** @class */ (function (_super) {
  13447. tslib.__extends(QueryStartAtConstraint, _super);
  13448. function QueryStartAtConstraint(_value, _key) {
  13449. var _this = _super.call(this) || this;
  13450. _this._value = _value;
  13451. _this._key = _key;
  13452. return _this;
  13453. }
  13454. QueryStartAtConstraint.prototype._apply = function (query) {
  13455. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13456. var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13457. validateLimit(newParams);
  13458. validateQueryEndpoints(newParams);
  13459. if (query._queryParams.hasStart()) {
  13460. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13461. 'startBefore or equalTo).');
  13462. }
  13463. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13464. };
  13465. return QueryStartAtConstraint;
  13466. }(QueryConstraint));
  13467. /**
  13468. * Creates a `QueryConstraint` with the specified starting point.
  13469. *
  13470. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13471. * allows you to choose arbitrary starting and ending points for your queries.
  13472. *
  13473. * The starting point is inclusive, so children with exactly the specified value
  13474. * will be included in the query. The optional key argument can be used to
  13475. * further limit the range of the query. If it is specified, then children that
  13476. * have exactly the specified value must also have a key name greater than or
  13477. * equal to the specified key.
  13478. *
  13479. * You can read more about `startAt()` in
  13480. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13481. *
  13482. * @param value - The value to start at. The argument type depends on which
  13483. * `orderBy*()` function was used in this query. Specify a value that matches
  13484. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13485. * value must be a string.
  13486. * @param key - The child key to start at. This argument is only allowed if
  13487. * ordering by child, value, or priority.
  13488. */
  13489. function startAt(value, key) {
  13490. if (value === void 0) { value = null; }
  13491. validateKey('startAt', 'key', key, true);
  13492. return new QueryStartAtConstraint(value, key);
  13493. }
  13494. var QueryStartAfterConstraint = /** @class */ (function (_super) {
  13495. tslib.__extends(QueryStartAfterConstraint, _super);
  13496. function QueryStartAfterConstraint(_value, _key) {
  13497. var _this = _super.call(this) || this;
  13498. _this._value = _value;
  13499. _this._key = _key;
  13500. return _this;
  13501. }
  13502. QueryStartAfterConstraint.prototype._apply = function (query) {
  13503. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13504. var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13505. validateLimit(newParams);
  13506. validateQueryEndpoints(newParams);
  13507. if (query._queryParams.hasStart()) {
  13508. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13509. 'startAfter, or equalTo).');
  13510. }
  13511. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13512. };
  13513. return QueryStartAfterConstraint;
  13514. }(QueryConstraint));
  13515. /**
  13516. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13517. *
  13518. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13519. * allows you to choose arbitrary starting and ending points for your queries.
  13520. *
  13521. * The starting point is exclusive. If only a value is provided, children
  13522. * with a value greater than the specified value will be included in the query.
  13523. * If a key is specified, then children must have a value greater than or equal
  13524. * to the specified value and a a key name greater than the specified key.
  13525. *
  13526. * @param value - The value to start after. The argument type depends on which
  13527. * `orderBy*()` function was used in this query. Specify a value that matches
  13528. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13529. * value must be a string.
  13530. * @param key - The child key to start after. This argument is only allowed if
  13531. * ordering by child, value, or priority.
  13532. */
  13533. function startAfter(value, key) {
  13534. validateKey('startAfter', 'key', key, true);
  13535. return new QueryStartAfterConstraint(value, key);
  13536. }
  13537. var QueryLimitToFirstConstraint = /** @class */ (function (_super) {
  13538. tslib.__extends(QueryLimitToFirstConstraint, _super);
  13539. function QueryLimitToFirstConstraint(_limit) {
  13540. var _this = _super.call(this) || this;
  13541. _this._limit = _limit;
  13542. return _this;
  13543. }
  13544. QueryLimitToFirstConstraint.prototype._apply = function (query) {
  13545. if (query._queryParams.hasLimit()) {
  13546. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13547. 'or limitToLast).');
  13548. }
  13549. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13550. };
  13551. return QueryLimitToFirstConstraint;
  13552. }(QueryConstraint));
  13553. /**
  13554. * Creates a new `QueryConstraint` that if limited to the first specific number
  13555. * of children.
  13556. *
  13557. * The `limitToFirst()` method is used to set a maximum number of children to be
  13558. * synced for a given callback. If we set a limit of 100, we will initially only
  13559. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13560. * stored in our Database, a `child_added` event will fire for each message.
  13561. * However, if we have over 100 messages, we will only receive a `child_added`
  13562. * event for the first 100 ordered messages. As items change, we will receive
  13563. * `child_removed` events for each item that drops out of the active list so
  13564. * that the total number stays at 100.
  13565. *
  13566. * You can read more about `limitToFirst()` in
  13567. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13568. *
  13569. * @param limit - The maximum number of nodes to include in this query.
  13570. */
  13571. function limitToFirst(limit) {
  13572. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13573. throw new Error('limitToFirst: First argument must be a positive integer.');
  13574. }
  13575. return new QueryLimitToFirstConstraint(limit);
  13576. }
  13577. var QueryLimitToLastConstraint = /** @class */ (function (_super) {
  13578. tslib.__extends(QueryLimitToLastConstraint, _super);
  13579. function QueryLimitToLastConstraint(_limit) {
  13580. var _this = _super.call(this) || this;
  13581. _this._limit = _limit;
  13582. return _this;
  13583. }
  13584. QueryLimitToLastConstraint.prototype._apply = function (query) {
  13585. if (query._queryParams.hasLimit()) {
  13586. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13587. 'or limitToLast).');
  13588. }
  13589. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13590. };
  13591. return QueryLimitToLastConstraint;
  13592. }(QueryConstraint));
  13593. /**
  13594. * Creates a new `QueryConstraint` that is limited to return only the last
  13595. * specified number of children.
  13596. *
  13597. * The `limitToLast()` method is used to set a maximum number of children to be
  13598. * synced for a given callback. If we set a limit of 100, we will initially only
  13599. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13600. * stored in our Database, a `child_added` event will fire for each message.
  13601. * However, if we have over 100 messages, we will only receive a `child_added`
  13602. * event for the last 100 ordered messages. As items change, we will receive
  13603. * `child_removed` events for each item that drops out of the active list so
  13604. * that the total number stays at 100.
  13605. *
  13606. * You can read more about `limitToLast()` in
  13607. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13608. *
  13609. * @param limit - The maximum number of nodes to include in this query.
  13610. */
  13611. function limitToLast(limit) {
  13612. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13613. throw new Error('limitToLast: First argument must be a positive integer.');
  13614. }
  13615. return new QueryLimitToLastConstraint(limit);
  13616. }
  13617. var QueryOrderByChildConstraint = /** @class */ (function (_super) {
  13618. tslib.__extends(QueryOrderByChildConstraint, _super);
  13619. function QueryOrderByChildConstraint(_path) {
  13620. var _this = _super.call(this) || this;
  13621. _this._path = _path;
  13622. return _this;
  13623. }
  13624. QueryOrderByChildConstraint.prototype._apply = function (query) {
  13625. validateNoPreviousOrderByCall(query, 'orderByChild');
  13626. var parsedPath = new Path(this._path);
  13627. if (pathIsEmpty(parsedPath)) {
  13628. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13629. }
  13630. var index = new PathIndex(parsedPath);
  13631. var newParams = queryParamsOrderBy(query._queryParams, index);
  13632. validateQueryEndpoints(newParams);
  13633. return new QueryImpl(query._repo, query._path, newParams,
  13634. /*orderByCalled=*/ true);
  13635. };
  13636. return QueryOrderByChildConstraint;
  13637. }(QueryConstraint));
  13638. /**
  13639. * Creates a new `QueryConstraint` that orders by the specified child key.
  13640. *
  13641. * Queries can only order by one key at a time. Calling `orderByChild()`
  13642. * multiple times on the same query is an error.
  13643. *
  13644. * Firebase queries allow you to order your data by any child key on the fly.
  13645. * However, if you know in advance what your indexes will be, you can define
  13646. * them via the .indexOn rule in your Security Rules for better performance. See
  13647. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13648. * rule for more information.
  13649. *
  13650. * You can read more about `orderByChild()` in
  13651. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13652. *
  13653. * @param path - The path to order by.
  13654. */
  13655. function orderByChild(path) {
  13656. if (path === '$key') {
  13657. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13658. }
  13659. else if (path === '$priority') {
  13660. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13661. }
  13662. else if (path === '$value') {
  13663. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13664. }
  13665. validatePathString('orderByChild', 'path', path, false);
  13666. return new QueryOrderByChildConstraint(path);
  13667. }
  13668. var QueryOrderByKeyConstraint = /** @class */ (function (_super) {
  13669. tslib.__extends(QueryOrderByKeyConstraint, _super);
  13670. function QueryOrderByKeyConstraint() {
  13671. return _super !== null && _super.apply(this, arguments) || this;
  13672. }
  13673. QueryOrderByKeyConstraint.prototype._apply = function (query) {
  13674. validateNoPreviousOrderByCall(query, 'orderByKey');
  13675. var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13676. validateQueryEndpoints(newParams);
  13677. return new QueryImpl(query._repo, query._path, newParams,
  13678. /*orderByCalled=*/ true);
  13679. };
  13680. return QueryOrderByKeyConstraint;
  13681. }(QueryConstraint));
  13682. /**
  13683. * Creates a new `QueryConstraint` that orders by the key.
  13684. *
  13685. * Sorts the results of a query by their (ascending) key values.
  13686. *
  13687. * You can read more about `orderByKey()` in
  13688. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13689. */
  13690. function orderByKey() {
  13691. return new QueryOrderByKeyConstraint();
  13692. }
  13693. var QueryOrderByPriorityConstraint = /** @class */ (function (_super) {
  13694. tslib.__extends(QueryOrderByPriorityConstraint, _super);
  13695. function QueryOrderByPriorityConstraint() {
  13696. return _super !== null && _super.apply(this, arguments) || this;
  13697. }
  13698. QueryOrderByPriorityConstraint.prototype._apply = function (query) {
  13699. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13700. var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13701. validateQueryEndpoints(newParams);
  13702. return new QueryImpl(query._repo, query._path, newParams,
  13703. /*orderByCalled=*/ true);
  13704. };
  13705. return QueryOrderByPriorityConstraint;
  13706. }(QueryConstraint));
  13707. /**
  13708. * Creates a new `QueryConstraint` that orders by priority.
  13709. *
  13710. * Applications need not use priority but can order collections by
  13711. * ordinary properties (see
  13712. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13713. * for alternatives to priority.
  13714. */
  13715. function orderByPriority() {
  13716. return new QueryOrderByPriorityConstraint();
  13717. }
  13718. var QueryOrderByValueConstraint = /** @class */ (function (_super) {
  13719. tslib.__extends(QueryOrderByValueConstraint, _super);
  13720. function QueryOrderByValueConstraint() {
  13721. return _super !== null && _super.apply(this, arguments) || this;
  13722. }
  13723. QueryOrderByValueConstraint.prototype._apply = function (query) {
  13724. validateNoPreviousOrderByCall(query, 'orderByValue');
  13725. var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13726. validateQueryEndpoints(newParams);
  13727. return new QueryImpl(query._repo, query._path, newParams,
  13728. /*orderByCalled=*/ true);
  13729. };
  13730. return QueryOrderByValueConstraint;
  13731. }(QueryConstraint));
  13732. /**
  13733. * Creates a new `QueryConstraint` that orders by value.
  13734. *
  13735. * If the children of a query are all scalar values (string, number, or
  13736. * boolean), you can order the results by their (ascending) values.
  13737. *
  13738. * You can read more about `orderByValue()` in
  13739. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13740. */
  13741. function orderByValue() {
  13742. return new QueryOrderByValueConstraint();
  13743. }
  13744. var QueryEqualToValueConstraint = /** @class */ (function (_super) {
  13745. tslib.__extends(QueryEqualToValueConstraint, _super);
  13746. function QueryEqualToValueConstraint(_value, _key) {
  13747. var _this = _super.call(this) || this;
  13748. _this._value = _value;
  13749. _this._key = _key;
  13750. return _this;
  13751. }
  13752. QueryEqualToValueConstraint.prototype._apply = function (query) {
  13753. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13754. if (query._queryParams.hasStart()) {
  13755. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13756. 'equalTo).');
  13757. }
  13758. if (query._queryParams.hasEnd()) {
  13759. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13760. 'equalTo).');
  13761. }
  13762. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13763. };
  13764. return QueryEqualToValueConstraint;
  13765. }(QueryConstraint));
  13766. /**
  13767. * Creates a `QueryConstraint` that includes children that match the specified
  13768. * value.
  13769. *
  13770. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13771. * allows you to choose arbitrary starting and ending points for your queries.
  13772. *
  13773. * The optional key argument can be used to further limit the range of the
  13774. * query. If it is specified, then children that have exactly the specified
  13775. * value must also have exactly the specified key as their key name. This can be
  13776. * used to filter result sets with many matches for the same value.
  13777. *
  13778. * You can read more about `equalTo()` in
  13779. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13780. *
  13781. * @param value - The value to match for. The argument type depends on which
  13782. * `orderBy*()` function was used in this query. Specify a value that matches
  13783. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13784. * value must be a string.
  13785. * @param key - The child key to start at, among the children with the
  13786. * previously specified priority. This argument is only allowed if ordering by
  13787. * child, value, or priority.
  13788. */
  13789. function equalTo(value, key) {
  13790. validateKey('equalTo', 'key', key, true);
  13791. return new QueryEqualToValueConstraint(value, key);
  13792. }
  13793. /**
  13794. * Creates a new immutable instance of `Query` that is extended to also include
  13795. * additional query constraints.
  13796. *
  13797. * @param query - The Query instance to use as a base for the new constraints.
  13798. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13799. * @throws if any of the provided query constraints cannot be combined with the
  13800. * existing or new constraints.
  13801. */
  13802. function query(query) {
  13803. var e_1, _a;
  13804. var queryConstraints = [];
  13805. for (var _i = 1; _i < arguments.length; _i++) {
  13806. queryConstraints[_i - 1] = arguments[_i];
  13807. }
  13808. var queryImpl = util.getModularInstance(query);
  13809. try {
  13810. for (var queryConstraints_1 = tslib.__values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
  13811. var constraint = queryConstraints_1_1.value;
  13812. queryImpl = constraint._apply(queryImpl);
  13813. }
  13814. }
  13815. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13816. finally {
  13817. try {
  13818. if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
  13819. }
  13820. finally { if (e_1) throw e_1.error; }
  13821. }
  13822. return queryImpl;
  13823. }
  13824. /**
  13825. * Define reference constructor in various modules
  13826. *
  13827. * We are doing this here to avoid several circular
  13828. * dependency issues
  13829. */
  13830. syncPointSetReferenceConstructor(ReferenceImpl);
  13831. syncTreeSetReferenceConstructor(ReferenceImpl);
  13832. /**
  13833. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13834. * modifying this definition, consult the definition in:
  13835. *
  13836. * https://github.com/firebase/firebase-admin-node
  13837. *
  13838. * and make sure the two are consistent.
  13839. */
  13840. var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13841. /**
  13842. * Creates and caches `Repo` instances.
  13843. */
  13844. var repos = {};
  13845. /**
  13846. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13847. */
  13848. var useRestClient = false;
  13849. /**
  13850. * Update an existing `Repo` in place to point to a new host/port.
  13851. */
  13852. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13853. repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
  13854. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13855. /*isUsingEmulator=*/ true);
  13856. if (tokenProvider) {
  13857. repo.authTokenProvider_ = tokenProvider;
  13858. }
  13859. }
  13860. /**
  13861. * This function should only ever be called to CREATE a new database instance.
  13862. * @internal
  13863. */
  13864. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13865. var dbUrl = url || app.options.databaseURL;
  13866. if (dbUrl === undefined) {
  13867. if (!app.options.projectId) {
  13868. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13869. ' a Project ID when calling firebase.initializeApp().');
  13870. }
  13871. log('Using default host for project ', app.options.projectId);
  13872. dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
  13873. }
  13874. var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13875. var repoInfo = parsedUrl.repoInfo;
  13876. var isEmulator;
  13877. var dbEmulatorHost = undefined;
  13878. if (typeof process !== 'undefined' && process.env) {
  13879. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13880. }
  13881. if (dbEmulatorHost) {
  13882. isEmulator = true;
  13883. dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
  13884. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13885. repoInfo = parsedUrl.repoInfo;
  13886. }
  13887. else {
  13888. isEmulator = !parsedUrl.repoInfo.secure;
  13889. }
  13890. var authTokenProvider = nodeAdmin && isEmulator
  13891. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13892. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13893. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13894. if (!pathIsEmpty(parsedUrl.path)) {
  13895. fatal('Database URL must point to the root of a Firebase Database ' +
  13896. '(not including a child path).');
  13897. }
  13898. var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13899. return new Database(repo, app);
  13900. }
  13901. /**
  13902. * Remove the repo and make sure it is disconnected.
  13903. *
  13904. */
  13905. function repoManagerDeleteRepo(repo, appName) {
  13906. var appRepos = repos[appName];
  13907. // This should never happen...
  13908. if (!appRepos || appRepos[repo.key] !== repo) {
  13909. fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
  13910. }
  13911. repoInterrupt(repo);
  13912. delete appRepos[repo.key];
  13913. }
  13914. /**
  13915. * Ensures a repo doesn't already exist and then creates one using the
  13916. * provided app.
  13917. *
  13918. * @param repoInfo - The metadata about the Repo
  13919. * @returns The Repo object for the specified server / repoName.
  13920. */
  13921. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13922. var appRepos = repos[app.name];
  13923. if (!appRepos) {
  13924. appRepos = {};
  13925. repos[app.name] = appRepos;
  13926. }
  13927. var repo = appRepos[repoInfo.toURLString()];
  13928. if (repo) {
  13929. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13930. }
  13931. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13932. appRepos[repoInfo.toURLString()] = repo;
  13933. return repo;
  13934. }
  13935. /**
  13936. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13937. */
  13938. function repoManagerForceRestClient(forceRestClient) {
  13939. useRestClient = forceRestClient;
  13940. }
  13941. /**
  13942. * Class representing a Firebase Realtime Database.
  13943. */
  13944. var Database = /** @class */ (function () {
  13945. /** @hideconstructor */
  13946. function Database(_repoInternal,
  13947. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13948. app) {
  13949. this._repoInternal = _repoInternal;
  13950. this.app = app;
  13951. /** Represents a `Database` instance. */
  13952. this['type'] = 'database';
  13953. /** Track if the instance has been used (root or repo accessed) */
  13954. this._instanceStarted = false;
  13955. }
  13956. Object.defineProperty(Database.prototype, "_repo", {
  13957. get: function () {
  13958. if (!this._instanceStarted) {
  13959. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13960. this._instanceStarted = true;
  13961. }
  13962. return this._repoInternal;
  13963. },
  13964. enumerable: false,
  13965. configurable: true
  13966. });
  13967. Object.defineProperty(Database.prototype, "_root", {
  13968. get: function () {
  13969. if (!this._rootInternal) {
  13970. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13971. }
  13972. return this._rootInternal;
  13973. },
  13974. enumerable: false,
  13975. configurable: true
  13976. });
  13977. Database.prototype._delete = function () {
  13978. if (this._rootInternal !== null) {
  13979. repoManagerDeleteRepo(this._repo, this.app.name);
  13980. this._repoInternal = null;
  13981. this._rootInternal = null;
  13982. }
  13983. return Promise.resolve();
  13984. };
  13985. Database.prototype._checkNotDeleted = function (apiName) {
  13986. if (this._rootInternal === null) {
  13987. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13988. }
  13989. };
  13990. return Database;
  13991. }());
  13992. function checkTransportInit() {
  13993. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13994. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13995. }
  13996. }
  13997. /**
  13998. * Force the use of websockets instead of longPolling.
  13999. */
  14000. function forceWebSockets() {
  14001. checkTransportInit();
  14002. BrowserPollConnection.forceDisallow();
  14003. }
  14004. /**
  14005. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  14006. */
  14007. function forceLongPolling() {
  14008. checkTransportInit();
  14009. WebSocketConnection.forceDisallow();
  14010. BrowserPollConnection.forceAllow();
  14011. }
  14012. /**
  14013. * Modify the provided instance to communicate with the Realtime Database
  14014. * emulator.
  14015. *
  14016. * <p>Note: This method must be called before performing any other operation.
  14017. *
  14018. * @param db - The instance to modify.
  14019. * @param host - The emulator host (ex: localhost)
  14020. * @param port - The emulator port (ex: 8080)
  14021. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  14022. */
  14023. function connectDatabaseEmulator(db, host, port, options) {
  14024. if (options === void 0) { options = {}; }
  14025. db = util.getModularInstance(db);
  14026. db._checkNotDeleted('useEmulator');
  14027. if (db._instanceStarted) {
  14028. fatal('Cannot call useEmulator() after instance has already been initialized.');
  14029. }
  14030. var repo = db._repoInternal;
  14031. var tokenProvider = undefined;
  14032. if (repo.repoInfo_.nodeAdmin) {
  14033. if (options.mockUserToken) {
  14034. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  14035. }
  14036. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  14037. }
  14038. else if (options.mockUserToken) {
  14039. var token = typeof options.mockUserToken === 'string'
  14040. ? options.mockUserToken
  14041. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  14042. tokenProvider = new EmulatorTokenProvider(token);
  14043. }
  14044. // Modify the repo to apply emulator settings
  14045. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  14046. }
  14047. /**
  14048. * Disconnects from the server (all Database operations will be completed
  14049. * offline).
  14050. *
  14051. * The client automatically maintains a persistent connection to the Database
  14052. * server, which will remain active indefinitely and reconnect when
  14053. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  14054. * to control the client connection in cases where a persistent connection is
  14055. * undesirable.
  14056. *
  14057. * While offline, the client will no longer receive data updates from the
  14058. * Database. However, all Database operations performed locally will continue to
  14059. * immediately fire events, allowing your application to continue behaving
  14060. * normally. Additionally, each operation performed locally will automatically
  14061. * be queued and retried upon reconnection to the Database server.
  14062. *
  14063. * To reconnect to the Database and begin receiving remote events, see
  14064. * `goOnline()`.
  14065. *
  14066. * @param db - The instance to disconnect.
  14067. */
  14068. function goOffline(db) {
  14069. db = util.getModularInstance(db);
  14070. db._checkNotDeleted('goOffline');
  14071. repoInterrupt(db._repo);
  14072. }
  14073. /**
  14074. * Reconnects to the server and synchronizes the offline Database state
  14075. * with the server state.
  14076. *
  14077. * This method should be used after disabling the active connection with
  14078. * `goOffline()`. Once reconnected, the client will transmit the proper data
  14079. * and fire the appropriate events so that your client "catches up"
  14080. * automatically.
  14081. *
  14082. * @param db - The instance to reconnect.
  14083. */
  14084. function goOnline(db) {
  14085. db = util.getModularInstance(db);
  14086. db._checkNotDeleted('goOnline');
  14087. repoResume(db._repo);
  14088. }
  14089. function enableLogging(logger, persistent) {
  14090. enableLogging$1(logger, persistent);
  14091. }
  14092. /**
  14093. * @license
  14094. * Copyright 2020 Google LLC
  14095. *
  14096. * Licensed under the Apache License, Version 2.0 (the "License");
  14097. * you may not use this file except in compliance with the License.
  14098. * You may obtain a copy of the License at
  14099. *
  14100. * http://www.apache.org/licenses/LICENSE-2.0
  14101. *
  14102. * Unless required by applicable law or agreed to in writing, software
  14103. * distributed under the License is distributed on an "AS IS" BASIS,
  14104. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14105. * See the License for the specific language governing permissions and
  14106. * limitations under the License.
  14107. */
  14108. var SERVER_TIMESTAMP = {
  14109. '.sv': 'timestamp'
  14110. };
  14111. /**
  14112. * Returns a placeholder value for auto-populating the current timestamp (time
  14113. * since the Unix epoch, in milliseconds) as determined by the Firebase
  14114. * servers.
  14115. */
  14116. function serverTimestamp() {
  14117. return SERVER_TIMESTAMP;
  14118. }
  14119. /**
  14120. * Returns a placeholder value that can be used to atomically increment the
  14121. * current database value by the provided delta.
  14122. *
  14123. * @param delta - the amount to modify the current value atomically.
  14124. * @returns A placeholder value for modifying data atomically server-side.
  14125. */
  14126. function increment(delta) {
  14127. return {
  14128. '.sv': {
  14129. 'increment': delta
  14130. }
  14131. };
  14132. }
  14133. /**
  14134. * @license
  14135. * Copyright 2020 Google LLC
  14136. *
  14137. * Licensed under the Apache License, Version 2.0 (the "License");
  14138. * you may not use this file except in compliance with the License.
  14139. * You may obtain a copy of the License at
  14140. *
  14141. * http://www.apache.org/licenses/LICENSE-2.0
  14142. *
  14143. * Unless required by applicable law or agreed to in writing, software
  14144. * distributed under the License is distributed on an "AS IS" BASIS,
  14145. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14146. * See the License for the specific language governing permissions and
  14147. * limitations under the License.
  14148. */
  14149. /**
  14150. * A type for the resolve value of {@link runTransaction}.
  14151. */
  14152. var TransactionResult = /** @class */ (function () {
  14153. /** @hideconstructor */
  14154. function TransactionResult(
  14155. /** Whether the transaction was successfully committed. */
  14156. committed,
  14157. /** The resulting data snapshot. */
  14158. snapshot) {
  14159. this.committed = committed;
  14160. this.snapshot = snapshot;
  14161. }
  14162. /** Returns a JSON-serializable representation of this object. */
  14163. TransactionResult.prototype.toJSON = function () {
  14164. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  14165. };
  14166. return TransactionResult;
  14167. }());
  14168. /**
  14169. * Atomically modifies the data at this location.
  14170. *
  14171. * Atomically modify the data at this location. Unlike a normal `set()`, which
  14172. * just overwrites the data regardless of its previous value, `runTransaction()` is
  14173. * used to modify the existing value to a new value, ensuring there are no
  14174. * conflicts with other clients writing to the same location at the same time.
  14175. *
  14176. * To accomplish this, you pass `runTransaction()` an update function which is
  14177. * used to transform the current value into a new value. If another client
  14178. * writes to the location before your new value is successfully written, your
  14179. * update function will be called again with the new current value, and the
  14180. * write will be retried. This will happen repeatedly until your write succeeds
  14181. * without conflict or you abort the transaction by not returning a value from
  14182. * your update function.
  14183. *
  14184. * Note: Modifying data with `set()` will cancel any pending transactions at
  14185. * that location, so extreme care should be taken if mixing `set()` and
  14186. * `runTransaction()` to update the same data.
  14187. *
  14188. * Note: When using transactions with Security and Firebase Rules in place, be
  14189. * aware that a client needs `.read` access in addition to `.write` access in
  14190. * order to perform a transaction. This is because the client-side nature of
  14191. * transactions requires the client to read the data in order to transactionally
  14192. * update it.
  14193. *
  14194. * @param ref - The location to atomically modify.
  14195. * @param transactionUpdate - A developer-supplied function which will be passed
  14196. * the current data stored at this location (as a JavaScript object). The
  14197. * function should return the new value it would like written (as a JavaScript
  14198. * object). If `undefined` is returned (i.e. you return with no arguments) the
  14199. * transaction will be aborted and the data at this location will not be
  14200. * modified.
  14201. * @param options - An options object to configure transactions.
  14202. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  14203. * callback to handle success and failure.
  14204. */
  14205. function runTransaction(ref,
  14206. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14207. transactionUpdate, options) {
  14208. var _a;
  14209. ref = util.getModularInstance(ref);
  14210. validateWritablePath('Reference.transaction', ref._path);
  14211. if (ref.key === '.length' || ref.key === '.keys') {
  14212. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  14213. }
  14214. var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  14215. var deferred = new util.Deferred();
  14216. var promiseComplete = function (error, committed, node) {
  14217. var dataSnapshot = null;
  14218. if (error) {
  14219. deferred.reject(error);
  14220. }
  14221. else {
  14222. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  14223. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  14224. }
  14225. };
  14226. // Add a watch to make sure we get server updates.
  14227. var unwatcher = onValue(ref, function () { });
  14228. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  14229. return deferred.promise;
  14230. }
  14231. /**
  14232. * @license
  14233. * Copyright 2017 Google LLC
  14234. *
  14235. * Licensed under the Apache License, Version 2.0 (the "License");
  14236. * you may not use this file except in compliance with the License.
  14237. * You may obtain a copy of the License at
  14238. *
  14239. * http://www.apache.org/licenses/LICENSE-2.0
  14240. *
  14241. * Unless required by applicable law or agreed to in writing, software
  14242. * distributed under the License is distributed on an "AS IS" BASIS,
  14243. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14244. * See the License for the specific language governing permissions and
  14245. * limitations under the License.
  14246. */
  14247. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14248. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  14249. this.sendRequest('q', { p: pathString }, onComplete);
  14250. };
  14251. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14252. PersistentConnection.prototype.echo = function (data, onEcho) {
  14253. this.sendRequest('echo', { d: data }, onEcho);
  14254. };
  14255. /**
  14256. * @internal
  14257. */
  14258. var hijackHash = function (newHash) {
  14259. var oldPut = PersistentConnection.prototype.put;
  14260. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  14261. if (hash !== undefined) {
  14262. hash = newHash();
  14263. }
  14264. oldPut.call(this, pathString, data, onComplete, hash);
  14265. };
  14266. return function () {
  14267. PersistentConnection.prototype.put = oldPut;
  14268. };
  14269. };
  14270. /**
  14271. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  14272. * @internal
  14273. */
  14274. var forceRestClient = function (forceRestClient) {
  14275. repoManagerForceRestClient(forceRestClient);
  14276. };
  14277. /**
  14278. * @license
  14279. * Copyright 2021 Google LLC
  14280. *
  14281. * Licensed under the Apache License, Version 2.0 (the "License");
  14282. * you may not use this file except in compliance with the License.
  14283. * You may obtain a copy of the License at
  14284. *
  14285. * http://www.apache.org/licenses/LICENSE-2.0
  14286. *
  14287. * Unless required by applicable law or agreed to in writing, software
  14288. * distributed under the License is distributed on an "AS IS" BASIS,
  14289. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14290. * See the License for the specific language governing permissions and
  14291. * limitations under the License.
  14292. */
  14293. setWebSocketImpl(Websocket__default["default"].Client);
  14294. exports.DataSnapshot = DataSnapshot;
  14295. exports.Database = Database;
  14296. exports.OnDisconnect = OnDisconnect;
  14297. exports.QueryConstraint = QueryConstraint;
  14298. exports.TransactionResult = TransactionResult;
  14299. exports._QueryImpl = QueryImpl;
  14300. exports._QueryParams = QueryParams;
  14301. exports._ReferenceImpl = ReferenceImpl;
  14302. exports._TEST_ACCESS_forceRestClient = forceRestClient;
  14303. exports._TEST_ACCESS_hijackHash = hijackHash;
  14304. exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  14305. exports._setSDKVersion = setSDKVersion;
  14306. exports._validatePathString = validatePathString;
  14307. exports._validateWritablePath = validateWritablePath;
  14308. exports.child = child;
  14309. exports.connectDatabaseEmulator = connectDatabaseEmulator;
  14310. exports.enableLogging = enableLogging;
  14311. exports.endAt = endAt;
  14312. exports.endBefore = endBefore;
  14313. exports.equalTo = equalTo;
  14314. exports.forceLongPolling = forceLongPolling;
  14315. exports.forceWebSockets = forceWebSockets;
  14316. exports.get = get;
  14317. exports.goOffline = goOffline;
  14318. exports.goOnline = goOnline;
  14319. exports.increment = increment;
  14320. exports.limitToFirst = limitToFirst;
  14321. exports.limitToLast = limitToLast;
  14322. exports.off = off;
  14323. exports.onChildAdded = onChildAdded;
  14324. exports.onChildChanged = onChildChanged;
  14325. exports.onChildMoved = onChildMoved;
  14326. exports.onChildRemoved = onChildRemoved;
  14327. exports.onDisconnect = onDisconnect;
  14328. exports.onValue = onValue;
  14329. exports.orderByChild = orderByChild;
  14330. exports.orderByKey = orderByKey;
  14331. exports.orderByPriority = orderByPriority;
  14332. exports.orderByValue = orderByValue;
  14333. exports.push = push;
  14334. exports.query = query;
  14335. exports.ref = ref;
  14336. exports.refFromURL = refFromURL;
  14337. exports.remove = remove;
  14338. exports.runTransaction = runTransaction;
  14339. exports.serverTimestamp = serverTimestamp;
  14340. exports.set = set;
  14341. exports.setPriority = setPriority;
  14342. exports.setWithPriority = setWithPriority;
  14343. exports.startAfter = startAfter;
  14344. exports.startAt = startAt;
  14345. exports.update = update;
  14346. //# sourceMappingURL=index.standalone.js.map