index.node.cjs.js 540 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var Websocket = require('faye-websocket');
  4. var util = require('@firebase/util');
  5. var logger$1 = require('@firebase/logger');
  6. var app = require('@firebase/app');
  7. var component = require('@firebase/component');
  8. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  9. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket);
  10. /**
  11. * @license
  12. * Copyright 2017 Google LLC
  13. *
  14. * Licensed under the Apache License, Version 2.0 (the "License");
  15. * you may not use this file except in compliance with the License.
  16. * You may obtain a copy of the License at
  17. *
  18. * http://www.apache.org/licenses/LICENSE-2.0
  19. *
  20. * Unless required by applicable law or agreed to in writing, software
  21. * distributed under the License is distributed on an "AS IS" BASIS,
  22. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. * See the License for the specific language governing permissions and
  24. * limitations under the License.
  25. */
  26. const PROTOCOL_VERSION = '5';
  27. const VERSION_PARAM = 'v';
  28. const TRANSPORT_SESSION_PARAM = 's';
  29. const REFERER_PARAM = 'r';
  30. const FORGE_REF = 'f';
  31. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  32. // firebase.corp.google.com
  33. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  34. const LAST_SESSION_PARAM = 'ls';
  35. const APPLICATION_ID_PARAM = 'p';
  36. const APP_CHECK_TOKEN_PARAM = 'ac';
  37. const WEBSOCKET = 'websocket';
  38. const LONG_POLLING = 'long_polling';
  39. /**
  40. * @license
  41. * Copyright 2017 Google LLC
  42. *
  43. * Licensed under the Apache License, Version 2.0 (the "License");
  44. * you may not use this file except in compliance with the License.
  45. * You may obtain a copy of the License at
  46. *
  47. * http://www.apache.org/licenses/LICENSE-2.0
  48. *
  49. * Unless required by applicable law or agreed to in writing, software
  50. * distributed under the License is distributed on an "AS IS" BASIS,
  51. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  52. * See the License for the specific language governing permissions and
  53. * limitations under the License.
  54. */
  55. /**
  56. * Wraps a DOM Storage object and:
  57. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  58. * - prefixes names with "firebase:" to avoid collisions with app data.
  59. *
  60. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  61. * and one for localStorage.
  62. *
  63. */
  64. class DOMStorageWrapper {
  65. /**
  66. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  67. */
  68. constructor(domStorage_) {
  69. this.domStorage_ = domStorage_;
  70. // Use a prefix to avoid collisions with other stuff saved by the app.
  71. this.prefix_ = 'firebase:';
  72. }
  73. /**
  74. * @param key - The key to save the value under
  75. * @param value - The value being stored, or null to remove the key.
  76. */
  77. set(key, value) {
  78. if (value == null) {
  79. this.domStorage_.removeItem(this.prefixedName_(key));
  80. }
  81. else {
  82. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  83. }
  84. }
  85. /**
  86. * @returns The value that was stored under this key, or null
  87. */
  88. get(key) {
  89. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  90. if (storedVal == null) {
  91. return null;
  92. }
  93. else {
  94. return util.jsonEval(storedVal);
  95. }
  96. }
  97. remove(key) {
  98. this.domStorage_.removeItem(this.prefixedName_(key));
  99. }
  100. prefixedName_(name) {
  101. return this.prefix_ + name;
  102. }
  103. toString() {
  104. return this.domStorage_.toString();
  105. }
  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. class MemoryStorage {
  128. constructor() {
  129. this.cache_ = {};
  130. this.isInMemoryStorage = true;
  131. }
  132. set(key, value) {
  133. if (value == null) {
  134. delete this.cache_[key];
  135. }
  136. else {
  137. this.cache_[key] = value;
  138. }
  139. }
  140. get(key) {
  141. if (util.contains(this.cache_, key)) {
  142. return this.cache_[key];
  143. }
  144. return null;
  145. }
  146. remove(key) {
  147. delete this.cache_[key];
  148. }
  149. }
  150. /**
  151. * @license
  152. * Copyright 2017 Google LLC
  153. *
  154. * Licensed under the Apache License, Version 2.0 (the "License");
  155. * you may not use this file except in compliance with the License.
  156. * You may obtain a copy of the License at
  157. *
  158. * http://www.apache.org/licenses/LICENSE-2.0
  159. *
  160. * Unless required by applicable law or agreed to in writing, software
  161. * distributed under the License is distributed on an "AS IS" BASIS,
  162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  163. * See the License for the specific language governing permissions and
  164. * limitations under the License.
  165. */
  166. /**
  167. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  168. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  169. * to reflect this type
  170. *
  171. * @param domStorageName - Name of the underlying storage object
  172. * (e.g. 'localStorage' or 'sessionStorage').
  173. * @returns Turning off type information until a common interface is defined.
  174. */
  175. const createStoragefor = function (domStorageName) {
  176. try {
  177. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  178. // so it must be inside the try/catch.
  179. if (typeof window !== 'undefined' &&
  180. typeof window[domStorageName] !== 'undefined') {
  181. // Need to test cache. Just because it's here doesn't mean it works
  182. const domStorage = window[domStorageName];
  183. domStorage.setItem('firebase:sentinel', 'cache');
  184. domStorage.removeItem('firebase:sentinel');
  185. return new DOMStorageWrapper(domStorage);
  186. }
  187. }
  188. catch (e) { }
  189. // Failed to create wrapper. Just return in-memory storage.
  190. // TODO: log?
  191. return new MemoryStorage();
  192. };
  193. /** A storage object that lasts across sessions */
  194. const PersistentStorage = createStoragefor('localStorage');
  195. /** A storage object that only lasts one session */
  196. const SessionStorage = createStoragefor('sessionStorage');
  197. /**
  198. * @license
  199. * Copyright 2017 Google LLC
  200. *
  201. * Licensed under the Apache License, Version 2.0 (the "License");
  202. * you may not use this file except in compliance with the License.
  203. * You may obtain a copy of the License at
  204. *
  205. * http://www.apache.org/licenses/LICENSE-2.0
  206. *
  207. * Unless required by applicable law or agreed to in writing, software
  208. * distributed under the License is distributed on an "AS IS" BASIS,
  209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  210. * See the License for the specific language governing permissions and
  211. * limitations under the License.
  212. */
  213. const logClient = new logger$1.Logger('@firebase/database');
  214. /**
  215. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  216. */
  217. const LUIDGenerator = (function () {
  218. let id = 1;
  219. return function () {
  220. return id++;
  221. };
  222. })();
  223. /**
  224. * Sha1 hash of the input string
  225. * @param str - The string to hash
  226. * @returns {!string} The resulting hash
  227. */
  228. const sha1 = function (str) {
  229. const utf8Bytes = util.stringToByteArray(str);
  230. const sha1 = new util.Sha1();
  231. sha1.update(utf8Bytes);
  232. const sha1Bytes = sha1.digest();
  233. return util.base64.encodeByteArray(sha1Bytes);
  234. };
  235. const buildLogMessage_ = function (...varArgs) {
  236. let message = '';
  237. for (let i = 0; i < varArgs.length; i++) {
  238. const arg = varArgs[i];
  239. if (Array.isArray(arg) ||
  240. (arg &&
  241. typeof arg === 'object' &&
  242. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  243. typeof arg.length === 'number')) {
  244. message += buildLogMessage_.apply(null, arg);
  245. }
  246. else if (typeof arg === 'object') {
  247. message += util.stringify(arg);
  248. }
  249. else {
  250. message += arg;
  251. }
  252. message += ' ';
  253. }
  254. return message;
  255. };
  256. /**
  257. * Use this for all debug messages in Firebase.
  258. */
  259. let logger = null;
  260. /**
  261. * Flag to check for log availability on first log message
  262. */
  263. let firstLog_ = true;
  264. /**
  265. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  266. * @param logger_ - A flag to turn on logging, or a custom logger
  267. * @param persistent - Whether or not to persist logging settings across refreshes
  268. */
  269. const enableLogging$1 = function (logger_, persistent) {
  270. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  271. if (logger_ === true) {
  272. logClient.logLevel = logger$1.LogLevel.VERBOSE;
  273. logger = logClient.log.bind(logClient);
  274. if (persistent) {
  275. SessionStorage.set('logging_enabled', true);
  276. }
  277. }
  278. else if (typeof logger_ === 'function') {
  279. logger = logger_;
  280. }
  281. else {
  282. logger = null;
  283. SessionStorage.remove('logging_enabled');
  284. }
  285. };
  286. const log = function (...varArgs) {
  287. if (firstLog_ === true) {
  288. firstLog_ = false;
  289. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  290. enableLogging$1(true);
  291. }
  292. }
  293. if (logger) {
  294. const message = buildLogMessage_.apply(null, varArgs);
  295. logger(message);
  296. }
  297. };
  298. const logWrapper = function (prefix) {
  299. return function (...varArgs) {
  300. log(prefix, ...varArgs);
  301. };
  302. };
  303. const error = function (...varArgs) {
  304. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  305. logClient.error(message);
  306. };
  307. const fatal = function (...varArgs) {
  308. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  309. logClient.error(message);
  310. throw new Error(message);
  311. };
  312. const warn = function (...varArgs) {
  313. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  314. logClient.warn(message);
  315. };
  316. /**
  317. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  318. * does not use https.
  319. */
  320. const warnIfPageIsSecure = function () {
  321. // Be very careful accessing browser globals. Who knows what may or may not exist.
  322. if (typeof window !== 'undefined' &&
  323. window.location &&
  324. window.location.protocol &&
  325. window.location.protocol.indexOf('https:') !== -1) {
  326. warn('Insecure Firebase access from a secure page. ' +
  327. 'Please use https in calls to new Firebase().');
  328. }
  329. };
  330. /**
  331. * Returns true if data is NaN, or +/- Infinity.
  332. */
  333. const isInvalidJSONNumber = function (data) {
  334. return (typeof data === 'number' &&
  335. (data !== data || // NaN
  336. data === Number.POSITIVE_INFINITY ||
  337. data === Number.NEGATIVE_INFINITY));
  338. };
  339. const executeWhenDOMReady = function (fn) {
  340. if (util.isNodeSdk() || document.readyState === 'complete') {
  341. fn();
  342. }
  343. else {
  344. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  345. // fire before onload), but fall back to onload.
  346. let called = false;
  347. const wrappedFn = function () {
  348. if (!document.body) {
  349. setTimeout(wrappedFn, Math.floor(10));
  350. return;
  351. }
  352. if (!called) {
  353. called = true;
  354. fn();
  355. }
  356. };
  357. if (document.addEventListener) {
  358. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  359. // fallback to onload.
  360. window.addEventListener('load', wrappedFn, false);
  361. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  362. }
  363. else if (document.attachEvent) {
  364. // IE.
  365. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  366. document.attachEvent('onreadystatechange', () => {
  367. if (document.readyState === 'complete') {
  368. wrappedFn();
  369. }
  370. });
  371. // fallback to onload.
  372. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  373. window.attachEvent('onload', wrappedFn);
  374. // jQuery has an extra hack for IE that we could employ (based on
  375. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  376. // I'm hoping we don't need it.
  377. }
  378. }
  379. };
  380. /**
  381. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  382. */
  383. const MIN_NAME = '[MIN_NAME]';
  384. /**
  385. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  386. */
  387. const MAX_NAME = '[MAX_NAME]';
  388. /**
  389. * Compares valid Firebase key names, plus min and max name
  390. */
  391. const nameCompare = function (a, b) {
  392. if (a === b) {
  393. return 0;
  394. }
  395. else if (a === MIN_NAME || b === MAX_NAME) {
  396. return -1;
  397. }
  398. else if (b === MIN_NAME || a === MAX_NAME) {
  399. return 1;
  400. }
  401. else {
  402. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  403. if (aAsInt !== null) {
  404. if (bAsInt !== null) {
  405. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  406. }
  407. else {
  408. return -1;
  409. }
  410. }
  411. else if (bAsInt !== null) {
  412. return 1;
  413. }
  414. else {
  415. return a < b ? -1 : 1;
  416. }
  417. }
  418. };
  419. /**
  420. * @returns {!number} comparison result.
  421. */
  422. const stringCompare = function (a, b) {
  423. if (a === b) {
  424. return 0;
  425. }
  426. else if (a < b) {
  427. return -1;
  428. }
  429. else {
  430. return 1;
  431. }
  432. };
  433. const requireKey = function (key, obj) {
  434. if (obj && key in obj) {
  435. return obj[key];
  436. }
  437. else {
  438. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  439. }
  440. };
  441. const ObjectToUniqueKey = function (obj) {
  442. if (typeof obj !== 'object' || obj === null) {
  443. return util.stringify(obj);
  444. }
  445. const keys = [];
  446. // eslint-disable-next-line guard-for-in
  447. for (const k in obj) {
  448. keys.push(k);
  449. }
  450. // Export as json, but with the keys sorted.
  451. keys.sort();
  452. let key = '{';
  453. for (let i = 0; i < keys.length; i++) {
  454. if (i !== 0) {
  455. key += ',';
  456. }
  457. key += util.stringify(keys[i]);
  458. key += ':';
  459. key += ObjectToUniqueKey(obj[keys[i]]);
  460. }
  461. key += '}';
  462. return key;
  463. };
  464. /**
  465. * Splits a string into a number of smaller segments of maximum size
  466. * @param str - The string
  467. * @param segsize - The maximum number of chars in the string.
  468. * @returns The string, split into appropriately-sized chunks
  469. */
  470. const splitStringBySize = function (str, segsize) {
  471. const len = str.length;
  472. if (len <= segsize) {
  473. return [str];
  474. }
  475. const dataSegs = [];
  476. for (let c = 0; c < len; c += segsize) {
  477. if (c + segsize > len) {
  478. dataSegs.push(str.substring(c, len));
  479. }
  480. else {
  481. dataSegs.push(str.substring(c, c + segsize));
  482. }
  483. }
  484. return dataSegs;
  485. };
  486. /**
  487. * Apply a function to each (key, value) pair in an object or
  488. * apply a function to each (index, value) pair in an array
  489. * @param obj - The object or array to iterate over
  490. * @param fn - The function to apply
  491. */
  492. function each(obj, fn) {
  493. for (const key in obj) {
  494. if (obj.hasOwnProperty(key)) {
  495. fn(key, obj[key]);
  496. }
  497. }
  498. }
  499. /**
  500. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  501. * I made one modification at the end and removed the NaN / Infinity
  502. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  503. * @param v - A double
  504. *
  505. */
  506. const doubleToIEEE754String = function (v) {
  507. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  508. const ebits = 11, fbits = 52;
  509. const bias = (1 << (ebits - 1)) - 1;
  510. let s, e, f, ln, i;
  511. // Compute sign, exponent, fraction
  512. // Skip NaN / Infinity handling --MJL.
  513. if (v === 0) {
  514. e = 0;
  515. f = 0;
  516. s = 1 / v === -Infinity ? 1 : 0;
  517. }
  518. else {
  519. s = v < 0;
  520. v = Math.abs(v);
  521. if (v >= Math.pow(2, 1 - bias)) {
  522. // Normalized
  523. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  524. e = ln + bias;
  525. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  526. }
  527. else {
  528. // Denormalized
  529. e = 0;
  530. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  531. }
  532. }
  533. // Pack sign, exponent, fraction
  534. const bits = [];
  535. for (i = fbits; i; i -= 1) {
  536. bits.push(f % 2 ? 1 : 0);
  537. f = Math.floor(f / 2);
  538. }
  539. for (i = ebits; i; i -= 1) {
  540. bits.push(e % 2 ? 1 : 0);
  541. e = Math.floor(e / 2);
  542. }
  543. bits.push(s ? 1 : 0);
  544. bits.reverse();
  545. const str = bits.join('');
  546. // Return the data as a hex string. --MJL
  547. let hexByteString = '';
  548. for (i = 0; i < 64; i += 8) {
  549. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  550. if (hexByte.length === 1) {
  551. hexByte = '0' + hexByte;
  552. }
  553. hexByteString = hexByteString + hexByte;
  554. }
  555. return hexByteString.toLowerCase();
  556. };
  557. /**
  558. * Used to detect if we're in a Chrome content script (which executes in an
  559. * isolated environment where long-polling doesn't work).
  560. */
  561. const isChromeExtensionContentScript = function () {
  562. return !!(typeof window === 'object' &&
  563. window['chrome'] &&
  564. window['chrome']['extension'] &&
  565. !/^chrome/.test(window.location.href));
  566. };
  567. /**
  568. * Used to detect if we're in a Windows 8 Store app.
  569. */
  570. const isWindowsStoreApp = function () {
  571. // Check for the presence of a couple WinRT globals
  572. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  573. };
  574. /**
  575. * Converts a server error code to a JavaScript Error
  576. */
  577. function errorForServerCode(code, query) {
  578. let reason = 'Unknown Error';
  579. if (code === 'too_big') {
  580. reason =
  581. 'The data requested exceeds the maximum size ' +
  582. 'that can be accessed with a single request.';
  583. }
  584. else if (code === 'permission_denied') {
  585. reason = "Client doesn't have permission to access the desired data.";
  586. }
  587. else if (code === 'unavailable') {
  588. reason = 'The service is unavailable';
  589. }
  590. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  591. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  592. error.code = code.toUpperCase();
  593. return error;
  594. }
  595. /**
  596. * Used to test for integer-looking strings
  597. */
  598. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  599. /**
  600. * For use in keys, the minimum possible 32-bit integer.
  601. */
  602. const INTEGER_32_MIN = -2147483648;
  603. /**
  604. * For use in keys, the maximum possible 32-bit integer.
  605. */
  606. const INTEGER_32_MAX = 2147483647;
  607. /**
  608. * If the string contains a 32-bit integer, return it. Else return null.
  609. */
  610. const tryParseInt = function (str) {
  611. if (INTEGER_REGEXP_.test(str)) {
  612. const intVal = Number(str);
  613. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  614. return intVal;
  615. }
  616. }
  617. return null;
  618. };
  619. /**
  620. * Helper to run some code but catch any exceptions and re-throw them later.
  621. * Useful for preventing user callbacks from breaking internal code.
  622. *
  623. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  624. * convenient (we don't have to try to figure out when is a safe point to
  625. * re-throw it), and the behavior seems reasonable:
  626. *
  627. * * If you aren't pausing on exceptions, you get an error in the console with
  628. * the correct stack trace.
  629. * * If you're pausing on all exceptions, the debugger will pause on your
  630. * exception and then again when we rethrow it.
  631. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  632. * on us re-throwing it.
  633. *
  634. * @param fn - The code to guard.
  635. */
  636. const exceptionGuard = function (fn) {
  637. try {
  638. fn();
  639. }
  640. catch (e) {
  641. // Re-throw exception when it's safe.
  642. setTimeout(() => {
  643. // It used to be that "throw e" would result in a good console error with
  644. // relevant context, but as of Chrome 39, you just get the firebase.js
  645. // file/line number where we re-throw it, which is useless. So we log
  646. // e.stack explicitly.
  647. const stack = e.stack || '';
  648. warn('Exception was thrown by user callback.', stack);
  649. throw e;
  650. }, Math.floor(0));
  651. }
  652. };
  653. /**
  654. * @returns {boolean} true if we think we're currently being crawled.
  655. */
  656. const beingCrawled = function () {
  657. const userAgent = (typeof window === 'object' &&
  658. window['navigator'] &&
  659. window['navigator']['userAgent']) ||
  660. '';
  661. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  662. // believe to support JavaScript/AJAX rendering.
  663. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  664. // would have seen the page" is flaky if we don't treat it as a crawler.
  665. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  666. };
  667. /**
  668. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  669. *
  670. * It is removed with clearTimeout() as normal.
  671. *
  672. * @param fn - Function to run.
  673. * @param time - Milliseconds to wait before running.
  674. * @returns The setTimeout() return value.
  675. */
  676. const setTimeoutNonBlocking = function (fn, time) {
  677. const timeout = setTimeout(fn, time);
  678. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  679. if (typeof timeout === 'number' &&
  680. // @ts-ignore Is only defined in Deno environments.
  681. typeof Deno !== 'undefined' &&
  682. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  683. Deno['unrefTimer']) {
  684. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  685. Deno.unrefTimer(timeout);
  686. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  687. }
  688. else if (typeof timeout === 'object' && timeout['unref']) {
  689. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  690. timeout['unref']();
  691. }
  692. return timeout;
  693. };
  694. /**
  695. * @license
  696. * Copyright 2017 Google LLC
  697. *
  698. * Licensed under the Apache License, Version 2.0 (the "License");
  699. * you may not use this file except in compliance with the License.
  700. * You may obtain a copy of the License at
  701. *
  702. * http://www.apache.org/licenses/LICENSE-2.0
  703. *
  704. * Unless required by applicable law or agreed to in writing, software
  705. * distributed under the License is distributed on an "AS IS" BASIS,
  706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  707. * See the License for the specific language governing permissions and
  708. * limitations under the License.
  709. */
  710. /**
  711. * A class that holds metadata about a Repo object
  712. */
  713. class RepoInfo {
  714. /**
  715. * @param host - Hostname portion of the url for the repo
  716. * @param secure - Whether or not this repo is accessed over ssl
  717. * @param namespace - The namespace represented by the repo
  718. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  719. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  720. * @param persistenceKey - Override the default session persistence storage key
  721. */
  722. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {
  723. this.secure = secure;
  724. this.namespace = namespace;
  725. this.webSocketOnly = webSocketOnly;
  726. this.nodeAdmin = nodeAdmin;
  727. this.persistenceKey = persistenceKey;
  728. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  729. this.isUsingEmulator = isUsingEmulator;
  730. this._host = host.toLowerCase();
  731. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  732. this.internalHost =
  733. PersistentStorage.get('host:' + host) || this._host;
  734. }
  735. isCacheableHost() {
  736. return this.internalHost.substr(0, 2) === 's-';
  737. }
  738. isCustomHost() {
  739. return (this._domain !== 'firebaseio.com' &&
  740. this._domain !== 'firebaseio-demo.com');
  741. }
  742. get host() {
  743. return this._host;
  744. }
  745. set host(newHost) {
  746. if (newHost !== this.internalHost) {
  747. this.internalHost = newHost;
  748. if (this.isCacheableHost()) {
  749. PersistentStorage.set('host:' + this._host, this.internalHost);
  750. }
  751. }
  752. }
  753. toString() {
  754. let str = this.toURLString();
  755. if (this.persistenceKey) {
  756. str += '<' + this.persistenceKey + '>';
  757. }
  758. return str;
  759. }
  760. toURLString() {
  761. const protocol = this.secure ? 'https://' : 'http://';
  762. const query = this.includeNamespaceInQueryParams
  763. ? `?ns=${this.namespace}`
  764. : '';
  765. return `${protocol}${this.host}/${query}`;
  766. }
  767. }
  768. function repoInfoNeedsQueryParam(repoInfo) {
  769. return (repoInfo.host !== repoInfo.internalHost ||
  770. repoInfo.isCustomHost() ||
  771. repoInfo.includeNamespaceInQueryParams);
  772. }
  773. /**
  774. * Returns the websocket URL for this repo
  775. * @param repoInfo - RepoInfo object
  776. * @param type - of connection
  777. * @param params - list
  778. * @returns The URL for this repo
  779. */
  780. function repoInfoConnectionURL(repoInfo, type, params) {
  781. util.assert(typeof type === 'string', 'typeof type must == string');
  782. util.assert(typeof params === 'object', 'typeof params must == object');
  783. let connURL;
  784. if (type === WEBSOCKET) {
  785. connURL =
  786. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  787. }
  788. else if (type === LONG_POLLING) {
  789. connURL =
  790. (repoInfo.secure ? 'https://' : 'http://') +
  791. repoInfo.internalHost +
  792. '/.lp?';
  793. }
  794. else {
  795. throw new Error('Unknown connection type: ' + type);
  796. }
  797. if (repoInfoNeedsQueryParam(repoInfo)) {
  798. params['ns'] = repoInfo.namespace;
  799. }
  800. const pairs = [];
  801. each(params, (key, value) => {
  802. pairs.push(key + '=' + value);
  803. });
  804. return connURL + pairs.join('&');
  805. }
  806. /**
  807. * @license
  808. * Copyright 2017 Google LLC
  809. *
  810. * Licensed under the Apache License, Version 2.0 (the "License");
  811. * you may not use this file except in compliance with the License.
  812. * You may obtain a copy of the License at
  813. *
  814. * http://www.apache.org/licenses/LICENSE-2.0
  815. *
  816. * Unless required by applicable law or agreed to in writing, software
  817. * distributed under the License is distributed on an "AS IS" BASIS,
  818. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  819. * See the License for the specific language governing permissions and
  820. * limitations under the License.
  821. */
  822. /**
  823. * Tracks a collection of stats.
  824. */
  825. class StatsCollection {
  826. constructor() {
  827. this.counters_ = {};
  828. }
  829. incrementCounter(name, amount = 1) {
  830. if (!util.contains(this.counters_, name)) {
  831. this.counters_[name] = 0;
  832. }
  833. this.counters_[name] += amount;
  834. }
  835. get() {
  836. return util.deepCopy(this.counters_);
  837. }
  838. }
  839. /**
  840. * @license
  841. * Copyright 2017 Google LLC
  842. *
  843. * Licensed under the Apache License, Version 2.0 (the "License");
  844. * you may not use this file except in compliance with the License.
  845. * You may obtain a copy of the License at
  846. *
  847. * http://www.apache.org/licenses/LICENSE-2.0
  848. *
  849. * Unless required by applicable law or agreed to in writing, software
  850. * distributed under the License is distributed on an "AS IS" BASIS,
  851. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  852. * See the License for the specific language governing permissions and
  853. * limitations under the License.
  854. */
  855. const collections = {};
  856. const reporters = {};
  857. function statsManagerGetCollection(repoInfo) {
  858. const hashString = repoInfo.toString();
  859. if (!collections[hashString]) {
  860. collections[hashString] = new StatsCollection();
  861. }
  862. return collections[hashString];
  863. }
  864. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  865. const hashString = repoInfo.toString();
  866. if (!reporters[hashString]) {
  867. reporters[hashString] = creatorFunction();
  868. }
  869. return reporters[hashString];
  870. }
  871. /**
  872. * @license
  873. * Copyright 2019 Google LLC
  874. *
  875. * Licensed under the Apache License, Version 2.0 (the "License");
  876. * you may not use this file except in compliance with the License.
  877. * You may obtain a copy of the License at
  878. *
  879. * http://www.apache.org/licenses/LICENSE-2.0
  880. *
  881. * Unless required by applicable law or agreed to in writing, software
  882. * distributed under the License is distributed on an "AS IS" BASIS,
  883. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  884. * See the License for the specific language governing permissions and
  885. * limitations under the License.
  886. */
  887. /** The semver (www.semver.org) version of the SDK. */
  888. let SDK_VERSION = '';
  889. /**
  890. * SDK_VERSION should be set before any database instance is created
  891. * @internal
  892. */
  893. function setSDKVersion(version) {
  894. SDK_VERSION = version;
  895. }
  896. /**
  897. * @license
  898. * Copyright 2017 Google LLC
  899. *
  900. * Licensed under the Apache License, Version 2.0 (the "License");
  901. * you may not use this file except in compliance with the License.
  902. * You may obtain a copy of the License at
  903. *
  904. * http://www.apache.org/licenses/LICENSE-2.0
  905. *
  906. * Unless required by applicable law or agreed to in writing, software
  907. * distributed under the License is distributed on an "AS IS" BASIS,
  908. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  909. * See the License for the specific language governing permissions and
  910. * limitations under the License.
  911. */
  912. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  913. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  914. let WebSocketImpl = null;
  915. if (typeof MozWebSocket !== 'undefined') {
  916. WebSocketImpl = MozWebSocket;
  917. }
  918. else if (typeof WebSocket !== 'undefined') {
  919. WebSocketImpl = WebSocket;
  920. }
  921. function setWebSocketImpl(impl) {
  922. WebSocketImpl = impl;
  923. }
  924. /**
  925. * Create a new websocket connection with the given callbacks.
  926. */
  927. class WebSocketConnection {
  928. /**
  929. * @param connId identifier for this transport
  930. * @param repoInfo The info for the websocket endpoint.
  931. * @param applicationId The Firebase App ID for this project.
  932. * @param appCheckToken The App Check Token for this client.
  933. * @param authToken The Auth Token for this client.
  934. * @param transportSessionId Optional transportSessionId if this is connecting
  935. * to an existing transport session
  936. * @param lastSessionId Optional lastSessionId if there was a previous
  937. * connection
  938. */
  939. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  940. this.connId = connId;
  941. this.applicationId = applicationId;
  942. this.appCheckToken = appCheckToken;
  943. this.authToken = authToken;
  944. this.keepaliveTimer = null;
  945. this.frames = null;
  946. this.totalFrames = 0;
  947. this.bytesSent = 0;
  948. this.bytesReceived = 0;
  949. this.log_ = logWrapper(this.connId);
  950. this.stats_ = statsManagerGetCollection(repoInfo);
  951. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  952. this.nodeAdmin = repoInfo.nodeAdmin;
  953. }
  954. /**
  955. * @param repoInfo - The info for the websocket endpoint.
  956. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  957. * session
  958. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  959. * @returns connection url
  960. */
  961. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  962. const urlParams = {};
  963. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  964. if (!util.isNodeSdk() &&
  965. typeof location !== 'undefined' &&
  966. location.hostname &&
  967. FORGE_DOMAIN_RE.test(location.hostname)) {
  968. urlParams[REFERER_PARAM] = FORGE_REF;
  969. }
  970. if (transportSessionId) {
  971. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  972. }
  973. if (lastSessionId) {
  974. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  975. }
  976. if (appCheckToken) {
  977. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  978. }
  979. if (applicationId) {
  980. urlParams[APPLICATION_ID_PARAM] = applicationId;
  981. }
  982. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  983. }
  984. /**
  985. * @param onMessage - Callback when messages arrive
  986. * @param onDisconnect - Callback with connection lost.
  987. */
  988. open(onMessage, onDisconnect) {
  989. this.onDisconnect = onDisconnect;
  990. this.onMessage = onMessage;
  991. this.log_('Websocket connecting to ' + this.connURL);
  992. this.everConnected_ = false;
  993. // Assume failure until proven otherwise.
  994. PersistentStorage.set('previous_websocket_failure', true);
  995. try {
  996. let options;
  997. if (util.isNodeSdk()) {
  998. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  999. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1000. options = {
  1001. headers: {
  1002. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  1003. 'X-Firebase-GMPID': this.applicationId || ''
  1004. }
  1005. };
  1006. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1007. // Note that we send the credentials here even if they aren't admin credentials, which is
  1008. // not a problem.
  1009. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1010. // through the websocket connection once it is established.
  1011. if (this.authToken) {
  1012. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1013. }
  1014. if (this.appCheckToken) {
  1015. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1016. }
  1017. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1018. const env = process['env'];
  1019. const proxy = this.connURL.indexOf('wss://') === 0
  1020. ? env['HTTPS_PROXY'] || env['https_proxy']
  1021. : env['HTTP_PROXY'] || env['http_proxy'];
  1022. if (proxy) {
  1023. options['proxy'] = { origin: proxy };
  1024. }
  1025. }
  1026. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1027. }
  1028. catch (e) {
  1029. this.log_('Error instantiating WebSocket.');
  1030. const error = e.message || e.data;
  1031. if (error) {
  1032. this.log_(error);
  1033. }
  1034. this.onClosed_();
  1035. return;
  1036. }
  1037. this.mySock.onopen = () => {
  1038. this.log_('Websocket connected.');
  1039. this.everConnected_ = true;
  1040. };
  1041. this.mySock.onclose = () => {
  1042. this.log_('Websocket connection was disconnected.');
  1043. this.mySock = null;
  1044. this.onClosed_();
  1045. };
  1046. this.mySock.onmessage = m => {
  1047. this.handleIncomingFrame(m);
  1048. };
  1049. this.mySock.onerror = e => {
  1050. this.log_('WebSocket error. Closing connection.');
  1051. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1052. const error = e.message || e.data;
  1053. if (error) {
  1054. this.log_(error);
  1055. }
  1056. this.onClosed_();
  1057. };
  1058. }
  1059. /**
  1060. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1061. */
  1062. start() { }
  1063. static forceDisallow() {
  1064. WebSocketConnection.forceDisallow_ = true;
  1065. }
  1066. static isAvailable() {
  1067. let isOldAndroid = false;
  1068. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1069. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1070. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1071. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1072. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1073. isOldAndroid = true;
  1074. }
  1075. }
  1076. }
  1077. return (!isOldAndroid &&
  1078. WebSocketImpl !== null &&
  1079. !WebSocketConnection.forceDisallow_);
  1080. }
  1081. /**
  1082. * Returns true if we previously failed to connect with this transport.
  1083. */
  1084. static previouslyFailed() {
  1085. // If our persistent storage is actually only in-memory storage,
  1086. // we default to assuming that it previously failed to be safe.
  1087. return (PersistentStorage.isInMemoryStorage ||
  1088. PersistentStorage.get('previous_websocket_failure') === true);
  1089. }
  1090. markConnectionHealthy() {
  1091. PersistentStorage.remove('previous_websocket_failure');
  1092. }
  1093. appendFrame_(data) {
  1094. this.frames.push(data);
  1095. if (this.frames.length === this.totalFrames) {
  1096. const fullMess = this.frames.join('');
  1097. this.frames = null;
  1098. const jsonMess = util.jsonEval(fullMess);
  1099. //handle the message
  1100. this.onMessage(jsonMess);
  1101. }
  1102. }
  1103. /**
  1104. * @param frameCount - The number of frames we are expecting from the server
  1105. */
  1106. handleNewFrameCount_(frameCount) {
  1107. this.totalFrames = frameCount;
  1108. this.frames = [];
  1109. }
  1110. /**
  1111. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1112. * @returns Any remaining data to be process, or null if there is none
  1113. */
  1114. extractFrameCount_(data) {
  1115. util.assert(this.frames === null, 'We already have a frame buffer');
  1116. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1117. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1118. if (data.length <= 6) {
  1119. const frameCount = Number(data);
  1120. if (!isNaN(frameCount)) {
  1121. this.handleNewFrameCount_(frameCount);
  1122. return null;
  1123. }
  1124. }
  1125. this.handleNewFrameCount_(1);
  1126. return data;
  1127. }
  1128. /**
  1129. * Process a websocket frame that has arrived from the server.
  1130. * @param mess - The frame data
  1131. */
  1132. handleIncomingFrame(mess) {
  1133. if (this.mySock === null) {
  1134. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1135. }
  1136. const data = mess['data'];
  1137. this.bytesReceived += data.length;
  1138. this.stats_.incrementCounter('bytes_received', data.length);
  1139. this.resetKeepAlive();
  1140. if (this.frames !== null) {
  1141. // we're buffering
  1142. this.appendFrame_(data);
  1143. }
  1144. else {
  1145. // try to parse out a frame count, otherwise, assume 1 and process it
  1146. const remainingData = this.extractFrameCount_(data);
  1147. if (remainingData !== null) {
  1148. this.appendFrame_(remainingData);
  1149. }
  1150. }
  1151. }
  1152. /**
  1153. * Send a message to the server
  1154. * @param data - The JSON object to transmit
  1155. */
  1156. send(data) {
  1157. this.resetKeepAlive();
  1158. const dataStr = util.stringify(data);
  1159. this.bytesSent += dataStr.length;
  1160. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1161. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1162. //up into multiple pieces if it doesn't fit in one request.
  1163. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1164. //Send the length header
  1165. if (dataSegs.length > 1) {
  1166. this.sendString_(String(dataSegs.length));
  1167. }
  1168. //Send the actual data in segments.
  1169. for (let i = 0; i < dataSegs.length; i++) {
  1170. this.sendString_(dataSegs[i]);
  1171. }
  1172. }
  1173. shutdown_() {
  1174. this.isClosed_ = true;
  1175. if (this.keepaliveTimer) {
  1176. clearInterval(this.keepaliveTimer);
  1177. this.keepaliveTimer = null;
  1178. }
  1179. if (this.mySock) {
  1180. this.mySock.close();
  1181. this.mySock = null;
  1182. }
  1183. }
  1184. onClosed_() {
  1185. if (!this.isClosed_) {
  1186. this.log_('WebSocket is closing itself');
  1187. this.shutdown_();
  1188. // since this is an internal close, trigger the close listener
  1189. if (this.onDisconnect) {
  1190. this.onDisconnect(this.everConnected_);
  1191. this.onDisconnect = null;
  1192. }
  1193. }
  1194. }
  1195. /**
  1196. * External-facing close handler.
  1197. * Close the websocket and kill the connection.
  1198. */
  1199. close() {
  1200. if (!this.isClosed_) {
  1201. this.log_('WebSocket is being closed');
  1202. this.shutdown_();
  1203. }
  1204. }
  1205. /**
  1206. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1207. * the last activity.
  1208. */
  1209. resetKeepAlive() {
  1210. clearInterval(this.keepaliveTimer);
  1211. this.keepaliveTimer = setInterval(() => {
  1212. //If there has been no websocket activity for a while, send a no-op
  1213. if (this.mySock) {
  1214. this.sendString_('0');
  1215. }
  1216. this.resetKeepAlive();
  1217. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1218. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1219. }
  1220. /**
  1221. * Send a string over the websocket.
  1222. *
  1223. * @param str - String to send.
  1224. */
  1225. sendString_(str) {
  1226. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1227. // calls for some unknown reason. We treat these as an error and disconnect.
  1228. // See https://app.asana.com/0/58926111402292/68021340250410
  1229. try {
  1230. this.mySock.send(str);
  1231. }
  1232. catch (e) {
  1233. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1234. setTimeout(this.onClosed_.bind(this), 0);
  1235. }
  1236. }
  1237. }
  1238. /**
  1239. * Number of response before we consider the connection "healthy."
  1240. */
  1241. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1242. /**
  1243. * Time to wait for the connection te become healthy before giving up.
  1244. */
  1245. WebSocketConnection.healthyTimeout = 30000;
  1246. const name = "@firebase/database";
  1247. const version = "1.0.9";
  1248. /**
  1249. * @license
  1250. * Copyright 2021 Google LLC
  1251. *
  1252. * Licensed under the Apache License, Version 2.0 (the "License");
  1253. * you may not use this file except in compliance with the License.
  1254. * You may obtain a copy of the License at
  1255. *
  1256. * http://www.apache.org/licenses/LICENSE-2.0
  1257. *
  1258. * Unless required by applicable law or agreed to in writing, software
  1259. * distributed under the License is distributed on an "AS IS" BASIS,
  1260. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1261. * See the License for the specific language governing permissions and
  1262. * limitations under the License.
  1263. */
  1264. /**
  1265. * Abstraction around AppCheck's token fetching capabilities.
  1266. */
  1267. class AppCheckTokenProvider {
  1268. constructor(appName_, appCheckProvider) {
  1269. this.appName_ = appName_;
  1270. this.appCheckProvider = appCheckProvider;
  1271. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1272. if (!this.appCheck) {
  1273. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  1274. }
  1275. }
  1276. getToken(forceRefresh) {
  1277. if (!this.appCheck) {
  1278. return new Promise((resolve, reject) => {
  1279. // Support delayed initialization of FirebaseAppCheck. This allows our
  1280. // customers to initialize the RTDB SDK before initializing Firebase
  1281. // AppCheck and ensures that all requests are authenticated if a token
  1282. // becomes available before the timeout below expires.
  1283. setTimeout(() => {
  1284. if (this.appCheck) {
  1285. this.getToken(forceRefresh).then(resolve, reject);
  1286. }
  1287. else {
  1288. resolve(null);
  1289. }
  1290. }, 0);
  1291. });
  1292. }
  1293. return this.appCheck.getToken(forceRefresh);
  1294. }
  1295. addTokenChangeListener(listener) {
  1296. var _a;
  1297. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  1298. }
  1299. notifyForInvalidToken() {
  1300. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  1301. 'are invalid. This usually indicates your app was not initialized correctly.');
  1302. }
  1303. }
  1304. /**
  1305. * @license
  1306. * Copyright 2017 Google LLC
  1307. *
  1308. * Licensed under the Apache License, Version 2.0 (the "License");
  1309. * you may not use this file except in compliance with the License.
  1310. * You may obtain a copy of the License at
  1311. *
  1312. * http://www.apache.org/licenses/LICENSE-2.0
  1313. *
  1314. * Unless required by applicable law or agreed to in writing, software
  1315. * distributed under the License is distributed on an "AS IS" BASIS,
  1316. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1317. * See the License for the specific language governing permissions and
  1318. * limitations under the License.
  1319. */
  1320. /**
  1321. * Abstraction around FirebaseApp's token fetching capabilities.
  1322. */
  1323. class FirebaseAuthTokenProvider {
  1324. constructor(appName_, firebaseOptions_, authProvider_) {
  1325. this.appName_ = appName_;
  1326. this.firebaseOptions_ = firebaseOptions_;
  1327. this.authProvider_ = authProvider_;
  1328. this.auth_ = null;
  1329. this.auth_ = authProvider_.getImmediate({ optional: true });
  1330. if (!this.auth_) {
  1331. authProvider_.onInit(auth => (this.auth_ = auth));
  1332. }
  1333. }
  1334. getToken(forceRefresh) {
  1335. if (!this.auth_) {
  1336. return new Promise((resolve, reject) => {
  1337. // Support delayed initialization of FirebaseAuth. This allows our
  1338. // customers to initialize the RTDB SDK before initializing Firebase
  1339. // Auth and ensures that all requests are authenticated if a token
  1340. // becomes available before the timeout below expires.
  1341. setTimeout(() => {
  1342. if (this.auth_) {
  1343. this.getToken(forceRefresh).then(resolve, reject);
  1344. }
  1345. else {
  1346. resolve(null);
  1347. }
  1348. }, 0);
  1349. });
  1350. }
  1351. return this.auth_.getToken(forceRefresh).catch(error => {
  1352. // TODO: Need to figure out all the cases this is raised and whether
  1353. // this makes sense.
  1354. if (error && error.code === 'auth/token-not-initialized') {
  1355. log('Got auth/token-not-initialized error. Treating as null token.');
  1356. return null;
  1357. }
  1358. else {
  1359. return Promise.reject(error);
  1360. }
  1361. });
  1362. }
  1363. addTokenChangeListener(listener) {
  1364. // TODO: We might want to wrap the listener and call it with no args to
  1365. // avoid a leaky abstraction, but that makes removing the listener harder.
  1366. if (this.auth_) {
  1367. this.auth_.addAuthTokenListener(listener);
  1368. }
  1369. else {
  1370. this.authProvider_
  1371. .get()
  1372. .then(auth => auth.addAuthTokenListener(listener));
  1373. }
  1374. }
  1375. removeTokenChangeListener(listener) {
  1376. this.authProvider_
  1377. .get()
  1378. .then(auth => auth.removeAuthTokenListener(listener));
  1379. }
  1380. notifyForInvalidToken() {
  1381. let errorMessage = 'Provided authentication credentials for the app named "' +
  1382. this.appName_ +
  1383. '" are invalid. This usually indicates your app was not ' +
  1384. 'initialized correctly. ';
  1385. if ('credential' in this.firebaseOptions_) {
  1386. errorMessage +=
  1387. 'Make sure the "credential" property provided to initializeApp() ' +
  1388. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1389. 'project.';
  1390. }
  1391. else if ('serviceAccount' in this.firebaseOptions_) {
  1392. errorMessage +=
  1393. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1394. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1395. 'project.';
  1396. }
  1397. else {
  1398. errorMessage +=
  1399. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1400. 'initializeApp() match the values provided for your app at ' +
  1401. 'https://console.firebase.google.com/.';
  1402. }
  1403. warn(errorMessage);
  1404. }
  1405. }
  1406. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1407. class EmulatorTokenProvider {
  1408. constructor(accessToken) {
  1409. this.accessToken = accessToken;
  1410. }
  1411. getToken(forceRefresh) {
  1412. return Promise.resolve({
  1413. accessToken: this.accessToken
  1414. });
  1415. }
  1416. addTokenChangeListener(listener) {
  1417. // Invoke the listener immediately to match the behavior in Firebase Auth
  1418. // (see packages/auth/src/auth.js#L1807)
  1419. listener(this.accessToken);
  1420. }
  1421. removeTokenChangeListener(listener) { }
  1422. notifyForInvalidToken() { }
  1423. }
  1424. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1425. EmulatorTokenProvider.OWNER = 'owner';
  1426. /**
  1427. * @license
  1428. * Copyright 2017 Google LLC
  1429. *
  1430. * Licensed under the Apache License, Version 2.0 (the "License");
  1431. * you may not use this file except in compliance with the License.
  1432. * You may obtain a copy of the License at
  1433. *
  1434. * http://www.apache.org/licenses/LICENSE-2.0
  1435. *
  1436. * Unless required by applicable law or agreed to in writing, software
  1437. * distributed under the License is distributed on an "AS IS" BASIS,
  1438. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1439. * See the License for the specific language governing permissions and
  1440. * limitations under the License.
  1441. */
  1442. /**
  1443. * This class ensures the packets from the server arrive in order
  1444. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1445. */
  1446. class PacketReceiver {
  1447. /**
  1448. * @param onMessage_
  1449. */
  1450. constructor(onMessage_) {
  1451. this.onMessage_ = onMessage_;
  1452. this.pendingResponses = [];
  1453. this.currentResponseNum = 0;
  1454. this.closeAfterResponse = -1;
  1455. this.onClose = null;
  1456. }
  1457. closeAfter(responseNum, callback) {
  1458. this.closeAfterResponse = responseNum;
  1459. this.onClose = callback;
  1460. if (this.closeAfterResponse < this.currentResponseNum) {
  1461. this.onClose();
  1462. this.onClose = null;
  1463. }
  1464. }
  1465. /**
  1466. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1467. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1468. * browsers will respond in the same order as the requests we sent
  1469. */
  1470. handleResponse(requestNum, data) {
  1471. this.pendingResponses[requestNum] = data;
  1472. while (this.pendingResponses[this.currentResponseNum]) {
  1473. const toProcess = this.pendingResponses[this.currentResponseNum];
  1474. delete this.pendingResponses[this.currentResponseNum];
  1475. for (let i = 0; i < toProcess.length; ++i) {
  1476. if (toProcess[i]) {
  1477. exceptionGuard(() => {
  1478. this.onMessage_(toProcess[i]);
  1479. });
  1480. }
  1481. }
  1482. if (this.currentResponseNum === this.closeAfterResponse) {
  1483. if (this.onClose) {
  1484. this.onClose();
  1485. this.onClose = null;
  1486. }
  1487. break;
  1488. }
  1489. this.currentResponseNum++;
  1490. }
  1491. }
  1492. }
  1493. /**
  1494. * @license
  1495. * Copyright 2017 Google LLC
  1496. *
  1497. * Licensed under the Apache License, Version 2.0 (the "License");
  1498. * you may not use this file except in compliance with the License.
  1499. * You may obtain a copy of the License at
  1500. *
  1501. * http://www.apache.org/licenses/LICENSE-2.0
  1502. *
  1503. * Unless required by applicable law or agreed to in writing, software
  1504. * distributed under the License is distributed on an "AS IS" BASIS,
  1505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1506. * See the License for the specific language governing permissions and
  1507. * limitations under the License.
  1508. */
  1509. // URL query parameters associated with longpolling
  1510. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1511. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1512. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1513. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1514. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1515. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1516. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1517. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1518. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1519. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1520. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1521. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1522. //Data size constants.
  1523. //TODO: Perf: the maximum length actually differs from browser to browser.
  1524. // We should check what browser we're on and set accordingly.
  1525. const MAX_URL_DATA_SIZE = 1870;
  1526. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1527. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1528. /**
  1529. * Keepalive period
  1530. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1531. * length of 30 seconds that we can't exceed.
  1532. */
  1533. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1534. /**
  1535. * How long to wait before aborting a long-polling connection attempt.
  1536. */
  1537. const LP_CONNECT_TIMEOUT = 30000;
  1538. /**
  1539. * This class manages a single long-polling connection.
  1540. */
  1541. class BrowserPollConnection {
  1542. /**
  1543. * @param connId An identifier for this connection, used for logging
  1544. * @param repoInfo The info for the endpoint to send data to.
  1545. * @param applicationId The Firebase App ID for this project.
  1546. * @param appCheckToken The AppCheck token for this client.
  1547. * @param authToken The AuthToken to use for this connection.
  1548. * @param transportSessionId Optional transportSessionid if we are
  1549. * reconnecting for an existing transport session
  1550. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1551. * already created a connection previously
  1552. */
  1553. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1554. this.connId = connId;
  1555. this.repoInfo = repoInfo;
  1556. this.applicationId = applicationId;
  1557. this.appCheckToken = appCheckToken;
  1558. this.authToken = authToken;
  1559. this.transportSessionId = transportSessionId;
  1560. this.lastSessionId = lastSessionId;
  1561. this.bytesSent = 0;
  1562. this.bytesReceived = 0;
  1563. this.everConnected_ = false;
  1564. this.log_ = logWrapper(connId);
  1565. this.stats_ = statsManagerGetCollection(repoInfo);
  1566. this.urlFn = (params) => {
  1567. // Always add the token if we have one.
  1568. if (this.appCheckToken) {
  1569. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1570. }
  1571. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1572. };
  1573. }
  1574. /**
  1575. * @param onMessage - Callback when messages arrive
  1576. * @param onDisconnect - Callback with connection lost.
  1577. */
  1578. open(onMessage, onDisconnect) {
  1579. this.curSegmentNum = 0;
  1580. this.onDisconnect_ = onDisconnect;
  1581. this.myPacketOrderer = new PacketReceiver(onMessage);
  1582. this.isClosed_ = false;
  1583. this.connectTimeoutTimer_ = setTimeout(() => {
  1584. this.log_('Timed out trying to connect.');
  1585. // Make sure we clear the host cache
  1586. this.onClosed_();
  1587. this.connectTimeoutTimer_ = null;
  1588. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1589. }, Math.floor(LP_CONNECT_TIMEOUT));
  1590. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1591. executeWhenDOMReady(() => {
  1592. if (this.isClosed_) {
  1593. return;
  1594. }
  1595. //Set up a callback that gets triggered once a connection is set up.
  1596. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1597. const [command, arg1, arg2, arg3, arg4] = args;
  1598. this.incrementIncomingBytes_(args);
  1599. if (!this.scriptTagHolder) {
  1600. return; // we closed the connection.
  1601. }
  1602. if (this.connectTimeoutTimer_) {
  1603. clearTimeout(this.connectTimeoutTimer_);
  1604. this.connectTimeoutTimer_ = null;
  1605. }
  1606. this.everConnected_ = true;
  1607. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1608. this.id = arg1;
  1609. this.password = arg2;
  1610. }
  1611. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1612. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1613. if (arg1) {
  1614. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1615. // through our already open polls), so don't send any more.
  1616. this.scriptTagHolder.sendNewPolls = false;
  1617. // arg1 in this case is the last response number sent by the server. We should try to receive
  1618. // all of the responses up to this one before closing
  1619. this.myPacketOrderer.closeAfter(arg1, () => {
  1620. this.onClosed_();
  1621. });
  1622. }
  1623. else {
  1624. this.onClosed_();
  1625. }
  1626. }
  1627. else {
  1628. throw new Error('Unrecognized command received: ' + command);
  1629. }
  1630. }, (...args) => {
  1631. const [pN, data] = args;
  1632. this.incrementIncomingBytes_(args);
  1633. this.myPacketOrderer.handleResponse(pN, data);
  1634. }, () => {
  1635. this.onClosed_();
  1636. }, this.urlFn);
  1637. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1638. //from cache.
  1639. const urlParams = {};
  1640. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1641. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1642. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1643. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1644. this.scriptTagHolder.uniqueCallbackIdentifier;
  1645. }
  1646. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1647. if (this.transportSessionId) {
  1648. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1649. }
  1650. if (this.lastSessionId) {
  1651. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1652. }
  1653. if (this.applicationId) {
  1654. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1655. }
  1656. if (this.appCheckToken) {
  1657. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1658. }
  1659. if (typeof location !== 'undefined' &&
  1660. location.hostname &&
  1661. FORGE_DOMAIN_RE.test(location.hostname)) {
  1662. urlParams[REFERER_PARAM] = FORGE_REF;
  1663. }
  1664. const connectURL = this.urlFn(urlParams);
  1665. this.log_('Connecting via long-poll to ' + connectURL);
  1666. this.scriptTagHolder.addTag(connectURL, () => {
  1667. /* do nothing */
  1668. });
  1669. });
  1670. }
  1671. /**
  1672. * Call this when a handshake has completed successfully and we want to consider the connection established
  1673. */
  1674. start() {
  1675. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1676. this.addDisconnectPingFrame(this.id, this.password);
  1677. }
  1678. /**
  1679. * Forces long polling to be considered as a potential transport
  1680. */
  1681. static forceAllow() {
  1682. BrowserPollConnection.forceAllow_ = true;
  1683. }
  1684. /**
  1685. * Forces longpolling to not be considered as a potential transport
  1686. */
  1687. static forceDisallow() {
  1688. BrowserPollConnection.forceDisallow_ = true;
  1689. }
  1690. // Static method, use string literal so it can be accessed in a generic way
  1691. static isAvailable() {
  1692. if (util.isNodeSdk()) {
  1693. return false;
  1694. }
  1695. else if (BrowserPollConnection.forceAllow_) {
  1696. return true;
  1697. }
  1698. else {
  1699. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1700. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1701. return (!BrowserPollConnection.forceDisallow_ &&
  1702. typeof document !== 'undefined' &&
  1703. document.createElement != null &&
  1704. !isChromeExtensionContentScript() &&
  1705. !isWindowsStoreApp());
  1706. }
  1707. }
  1708. /**
  1709. * No-op for polling
  1710. */
  1711. markConnectionHealthy() { }
  1712. /**
  1713. * Stops polling and cleans up the iframe
  1714. */
  1715. shutdown_() {
  1716. this.isClosed_ = true;
  1717. if (this.scriptTagHolder) {
  1718. this.scriptTagHolder.close();
  1719. this.scriptTagHolder = null;
  1720. }
  1721. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1722. if (this.myDisconnFrame) {
  1723. document.body.removeChild(this.myDisconnFrame);
  1724. this.myDisconnFrame = null;
  1725. }
  1726. if (this.connectTimeoutTimer_) {
  1727. clearTimeout(this.connectTimeoutTimer_);
  1728. this.connectTimeoutTimer_ = null;
  1729. }
  1730. }
  1731. /**
  1732. * Triggered when this transport is closed
  1733. */
  1734. onClosed_() {
  1735. if (!this.isClosed_) {
  1736. this.log_('Longpoll is closing itself');
  1737. this.shutdown_();
  1738. if (this.onDisconnect_) {
  1739. this.onDisconnect_(this.everConnected_);
  1740. this.onDisconnect_ = null;
  1741. }
  1742. }
  1743. }
  1744. /**
  1745. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1746. * that we've left.
  1747. */
  1748. close() {
  1749. if (!this.isClosed_) {
  1750. this.log_('Longpoll is being closed.');
  1751. this.shutdown_();
  1752. }
  1753. }
  1754. /**
  1755. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1756. * broken into chunks (since URLs have a small maximum length).
  1757. * @param data - The JSON data to transmit.
  1758. */
  1759. send(data) {
  1760. const dataStr = util.stringify(data);
  1761. this.bytesSent += dataStr.length;
  1762. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1763. //first, lets get the base64-encoded data
  1764. const base64data = util.base64Encode(dataStr);
  1765. //We can only fit a certain amount in each URL, so we need to split this request
  1766. //up into multiple pieces if it doesn't fit in one request.
  1767. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1768. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1769. //of segments so that we can reassemble the packet on the server.
  1770. for (let i = 0; i < dataSegs.length; i++) {
  1771. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1772. this.curSegmentNum++;
  1773. }
  1774. }
  1775. /**
  1776. * This is how we notify the server that we're leaving.
  1777. * We aren't able to send requests with DHTML on a window close event, but we can
  1778. * trigger XHR requests in some browsers (everything but Opera basically).
  1779. */
  1780. addDisconnectPingFrame(id, pw) {
  1781. if (util.isNodeSdk()) {
  1782. return;
  1783. }
  1784. this.myDisconnFrame = document.createElement('iframe');
  1785. const urlParams = {};
  1786. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1787. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1788. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1789. this.myDisconnFrame.src = this.urlFn(urlParams);
  1790. this.myDisconnFrame.style.display = 'none';
  1791. document.body.appendChild(this.myDisconnFrame);
  1792. }
  1793. /**
  1794. * Used to track the bytes received by this client
  1795. */
  1796. incrementIncomingBytes_(args) {
  1797. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1798. const bytesReceived = util.stringify(args).length;
  1799. this.bytesReceived += bytesReceived;
  1800. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1801. }
  1802. }
  1803. /*********************************************************************************************
  1804. * A wrapper around an iframe that is used as a long-polling script holder.
  1805. *********************************************************************************************/
  1806. class FirebaseIFrameScriptHolder {
  1807. /**
  1808. * @param commandCB - The callback to be called when control commands are received from the server.
  1809. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1810. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1811. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1812. */
  1813. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1814. this.onDisconnect = onDisconnect;
  1815. this.urlFn = urlFn;
  1816. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1817. //problems in some browsers.
  1818. this.outstandingRequests = new Set();
  1819. //A queue of the pending segments waiting for transmission to the server.
  1820. this.pendingSegs = [];
  1821. //A serial number. We use this for two things:
  1822. // 1) A way to ensure the browser doesn't cache responses to polls
  1823. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1824. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1825. // JSONP code in the order it was added to the iframe.
  1826. this.currentSerial = Math.floor(Math.random() * 100000000);
  1827. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1828. // incoming data from the server that we're waiting for).
  1829. this.sendNewPolls = true;
  1830. if (!util.isNodeSdk()) {
  1831. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1832. //iframes where we put the long-polling script tags. We have two callbacks:
  1833. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1834. // 2) Message Callback - Triggered when new data arrives.
  1835. this.uniqueCallbackIdentifier = LUIDGenerator();
  1836. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1837. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1838. onMessageCB;
  1839. //Create an iframe for us to add script tags to.
  1840. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1841. // Set the iframe's contents.
  1842. let script = '';
  1843. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1844. // for ie9, but ie8 needs to do it again in the document itself.
  1845. if (this.myIFrame.src &&
  1846. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1847. const currentDomain = document.domain;
  1848. script = '<script>document.domain="' + currentDomain + '";</script>';
  1849. }
  1850. const iframeContents = '<html><body>' + script + '</body></html>';
  1851. try {
  1852. this.myIFrame.doc.open();
  1853. this.myIFrame.doc.write(iframeContents);
  1854. this.myIFrame.doc.close();
  1855. }
  1856. catch (e) {
  1857. log('frame writing exception');
  1858. if (e.stack) {
  1859. log(e.stack);
  1860. }
  1861. log(e);
  1862. }
  1863. }
  1864. else {
  1865. this.commandCB = commandCB;
  1866. this.onMessageCB = onMessageCB;
  1867. }
  1868. }
  1869. /**
  1870. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1871. * actually use.
  1872. */
  1873. static createIFrame_() {
  1874. const iframe = document.createElement('iframe');
  1875. iframe.style.display = 'none';
  1876. // This is necessary in order to initialize the document inside the iframe
  1877. if (document.body) {
  1878. document.body.appendChild(iframe);
  1879. try {
  1880. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1881. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1882. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1883. const a = iframe.contentWindow.document;
  1884. if (!a) {
  1885. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1886. log('No IE domain setting required');
  1887. }
  1888. }
  1889. catch (e) {
  1890. const domain = document.domain;
  1891. iframe.src =
  1892. "javascript:void((function(){document.open();document.domain='" +
  1893. domain +
  1894. "';document.close();})())";
  1895. }
  1896. }
  1897. else {
  1898. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1899. // never gets hit.
  1900. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1901. }
  1902. // Get the document of the iframe in a browser-specific way.
  1903. if (iframe.contentDocument) {
  1904. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1905. }
  1906. else if (iframe.contentWindow) {
  1907. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1908. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1909. }
  1910. else if (iframe.document) {
  1911. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1912. iframe.doc = iframe.document; //others?
  1913. }
  1914. return iframe;
  1915. }
  1916. /**
  1917. * Cancel all outstanding queries and remove the frame.
  1918. */
  1919. close() {
  1920. //Mark this iframe as dead, so no new requests are sent.
  1921. this.alive = false;
  1922. if (this.myIFrame) {
  1923. //We have to actually remove all of the html inside this iframe before removing it from the
  1924. //window, or IE will continue loading and executing the script tags we've already added, which
  1925. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1926. this.myIFrame.doc.body.textContent = '';
  1927. setTimeout(() => {
  1928. if (this.myIFrame !== null) {
  1929. document.body.removeChild(this.myIFrame);
  1930. this.myIFrame = null;
  1931. }
  1932. }, Math.floor(0));
  1933. }
  1934. // Protect from being called recursively.
  1935. const onDisconnect = this.onDisconnect;
  1936. if (onDisconnect) {
  1937. this.onDisconnect = null;
  1938. onDisconnect();
  1939. }
  1940. }
  1941. /**
  1942. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1943. * @param id - The ID of this connection
  1944. * @param pw - The password for this connection
  1945. */
  1946. startLongPoll(id, pw) {
  1947. this.myID = id;
  1948. this.myPW = pw;
  1949. this.alive = true;
  1950. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1951. while (this.newRequest_()) { }
  1952. }
  1953. /**
  1954. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1955. * too many outstanding requests and we are still alive.
  1956. *
  1957. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1958. * needed.
  1959. */
  1960. newRequest_() {
  1961. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1962. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1963. // close the old request.
  1964. if (this.alive &&
  1965. this.sendNewPolls &&
  1966. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1967. //construct our url
  1968. this.currentSerial++;
  1969. const urlParams = {};
  1970. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1971. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1972. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1973. let theURL = this.urlFn(urlParams);
  1974. //Now add as much data as we can.
  1975. let curDataString = '';
  1976. let i = 0;
  1977. while (this.pendingSegs.length > 0) {
  1978. //first, lets see if the next segment will fit.
  1979. const nextSeg = this.pendingSegs[0];
  1980. if (nextSeg.d.length +
  1981. SEG_HEADER_SIZE +
  1982. curDataString.length <=
  1983. MAX_URL_DATA_SIZE) {
  1984. //great, the segment will fit. Lets append it.
  1985. const theSeg = this.pendingSegs.shift();
  1986. curDataString =
  1987. curDataString +
  1988. '&' +
  1989. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1990. i +
  1991. '=' +
  1992. theSeg.seg +
  1993. '&' +
  1994. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1995. i +
  1996. '=' +
  1997. theSeg.ts +
  1998. '&' +
  1999. FIREBASE_LONGPOLL_DATA_PARAM +
  2000. i +
  2001. '=' +
  2002. theSeg.d;
  2003. i++;
  2004. }
  2005. else {
  2006. break;
  2007. }
  2008. }
  2009. theURL = theURL + curDataString;
  2010. this.addLongPollTag_(theURL, this.currentSerial);
  2011. return true;
  2012. }
  2013. else {
  2014. return false;
  2015. }
  2016. }
  2017. /**
  2018. * Queue a packet for transmission to the server.
  2019. * @param segnum - A sequential id for this packet segment used for reassembly
  2020. * @param totalsegs - The total number of segments in this packet
  2021. * @param data - The data for this segment.
  2022. */
  2023. enqueueSegment(segnum, totalsegs, data) {
  2024. //add this to the queue of segments to send.
  2025. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2026. //send the data immediately if there isn't already data being transmitted, unless
  2027. //startLongPoll hasn't been called yet.
  2028. if (this.alive) {
  2029. this.newRequest_();
  2030. }
  2031. }
  2032. /**
  2033. * Add a script tag for a regular long-poll request.
  2034. * @param url - The URL of the script tag.
  2035. * @param serial - The serial number of the request.
  2036. */
  2037. addLongPollTag_(url, serial) {
  2038. //remember that we sent this request.
  2039. this.outstandingRequests.add(serial);
  2040. const doNewRequest = () => {
  2041. this.outstandingRequests.delete(serial);
  2042. this.newRequest_();
  2043. };
  2044. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2045. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2046. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2047. const readyStateCB = () => {
  2048. // Request completed. Cancel the keepalive.
  2049. clearTimeout(keepaliveTimeout);
  2050. // Trigger a new request so we can continue receiving data.
  2051. doNewRequest();
  2052. };
  2053. this.addTag(url, readyStateCB);
  2054. }
  2055. /**
  2056. * Add an arbitrary script tag to the iframe.
  2057. * @param url - The URL for the script tag source.
  2058. * @param loadCB - A callback to be triggered once the script has loaded.
  2059. */
  2060. addTag(url, loadCB) {
  2061. if (util.isNodeSdk()) {
  2062. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2063. this.doNodeLongPoll(url, loadCB);
  2064. }
  2065. else {
  2066. setTimeout(() => {
  2067. try {
  2068. // if we're already closed, don't add this poll
  2069. if (!this.sendNewPolls) {
  2070. return;
  2071. }
  2072. const newScript = this.myIFrame.doc.createElement('script');
  2073. newScript.type = 'text/javascript';
  2074. newScript.async = true;
  2075. newScript.src = url;
  2076. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2077. newScript.onload = newScript.onreadystatechange =
  2078. function () {
  2079. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2080. const rstate = newScript.readyState;
  2081. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2082. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2083. newScript.onload = newScript.onreadystatechange = null;
  2084. if (newScript.parentNode) {
  2085. newScript.parentNode.removeChild(newScript);
  2086. }
  2087. loadCB();
  2088. }
  2089. };
  2090. newScript.onerror = () => {
  2091. log('Long-poll script failed to load: ' + url);
  2092. this.sendNewPolls = false;
  2093. this.close();
  2094. };
  2095. this.myIFrame.doc.body.appendChild(newScript);
  2096. }
  2097. catch (e) {
  2098. // TODO: we should make this error visible somehow
  2099. }
  2100. }, Math.floor(1));
  2101. }
  2102. }
  2103. }
  2104. /**
  2105. * @license
  2106. * Copyright 2017 Google LLC
  2107. *
  2108. * Licensed under the Apache License, Version 2.0 (the "License");
  2109. * you may not use this file except in compliance with the License.
  2110. * You may obtain a copy of the License at
  2111. *
  2112. * http://www.apache.org/licenses/LICENSE-2.0
  2113. *
  2114. * Unless required by applicable law or agreed to in writing, software
  2115. * distributed under the License is distributed on an "AS IS" BASIS,
  2116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2117. * See the License for the specific language governing permissions and
  2118. * limitations under the License.
  2119. */
  2120. /**
  2121. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2122. * lifecycle.
  2123. *
  2124. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2125. * they are available.
  2126. */
  2127. class TransportManager {
  2128. /**
  2129. * @param repoInfo - Metadata around the namespace we're connecting to
  2130. */
  2131. constructor(repoInfo) {
  2132. this.initTransports_(repoInfo);
  2133. }
  2134. static get ALL_TRANSPORTS() {
  2135. return [BrowserPollConnection, WebSocketConnection];
  2136. }
  2137. /**
  2138. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2139. * TransportManager has already set up transports_
  2140. */
  2141. static get IS_TRANSPORT_INITIALIZED() {
  2142. return this.globalTransportInitialized_;
  2143. }
  2144. initTransports_(repoInfo) {
  2145. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2146. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2147. if (repoInfo.webSocketOnly) {
  2148. if (!isWebSocketsAvailable) {
  2149. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2150. }
  2151. isSkipPollConnection = true;
  2152. }
  2153. if (isSkipPollConnection) {
  2154. this.transports_ = [WebSocketConnection];
  2155. }
  2156. else {
  2157. const transports = (this.transports_ = []);
  2158. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2159. if (transport && transport['isAvailable']()) {
  2160. transports.push(transport);
  2161. }
  2162. }
  2163. TransportManager.globalTransportInitialized_ = true;
  2164. }
  2165. }
  2166. /**
  2167. * @returns The constructor for the initial transport to use
  2168. */
  2169. initialTransport() {
  2170. if (this.transports_.length > 0) {
  2171. return this.transports_[0];
  2172. }
  2173. else {
  2174. throw new Error('No transports available');
  2175. }
  2176. }
  2177. /**
  2178. * @returns The constructor for the next transport, or null
  2179. */
  2180. upgradeTransport() {
  2181. if (this.transports_.length > 1) {
  2182. return this.transports_[1];
  2183. }
  2184. else {
  2185. return null;
  2186. }
  2187. }
  2188. }
  2189. // Keeps track of whether the TransportManager has already chosen a transport to use
  2190. TransportManager.globalTransportInitialized_ = false;
  2191. /**
  2192. * @license
  2193. * Copyright 2017 Google LLC
  2194. *
  2195. * Licensed under the Apache License, Version 2.0 (the "License");
  2196. * you may not use this file except in compliance with the License.
  2197. * You may obtain a copy of the License at
  2198. *
  2199. * http://www.apache.org/licenses/LICENSE-2.0
  2200. *
  2201. * Unless required by applicable law or agreed to in writing, software
  2202. * distributed under the License is distributed on an "AS IS" BASIS,
  2203. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2204. * See the License for the specific language governing permissions and
  2205. * limitations under the License.
  2206. */
  2207. // Abort upgrade attempt if it takes longer than 60s.
  2208. const UPGRADE_TIMEOUT = 60000;
  2209. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2210. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2211. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2212. // 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)
  2213. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2214. // but we've sent/received enough bytes, we don't cancel the connection.
  2215. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2216. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2217. const MESSAGE_TYPE = 't';
  2218. const MESSAGE_DATA = 'd';
  2219. const CONTROL_SHUTDOWN = 's';
  2220. const CONTROL_RESET = 'r';
  2221. const CONTROL_ERROR = 'e';
  2222. const CONTROL_PONG = 'o';
  2223. const SWITCH_ACK = 'a';
  2224. const END_TRANSMISSION = 'n';
  2225. const PING = 'p';
  2226. const SERVER_HELLO = 'h';
  2227. /**
  2228. * Creates a new real-time connection to the server using whichever method works
  2229. * best in the current browser.
  2230. */
  2231. class Connection {
  2232. /**
  2233. * @param id - an id for this connection
  2234. * @param repoInfo_ - the info for the endpoint to connect to
  2235. * @param applicationId_ - the Firebase App ID for this project
  2236. * @param appCheckToken_ - The App Check Token for this device.
  2237. * @param authToken_ - The auth token for this session.
  2238. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2239. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2240. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2241. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2242. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2243. */
  2244. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2245. this.id = id;
  2246. this.repoInfo_ = repoInfo_;
  2247. this.applicationId_ = applicationId_;
  2248. this.appCheckToken_ = appCheckToken_;
  2249. this.authToken_ = authToken_;
  2250. this.onMessage_ = onMessage_;
  2251. this.onReady_ = onReady_;
  2252. this.onDisconnect_ = onDisconnect_;
  2253. this.onKill_ = onKill_;
  2254. this.lastSessionId = lastSessionId;
  2255. this.connectionCount = 0;
  2256. this.pendingDataMessages = [];
  2257. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2258. this.log_ = logWrapper('c:' + this.id + ':');
  2259. this.transportManager_ = new TransportManager(repoInfo_);
  2260. this.log_('Connection created');
  2261. this.start_();
  2262. }
  2263. /**
  2264. * Starts a connection attempt
  2265. */
  2266. start_() {
  2267. const conn = this.transportManager_.initialTransport();
  2268. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2269. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2270. // can consider the transport healthy.
  2271. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2272. const onMessageReceived = this.connReceiver_(this.conn_);
  2273. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2274. this.tx_ = this.conn_;
  2275. this.rx_ = this.conn_;
  2276. this.secondaryConn_ = null;
  2277. this.isHealthy_ = false;
  2278. /*
  2279. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2280. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2281. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2282. * still have the context of your originating frame.
  2283. */
  2284. setTimeout(() => {
  2285. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2286. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2287. }, Math.floor(0));
  2288. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2289. if (healthyTimeoutMS > 0) {
  2290. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2291. this.healthyTimeout_ = null;
  2292. if (!this.isHealthy_) {
  2293. if (this.conn_ &&
  2294. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2295. this.log_('Connection exceeded healthy timeout but has received ' +
  2296. this.conn_.bytesReceived +
  2297. ' bytes. Marking connection healthy.');
  2298. this.isHealthy_ = true;
  2299. this.conn_.markConnectionHealthy();
  2300. }
  2301. else if (this.conn_ &&
  2302. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2303. this.log_('Connection exceeded healthy timeout but has sent ' +
  2304. this.conn_.bytesSent +
  2305. ' bytes. Leaving connection alive.');
  2306. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2307. // the server.
  2308. }
  2309. else {
  2310. this.log_('Closing unhealthy connection after timeout.');
  2311. this.close();
  2312. }
  2313. }
  2314. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2315. }, Math.floor(healthyTimeoutMS));
  2316. }
  2317. }
  2318. nextTransportId_() {
  2319. return 'c:' + this.id + ':' + this.connectionCount++;
  2320. }
  2321. disconnReceiver_(conn) {
  2322. return everConnected => {
  2323. if (conn === this.conn_) {
  2324. this.onConnectionLost_(everConnected);
  2325. }
  2326. else if (conn === this.secondaryConn_) {
  2327. this.log_('Secondary connection lost.');
  2328. this.onSecondaryConnectionLost_();
  2329. }
  2330. else {
  2331. this.log_('closing an old connection');
  2332. }
  2333. };
  2334. }
  2335. connReceiver_(conn) {
  2336. return (message) => {
  2337. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2338. if (conn === this.rx_) {
  2339. this.onPrimaryMessageReceived_(message);
  2340. }
  2341. else if (conn === this.secondaryConn_) {
  2342. this.onSecondaryMessageReceived_(message);
  2343. }
  2344. else {
  2345. this.log_('message on old connection');
  2346. }
  2347. }
  2348. };
  2349. }
  2350. /**
  2351. * @param dataMsg - An arbitrary data message to be sent to the server
  2352. */
  2353. sendRequest(dataMsg) {
  2354. // wrap in a data message envelope and send it on
  2355. const msg = { t: 'd', d: dataMsg };
  2356. this.sendData_(msg);
  2357. }
  2358. tryCleanupConnection() {
  2359. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2360. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2361. this.conn_ = this.secondaryConn_;
  2362. this.secondaryConn_ = null;
  2363. // the server will shutdown the old connection
  2364. }
  2365. }
  2366. onSecondaryControl_(controlData) {
  2367. if (MESSAGE_TYPE in controlData) {
  2368. const cmd = controlData[MESSAGE_TYPE];
  2369. if (cmd === SWITCH_ACK) {
  2370. this.upgradeIfSecondaryHealthy_();
  2371. }
  2372. else if (cmd === CONTROL_RESET) {
  2373. // Most likely the session wasn't valid. Abandon the switch attempt
  2374. this.log_('Got a reset on secondary, closing it');
  2375. this.secondaryConn_.close();
  2376. // If we were already using this connection for something, than we need to fully close
  2377. if (this.tx_ === this.secondaryConn_ ||
  2378. this.rx_ === this.secondaryConn_) {
  2379. this.close();
  2380. }
  2381. }
  2382. else if (cmd === CONTROL_PONG) {
  2383. this.log_('got pong on secondary.');
  2384. this.secondaryResponsesRequired_--;
  2385. this.upgradeIfSecondaryHealthy_();
  2386. }
  2387. }
  2388. }
  2389. onSecondaryMessageReceived_(parsedData) {
  2390. const layer = requireKey('t', parsedData);
  2391. const data = requireKey('d', parsedData);
  2392. if (layer === 'c') {
  2393. this.onSecondaryControl_(data);
  2394. }
  2395. else if (layer === 'd') {
  2396. // got a data message, but we're still second connection. Need to buffer it up
  2397. this.pendingDataMessages.push(data);
  2398. }
  2399. else {
  2400. throw new Error('Unknown protocol layer: ' + layer);
  2401. }
  2402. }
  2403. upgradeIfSecondaryHealthy_() {
  2404. if (this.secondaryResponsesRequired_ <= 0) {
  2405. this.log_('Secondary connection is healthy.');
  2406. this.isHealthy_ = true;
  2407. this.secondaryConn_.markConnectionHealthy();
  2408. this.proceedWithUpgrade_();
  2409. }
  2410. else {
  2411. // Send a ping to make sure the connection is healthy.
  2412. this.log_('sending ping on secondary.');
  2413. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2414. }
  2415. }
  2416. proceedWithUpgrade_() {
  2417. // tell this connection to consider itself open
  2418. this.secondaryConn_.start();
  2419. // send ack
  2420. this.log_('sending client ack on secondary');
  2421. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2422. // send end packet on primary transport, switch to sending on this one
  2423. // can receive on this one, buffer responses until end received on primary transport
  2424. this.log_('Ending transmission on primary');
  2425. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2426. this.tx_ = this.secondaryConn_;
  2427. this.tryCleanupConnection();
  2428. }
  2429. onPrimaryMessageReceived_(parsedData) {
  2430. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2431. const layer = requireKey('t', parsedData);
  2432. const data = requireKey('d', parsedData);
  2433. if (layer === 'c') {
  2434. this.onControl_(data);
  2435. }
  2436. else if (layer === 'd') {
  2437. this.onDataMessage_(data);
  2438. }
  2439. }
  2440. onDataMessage_(message) {
  2441. this.onPrimaryResponse_();
  2442. // We don't do anything with data messages, just kick them up a level
  2443. this.onMessage_(message);
  2444. }
  2445. onPrimaryResponse_() {
  2446. if (!this.isHealthy_) {
  2447. this.primaryResponsesRequired_--;
  2448. if (this.primaryResponsesRequired_ <= 0) {
  2449. this.log_('Primary connection is healthy.');
  2450. this.isHealthy_ = true;
  2451. this.conn_.markConnectionHealthy();
  2452. }
  2453. }
  2454. }
  2455. onControl_(controlData) {
  2456. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2457. if (MESSAGE_DATA in controlData) {
  2458. const payload = controlData[MESSAGE_DATA];
  2459. if (cmd === SERVER_HELLO) {
  2460. const handshakePayload = Object.assign({}, payload);
  2461. if (this.repoInfo_.isUsingEmulator) {
  2462. // 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.
  2463. handshakePayload.h = this.repoInfo_.host;
  2464. }
  2465. this.onHandshake_(handshakePayload);
  2466. }
  2467. else if (cmd === END_TRANSMISSION) {
  2468. this.log_('recvd end transmission on primary');
  2469. this.rx_ = this.secondaryConn_;
  2470. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2471. this.onDataMessage_(this.pendingDataMessages[i]);
  2472. }
  2473. this.pendingDataMessages = [];
  2474. this.tryCleanupConnection();
  2475. }
  2476. else if (cmd === CONTROL_SHUTDOWN) {
  2477. // This was previously the 'onKill' callback passed to the lower-level connection
  2478. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2479. this.onConnectionShutdown_(payload);
  2480. }
  2481. else if (cmd === CONTROL_RESET) {
  2482. // payload in this case is the host we should contact
  2483. this.onReset_(payload);
  2484. }
  2485. else if (cmd === CONTROL_ERROR) {
  2486. error('Server Error: ' + payload);
  2487. }
  2488. else if (cmd === CONTROL_PONG) {
  2489. this.log_('got pong on primary.');
  2490. this.onPrimaryResponse_();
  2491. this.sendPingOnPrimaryIfNecessary_();
  2492. }
  2493. else {
  2494. error('Unknown control packet command: ' + cmd);
  2495. }
  2496. }
  2497. }
  2498. /**
  2499. * @param handshake - The handshake data returned from the server
  2500. */
  2501. onHandshake_(handshake) {
  2502. const timestamp = handshake.ts;
  2503. const version = handshake.v;
  2504. const host = handshake.h;
  2505. this.sessionId = handshake.s;
  2506. this.repoInfo_.host = host;
  2507. // if we've already closed the connection, then don't bother trying to progress further
  2508. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2509. this.conn_.start();
  2510. this.onConnectionEstablished_(this.conn_, timestamp);
  2511. if (PROTOCOL_VERSION !== version) {
  2512. warn('Protocol version mismatch detected');
  2513. }
  2514. // TODO: do we want to upgrade? when? maybe a delay?
  2515. this.tryStartUpgrade_();
  2516. }
  2517. }
  2518. tryStartUpgrade_() {
  2519. const conn = this.transportManager_.upgradeTransport();
  2520. if (conn) {
  2521. this.startUpgrade_(conn);
  2522. }
  2523. }
  2524. startUpgrade_(conn) {
  2525. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2526. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2527. // can consider the transport healthy.
  2528. this.secondaryResponsesRequired_ =
  2529. conn['responsesRequiredToBeHealthy'] || 0;
  2530. const onMessage = this.connReceiver_(this.secondaryConn_);
  2531. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2532. this.secondaryConn_.open(onMessage, onDisconnect);
  2533. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2534. setTimeoutNonBlocking(() => {
  2535. if (this.secondaryConn_) {
  2536. this.log_('Timed out trying to upgrade.');
  2537. this.secondaryConn_.close();
  2538. }
  2539. }, Math.floor(UPGRADE_TIMEOUT));
  2540. }
  2541. onReset_(host) {
  2542. this.log_('Reset packet received. New host: ' + host);
  2543. this.repoInfo_.host = host;
  2544. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2545. // We don't currently support resets after the connection has already been established
  2546. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2547. this.close();
  2548. }
  2549. else {
  2550. // Close whatever connections we have open and start again.
  2551. this.closeConnections_();
  2552. this.start_();
  2553. }
  2554. }
  2555. onConnectionEstablished_(conn, timestamp) {
  2556. this.log_('Realtime connection established.');
  2557. this.conn_ = conn;
  2558. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2559. if (this.onReady_) {
  2560. this.onReady_(timestamp, this.sessionId);
  2561. this.onReady_ = null;
  2562. }
  2563. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2564. // send some pings.
  2565. if (this.primaryResponsesRequired_ === 0) {
  2566. this.log_('Primary connection is healthy.');
  2567. this.isHealthy_ = true;
  2568. }
  2569. else {
  2570. setTimeoutNonBlocking(() => {
  2571. this.sendPingOnPrimaryIfNecessary_();
  2572. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2573. }
  2574. }
  2575. sendPingOnPrimaryIfNecessary_() {
  2576. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2577. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2578. this.log_('sending ping on primary.');
  2579. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2580. }
  2581. }
  2582. onSecondaryConnectionLost_() {
  2583. const conn = this.secondaryConn_;
  2584. this.secondaryConn_ = null;
  2585. if (this.tx_ === conn || this.rx_ === conn) {
  2586. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2587. this.close();
  2588. }
  2589. }
  2590. /**
  2591. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2592. * we should flush the host cache
  2593. */
  2594. onConnectionLost_(everConnected) {
  2595. this.conn_ = null;
  2596. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2597. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2598. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2599. this.log_('Realtime connection failed.');
  2600. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2601. if (this.repoInfo_.isCacheableHost()) {
  2602. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2603. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2604. this.repoInfo_.internalHost = this.repoInfo_.host;
  2605. }
  2606. }
  2607. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2608. this.log_('Realtime connection lost.');
  2609. }
  2610. this.close();
  2611. }
  2612. onConnectionShutdown_(reason) {
  2613. this.log_('Connection shutdown command received. Shutting down...');
  2614. if (this.onKill_) {
  2615. this.onKill_(reason);
  2616. this.onKill_ = null;
  2617. }
  2618. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2619. // so clear the callback.
  2620. this.onDisconnect_ = null;
  2621. this.close();
  2622. }
  2623. sendData_(data) {
  2624. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2625. throw 'Connection is not connected';
  2626. }
  2627. else {
  2628. this.tx_.send(data);
  2629. }
  2630. }
  2631. /**
  2632. * Cleans up this connection, calling the appropriate callbacks
  2633. */
  2634. close() {
  2635. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2636. this.log_('Closing realtime connection.');
  2637. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2638. this.closeConnections_();
  2639. if (this.onDisconnect_) {
  2640. this.onDisconnect_();
  2641. this.onDisconnect_ = null;
  2642. }
  2643. }
  2644. }
  2645. closeConnections_() {
  2646. this.log_('Shutting down all connections');
  2647. if (this.conn_) {
  2648. this.conn_.close();
  2649. this.conn_ = null;
  2650. }
  2651. if (this.secondaryConn_) {
  2652. this.secondaryConn_.close();
  2653. this.secondaryConn_ = null;
  2654. }
  2655. if (this.healthyTimeout_) {
  2656. clearTimeout(this.healthyTimeout_);
  2657. this.healthyTimeout_ = null;
  2658. }
  2659. }
  2660. }
  2661. /**
  2662. * @license
  2663. * Copyright 2017 Google LLC
  2664. *
  2665. * Licensed under the Apache License, Version 2.0 (the "License");
  2666. * you may not use this file except in compliance with the License.
  2667. * You may obtain a copy of the License at
  2668. *
  2669. * http://www.apache.org/licenses/LICENSE-2.0
  2670. *
  2671. * Unless required by applicable law or agreed to in writing, software
  2672. * distributed under the License is distributed on an "AS IS" BASIS,
  2673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2674. * See the License for the specific language governing permissions and
  2675. * limitations under the License.
  2676. */
  2677. /**
  2678. * Interface defining the set of actions that can be performed against the Firebase server
  2679. * (basically corresponds to our wire protocol).
  2680. *
  2681. * @interface
  2682. */
  2683. class ServerActions {
  2684. put(pathString, data, onComplete, hash) { }
  2685. merge(pathString, data, onComplete, hash) { }
  2686. /**
  2687. * Refreshes the auth token for the current connection.
  2688. * @param token - The authentication token
  2689. */
  2690. refreshAuthToken(token) { }
  2691. /**
  2692. * Refreshes the app check token for the current connection.
  2693. * @param token The app check token
  2694. */
  2695. refreshAppCheckToken(token) { }
  2696. onDisconnectPut(pathString, data, onComplete) { }
  2697. onDisconnectMerge(pathString, data, onComplete) { }
  2698. onDisconnectCancel(pathString, onComplete) { }
  2699. reportStats(stats) { }
  2700. }
  2701. /**
  2702. * @license
  2703. * Copyright 2017 Google LLC
  2704. *
  2705. * Licensed under the Apache License, Version 2.0 (the "License");
  2706. * you may not use this file except in compliance with the License.
  2707. * You may obtain a copy of the License at
  2708. *
  2709. * http://www.apache.org/licenses/LICENSE-2.0
  2710. *
  2711. * Unless required by applicable law or agreed to in writing, software
  2712. * distributed under the License is distributed on an "AS IS" BASIS,
  2713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2714. * See the License for the specific language governing permissions and
  2715. * limitations under the License.
  2716. */
  2717. /**
  2718. * Base class to be used if you want to emit events. Call the constructor with
  2719. * the set of allowed event names.
  2720. */
  2721. class EventEmitter {
  2722. constructor(allowedEvents_) {
  2723. this.allowedEvents_ = allowedEvents_;
  2724. this.listeners_ = {};
  2725. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2726. }
  2727. /**
  2728. * To be called by derived classes to trigger events.
  2729. */
  2730. trigger(eventType, ...varArgs) {
  2731. if (Array.isArray(this.listeners_[eventType])) {
  2732. // Clone the list, since callbacks could add/remove listeners.
  2733. const listeners = [...this.listeners_[eventType]];
  2734. for (let i = 0; i < listeners.length; i++) {
  2735. listeners[i].callback.apply(listeners[i].context, varArgs);
  2736. }
  2737. }
  2738. }
  2739. on(eventType, callback, context) {
  2740. this.validateEventType_(eventType);
  2741. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2742. this.listeners_[eventType].push({ callback, context });
  2743. const eventData = this.getInitialEvent(eventType);
  2744. if (eventData) {
  2745. callback.apply(context, eventData);
  2746. }
  2747. }
  2748. off(eventType, callback, context) {
  2749. this.validateEventType_(eventType);
  2750. const listeners = this.listeners_[eventType] || [];
  2751. for (let i = 0; i < listeners.length; i++) {
  2752. if (listeners[i].callback === callback &&
  2753. (!context || context === listeners[i].context)) {
  2754. listeners.splice(i, 1);
  2755. return;
  2756. }
  2757. }
  2758. }
  2759. validateEventType_(eventType) {
  2760. util.assert(this.allowedEvents_.find(et => {
  2761. return et === eventType;
  2762. }), 'Unknown event: ' + eventType);
  2763. }
  2764. }
  2765. /**
  2766. * @license
  2767. * Copyright 2017 Google LLC
  2768. *
  2769. * Licensed under the Apache License, Version 2.0 (the "License");
  2770. * you may not use this file except in compliance with the License.
  2771. * You may obtain a copy of the License at
  2772. *
  2773. * http://www.apache.org/licenses/LICENSE-2.0
  2774. *
  2775. * Unless required by applicable law or agreed to in writing, software
  2776. * distributed under the License is distributed on an "AS IS" BASIS,
  2777. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2778. * See the License for the specific language governing permissions and
  2779. * limitations under the License.
  2780. */
  2781. /**
  2782. * Monitors online state (as reported by window.online/offline events).
  2783. *
  2784. * The expectation is that this could have many false positives (thinks we are online
  2785. * when we're not), but no false negatives. So we can safely use it to determine when
  2786. * we definitely cannot reach the internet.
  2787. */
  2788. class OnlineMonitor extends EventEmitter {
  2789. constructor() {
  2790. super(['online']);
  2791. this.online_ = true;
  2792. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2793. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2794. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2795. // for Cordova.
  2796. if (typeof window !== 'undefined' &&
  2797. typeof window.addEventListener !== 'undefined' &&
  2798. !util.isMobileCordova()) {
  2799. window.addEventListener('online', () => {
  2800. if (!this.online_) {
  2801. this.online_ = true;
  2802. this.trigger('online', true);
  2803. }
  2804. }, false);
  2805. window.addEventListener('offline', () => {
  2806. if (this.online_) {
  2807. this.online_ = false;
  2808. this.trigger('online', false);
  2809. }
  2810. }, false);
  2811. }
  2812. }
  2813. static getInstance() {
  2814. return new OnlineMonitor();
  2815. }
  2816. getInitialEvent(eventType) {
  2817. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2818. return [this.online_];
  2819. }
  2820. currentlyOnline() {
  2821. return this.online_;
  2822. }
  2823. }
  2824. /**
  2825. * @license
  2826. * Copyright 2017 Google LLC
  2827. *
  2828. * Licensed under the Apache License, Version 2.0 (the "License");
  2829. * you may not use this file except in compliance with the License.
  2830. * You may obtain a copy of the License at
  2831. *
  2832. * http://www.apache.org/licenses/LICENSE-2.0
  2833. *
  2834. * Unless required by applicable law or agreed to in writing, software
  2835. * distributed under the License is distributed on an "AS IS" BASIS,
  2836. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2837. * See the License for the specific language governing permissions and
  2838. * limitations under the License.
  2839. */
  2840. /** Maximum key depth. */
  2841. const MAX_PATH_DEPTH = 32;
  2842. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2843. const MAX_PATH_LENGTH_BYTES = 768;
  2844. /**
  2845. * An immutable object representing a parsed path. It's immutable so that you
  2846. * can pass them around to other functions without worrying about them changing
  2847. * it.
  2848. */
  2849. class Path {
  2850. /**
  2851. * @param pathOrString - Path string to parse, or another path, or the raw
  2852. * tokens array
  2853. */
  2854. constructor(pathOrString, pieceNum) {
  2855. if (pieceNum === void 0) {
  2856. this.pieces_ = pathOrString.split('/');
  2857. // Remove empty pieces.
  2858. let copyTo = 0;
  2859. for (let i = 0; i < this.pieces_.length; i++) {
  2860. if (this.pieces_[i].length > 0) {
  2861. this.pieces_[copyTo] = this.pieces_[i];
  2862. copyTo++;
  2863. }
  2864. }
  2865. this.pieces_.length = copyTo;
  2866. this.pieceNum_ = 0;
  2867. }
  2868. else {
  2869. this.pieces_ = pathOrString;
  2870. this.pieceNum_ = pieceNum;
  2871. }
  2872. }
  2873. toString() {
  2874. let pathString = '';
  2875. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2876. if (this.pieces_[i] !== '') {
  2877. pathString += '/' + this.pieces_[i];
  2878. }
  2879. }
  2880. return pathString || '/';
  2881. }
  2882. }
  2883. function newEmptyPath() {
  2884. return new Path('');
  2885. }
  2886. function pathGetFront(path) {
  2887. if (path.pieceNum_ >= path.pieces_.length) {
  2888. return null;
  2889. }
  2890. return path.pieces_[path.pieceNum_];
  2891. }
  2892. /**
  2893. * @returns The number of segments in this path
  2894. */
  2895. function pathGetLength(path) {
  2896. return path.pieces_.length - path.pieceNum_;
  2897. }
  2898. function pathPopFront(path) {
  2899. let pieceNum = path.pieceNum_;
  2900. if (pieceNum < path.pieces_.length) {
  2901. pieceNum++;
  2902. }
  2903. return new Path(path.pieces_, pieceNum);
  2904. }
  2905. function pathGetBack(path) {
  2906. if (path.pieceNum_ < path.pieces_.length) {
  2907. return path.pieces_[path.pieces_.length - 1];
  2908. }
  2909. return null;
  2910. }
  2911. function pathToUrlEncodedString(path) {
  2912. let pathString = '';
  2913. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2914. if (path.pieces_[i] !== '') {
  2915. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2916. }
  2917. }
  2918. return pathString || '/';
  2919. }
  2920. /**
  2921. * Shallow copy of the parts of the path.
  2922. *
  2923. */
  2924. function pathSlice(path, begin = 0) {
  2925. return path.pieces_.slice(path.pieceNum_ + begin);
  2926. }
  2927. function pathParent(path) {
  2928. if (path.pieceNum_ >= path.pieces_.length) {
  2929. return null;
  2930. }
  2931. const pieces = [];
  2932. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2933. pieces.push(path.pieces_[i]);
  2934. }
  2935. return new Path(pieces, 0);
  2936. }
  2937. function pathChild(path, childPathObj) {
  2938. const pieces = [];
  2939. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2940. pieces.push(path.pieces_[i]);
  2941. }
  2942. if (childPathObj instanceof Path) {
  2943. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2944. pieces.push(childPathObj.pieces_[i]);
  2945. }
  2946. }
  2947. else {
  2948. const childPieces = childPathObj.split('/');
  2949. for (let i = 0; i < childPieces.length; i++) {
  2950. if (childPieces[i].length > 0) {
  2951. pieces.push(childPieces[i]);
  2952. }
  2953. }
  2954. }
  2955. return new Path(pieces, 0);
  2956. }
  2957. /**
  2958. * @returns True if there are no segments in this path
  2959. */
  2960. function pathIsEmpty(path) {
  2961. return path.pieceNum_ >= path.pieces_.length;
  2962. }
  2963. /**
  2964. * @returns The path from outerPath to innerPath
  2965. */
  2966. function newRelativePath(outerPath, innerPath) {
  2967. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2968. if (outer === null) {
  2969. return innerPath;
  2970. }
  2971. else if (outer === inner) {
  2972. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2973. }
  2974. else {
  2975. throw new Error('INTERNAL ERROR: innerPath (' +
  2976. innerPath +
  2977. ') is not within ' +
  2978. 'outerPath (' +
  2979. outerPath +
  2980. ')');
  2981. }
  2982. }
  2983. /**
  2984. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2985. */
  2986. function pathCompare(left, right) {
  2987. const leftKeys = pathSlice(left, 0);
  2988. const rightKeys = pathSlice(right, 0);
  2989. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2990. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2991. if (cmp !== 0) {
  2992. return cmp;
  2993. }
  2994. }
  2995. if (leftKeys.length === rightKeys.length) {
  2996. return 0;
  2997. }
  2998. return leftKeys.length < rightKeys.length ? -1 : 1;
  2999. }
  3000. /**
  3001. * @returns true if paths are the same.
  3002. */
  3003. function pathEquals(path, other) {
  3004. if (pathGetLength(path) !== pathGetLength(other)) {
  3005. return false;
  3006. }
  3007. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3008. if (path.pieces_[i] !== other.pieces_[j]) {
  3009. return false;
  3010. }
  3011. }
  3012. return true;
  3013. }
  3014. /**
  3015. * @returns True if this path is a parent of (or the same as) other
  3016. */
  3017. function pathContains(path, other) {
  3018. let i = path.pieceNum_;
  3019. let j = other.pieceNum_;
  3020. if (pathGetLength(path) > pathGetLength(other)) {
  3021. return false;
  3022. }
  3023. while (i < path.pieces_.length) {
  3024. if (path.pieces_[i] !== other.pieces_[j]) {
  3025. return false;
  3026. }
  3027. ++i;
  3028. ++j;
  3029. }
  3030. return true;
  3031. }
  3032. /**
  3033. * Dynamic (mutable) path used to count path lengths.
  3034. *
  3035. * This class is used to efficiently check paths for valid
  3036. * length (in UTF8 bytes) and depth (used in path validation).
  3037. *
  3038. * Throws Error exception if path is ever invalid.
  3039. *
  3040. * The definition of a path always begins with '/'.
  3041. */
  3042. class ValidationPath {
  3043. /**
  3044. * @param path - Initial Path.
  3045. * @param errorPrefix_ - Prefix for any error messages.
  3046. */
  3047. constructor(path, errorPrefix_) {
  3048. this.errorPrefix_ = errorPrefix_;
  3049. this.parts_ = pathSlice(path, 0);
  3050. /** Initialize to number of '/' chars needed in path. */
  3051. this.byteLength_ = Math.max(1, this.parts_.length);
  3052. for (let i = 0; i < this.parts_.length; i++) {
  3053. this.byteLength_ += util.stringLength(this.parts_[i]);
  3054. }
  3055. validationPathCheckValid(this);
  3056. }
  3057. }
  3058. function validationPathPush(validationPath, child) {
  3059. // Count the needed '/'
  3060. if (validationPath.parts_.length > 0) {
  3061. validationPath.byteLength_ += 1;
  3062. }
  3063. validationPath.parts_.push(child);
  3064. validationPath.byteLength_ += util.stringLength(child);
  3065. validationPathCheckValid(validationPath);
  3066. }
  3067. function validationPathPop(validationPath) {
  3068. const last = validationPath.parts_.pop();
  3069. validationPath.byteLength_ -= util.stringLength(last);
  3070. // Un-count the previous '/'
  3071. if (validationPath.parts_.length > 0) {
  3072. validationPath.byteLength_ -= 1;
  3073. }
  3074. }
  3075. function validationPathCheckValid(validationPath) {
  3076. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3077. throw new Error(validationPath.errorPrefix_ +
  3078. 'has a key path longer than ' +
  3079. MAX_PATH_LENGTH_BYTES +
  3080. ' bytes (' +
  3081. validationPath.byteLength_ +
  3082. ').');
  3083. }
  3084. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3085. throw new Error(validationPath.errorPrefix_ +
  3086. 'path specified exceeds the maximum depth that can be written (' +
  3087. MAX_PATH_DEPTH +
  3088. ') or object contains a cycle ' +
  3089. validationPathToErrorString(validationPath));
  3090. }
  3091. }
  3092. /**
  3093. * String for use in error messages - uses '.' notation for path.
  3094. */
  3095. function validationPathToErrorString(validationPath) {
  3096. if (validationPath.parts_.length === 0) {
  3097. return '';
  3098. }
  3099. return "in property '" + validationPath.parts_.join('.') + "'";
  3100. }
  3101. /**
  3102. * @license
  3103. * Copyright 2017 Google LLC
  3104. *
  3105. * Licensed under the Apache License, Version 2.0 (the "License");
  3106. * you may not use this file except in compliance with the License.
  3107. * You may obtain a copy of the License at
  3108. *
  3109. * http://www.apache.org/licenses/LICENSE-2.0
  3110. *
  3111. * Unless required by applicable law or agreed to in writing, software
  3112. * distributed under the License is distributed on an "AS IS" BASIS,
  3113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3114. * See the License for the specific language governing permissions and
  3115. * limitations under the License.
  3116. */
  3117. class VisibilityMonitor extends EventEmitter {
  3118. constructor() {
  3119. super(['visible']);
  3120. let hidden;
  3121. let visibilityChange;
  3122. if (typeof document !== 'undefined' &&
  3123. typeof document.addEventListener !== 'undefined') {
  3124. if (typeof document['hidden'] !== 'undefined') {
  3125. // Opera 12.10 and Firefox 18 and later support
  3126. visibilityChange = 'visibilitychange';
  3127. hidden = 'hidden';
  3128. }
  3129. else if (typeof document['mozHidden'] !== 'undefined') {
  3130. visibilityChange = 'mozvisibilitychange';
  3131. hidden = 'mozHidden';
  3132. }
  3133. else if (typeof document['msHidden'] !== 'undefined') {
  3134. visibilityChange = 'msvisibilitychange';
  3135. hidden = 'msHidden';
  3136. }
  3137. else if (typeof document['webkitHidden'] !== 'undefined') {
  3138. visibilityChange = 'webkitvisibilitychange';
  3139. hidden = 'webkitHidden';
  3140. }
  3141. }
  3142. // Initially, we always assume we are visible. This ensures that in browsers
  3143. // without page visibility support or in cases where we are never visible
  3144. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3145. // reconnects
  3146. this.visible_ = true;
  3147. if (visibilityChange) {
  3148. document.addEventListener(visibilityChange, () => {
  3149. const visible = !document[hidden];
  3150. if (visible !== this.visible_) {
  3151. this.visible_ = visible;
  3152. this.trigger('visible', visible);
  3153. }
  3154. }, false);
  3155. }
  3156. }
  3157. static getInstance() {
  3158. return new VisibilityMonitor();
  3159. }
  3160. getInitialEvent(eventType) {
  3161. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3162. return [this.visible_];
  3163. }
  3164. }
  3165. /**
  3166. * @license
  3167. * Copyright 2017 Google LLC
  3168. *
  3169. * Licensed under the Apache License, Version 2.0 (the "License");
  3170. * you may not use this file except in compliance with the License.
  3171. * You may obtain a copy of the License at
  3172. *
  3173. * http://www.apache.org/licenses/LICENSE-2.0
  3174. *
  3175. * Unless required by applicable law or agreed to in writing, software
  3176. * distributed under the License is distributed on an "AS IS" BASIS,
  3177. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3178. * See the License for the specific language governing permissions and
  3179. * limitations under the License.
  3180. */
  3181. const RECONNECT_MIN_DELAY = 1000;
  3182. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3183. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3184. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3185. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3186. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3187. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3188. const INVALID_TOKEN_THRESHOLD = 3;
  3189. /**
  3190. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3191. *
  3192. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3193. * in quotes to make sure the closure compiler does not minify them.
  3194. */
  3195. class PersistentConnection extends ServerActions {
  3196. /**
  3197. * @param repoInfo_ - Data about the namespace we are connecting to
  3198. * @param applicationId_ - The Firebase App ID for this project
  3199. * @param onDataUpdate_ - A callback for new data from the server
  3200. */
  3201. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3202. super();
  3203. this.repoInfo_ = repoInfo_;
  3204. this.applicationId_ = applicationId_;
  3205. this.onDataUpdate_ = onDataUpdate_;
  3206. this.onConnectStatus_ = onConnectStatus_;
  3207. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3208. this.authTokenProvider_ = authTokenProvider_;
  3209. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3210. this.authOverride_ = authOverride_;
  3211. // Used for diagnostic logging.
  3212. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3213. this.log_ = logWrapper('p:' + this.id + ':');
  3214. this.interruptReasons_ = {};
  3215. this.listens = new Map();
  3216. this.outstandingPuts_ = [];
  3217. this.outstandingGets_ = [];
  3218. this.outstandingPutCount_ = 0;
  3219. this.outstandingGetCount_ = 0;
  3220. this.onDisconnectRequestQueue_ = [];
  3221. this.connected_ = false;
  3222. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3223. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3224. this.securityDebugCallback_ = null;
  3225. this.lastSessionId = null;
  3226. this.establishConnectionTimer_ = null;
  3227. this.visible_ = false;
  3228. // Before we get connected, we keep a queue of pending messages to send.
  3229. this.requestCBHash_ = {};
  3230. this.requestNumber_ = 0;
  3231. this.realtime_ = null;
  3232. this.authToken_ = null;
  3233. this.appCheckToken_ = null;
  3234. this.forceTokenRefresh_ = false;
  3235. this.invalidAuthTokenCount_ = 0;
  3236. this.invalidAppCheckTokenCount_ = 0;
  3237. this.firstConnection_ = true;
  3238. this.lastConnectionAttemptTime_ = null;
  3239. this.lastConnectionEstablishedTime_ = null;
  3240. if (authOverride_ && !util.isNodeSdk()) {
  3241. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3242. }
  3243. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3244. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3245. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3246. }
  3247. }
  3248. sendRequest(action, body, onResponse) {
  3249. const curReqNum = ++this.requestNumber_;
  3250. const msg = { r: curReqNum, a: action, b: body };
  3251. this.log_(util.stringify(msg));
  3252. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3253. this.realtime_.sendRequest(msg);
  3254. if (onResponse) {
  3255. this.requestCBHash_[curReqNum] = onResponse;
  3256. }
  3257. }
  3258. get(query) {
  3259. this.initConnection_();
  3260. const deferred = new util.Deferred();
  3261. const request = {
  3262. p: query._path.toString(),
  3263. q: query._queryObject
  3264. };
  3265. const outstandingGet = {
  3266. action: 'g',
  3267. request,
  3268. onComplete: (message) => {
  3269. const payload = message['d'];
  3270. if (message['s'] === 'ok') {
  3271. deferred.resolve(payload);
  3272. }
  3273. else {
  3274. deferred.reject(payload);
  3275. }
  3276. }
  3277. };
  3278. this.outstandingGets_.push(outstandingGet);
  3279. this.outstandingGetCount_++;
  3280. const index = this.outstandingGets_.length - 1;
  3281. if (this.connected_) {
  3282. this.sendGet_(index);
  3283. }
  3284. return deferred.promise;
  3285. }
  3286. listen(query, currentHashFn, tag, onComplete) {
  3287. this.initConnection_();
  3288. const queryId = query._queryIdentifier;
  3289. const pathString = query._path.toString();
  3290. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3291. if (!this.listens.has(pathString)) {
  3292. this.listens.set(pathString, new Map());
  3293. }
  3294. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3295. util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3296. const listenSpec = {
  3297. onComplete,
  3298. hashFn: currentHashFn,
  3299. query,
  3300. tag
  3301. };
  3302. this.listens.get(pathString).set(queryId, listenSpec);
  3303. if (this.connected_) {
  3304. this.sendListen_(listenSpec);
  3305. }
  3306. }
  3307. sendGet_(index) {
  3308. const get = this.outstandingGets_[index];
  3309. this.sendRequest('g', get.request, (message) => {
  3310. delete this.outstandingGets_[index];
  3311. this.outstandingGetCount_--;
  3312. if (this.outstandingGetCount_ === 0) {
  3313. this.outstandingGets_ = [];
  3314. }
  3315. if (get.onComplete) {
  3316. get.onComplete(message);
  3317. }
  3318. });
  3319. }
  3320. sendListen_(listenSpec) {
  3321. const query = listenSpec.query;
  3322. const pathString = query._path.toString();
  3323. const queryId = query._queryIdentifier;
  3324. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3325. const req = { /*path*/ p: pathString };
  3326. const action = 'q';
  3327. // Only bother to send query if it's non-default.
  3328. if (listenSpec.tag) {
  3329. req['q'] = query._queryObject;
  3330. req['t'] = listenSpec.tag;
  3331. }
  3332. req[ /*hash*/'h'] = listenSpec.hashFn();
  3333. this.sendRequest(action, req, (message) => {
  3334. const payload = message[ /*data*/'d'];
  3335. const status = message[ /*status*/'s'];
  3336. // print warnings in any case...
  3337. PersistentConnection.warnOnListenWarnings_(payload, query);
  3338. const currentListenSpec = this.listens.get(pathString) &&
  3339. this.listens.get(pathString).get(queryId);
  3340. // only trigger actions if the listen hasn't been removed and readded
  3341. if (currentListenSpec === listenSpec) {
  3342. this.log_('listen response', message);
  3343. if (status !== 'ok') {
  3344. this.removeListen_(pathString, queryId);
  3345. }
  3346. if (listenSpec.onComplete) {
  3347. listenSpec.onComplete(status, payload);
  3348. }
  3349. }
  3350. });
  3351. }
  3352. static warnOnListenWarnings_(payload, query) {
  3353. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  3354. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3355. const warnings = util.safeGet(payload, 'w');
  3356. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3357. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3358. const indexPath = query._path.toString();
  3359. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3360. `filtered on the client. Consider adding ${indexSpec} at ` +
  3361. `${indexPath} to your security rules for better performance.`);
  3362. }
  3363. }
  3364. }
  3365. refreshAuthToken(token) {
  3366. this.authToken_ = token;
  3367. this.log_('Auth token refreshed');
  3368. if (this.authToken_) {
  3369. this.tryAuth();
  3370. }
  3371. else {
  3372. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3373. //the credential so we dont become authenticated next time we connect.
  3374. if (this.connected_) {
  3375. this.sendRequest('unauth', {}, () => { });
  3376. }
  3377. }
  3378. this.reduceReconnectDelayIfAdminCredential_(token);
  3379. }
  3380. reduceReconnectDelayIfAdminCredential_(credential) {
  3381. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3382. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3383. const isFirebaseSecret = credential && credential.length === 40;
  3384. if (isFirebaseSecret || util.isAdmin(credential)) {
  3385. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3386. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3387. }
  3388. }
  3389. refreshAppCheckToken(token) {
  3390. this.appCheckToken_ = token;
  3391. this.log_('App check token refreshed');
  3392. if (this.appCheckToken_) {
  3393. this.tryAppCheck();
  3394. }
  3395. else {
  3396. //If we're connected we want to let the server know to unauthenticate us.
  3397. //If we're not connected, simply delete the credential so we dont become
  3398. // authenticated next time we connect.
  3399. if (this.connected_) {
  3400. this.sendRequest('unappeck', {}, () => { });
  3401. }
  3402. }
  3403. }
  3404. /**
  3405. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3406. * a auth revoked (the connection is closed).
  3407. */
  3408. tryAuth() {
  3409. if (this.connected_ && this.authToken_) {
  3410. const token = this.authToken_;
  3411. const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth';
  3412. const requestData = { cred: token };
  3413. if (this.authOverride_ === null) {
  3414. requestData['noauth'] = true;
  3415. }
  3416. else if (typeof this.authOverride_ === 'object') {
  3417. requestData['authvar'] = this.authOverride_;
  3418. }
  3419. this.sendRequest(authMethod, requestData, (res) => {
  3420. const status = res[ /*status*/'s'];
  3421. const data = res[ /*data*/'d'] || 'error';
  3422. if (this.authToken_ === token) {
  3423. if (status === 'ok') {
  3424. this.invalidAuthTokenCount_ = 0;
  3425. }
  3426. else {
  3427. // Triggers reconnect and force refresh for auth token
  3428. this.onAuthRevoked_(status, data);
  3429. }
  3430. }
  3431. });
  3432. }
  3433. }
  3434. /**
  3435. * Attempts to authenticate with the given token. If the authentication
  3436. * attempt fails, it's triggered like the token was revoked (the connection is
  3437. * closed).
  3438. */
  3439. tryAppCheck() {
  3440. if (this.connected_ && this.appCheckToken_) {
  3441. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3442. const status = res[ /*status*/'s'];
  3443. const data = res[ /*data*/'d'] || 'error';
  3444. if (status === 'ok') {
  3445. this.invalidAppCheckTokenCount_ = 0;
  3446. }
  3447. else {
  3448. this.onAppCheckRevoked_(status, data);
  3449. }
  3450. });
  3451. }
  3452. }
  3453. /**
  3454. * @inheritDoc
  3455. */
  3456. unlisten(query, tag) {
  3457. const pathString = query._path.toString();
  3458. const queryId = query._queryIdentifier;
  3459. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3460. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3461. const listen = this.removeListen_(pathString, queryId);
  3462. if (listen && this.connected_) {
  3463. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3464. }
  3465. }
  3466. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3467. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3468. const req = { /*path*/ p: pathString };
  3469. const action = 'n';
  3470. // Only bother sending queryId if it's non-default.
  3471. if (tag) {
  3472. req['q'] = queryObj;
  3473. req['t'] = tag;
  3474. }
  3475. this.sendRequest(action, req);
  3476. }
  3477. onDisconnectPut(pathString, data, onComplete) {
  3478. this.initConnection_();
  3479. if (this.connected_) {
  3480. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3481. }
  3482. else {
  3483. this.onDisconnectRequestQueue_.push({
  3484. pathString,
  3485. action: 'o',
  3486. data,
  3487. onComplete
  3488. });
  3489. }
  3490. }
  3491. onDisconnectMerge(pathString, data, onComplete) {
  3492. this.initConnection_();
  3493. if (this.connected_) {
  3494. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3495. }
  3496. else {
  3497. this.onDisconnectRequestQueue_.push({
  3498. pathString,
  3499. action: 'om',
  3500. data,
  3501. onComplete
  3502. });
  3503. }
  3504. }
  3505. onDisconnectCancel(pathString, onComplete) {
  3506. this.initConnection_();
  3507. if (this.connected_) {
  3508. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3509. }
  3510. else {
  3511. this.onDisconnectRequestQueue_.push({
  3512. pathString,
  3513. action: 'oc',
  3514. data: null,
  3515. onComplete
  3516. });
  3517. }
  3518. }
  3519. sendOnDisconnect_(action, pathString, data, onComplete) {
  3520. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3521. this.log_('onDisconnect ' + action, request);
  3522. this.sendRequest(action, request, (response) => {
  3523. if (onComplete) {
  3524. setTimeout(() => {
  3525. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3526. }, Math.floor(0));
  3527. }
  3528. });
  3529. }
  3530. put(pathString, data, onComplete, hash) {
  3531. this.putInternal('p', pathString, data, onComplete, hash);
  3532. }
  3533. merge(pathString, data, onComplete, hash) {
  3534. this.putInternal('m', pathString, data, onComplete, hash);
  3535. }
  3536. putInternal(action, pathString, data, onComplete, hash) {
  3537. this.initConnection_();
  3538. const request = {
  3539. /*path*/ p: pathString,
  3540. /*data*/ d: data
  3541. };
  3542. if (hash !== undefined) {
  3543. request[ /*hash*/'h'] = hash;
  3544. }
  3545. // TODO: Only keep track of the most recent put for a given path?
  3546. this.outstandingPuts_.push({
  3547. action,
  3548. request,
  3549. onComplete
  3550. });
  3551. this.outstandingPutCount_++;
  3552. const index = this.outstandingPuts_.length - 1;
  3553. if (this.connected_) {
  3554. this.sendPut_(index);
  3555. }
  3556. else {
  3557. this.log_('Buffering put: ' + pathString);
  3558. }
  3559. }
  3560. sendPut_(index) {
  3561. const action = this.outstandingPuts_[index].action;
  3562. const request = this.outstandingPuts_[index].request;
  3563. const onComplete = this.outstandingPuts_[index].onComplete;
  3564. this.outstandingPuts_[index].queued = this.connected_;
  3565. this.sendRequest(action, request, (message) => {
  3566. this.log_(action + ' response', message);
  3567. delete this.outstandingPuts_[index];
  3568. this.outstandingPutCount_--;
  3569. // Clean up array occasionally.
  3570. if (this.outstandingPutCount_ === 0) {
  3571. this.outstandingPuts_ = [];
  3572. }
  3573. if (onComplete) {
  3574. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3575. }
  3576. });
  3577. }
  3578. reportStats(stats) {
  3579. // If we're not connected, we just drop the stats.
  3580. if (this.connected_) {
  3581. const request = { /*counters*/ c: stats };
  3582. this.log_('reportStats', request);
  3583. this.sendRequest(/*stats*/ 's', request, result => {
  3584. const status = result[ /*status*/'s'];
  3585. if (status !== 'ok') {
  3586. const errorReason = result[ /* data */'d'];
  3587. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3588. }
  3589. });
  3590. }
  3591. }
  3592. onDataMessage_(message) {
  3593. if ('r' in message) {
  3594. // this is a response
  3595. this.log_('from server: ' + util.stringify(message));
  3596. const reqNum = message['r'];
  3597. const onResponse = this.requestCBHash_[reqNum];
  3598. if (onResponse) {
  3599. delete this.requestCBHash_[reqNum];
  3600. onResponse(message[ /*body*/'b']);
  3601. }
  3602. }
  3603. else if ('error' in message) {
  3604. throw 'A server-side error has occurred: ' + message['error'];
  3605. }
  3606. else if ('a' in message) {
  3607. // a and b are action and body, respectively
  3608. this.onDataPush_(message['a'], message['b']);
  3609. }
  3610. }
  3611. onDataPush_(action, body) {
  3612. this.log_('handleServerMessage', action, body);
  3613. if (action === 'd') {
  3614. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3615. /*isMerge*/ false, body['t']);
  3616. }
  3617. else if (action === 'm') {
  3618. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3619. /*isMerge=*/ true, body['t']);
  3620. }
  3621. else if (action === 'c') {
  3622. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3623. }
  3624. else if (action === 'ac') {
  3625. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3626. }
  3627. else if (action === 'apc') {
  3628. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3629. }
  3630. else if (action === 'sd') {
  3631. this.onSecurityDebugPacket_(body);
  3632. }
  3633. else {
  3634. error('Unrecognized action received from server: ' +
  3635. util.stringify(action) +
  3636. '\nAre you using the latest client?');
  3637. }
  3638. }
  3639. onReady_(timestamp, sessionId) {
  3640. this.log_('connection ready');
  3641. this.connected_ = true;
  3642. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3643. this.handleTimestamp_(timestamp);
  3644. this.lastSessionId = sessionId;
  3645. if (this.firstConnection_) {
  3646. this.sendConnectStats_();
  3647. }
  3648. this.restoreState_();
  3649. this.firstConnection_ = false;
  3650. this.onConnectStatus_(true);
  3651. }
  3652. scheduleConnect_(timeout) {
  3653. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3654. if (this.establishConnectionTimer_) {
  3655. clearTimeout(this.establishConnectionTimer_);
  3656. }
  3657. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3658. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3659. this.establishConnectionTimer_ = setTimeout(() => {
  3660. this.establishConnectionTimer_ = null;
  3661. this.establishConnection_();
  3662. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3663. }, Math.floor(timeout));
  3664. }
  3665. initConnection_() {
  3666. if (!this.realtime_ && this.firstConnection_) {
  3667. this.scheduleConnect_(0);
  3668. }
  3669. }
  3670. onVisible_(visible) {
  3671. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3672. if (visible &&
  3673. !this.visible_ &&
  3674. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3675. this.log_('Window became visible. Reducing delay.');
  3676. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3677. if (!this.realtime_) {
  3678. this.scheduleConnect_(0);
  3679. }
  3680. }
  3681. this.visible_ = visible;
  3682. }
  3683. onOnline_(online) {
  3684. if (online) {
  3685. this.log_('Browser went online.');
  3686. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3687. if (!this.realtime_) {
  3688. this.scheduleConnect_(0);
  3689. }
  3690. }
  3691. else {
  3692. this.log_('Browser went offline. Killing connection.');
  3693. if (this.realtime_) {
  3694. this.realtime_.close();
  3695. }
  3696. }
  3697. }
  3698. onRealtimeDisconnect_() {
  3699. this.log_('data client disconnected');
  3700. this.connected_ = false;
  3701. this.realtime_ = null;
  3702. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3703. this.cancelSentTransactions_();
  3704. // Clear out the pending requests.
  3705. this.requestCBHash_ = {};
  3706. if (this.shouldReconnect_()) {
  3707. if (!this.visible_) {
  3708. this.log_("Window isn't visible. Delaying reconnect.");
  3709. this.reconnectDelay_ = this.maxReconnectDelay_;
  3710. this.lastConnectionAttemptTime_ = new Date().getTime();
  3711. }
  3712. else if (this.lastConnectionEstablishedTime_) {
  3713. // If we've been connected long enough, reset reconnect delay to minimum.
  3714. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3715. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3716. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3717. }
  3718. this.lastConnectionEstablishedTime_ = null;
  3719. }
  3720. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3721. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3722. reconnectDelay = Math.random() * reconnectDelay;
  3723. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3724. this.scheduleConnect_(reconnectDelay);
  3725. // Adjust reconnect delay for next time.
  3726. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3727. }
  3728. this.onConnectStatus_(false);
  3729. }
  3730. async establishConnection_() {
  3731. if (this.shouldReconnect_()) {
  3732. this.log_('Making a connection attempt');
  3733. this.lastConnectionAttemptTime_ = new Date().getTime();
  3734. this.lastConnectionEstablishedTime_ = null;
  3735. const onDataMessage = this.onDataMessage_.bind(this);
  3736. const onReady = this.onReady_.bind(this);
  3737. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3738. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3739. const lastSessionId = this.lastSessionId;
  3740. let canceled = false;
  3741. let connection = null;
  3742. const closeFn = function () {
  3743. if (connection) {
  3744. connection.close();
  3745. }
  3746. else {
  3747. canceled = true;
  3748. onDisconnect();
  3749. }
  3750. };
  3751. const sendRequestFn = function (msg) {
  3752. util.assert(connection, "sendRequest call when we're not connected not allowed.");
  3753. connection.sendRequest(msg);
  3754. };
  3755. this.realtime_ = {
  3756. close: closeFn,
  3757. sendRequest: sendRequestFn
  3758. };
  3759. const forceRefresh = this.forceTokenRefresh_;
  3760. this.forceTokenRefresh_ = false;
  3761. try {
  3762. // First fetch auth and app check token, and establish connection after
  3763. // fetching the token was successful
  3764. const [authToken, appCheckToken] = await Promise.all([
  3765. this.authTokenProvider_.getToken(forceRefresh),
  3766. this.appCheckTokenProvider_.getToken(forceRefresh)
  3767. ]);
  3768. if (!canceled) {
  3769. log('getToken() completed. Creating connection.');
  3770. this.authToken_ = authToken && authToken.accessToken;
  3771. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3772. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3773. /* onKill= */ reason => {
  3774. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3775. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3776. }, lastSessionId);
  3777. }
  3778. else {
  3779. log('getToken() completed but was canceled');
  3780. }
  3781. }
  3782. catch (error) {
  3783. this.log_('Failed to get token: ' + error);
  3784. if (!canceled) {
  3785. if (this.repoInfo_.nodeAdmin) {
  3786. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3787. // But getToken() may also just have temporarily failed, so we still want to
  3788. // continue retrying.
  3789. warn(error);
  3790. }
  3791. closeFn();
  3792. }
  3793. }
  3794. }
  3795. }
  3796. interrupt(reason) {
  3797. log('Interrupting connection for reason: ' + reason);
  3798. this.interruptReasons_[reason] = true;
  3799. if (this.realtime_) {
  3800. this.realtime_.close();
  3801. }
  3802. else {
  3803. if (this.establishConnectionTimer_) {
  3804. clearTimeout(this.establishConnectionTimer_);
  3805. this.establishConnectionTimer_ = null;
  3806. }
  3807. if (this.connected_) {
  3808. this.onRealtimeDisconnect_();
  3809. }
  3810. }
  3811. }
  3812. resume(reason) {
  3813. log('Resuming connection for reason: ' + reason);
  3814. delete this.interruptReasons_[reason];
  3815. if (util.isEmpty(this.interruptReasons_)) {
  3816. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3817. if (!this.realtime_) {
  3818. this.scheduleConnect_(0);
  3819. }
  3820. }
  3821. }
  3822. handleTimestamp_(timestamp) {
  3823. const delta = timestamp - new Date().getTime();
  3824. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3825. }
  3826. cancelSentTransactions_() {
  3827. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3828. const put = this.outstandingPuts_[i];
  3829. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3830. if (put.onComplete) {
  3831. put.onComplete('disconnect');
  3832. }
  3833. delete this.outstandingPuts_[i];
  3834. this.outstandingPutCount_--;
  3835. }
  3836. }
  3837. // Clean up array occasionally.
  3838. if (this.outstandingPutCount_ === 0) {
  3839. this.outstandingPuts_ = [];
  3840. }
  3841. }
  3842. onListenRevoked_(pathString, query) {
  3843. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3844. let queryId;
  3845. if (!query) {
  3846. queryId = 'default';
  3847. }
  3848. else {
  3849. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3850. }
  3851. const listen = this.removeListen_(pathString, queryId);
  3852. if (listen && listen.onComplete) {
  3853. listen.onComplete('permission_denied');
  3854. }
  3855. }
  3856. removeListen_(pathString, queryId) {
  3857. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3858. let listen;
  3859. if (this.listens.has(normalizedPathString)) {
  3860. const map = this.listens.get(normalizedPathString);
  3861. listen = map.get(queryId);
  3862. map.delete(queryId);
  3863. if (map.size === 0) {
  3864. this.listens.delete(normalizedPathString);
  3865. }
  3866. }
  3867. else {
  3868. // all listens for this path has already been removed
  3869. listen = undefined;
  3870. }
  3871. return listen;
  3872. }
  3873. onAuthRevoked_(statusCode, explanation) {
  3874. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3875. this.authToken_ = null;
  3876. this.forceTokenRefresh_ = true;
  3877. this.realtime_.close();
  3878. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3879. // We'll wait a couple times before logging the warning / increasing the
  3880. // retry period since oauth tokens will report as "invalid" if they're
  3881. // just expired. Plus there may be transient issues that resolve themselves.
  3882. this.invalidAuthTokenCount_++;
  3883. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3884. // Set a long reconnect delay because recovery is unlikely
  3885. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3886. // Notify the auth token provider that the token is invalid, which will log
  3887. // a warning
  3888. this.authTokenProvider_.notifyForInvalidToken();
  3889. }
  3890. }
  3891. }
  3892. onAppCheckRevoked_(statusCode, explanation) {
  3893. log('App check token revoked: ' + statusCode + '/' + explanation);
  3894. this.appCheckToken_ = null;
  3895. this.forceTokenRefresh_ = true;
  3896. // Note: We don't close the connection as the developer may not have
  3897. // enforcement enabled. The backend closes connections with enforcements.
  3898. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3899. // We'll wait a couple times before logging the warning / increasing the
  3900. // retry period since oauth tokens will report as "invalid" if they're
  3901. // just expired. Plus there may be transient issues that resolve themselves.
  3902. this.invalidAppCheckTokenCount_++;
  3903. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3904. this.appCheckTokenProvider_.notifyForInvalidToken();
  3905. }
  3906. }
  3907. }
  3908. onSecurityDebugPacket_(body) {
  3909. if (this.securityDebugCallback_) {
  3910. this.securityDebugCallback_(body);
  3911. }
  3912. else {
  3913. if ('msg' in body) {
  3914. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3915. }
  3916. }
  3917. }
  3918. restoreState_() {
  3919. //Re-authenticate ourselves if we have a credential stored.
  3920. this.tryAuth();
  3921. this.tryAppCheck();
  3922. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3923. // make sure to send listens before puts.
  3924. for (const queries of this.listens.values()) {
  3925. for (const listenSpec of queries.values()) {
  3926. this.sendListen_(listenSpec);
  3927. }
  3928. }
  3929. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3930. if (this.outstandingPuts_[i]) {
  3931. this.sendPut_(i);
  3932. }
  3933. }
  3934. while (this.onDisconnectRequestQueue_.length) {
  3935. const request = this.onDisconnectRequestQueue_.shift();
  3936. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3937. }
  3938. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3939. if (this.outstandingGets_[i]) {
  3940. this.sendGet_(i);
  3941. }
  3942. }
  3943. }
  3944. /**
  3945. * Sends client stats for first connection
  3946. */
  3947. sendConnectStats_() {
  3948. const stats = {};
  3949. let clientName = 'js';
  3950. if (util.isNodeSdk()) {
  3951. if (this.repoInfo_.nodeAdmin) {
  3952. clientName = 'admin_node';
  3953. }
  3954. else {
  3955. clientName = 'node';
  3956. }
  3957. }
  3958. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3959. if (util.isMobileCordova()) {
  3960. stats['framework.cordova'] = 1;
  3961. }
  3962. else if (util.isReactNative()) {
  3963. stats['framework.reactnative'] = 1;
  3964. }
  3965. this.reportStats(stats);
  3966. }
  3967. shouldReconnect_() {
  3968. const online = OnlineMonitor.getInstance().currentlyOnline();
  3969. return util.isEmpty(this.interruptReasons_) && online;
  3970. }
  3971. }
  3972. PersistentConnection.nextPersistentConnectionId_ = 0;
  3973. /**
  3974. * Counter for number of connections created. Mainly used for tagging in the logs
  3975. */
  3976. PersistentConnection.nextConnectionId_ = 0;
  3977. /**
  3978. * @license
  3979. * Copyright 2017 Google LLC
  3980. *
  3981. * Licensed under the Apache License, Version 2.0 (the "License");
  3982. * you may not use this file except in compliance with the License.
  3983. * You may obtain a copy of the License at
  3984. *
  3985. * http://www.apache.org/licenses/LICENSE-2.0
  3986. *
  3987. * Unless required by applicable law or agreed to in writing, software
  3988. * distributed under the License is distributed on an "AS IS" BASIS,
  3989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3990. * See the License for the specific language governing permissions and
  3991. * limitations under the License.
  3992. */
  3993. class NamedNode {
  3994. constructor(name, node) {
  3995. this.name = name;
  3996. this.node = node;
  3997. }
  3998. static Wrap(name, node) {
  3999. return new NamedNode(name, node);
  4000. }
  4001. }
  4002. /**
  4003. * @license
  4004. * Copyright 2017 Google LLC
  4005. *
  4006. * Licensed under the Apache License, Version 2.0 (the "License");
  4007. * you may not use this file except in compliance with the License.
  4008. * You may obtain a copy of the License at
  4009. *
  4010. * http://www.apache.org/licenses/LICENSE-2.0
  4011. *
  4012. * Unless required by applicable law or agreed to in writing, software
  4013. * distributed under the License is distributed on an "AS IS" BASIS,
  4014. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4015. * See the License for the specific language governing permissions and
  4016. * limitations under the License.
  4017. */
  4018. class Index {
  4019. /**
  4020. * @returns A standalone comparison function for
  4021. * this index
  4022. */
  4023. getCompare() {
  4024. return this.compare.bind(this);
  4025. }
  4026. /**
  4027. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4028. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4029. *
  4030. *
  4031. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4032. */
  4033. indexedValueChanged(oldNode, newNode) {
  4034. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4035. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4036. return this.compare(oldWrapped, newWrapped) !== 0;
  4037. }
  4038. /**
  4039. * @returns a node wrapper that will sort equal to or less than
  4040. * any other node wrapper, using this index
  4041. */
  4042. minPost() {
  4043. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4044. return NamedNode.MIN;
  4045. }
  4046. }
  4047. /**
  4048. * @license
  4049. * Copyright 2017 Google LLC
  4050. *
  4051. * Licensed under the Apache License, Version 2.0 (the "License");
  4052. * you may not use this file except in compliance with the License.
  4053. * You may obtain a copy of the License at
  4054. *
  4055. * http://www.apache.org/licenses/LICENSE-2.0
  4056. *
  4057. * Unless required by applicable law or agreed to in writing, software
  4058. * distributed under the License is distributed on an "AS IS" BASIS,
  4059. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4060. * See the License for the specific language governing permissions and
  4061. * limitations under the License.
  4062. */
  4063. let __EMPTY_NODE;
  4064. class KeyIndex extends Index {
  4065. static get __EMPTY_NODE() {
  4066. return __EMPTY_NODE;
  4067. }
  4068. static set __EMPTY_NODE(val) {
  4069. __EMPTY_NODE = val;
  4070. }
  4071. compare(a, b) {
  4072. return nameCompare(a.name, b.name);
  4073. }
  4074. isDefinedOn(node) {
  4075. // We could probably return true here (since every node has a key), but it's never called
  4076. // so just leaving unimplemented for now.
  4077. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4078. }
  4079. indexedValueChanged(oldNode, newNode) {
  4080. return false; // The key for a node never changes.
  4081. }
  4082. minPost() {
  4083. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4084. return NamedNode.MIN;
  4085. }
  4086. maxPost() {
  4087. // TODO: This should really be created once and cached in a static property, but
  4088. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4089. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4090. }
  4091. makePost(indexValue, name) {
  4092. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4093. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4094. return new NamedNode(indexValue, __EMPTY_NODE);
  4095. }
  4096. /**
  4097. * @returns String representation for inclusion in a query spec
  4098. */
  4099. toString() {
  4100. return '.key';
  4101. }
  4102. }
  4103. const KEY_INDEX = new KeyIndex();
  4104. /**
  4105. * @license
  4106. * Copyright 2017 Google LLC
  4107. *
  4108. * Licensed under the Apache License, Version 2.0 (the "License");
  4109. * you may not use this file except in compliance with the License.
  4110. * You may obtain a copy of the License at
  4111. *
  4112. * http://www.apache.org/licenses/LICENSE-2.0
  4113. *
  4114. * Unless required by applicable law or agreed to in writing, software
  4115. * distributed under the License is distributed on an "AS IS" BASIS,
  4116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4117. * See the License for the specific language governing permissions and
  4118. * limitations under the License.
  4119. */
  4120. /**
  4121. * An iterator over an LLRBNode.
  4122. */
  4123. class SortedMapIterator {
  4124. /**
  4125. * @param node - Node to iterate.
  4126. * @param isReverse_ - Whether or not to iterate in reverse
  4127. */
  4128. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4129. this.isReverse_ = isReverse_;
  4130. this.resultGenerator_ = resultGenerator_;
  4131. this.nodeStack_ = [];
  4132. let cmp = 1;
  4133. while (!node.isEmpty()) {
  4134. node = node;
  4135. cmp = startKey ? comparator(node.key, startKey) : 1;
  4136. // flip the comparison if we're going in reverse
  4137. if (isReverse_) {
  4138. cmp *= -1;
  4139. }
  4140. if (cmp < 0) {
  4141. // This node is less than our start key. ignore it
  4142. if (this.isReverse_) {
  4143. node = node.left;
  4144. }
  4145. else {
  4146. node = node.right;
  4147. }
  4148. }
  4149. else if (cmp === 0) {
  4150. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4151. this.nodeStack_.push(node);
  4152. break;
  4153. }
  4154. else {
  4155. // This node is greater than our start key, add it to the stack and move to the next one
  4156. this.nodeStack_.push(node);
  4157. if (this.isReverse_) {
  4158. node = node.right;
  4159. }
  4160. else {
  4161. node = node.left;
  4162. }
  4163. }
  4164. }
  4165. }
  4166. getNext() {
  4167. if (this.nodeStack_.length === 0) {
  4168. return null;
  4169. }
  4170. let node = this.nodeStack_.pop();
  4171. let result;
  4172. if (this.resultGenerator_) {
  4173. result = this.resultGenerator_(node.key, node.value);
  4174. }
  4175. else {
  4176. result = { key: node.key, value: node.value };
  4177. }
  4178. if (this.isReverse_) {
  4179. node = node.left;
  4180. while (!node.isEmpty()) {
  4181. this.nodeStack_.push(node);
  4182. node = node.right;
  4183. }
  4184. }
  4185. else {
  4186. node = node.right;
  4187. while (!node.isEmpty()) {
  4188. this.nodeStack_.push(node);
  4189. node = node.left;
  4190. }
  4191. }
  4192. return result;
  4193. }
  4194. hasNext() {
  4195. return this.nodeStack_.length > 0;
  4196. }
  4197. peek() {
  4198. if (this.nodeStack_.length === 0) {
  4199. return null;
  4200. }
  4201. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4202. if (this.resultGenerator_) {
  4203. return this.resultGenerator_(node.key, node.value);
  4204. }
  4205. else {
  4206. return { key: node.key, value: node.value };
  4207. }
  4208. }
  4209. }
  4210. /**
  4211. * Represents a node in a Left-leaning Red-Black tree.
  4212. */
  4213. class LLRBNode {
  4214. /**
  4215. * @param key - Key associated with this node.
  4216. * @param value - Value associated with this node.
  4217. * @param color - Whether this node is red.
  4218. * @param left - Left child.
  4219. * @param right - Right child.
  4220. */
  4221. constructor(key, value, color, left, right) {
  4222. this.key = key;
  4223. this.value = value;
  4224. this.color = color != null ? color : LLRBNode.RED;
  4225. this.left =
  4226. left != null ? left : SortedMap.EMPTY_NODE;
  4227. this.right =
  4228. right != null ? right : SortedMap.EMPTY_NODE;
  4229. }
  4230. /**
  4231. * Returns a copy of the current node, optionally replacing pieces of it.
  4232. *
  4233. * @param key - New key for the node, or null.
  4234. * @param value - New value for the node, or null.
  4235. * @param color - New color for the node, or null.
  4236. * @param left - New left child for the node, or null.
  4237. * @param right - New right child for the node, or null.
  4238. * @returns The node copy.
  4239. */
  4240. copy(key, value, color, left, right) {
  4241. 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);
  4242. }
  4243. /**
  4244. * @returns The total number of nodes in the tree.
  4245. */
  4246. count() {
  4247. return this.left.count() + 1 + this.right.count();
  4248. }
  4249. /**
  4250. * @returns True if the tree is empty.
  4251. */
  4252. isEmpty() {
  4253. return false;
  4254. }
  4255. /**
  4256. * Traverses the tree in key order and calls the specified action function
  4257. * for each node.
  4258. *
  4259. * @param action - Callback function to be called for each
  4260. * node. If it returns true, traversal is aborted.
  4261. * @returns The first truthy value returned by action, or the last falsey
  4262. * value returned by action
  4263. */
  4264. inorderTraversal(action) {
  4265. return (this.left.inorderTraversal(action) ||
  4266. !!action(this.key, this.value) ||
  4267. this.right.inorderTraversal(action));
  4268. }
  4269. /**
  4270. * Traverses the tree in reverse key order and calls the specified action function
  4271. * for each node.
  4272. *
  4273. * @param action - Callback function to be called for each
  4274. * node. If it returns true, traversal is aborted.
  4275. * @returns True if traversal was aborted.
  4276. */
  4277. reverseTraversal(action) {
  4278. return (this.right.reverseTraversal(action) ||
  4279. action(this.key, this.value) ||
  4280. this.left.reverseTraversal(action));
  4281. }
  4282. /**
  4283. * @returns The minimum node in the tree.
  4284. */
  4285. min_() {
  4286. if (this.left.isEmpty()) {
  4287. return this;
  4288. }
  4289. else {
  4290. return this.left.min_();
  4291. }
  4292. }
  4293. /**
  4294. * @returns The maximum key in the tree.
  4295. */
  4296. minKey() {
  4297. return this.min_().key;
  4298. }
  4299. /**
  4300. * @returns The maximum key in the tree.
  4301. */
  4302. maxKey() {
  4303. if (this.right.isEmpty()) {
  4304. return this.key;
  4305. }
  4306. else {
  4307. return this.right.maxKey();
  4308. }
  4309. }
  4310. /**
  4311. * @param key - Key to insert.
  4312. * @param value - Value to insert.
  4313. * @param comparator - Comparator.
  4314. * @returns New tree, with the key/value added.
  4315. */
  4316. insert(key, value, comparator) {
  4317. let n = this;
  4318. const cmp = comparator(key, n.key);
  4319. if (cmp < 0) {
  4320. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4321. }
  4322. else if (cmp === 0) {
  4323. n = n.copy(null, value, null, null, null);
  4324. }
  4325. else {
  4326. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4327. }
  4328. return n.fixUp_();
  4329. }
  4330. /**
  4331. * @returns New tree, with the minimum key removed.
  4332. */
  4333. removeMin_() {
  4334. if (this.left.isEmpty()) {
  4335. return SortedMap.EMPTY_NODE;
  4336. }
  4337. let n = this;
  4338. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4339. n = n.moveRedLeft_();
  4340. }
  4341. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4342. return n.fixUp_();
  4343. }
  4344. /**
  4345. * @param key - The key of the item to remove.
  4346. * @param comparator - Comparator.
  4347. * @returns New tree, with the specified item removed.
  4348. */
  4349. remove(key, comparator) {
  4350. let n, smallest;
  4351. n = this;
  4352. if (comparator(key, n.key) < 0) {
  4353. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4354. n = n.moveRedLeft_();
  4355. }
  4356. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4357. }
  4358. else {
  4359. if (n.left.isRed_()) {
  4360. n = n.rotateRight_();
  4361. }
  4362. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4363. n = n.moveRedRight_();
  4364. }
  4365. if (comparator(key, n.key) === 0) {
  4366. if (n.right.isEmpty()) {
  4367. return SortedMap.EMPTY_NODE;
  4368. }
  4369. else {
  4370. smallest = n.right.min_();
  4371. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4372. }
  4373. }
  4374. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4375. }
  4376. return n.fixUp_();
  4377. }
  4378. /**
  4379. * @returns Whether this is a RED node.
  4380. */
  4381. isRed_() {
  4382. return this.color;
  4383. }
  4384. /**
  4385. * @returns New tree after performing any needed rotations.
  4386. */
  4387. fixUp_() {
  4388. let n = this;
  4389. if (n.right.isRed_() && !n.left.isRed_()) {
  4390. n = n.rotateLeft_();
  4391. }
  4392. if (n.left.isRed_() && n.left.left.isRed_()) {
  4393. n = n.rotateRight_();
  4394. }
  4395. if (n.left.isRed_() && n.right.isRed_()) {
  4396. n = n.colorFlip_();
  4397. }
  4398. return n;
  4399. }
  4400. /**
  4401. * @returns New tree, after moveRedLeft.
  4402. */
  4403. moveRedLeft_() {
  4404. let n = this.colorFlip_();
  4405. if (n.right.left.isRed_()) {
  4406. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4407. n = n.rotateLeft_();
  4408. n = n.colorFlip_();
  4409. }
  4410. return n;
  4411. }
  4412. /**
  4413. * @returns New tree, after moveRedRight.
  4414. */
  4415. moveRedRight_() {
  4416. let n = this.colorFlip_();
  4417. if (n.left.left.isRed_()) {
  4418. n = n.rotateRight_();
  4419. n = n.colorFlip_();
  4420. }
  4421. return n;
  4422. }
  4423. /**
  4424. * @returns New tree, after rotateLeft.
  4425. */
  4426. rotateLeft_() {
  4427. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4428. return this.right.copy(null, null, this.color, nl, null);
  4429. }
  4430. /**
  4431. * @returns New tree, after rotateRight.
  4432. */
  4433. rotateRight_() {
  4434. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4435. return this.left.copy(null, null, this.color, null, nr);
  4436. }
  4437. /**
  4438. * @returns Newt ree, after colorFlip.
  4439. */
  4440. colorFlip_() {
  4441. const left = this.left.copy(null, null, !this.left.color, null, null);
  4442. const right = this.right.copy(null, null, !this.right.color, null, null);
  4443. return this.copy(null, null, !this.color, left, right);
  4444. }
  4445. /**
  4446. * For testing.
  4447. *
  4448. * @returns True if all is well.
  4449. */
  4450. checkMaxDepth_() {
  4451. const blackDepth = this.check_();
  4452. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4453. }
  4454. check_() {
  4455. if (this.isRed_() && this.left.isRed_()) {
  4456. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4457. }
  4458. if (this.right.isRed_()) {
  4459. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4460. }
  4461. const blackDepth = this.left.check_();
  4462. if (blackDepth !== this.right.check_()) {
  4463. throw new Error('Black depths differ');
  4464. }
  4465. else {
  4466. return blackDepth + (this.isRed_() ? 0 : 1);
  4467. }
  4468. }
  4469. }
  4470. LLRBNode.RED = true;
  4471. LLRBNode.BLACK = false;
  4472. /**
  4473. * Represents an empty node (a leaf node in the Red-Black Tree).
  4474. */
  4475. class LLRBEmptyNode {
  4476. /**
  4477. * Returns a copy of the current node.
  4478. *
  4479. * @returns The node copy.
  4480. */
  4481. copy(key, value, color, left, right) {
  4482. return this;
  4483. }
  4484. /**
  4485. * Returns a copy of the tree, with the specified key/value added.
  4486. *
  4487. * @param key - Key to be added.
  4488. * @param value - Value to be added.
  4489. * @param comparator - Comparator.
  4490. * @returns New tree, with item added.
  4491. */
  4492. insert(key, value, comparator) {
  4493. return new LLRBNode(key, value, null);
  4494. }
  4495. /**
  4496. * Returns a copy of the tree, with the specified key removed.
  4497. *
  4498. * @param key - The key to remove.
  4499. * @param comparator - Comparator.
  4500. * @returns New tree, with item removed.
  4501. */
  4502. remove(key, comparator) {
  4503. return this;
  4504. }
  4505. /**
  4506. * @returns The total number of nodes in the tree.
  4507. */
  4508. count() {
  4509. return 0;
  4510. }
  4511. /**
  4512. * @returns True if the tree is empty.
  4513. */
  4514. isEmpty() {
  4515. return true;
  4516. }
  4517. /**
  4518. * Traverses the tree in key order and calls the specified action function
  4519. * for each node.
  4520. *
  4521. * @param action - Callback function to be called for each
  4522. * node. If it returns true, traversal is aborted.
  4523. * @returns True if traversal was aborted.
  4524. */
  4525. inorderTraversal(action) {
  4526. return false;
  4527. }
  4528. /**
  4529. * Traverses the tree in reverse key order and calls the specified action function
  4530. * for each node.
  4531. *
  4532. * @param action - Callback function to be called for each
  4533. * node. If it returns true, traversal is aborted.
  4534. * @returns True if traversal was aborted.
  4535. */
  4536. reverseTraversal(action) {
  4537. return false;
  4538. }
  4539. minKey() {
  4540. return null;
  4541. }
  4542. maxKey() {
  4543. return null;
  4544. }
  4545. check_() {
  4546. return 0;
  4547. }
  4548. /**
  4549. * @returns Whether this node is red.
  4550. */
  4551. isRed_() {
  4552. return false;
  4553. }
  4554. }
  4555. /**
  4556. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4557. * tree.
  4558. */
  4559. class SortedMap {
  4560. /**
  4561. * @param comparator_ - Key comparator.
  4562. * @param root_ - Optional root node for the map.
  4563. */
  4564. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4565. this.comparator_ = comparator_;
  4566. this.root_ = root_;
  4567. }
  4568. /**
  4569. * Returns a copy of the map, with the specified key/value added or replaced.
  4570. * (TODO: We should perhaps rename this method to 'put')
  4571. *
  4572. * @param key - Key to be added.
  4573. * @param value - Value to be added.
  4574. * @returns New map, with item added.
  4575. */
  4576. insert(key, value) {
  4577. return new SortedMap(this.comparator_, this.root_
  4578. .insert(key, value, this.comparator_)
  4579. .copy(null, null, LLRBNode.BLACK, null, null));
  4580. }
  4581. /**
  4582. * Returns a copy of the map, with the specified key removed.
  4583. *
  4584. * @param key - The key to remove.
  4585. * @returns New map, with item removed.
  4586. */
  4587. remove(key) {
  4588. return new SortedMap(this.comparator_, this.root_
  4589. .remove(key, this.comparator_)
  4590. .copy(null, null, LLRBNode.BLACK, null, null));
  4591. }
  4592. /**
  4593. * Returns the value of the node with the given key, or null.
  4594. *
  4595. * @param key - The key to look up.
  4596. * @returns The value of the node with the given key, or null if the
  4597. * key doesn't exist.
  4598. */
  4599. get(key) {
  4600. let cmp;
  4601. let node = this.root_;
  4602. while (!node.isEmpty()) {
  4603. cmp = this.comparator_(key, node.key);
  4604. if (cmp === 0) {
  4605. return node.value;
  4606. }
  4607. else if (cmp < 0) {
  4608. node = node.left;
  4609. }
  4610. else if (cmp > 0) {
  4611. node = node.right;
  4612. }
  4613. }
  4614. return null;
  4615. }
  4616. /**
  4617. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4618. * @param key - The key to find the predecessor of
  4619. * @returns The predecessor key.
  4620. */
  4621. getPredecessorKey(key) {
  4622. let cmp, node = this.root_, rightParent = null;
  4623. while (!node.isEmpty()) {
  4624. cmp = this.comparator_(key, node.key);
  4625. if (cmp === 0) {
  4626. if (!node.left.isEmpty()) {
  4627. node = node.left;
  4628. while (!node.right.isEmpty()) {
  4629. node = node.right;
  4630. }
  4631. return node.key;
  4632. }
  4633. else if (rightParent) {
  4634. return rightParent.key;
  4635. }
  4636. else {
  4637. return null; // first item.
  4638. }
  4639. }
  4640. else if (cmp < 0) {
  4641. node = node.left;
  4642. }
  4643. else if (cmp > 0) {
  4644. rightParent = node;
  4645. node = node.right;
  4646. }
  4647. }
  4648. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4649. }
  4650. /**
  4651. * @returns True if the map is empty.
  4652. */
  4653. isEmpty() {
  4654. return this.root_.isEmpty();
  4655. }
  4656. /**
  4657. * @returns The total number of nodes in the map.
  4658. */
  4659. count() {
  4660. return this.root_.count();
  4661. }
  4662. /**
  4663. * @returns The minimum key in the map.
  4664. */
  4665. minKey() {
  4666. return this.root_.minKey();
  4667. }
  4668. /**
  4669. * @returns The maximum key in the map.
  4670. */
  4671. maxKey() {
  4672. return this.root_.maxKey();
  4673. }
  4674. /**
  4675. * Traverses the map in key order and calls the specified action function
  4676. * for each key/value pair.
  4677. *
  4678. * @param action - Callback function to be called
  4679. * for each key/value pair. If action returns true, traversal is aborted.
  4680. * @returns The first truthy value returned by action, or the last falsey
  4681. * value returned by action
  4682. */
  4683. inorderTraversal(action) {
  4684. return this.root_.inorderTraversal(action);
  4685. }
  4686. /**
  4687. * Traverses the map in reverse key order and calls the specified action function
  4688. * for each key/value pair.
  4689. *
  4690. * @param action - Callback function to be called
  4691. * for each key/value pair. If action returns true, traversal is aborted.
  4692. * @returns True if the traversal was aborted.
  4693. */
  4694. reverseTraversal(action) {
  4695. return this.root_.reverseTraversal(action);
  4696. }
  4697. /**
  4698. * Returns an iterator over the SortedMap.
  4699. * @returns The iterator.
  4700. */
  4701. getIterator(resultGenerator) {
  4702. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4703. }
  4704. getIteratorFrom(key, resultGenerator) {
  4705. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4706. }
  4707. getReverseIteratorFrom(key, resultGenerator) {
  4708. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4709. }
  4710. getReverseIterator(resultGenerator) {
  4711. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4712. }
  4713. }
  4714. /**
  4715. * Always use the same empty node, to reduce memory.
  4716. */
  4717. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4718. /**
  4719. * @license
  4720. * Copyright 2017 Google LLC
  4721. *
  4722. * Licensed under the Apache License, Version 2.0 (the "License");
  4723. * you may not use this file except in compliance with the License.
  4724. * You may obtain a copy of the License at
  4725. *
  4726. * http://www.apache.org/licenses/LICENSE-2.0
  4727. *
  4728. * Unless required by applicable law or agreed to in writing, software
  4729. * distributed under the License is distributed on an "AS IS" BASIS,
  4730. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4731. * See the License for the specific language governing permissions and
  4732. * limitations under the License.
  4733. */
  4734. function NAME_ONLY_COMPARATOR(left, right) {
  4735. return nameCompare(left.name, right.name);
  4736. }
  4737. function NAME_COMPARATOR(left, right) {
  4738. return nameCompare(left, right);
  4739. }
  4740. /**
  4741. * @license
  4742. * Copyright 2017 Google LLC
  4743. *
  4744. * Licensed under the Apache License, Version 2.0 (the "License");
  4745. * you may not use this file except in compliance with the License.
  4746. * You may obtain a copy of the License at
  4747. *
  4748. * http://www.apache.org/licenses/LICENSE-2.0
  4749. *
  4750. * Unless required by applicable law or agreed to in writing, software
  4751. * distributed under the License is distributed on an "AS IS" BASIS,
  4752. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4753. * See the License for the specific language governing permissions and
  4754. * limitations under the License.
  4755. */
  4756. let MAX_NODE$2;
  4757. function setMaxNode$1(val) {
  4758. MAX_NODE$2 = val;
  4759. }
  4760. const priorityHashText = function (priority) {
  4761. if (typeof priority === 'number') {
  4762. return 'number:' + doubleToIEEE754String(priority);
  4763. }
  4764. else {
  4765. return 'string:' + priority;
  4766. }
  4767. };
  4768. /**
  4769. * Validates that a priority snapshot Node is valid.
  4770. */
  4771. const validatePriorityNode = function (priorityNode) {
  4772. if (priorityNode.isLeafNode()) {
  4773. const val = priorityNode.val();
  4774. util.assert(typeof val === 'string' ||
  4775. typeof val === 'number' ||
  4776. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  4777. }
  4778. else {
  4779. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4780. }
  4781. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4782. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4783. };
  4784. /**
  4785. * @license
  4786. * Copyright 2017 Google LLC
  4787. *
  4788. * Licensed under the Apache License, Version 2.0 (the "License");
  4789. * you may not use this file except in compliance with the License.
  4790. * You may obtain a copy of the License at
  4791. *
  4792. * http://www.apache.org/licenses/LICENSE-2.0
  4793. *
  4794. * Unless required by applicable law or agreed to in writing, software
  4795. * distributed under the License is distributed on an "AS IS" BASIS,
  4796. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4797. * See the License for the specific language governing permissions and
  4798. * limitations under the License.
  4799. */
  4800. let __childrenNodeConstructor;
  4801. /**
  4802. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4803. * implements Node and stores the value of the node (a string,
  4804. * number, or boolean) accessible via getValue().
  4805. */
  4806. class LeafNode {
  4807. /**
  4808. * @param value_ - The value to store in this leaf node. The object type is
  4809. * possible in the event of a deferred value
  4810. * @param priorityNode_ - The priority of this node.
  4811. */
  4812. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4813. this.value_ = value_;
  4814. this.priorityNode_ = priorityNode_;
  4815. this.lazyHash_ = null;
  4816. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4817. validatePriorityNode(this.priorityNode_);
  4818. }
  4819. static set __childrenNodeConstructor(val) {
  4820. __childrenNodeConstructor = val;
  4821. }
  4822. static get __childrenNodeConstructor() {
  4823. return __childrenNodeConstructor;
  4824. }
  4825. /** @inheritDoc */
  4826. isLeafNode() {
  4827. return true;
  4828. }
  4829. /** @inheritDoc */
  4830. getPriority() {
  4831. return this.priorityNode_;
  4832. }
  4833. /** @inheritDoc */
  4834. updatePriority(newPriorityNode) {
  4835. return new LeafNode(this.value_, newPriorityNode);
  4836. }
  4837. /** @inheritDoc */
  4838. getImmediateChild(childName) {
  4839. // Hack to treat priority as a regular child
  4840. if (childName === '.priority') {
  4841. return this.priorityNode_;
  4842. }
  4843. else {
  4844. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4845. }
  4846. }
  4847. /** @inheritDoc */
  4848. getChild(path) {
  4849. if (pathIsEmpty(path)) {
  4850. return this;
  4851. }
  4852. else if (pathGetFront(path) === '.priority') {
  4853. return this.priorityNode_;
  4854. }
  4855. else {
  4856. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4857. }
  4858. }
  4859. hasChild() {
  4860. return false;
  4861. }
  4862. /** @inheritDoc */
  4863. getPredecessorChildName(childName, childNode) {
  4864. return null;
  4865. }
  4866. /** @inheritDoc */
  4867. updateImmediateChild(childName, newChildNode) {
  4868. if (childName === '.priority') {
  4869. return this.updatePriority(newChildNode);
  4870. }
  4871. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4872. return this;
  4873. }
  4874. else {
  4875. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4876. }
  4877. }
  4878. /** @inheritDoc */
  4879. updateChild(path, newChildNode) {
  4880. const front = pathGetFront(path);
  4881. if (front === null) {
  4882. return newChildNode;
  4883. }
  4884. else if (newChildNode.isEmpty() && front !== '.priority') {
  4885. return this;
  4886. }
  4887. else {
  4888. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4889. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4890. }
  4891. }
  4892. /** @inheritDoc */
  4893. isEmpty() {
  4894. return false;
  4895. }
  4896. /** @inheritDoc */
  4897. numChildren() {
  4898. return 0;
  4899. }
  4900. /** @inheritDoc */
  4901. forEachChild(index, action) {
  4902. return false;
  4903. }
  4904. val(exportFormat) {
  4905. if (exportFormat && !this.getPriority().isEmpty()) {
  4906. return {
  4907. '.value': this.getValue(),
  4908. '.priority': this.getPriority().val()
  4909. };
  4910. }
  4911. else {
  4912. return this.getValue();
  4913. }
  4914. }
  4915. /** @inheritDoc */
  4916. hash() {
  4917. if (this.lazyHash_ === null) {
  4918. let toHash = '';
  4919. if (!this.priorityNode_.isEmpty()) {
  4920. toHash +=
  4921. 'priority:' +
  4922. priorityHashText(this.priorityNode_.val()) +
  4923. ':';
  4924. }
  4925. const type = typeof this.value_;
  4926. toHash += type + ':';
  4927. if (type === 'number') {
  4928. toHash += doubleToIEEE754String(this.value_);
  4929. }
  4930. else {
  4931. toHash += this.value_;
  4932. }
  4933. this.lazyHash_ = sha1(toHash);
  4934. }
  4935. return this.lazyHash_;
  4936. }
  4937. /**
  4938. * Returns the value of the leaf node.
  4939. * @returns The value of the node.
  4940. */
  4941. getValue() {
  4942. return this.value_;
  4943. }
  4944. compareTo(other) {
  4945. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4946. return 1;
  4947. }
  4948. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4949. return -1;
  4950. }
  4951. else {
  4952. util.assert(other.isLeafNode(), 'Unknown node type');
  4953. return this.compareToLeafNode_(other);
  4954. }
  4955. }
  4956. /**
  4957. * Comparison specifically for two leaf nodes
  4958. */
  4959. compareToLeafNode_(otherLeaf) {
  4960. const otherLeafType = typeof otherLeaf.value_;
  4961. const thisLeafType = typeof this.value_;
  4962. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4963. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4964. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4965. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4966. if (otherIndex === thisIndex) {
  4967. // Same type, compare values
  4968. if (thisLeafType === 'object') {
  4969. // Deferred value nodes are all equal, but we should also never get to this point...
  4970. return 0;
  4971. }
  4972. else {
  4973. // Note that this works because true > false, all others are number or string comparisons
  4974. if (this.value_ < otherLeaf.value_) {
  4975. return -1;
  4976. }
  4977. else if (this.value_ === otherLeaf.value_) {
  4978. return 0;
  4979. }
  4980. else {
  4981. return 1;
  4982. }
  4983. }
  4984. }
  4985. else {
  4986. return thisIndex - otherIndex;
  4987. }
  4988. }
  4989. withIndex() {
  4990. return this;
  4991. }
  4992. isIndexed() {
  4993. return true;
  4994. }
  4995. equals(other) {
  4996. if (other === this) {
  4997. return true;
  4998. }
  4999. else if (other.isLeafNode()) {
  5000. const otherLeaf = other;
  5001. return (this.value_ === otherLeaf.value_ &&
  5002. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5003. }
  5004. else {
  5005. return false;
  5006. }
  5007. }
  5008. }
  5009. /**
  5010. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5011. * the same type, the comparison falls back to their value
  5012. */
  5013. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5014. /**
  5015. * @license
  5016. * Copyright 2017 Google LLC
  5017. *
  5018. * Licensed under the Apache License, Version 2.0 (the "License");
  5019. * you may not use this file except in compliance with the License.
  5020. * You may obtain a copy of the License at
  5021. *
  5022. * http://www.apache.org/licenses/LICENSE-2.0
  5023. *
  5024. * Unless required by applicable law or agreed to in writing, software
  5025. * distributed under the License is distributed on an "AS IS" BASIS,
  5026. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5027. * See the License for the specific language governing permissions and
  5028. * limitations under the License.
  5029. */
  5030. let nodeFromJSON$1;
  5031. let MAX_NODE$1;
  5032. function setNodeFromJSON(val) {
  5033. nodeFromJSON$1 = val;
  5034. }
  5035. function setMaxNode(val) {
  5036. MAX_NODE$1 = val;
  5037. }
  5038. class PriorityIndex extends Index {
  5039. compare(a, b) {
  5040. const aPriority = a.node.getPriority();
  5041. const bPriority = b.node.getPriority();
  5042. const indexCmp = aPriority.compareTo(bPriority);
  5043. if (indexCmp === 0) {
  5044. return nameCompare(a.name, b.name);
  5045. }
  5046. else {
  5047. return indexCmp;
  5048. }
  5049. }
  5050. isDefinedOn(node) {
  5051. return !node.getPriority().isEmpty();
  5052. }
  5053. indexedValueChanged(oldNode, newNode) {
  5054. return !oldNode.getPriority().equals(newNode.getPriority());
  5055. }
  5056. minPost() {
  5057. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5058. return NamedNode.MIN;
  5059. }
  5060. maxPost() {
  5061. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5062. }
  5063. makePost(indexValue, name) {
  5064. const priorityNode = nodeFromJSON$1(indexValue);
  5065. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5066. }
  5067. /**
  5068. * @returns String representation for inclusion in a query spec
  5069. */
  5070. toString() {
  5071. return '.priority';
  5072. }
  5073. }
  5074. const PRIORITY_INDEX = new PriorityIndex();
  5075. /**
  5076. * @license
  5077. * Copyright 2017 Google LLC
  5078. *
  5079. * Licensed under the Apache License, Version 2.0 (the "License");
  5080. * you may not use this file except in compliance with the License.
  5081. * You may obtain a copy of the License at
  5082. *
  5083. * http://www.apache.org/licenses/LICENSE-2.0
  5084. *
  5085. * Unless required by applicable law or agreed to in writing, software
  5086. * distributed under the License is distributed on an "AS IS" BASIS,
  5087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5088. * See the License for the specific language governing permissions and
  5089. * limitations under the License.
  5090. */
  5091. const LOG_2 = Math.log(2);
  5092. class Base12Num {
  5093. constructor(length) {
  5094. const logBase2 = (num) =>
  5095. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5096. parseInt((Math.log(num) / LOG_2), 10);
  5097. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5098. this.count = logBase2(length + 1);
  5099. this.current_ = this.count - 1;
  5100. const mask = bitMask(this.count);
  5101. this.bits_ = (length + 1) & mask;
  5102. }
  5103. nextBitIsOne() {
  5104. //noinspection JSBitwiseOperatorUsage
  5105. const result = !(this.bits_ & (0x1 << this.current_));
  5106. this.current_--;
  5107. return result;
  5108. }
  5109. }
  5110. /**
  5111. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5112. * function
  5113. *
  5114. * Uses the algorithm described in the paper linked here:
  5115. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5116. *
  5117. * @param childList - Unsorted list of children
  5118. * @param cmp - The comparison method to be used
  5119. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5120. * type is not NamedNode
  5121. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5122. */
  5123. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5124. childList.sort(cmp);
  5125. const buildBalancedTree = function (low, high) {
  5126. const length = high - low;
  5127. let namedNode;
  5128. let key;
  5129. if (length === 0) {
  5130. return null;
  5131. }
  5132. else if (length === 1) {
  5133. namedNode = childList[low];
  5134. key = keyFn ? keyFn(namedNode) : namedNode;
  5135. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5136. }
  5137. else {
  5138. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5139. const middle = parseInt((length / 2), 10) + low;
  5140. const left = buildBalancedTree(low, middle);
  5141. const right = buildBalancedTree(middle + 1, high);
  5142. namedNode = childList[middle];
  5143. key = keyFn ? keyFn(namedNode) : namedNode;
  5144. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5145. }
  5146. };
  5147. const buildFrom12Array = function (base12) {
  5148. let node = null;
  5149. let root = null;
  5150. let index = childList.length;
  5151. const buildPennant = function (chunkSize, color) {
  5152. const low = index - chunkSize;
  5153. const high = index;
  5154. index -= chunkSize;
  5155. const childTree = buildBalancedTree(low + 1, high);
  5156. const namedNode = childList[low];
  5157. const key = keyFn ? keyFn(namedNode) : namedNode;
  5158. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5159. };
  5160. const attachPennant = function (pennant) {
  5161. if (node) {
  5162. node.left = pennant;
  5163. node = pennant;
  5164. }
  5165. else {
  5166. root = pennant;
  5167. node = pennant;
  5168. }
  5169. };
  5170. for (let i = 0; i < base12.count; ++i) {
  5171. const isOne = base12.nextBitIsOne();
  5172. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5173. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5174. if (isOne) {
  5175. buildPennant(chunkSize, LLRBNode.BLACK);
  5176. }
  5177. else {
  5178. // current == 2
  5179. buildPennant(chunkSize, LLRBNode.BLACK);
  5180. buildPennant(chunkSize, LLRBNode.RED);
  5181. }
  5182. }
  5183. return root;
  5184. };
  5185. const base12 = new Base12Num(childList.length);
  5186. const root = buildFrom12Array(base12);
  5187. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5188. return new SortedMap(mapSortFn || cmp, root);
  5189. };
  5190. /**
  5191. * @license
  5192. * Copyright 2017 Google LLC
  5193. *
  5194. * Licensed under the Apache License, Version 2.0 (the "License");
  5195. * you may not use this file except in compliance with the License.
  5196. * You may obtain a copy of the License at
  5197. *
  5198. * http://www.apache.org/licenses/LICENSE-2.0
  5199. *
  5200. * Unless required by applicable law or agreed to in writing, software
  5201. * distributed under the License is distributed on an "AS IS" BASIS,
  5202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5203. * See the License for the specific language governing permissions and
  5204. * limitations under the License.
  5205. */
  5206. let _defaultIndexMap;
  5207. const fallbackObject = {};
  5208. class IndexMap {
  5209. constructor(indexes_, indexSet_) {
  5210. this.indexes_ = indexes_;
  5211. this.indexSet_ = indexSet_;
  5212. }
  5213. /**
  5214. * The default IndexMap for nodes without a priority
  5215. */
  5216. static get Default() {
  5217. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5218. _defaultIndexMap =
  5219. _defaultIndexMap ||
  5220. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5221. return _defaultIndexMap;
  5222. }
  5223. get(indexKey) {
  5224. const sortedMap = util.safeGet(this.indexes_, indexKey);
  5225. if (!sortedMap) {
  5226. throw new Error('No index defined for ' + indexKey);
  5227. }
  5228. if (sortedMap instanceof SortedMap) {
  5229. return sortedMap;
  5230. }
  5231. else {
  5232. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5233. // regular child map
  5234. return null;
  5235. }
  5236. }
  5237. hasIndex(indexDefinition) {
  5238. return util.contains(this.indexSet_, indexDefinition.toString());
  5239. }
  5240. addIndex(indexDefinition, existingChildren) {
  5241. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5242. const childList = [];
  5243. let sawIndexedValue = false;
  5244. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5245. let next = iter.getNext();
  5246. while (next) {
  5247. sawIndexedValue =
  5248. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5249. childList.push(next);
  5250. next = iter.getNext();
  5251. }
  5252. let newIndex;
  5253. if (sawIndexedValue) {
  5254. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5255. }
  5256. else {
  5257. newIndex = fallbackObject;
  5258. }
  5259. const indexName = indexDefinition.toString();
  5260. const newIndexSet = Object.assign({}, this.indexSet_);
  5261. newIndexSet[indexName] = indexDefinition;
  5262. const newIndexes = Object.assign({}, this.indexes_);
  5263. newIndexes[indexName] = newIndex;
  5264. return new IndexMap(newIndexes, newIndexSet);
  5265. }
  5266. /**
  5267. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5268. */
  5269. addToIndexes(namedNode, existingChildren) {
  5270. const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => {
  5271. const index = util.safeGet(this.indexSet_, indexName);
  5272. util.assert(index, 'Missing index implementation for ' + indexName);
  5273. if (indexedChildren === fallbackObject) {
  5274. // Check to see if we need to index everything
  5275. if (index.isDefinedOn(namedNode.node)) {
  5276. // We need to build this index
  5277. const childList = [];
  5278. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5279. let next = iter.getNext();
  5280. while (next) {
  5281. if (next.name !== namedNode.name) {
  5282. childList.push(next);
  5283. }
  5284. next = iter.getNext();
  5285. }
  5286. childList.push(namedNode);
  5287. return buildChildSet(childList, index.getCompare());
  5288. }
  5289. else {
  5290. // No change, this remains a fallback
  5291. return fallbackObject;
  5292. }
  5293. }
  5294. else {
  5295. const existingSnap = existingChildren.get(namedNode.name);
  5296. let newChildren = indexedChildren;
  5297. if (existingSnap) {
  5298. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5299. }
  5300. return newChildren.insert(namedNode, namedNode.node);
  5301. }
  5302. });
  5303. return new IndexMap(newIndexes, this.indexSet_);
  5304. }
  5305. /**
  5306. * Create a new IndexMap instance with the given value removed
  5307. */
  5308. removeFromIndexes(namedNode, existingChildren) {
  5309. const newIndexes = util.map(this.indexes_, (indexedChildren) => {
  5310. if (indexedChildren === fallbackObject) {
  5311. // This is the fallback. Just return it, nothing to do in this case
  5312. return indexedChildren;
  5313. }
  5314. else {
  5315. const existingSnap = existingChildren.get(namedNode.name);
  5316. if (existingSnap) {
  5317. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5318. }
  5319. else {
  5320. // No record of this child
  5321. return indexedChildren;
  5322. }
  5323. }
  5324. });
  5325. return new IndexMap(newIndexes, this.indexSet_);
  5326. }
  5327. }
  5328. /**
  5329. * @license
  5330. * Copyright 2017 Google LLC
  5331. *
  5332. * Licensed under the Apache License, Version 2.0 (the "License");
  5333. * you may not use this file except in compliance with the License.
  5334. * You may obtain a copy of the License at
  5335. *
  5336. * http://www.apache.org/licenses/LICENSE-2.0
  5337. *
  5338. * Unless required by applicable law or agreed to in writing, software
  5339. * distributed under the License is distributed on an "AS IS" BASIS,
  5340. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5341. * See the License for the specific language governing permissions and
  5342. * limitations under the License.
  5343. */
  5344. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5345. let EMPTY_NODE;
  5346. /**
  5347. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5348. * (i.e. nodes with children). It implements Node and stores the
  5349. * list of children in the children property, sorted by child name.
  5350. */
  5351. class ChildrenNode {
  5352. /**
  5353. * @param children_ - List of children of this node..
  5354. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5355. */
  5356. constructor(children_, priorityNode_, indexMap_) {
  5357. this.children_ = children_;
  5358. this.priorityNode_ = priorityNode_;
  5359. this.indexMap_ = indexMap_;
  5360. this.lazyHash_ = null;
  5361. /**
  5362. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5363. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5364. * class instead of an empty ChildrenNode.
  5365. */
  5366. if (this.priorityNode_) {
  5367. validatePriorityNode(this.priorityNode_);
  5368. }
  5369. if (this.children_.isEmpty()) {
  5370. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5371. }
  5372. }
  5373. static get EMPTY_NODE() {
  5374. return (EMPTY_NODE ||
  5375. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5376. }
  5377. /** @inheritDoc */
  5378. isLeafNode() {
  5379. return false;
  5380. }
  5381. /** @inheritDoc */
  5382. getPriority() {
  5383. return this.priorityNode_ || EMPTY_NODE;
  5384. }
  5385. /** @inheritDoc */
  5386. updatePriority(newPriorityNode) {
  5387. if (this.children_.isEmpty()) {
  5388. // Don't allow priorities on empty nodes
  5389. return this;
  5390. }
  5391. else {
  5392. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5393. }
  5394. }
  5395. /** @inheritDoc */
  5396. getImmediateChild(childName) {
  5397. // Hack to treat priority as a regular child
  5398. if (childName === '.priority') {
  5399. return this.getPriority();
  5400. }
  5401. else {
  5402. const child = this.children_.get(childName);
  5403. return child === null ? EMPTY_NODE : child;
  5404. }
  5405. }
  5406. /** @inheritDoc */
  5407. getChild(path) {
  5408. const front = pathGetFront(path);
  5409. if (front === null) {
  5410. return this;
  5411. }
  5412. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5413. }
  5414. /** @inheritDoc */
  5415. hasChild(childName) {
  5416. return this.children_.get(childName) !== null;
  5417. }
  5418. /** @inheritDoc */
  5419. updateImmediateChild(childName, newChildNode) {
  5420. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  5421. if (childName === '.priority') {
  5422. return this.updatePriority(newChildNode);
  5423. }
  5424. else {
  5425. const namedNode = new NamedNode(childName, newChildNode);
  5426. let newChildren, newIndexMap;
  5427. if (newChildNode.isEmpty()) {
  5428. newChildren = this.children_.remove(childName);
  5429. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5430. }
  5431. else {
  5432. newChildren = this.children_.insert(childName, newChildNode);
  5433. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5434. }
  5435. const newPriority = newChildren.isEmpty()
  5436. ? EMPTY_NODE
  5437. : this.priorityNode_;
  5438. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5439. }
  5440. }
  5441. /** @inheritDoc */
  5442. updateChild(path, newChildNode) {
  5443. const front = pathGetFront(path);
  5444. if (front === null) {
  5445. return newChildNode;
  5446. }
  5447. else {
  5448. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5449. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5450. return this.updateImmediateChild(front, newImmediateChild);
  5451. }
  5452. }
  5453. /** @inheritDoc */
  5454. isEmpty() {
  5455. return this.children_.isEmpty();
  5456. }
  5457. /** @inheritDoc */
  5458. numChildren() {
  5459. return this.children_.count();
  5460. }
  5461. /** @inheritDoc */
  5462. val(exportFormat) {
  5463. if (this.isEmpty()) {
  5464. return null;
  5465. }
  5466. const obj = {};
  5467. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5468. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5469. obj[key] = childNode.val(exportFormat);
  5470. numKeys++;
  5471. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5472. maxKey = Math.max(maxKey, Number(key));
  5473. }
  5474. else {
  5475. allIntegerKeys = false;
  5476. }
  5477. });
  5478. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5479. // convert to array.
  5480. const array = [];
  5481. // eslint-disable-next-line guard-for-in
  5482. for (const key in obj) {
  5483. array[key] = obj[key];
  5484. }
  5485. return array;
  5486. }
  5487. else {
  5488. if (exportFormat && !this.getPriority().isEmpty()) {
  5489. obj['.priority'] = this.getPriority().val();
  5490. }
  5491. return obj;
  5492. }
  5493. }
  5494. /** @inheritDoc */
  5495. hash() {
  5496. if (this.lazyHash_ === null) {
  5497. let toHash = '';
  5498. if (!this.getPriority().isEmpty()) {
  5499. toHash +=
  5500. 'priority:' +
  5501. priorityHashText(this.getPriority().val()) +
  5502. ':';
  5503. }
  5504. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5505. const childHash = childNode.hash();
  5506. if (childHash !== '') {
  5507. toHash += ':' + key + ':' + childHash;
  5508. }
  5509. });
  5510. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5511. }
  5512. return this.lazyHash_;
  5513. }
  5514. /** @inheritDoc */
  5515. getPredecessorChildName(childName, childNode, index) {
  5516. const idx = this.resolveIndex_(index);
  5517. if (idx) {
  5518. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5519. return predecessor ? predecessor.name : null;
  5520. }
  5521. else {
  5522. return this.children_.getPredecessorKey(childName);
  5523. }
  5524. }
  5525. getFirstChildName(indexDefinition) {
  5526. const idx = this.resolveIndex_(indexDefinition);
  5527. if (idx) {
  5528. const minKey = idx.minKey();
  5529. return minKey && minKey.name;
  5530. }
  5531. else {
  5532. return this.children_.minKey();
  5533. }
  5534. }
  5535. getFirstChild(indexDefinition) {
  5536. const minKey = this.getFirstChildName(indexDefinition);
  5537. if (minKey) {
  5538. return new NamedNode(minKey, this.children_.get(minKey));
  5539. }
  5540. else {
  5541. return null;
  5542. }
  5543. }
  5544. /**
  5545. * Given an index, return the key name of the largest value we have, according to that index
  5546. */
  5547. getLastChildName(indexDefinition) {
  5548. const idx = this.resolveIndex_(indexDefinition);
  5549. if (idx) {
  5550. const maxKey = idx.maxKey();
  5551. return maxKey && maxKey.name;
  5552. }
  5553. else {
  5554. return this.children_.maxKey();
  5555. }
  5556. }
  5557. getLastChild(indexDefinition) {
  5558. const maxKey = this.getLastChildName(indexDefinition);
  5559. if (maxKey) {
  5560. return new NamedNode(maxKey, this.children_.get(maxKey));
  5561. }
  5562. else {
  5563. return null;
  5564. }
  5565. }
  5566. forEachChild(index, action) {
  5567. const idx = this.resolveIndex_(index);
  5568. if (idx) {
  5569. return idx.inorderTraversal(wrappedNode => {
  5570. return action(wrappedNode.name, wrappedNode.node);
  5571. });
  5572. }
  5573. else {
  5574. return this.children_.inorderTraversal(action);
  5575. }
  5576. }
  5577. getIterator(indexDefinition) {
  5578. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5579. }
  5580. getIteratorFrom(startPost, indexDefinition) {
  5581. const idx = this.resolveIndex_(indexDefinition);
  5582. if (idx) {
  5583. return idx.getIteratorFrom(startPost, key => key);
  5584. }
  5585. else {
  5586. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5587. let next = iterator.peek();
  5588. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5589. iterator.getNext();
  5590. next = iterator.peek();
  5591. }
  5592. return iterator;
  5593. }
  5594. }
  5595. getReverseIterator(indexDefinition) {
  5596. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5597. }
  5598. getReverseIteratorFrom(endPost, indexDefinition) {
  5599. const idx = this.resolveIndex_(indexDefinition);
  5600. if (idx) {
  5601. return idx.getReverseIteratorFrom(endPost, key => {
  5602. return key;
  5603. });
  5604. }
  5605. else {
  5606. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5607. let next = iterator.peek();
  5608. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5609. iterator.getNext();
  5610. next = iterator.peek();
  5611. }
  5612. return iterator;
  5613. }
  5614. }
  5615. compareTo(other) {
  5616. if (this.isEmpty()) {
  5617. if (other.isEmpty()) {
  5618. return 0;
  5619. }
  5620. else {
  5621. return -1;
  5622. }
  5623. }
  5624. else if (other.isLeafNode() || other.isEmpty()) {
  5625. return 1;
  5626. }
  5627. else if (other === MAX_NODE) {
  5628. return -1;
  5629. }
  5630. else {
  5631. // Must be another node with children.
  5632. return 0;
  5633. }
  5634. }
  5635. withIndex(indexDefinition) {
  5636. if (indexDefinition === KEY_INDEX ||
  5637. this.indexMap_.hasIndex(indexDefinition)) {
  5638. return this;
  5639. }
  5640. else {
  5641. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5642. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5643. }
  5644. }
  5645. isIndexed(index) {
  5646. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5647. }
  5648. equals(other) {
  5649. if (other === this) {
  5650. return true;
  5651. }
  5652. else if (other.isLeafNode()) {
  5653. return false;
  5654. }
  5655. else {
  5656. const otherChildrenNode = other;
  5657. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5658. return false;
  5659. }
  5660. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5661. const thisIter = this.getIterator(PRIORITY_INDEX);
  5662. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5663. let thisCurrent = thisIter.getNext();
  5664. let otherCurrent = otherIter.getNext();
  5665. while (thisCurrent && otherCurrent) {
  5666. if (thisCurrent.name !== otherCurrent.name ||
  5667. !thisCurrent.node.equals(otherCurrent.node)) {
  5668. return false;
  5669. }
  5670. thisCurrent = thisIter.getNext();
  5671. otherCurrent = otherIter.getNext();
  5672. }
  5673. return thisCurrent === null && otherCurrent === null;
  5674. }
  5675. else {
  5676. return false;
  5677. }
  5678. }
  5679. }
  5680. /**
  5681. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5682. * instead.
  5683. *
  5684. */
  5685. resolveIndex_(indexDefinition) {
  5686. if (indexDefinition === KEY_INDEX) {
  5687. return null;
  5688. }
  5689. else {
  5690. return this.indexMap_.get(indexDefinition.toString());
  5691. }
  5692. }
  5693. }
  5694. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5695. class MaxNode extends ChildrenNode {
  5696. constructor() {
  5697. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5698. }
  5699. compareTo(other) {
  5700. if (other === this) {
  5701. return 0;
  5702. }
  5703. else {
  5704. return 1;
  5705. }
  5706. }
  5707. equals(other) {
  5708. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5709. return other === this;
  5710. }
  5711. getPriority() {
  5712. return this;
  5713. }
  5714. getImmediateChild(childName) {
  5715. return ChildrenNode.EMPTY_NODE;
  5716. }
  5717. isEmpty() {
  5718. return false;
  5719. }
  5720. }
  5721. /**
  5722. * Marker that will sort higher than any other snapshot.
  5723. */
  5724. const MAX_NODE = new MaxNode();
  5725. Object.defineProperties(NamedNode, {
  5726. MIN: {
  5727. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5728. },
  5729. MAX: {
  5730. value: new NamedNode(MAX_NAME, MAX_NODE)
  5731. }
  5732. });
  5733. /**
  5734. * Reference Extensions
  5735. */
  5736. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5737. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5738. setMaxNode$1(MAX_NODE);
  5739. setMaxNode(MAX_NODE);
  5740. /**
  5741. * @license
  5742. * Copyright 2017 Google LLC
  5743. *
  5744. * Licensed under the Apache License, Version 2.0 (the "License");
  5745. * you may not use this file except in compliance with the License.
  5746. * You may obtain a copy of the License at
  5747. *
  5748. * http://www.apache.org/licenses/LICENSE-2.0
  5749. *
  5750. * Unless required by applicable law or agreed to in writing, software
  5751. * distributed under the License is distributed on an "AS IS" BASIS,
  5752. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5753. * See the License for the specific language governing permissions and
  5754. * limitations under the License.
  5755. */
  5756. const USE_HINZE = true;
  5757. /**
  5758. * Constructs a snapshot node representing the passed JSON and returns it.
  5759. * @param json - JSON to create a node for.
  5760. * @param priority - Optional priority to use. This will be ignored if the
  5761. * passed JSON contains a .priority property.
  5762. */
  5763. function nodeFromJSON(json, priority = null) {
  5764. if (json === null) {
  5765. return ChildrenNode.EMPTY_NODE;
  5766. }
  5767. if (typeof json === 'object' && '.priority' in json) {
  5768. priority = json['.priority'];
  5769. }
  5770. util.assert(priority === null ||
  5771. typeof priority === 'string' ||
  5772. typeof priority === 'number' ||
  5773. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5774. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5775. json = json['.value'];
  5776. }
  5777. // Valid leaf nodes include non-objects or server-value wrapper objects
  5778. if (typeof json !== 'object' || '.sv' in json) {
  5779. const jsonLeaf = json;
  5780. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5781. }
  5782. if (!(json instanceof Array) && USE_HINZE) {
  5783. const children = [];
  5784. let childrenHavePriority = false;
  5785. const hinzeJsonObj = json;
  5786. each(hinzeJsonObj, (key, child) => {
  5787. if (key.substring(0, 1) !== '.') {
  5788. // Ignore metadata nodes
  5789. const childNode = nodeFromJSON(child);
  5790. if (!childNode.isEmpty()) {
  5791. childrenHavePriority =
  5792. childrenHavePriority || !childNode.getPriority().isEmpty();
  5793. children.push(new NamedNode(key, childNode));
  5794. }
  5795. }
  5796. });
  5797. if (children.length === 0) {
  5798. return ChildrenNode.EMPTY_NODE;
  5799. }
  5800. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5801. if (childrenHavePriority) {
  5802. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5803. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5804. }
  5805. else {
  5806. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5807. }
  5808. }
  5809. else {
  5810. let node = ChildrenNode.EMPTY_NODE;
  5811. each(json, (key, childData) => {
  5812. if (util.contains(json, key)) {
  5813. if (key.substring(0, 1) !== '.') {
  5814. // ignore metadata nodes.
  5815. const childNode = nodeFromJSON(childData);
  5816. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5817. node = node.updateImmediateChild(key, childNode);
  5818. }
  5819. }
  5820. }
  5821. });
  5822. return node.updatePriority(nodeFromJSON(priority));
  5823. }
  5824. }
  5825. setNodeFromJSON(nodeFromJSON);
  5826. /**
  5827. * @license
  5828. * Copyright 2017 Google LLC
  5829. *
  5830. * Licensed under the Apache License, Version 2.0 (the "License");
  5831. * you may not use this file except in compliance with the License.
  5832. * You may obtain a copy of the License at
  5833. *
  5834. * http://www.apache.org/licenses/LICENSE-2.0
  5835. *
  5836. * Unless required by applicable law or agreed to in writing, software
  5837. * distributed under the License is distributed on an "AS IS" BASIS,
  5838. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5839. * See the License for the specific language governing permissions and
  5840. * limitations under the License.
  5841. */
  5842. class PathIndex extends Index {
  5843. constructor(indexPath_) {
  5844. super();
  5845. this.indexPath_ = indexPath_;
  5846. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5847. }
  5848. extractChild(snap) {
  5849. return snap.getChild(this.indexPath_);
  5850. }
  5851. isDefinedOn(node) {
  5852. return !node.getChild(this.indexPath_).isEmpty();
  5853. }
  5854. compare(a, b) {
  5855. const aChild = this.extractChild(a.node);
  5856. const bChild = this.extractChild(b.node);
  5857. const indexCmp = aChild.compareTo(bChild);
  5858. if (indexCmp === 0) {
  5859. return nameCompare(a.name, b.name);
  5860. }
  5861. else {
  5862. return indexCmp;
  5863. }
  5864. }
  5865. makePost(indexValue, name) {
  5866. const valueNode = nodeFromJSON(indexValue);
  5867. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5868. return new NamedNode(name, node);
  5869. }
  5870. maxPost() {
  5871. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5872. return new NamedNode(MAX_NAME, node);
  5873. }
  5874. toString() {
  5875. return pathSlice(this.indexPath_, 0).join('/');
  5876. }
  5877. }
  5878. /**
  5879. * @license
  5880. * Copyright 2017 Google LLC
  5881. *
  5882. * Licensed under the Apache License, Version 2.0 (the "License");
  5883. * you may not use this file except in compliance with the License.
  5884. * You may obtain a copy of the License at
  5885. *
  5886. * http://www.apache.org/licenses/LICENSE-2.0
  5887. *
  5888. * Unless required by applicable law or agreed to in writing, software
  5889. * distributed under the License is distributed on an "AS IS" BASIS,
  5890. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5891. * See the License for the specific language governing permissions and
  5892. * limitations under the License.
  5893. */
  5894. class ValueIndex extends Index {
  5895. compare(a, b) {
  5896. const indexCmp = a.node.compareTo(b.node);
  5897. if (indexCmp === 0) {
  5898. return nameCompare(a.name, b.name);
  5899. }
  5900. else {
  5901. return indexCmp;
  5902. }
  5903. }
  5904. isDefinedOn(node) {
  5905. return true;
  5906. }
  5907. indexedValueChanged(oldNode, newNode) {
  5908. return !oldNode.equals(newNode);
  5909. }
  5910. minPost() {
  5911. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5912. return NamedNode.MIN;
  5913. }
  5914. maxPost() {
  5915. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5916. return NamedNode.MAX;
  5917. }
  5918. makePost(indexValue, name) {
  5919. const valueNode = nodeFromJSON(indexValue);
  5920. return new NamedNode(name, valueNode);
  5921. }
  5922. /**
  5923. * @returns String representation for inclusion in a query spec
  5924. */
  5925. toString() {
  5926. return '.value';
  5927. }
  5928. }
  5929. const VALUE_INDEX = new ValueIndex();
  5930. /**
  5931. * @license
  5932. * Copyright 2017 Google LLC
  5933. *
  5934. * Licensed under the Apache License, Version 2.0 (the "License");
  5935. * you may not use this file except in compliance with the License.
  5936. * You may obtain a copy of the License at
  5937. *
  5938. * http://www.apache.org/licenses/LICENSE-2.0
  5939. *
  5940. * Unless required by applicable law or agreed to in writing, software
  5941. * distributed under the License is distributed on an "AS IS" BASIS,
  5942. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5943. * See the License for the specific language governing permissions and
  5944. * limitations under the License.
  5945. */
  5946. function changeValue(snapshotNode) {
  5947. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5948. }
  5949. function changeChildAdded(childName, snapshotNode) {
  5950. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5951. }
  5952. function changeChildRemoved(childName, snapshotNode) {
  5953. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5954. }
  5955. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5956. return {
  5957. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5958. snapshotNode,
  5959. childName,
  5960. oldSnap
  5961. };
  5962. }
  5963. function changeChildMoved(childName, snapshotNode) {
  5964. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5965. }
  5966. /**
  5967. * @license
  5968. * Copyright 2017 Google LLC
  5969. *
  5970. * Licensed under the Apache License, Version 2.0 (the "License");
  5971. * you may not use this file except in compliance with the License.
  5972. * You may obtain a copy of the License at
  5973. *
  5974. * http://www.apache.org/licenses/LICENSE-2.0
  5975. *
  5976. * Unless required by applicable law or agreed to in writing, software
  5977. * distributed under the License is distributed on an "AS IS" BASIS,
  5978. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5979. * See the License for the specific language governing permissions and
  5980. * limitations under the License.
  5981. */
  5982. /**
  5983. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5984. */
  5985. class IndexedFilter {
  5986. constructor(index_) {
  5987. this.index_ = index_;
  5988. }
  5989. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5990. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5991. const oldChild = snap.getImmediateChild(key);
  5992. // Check if anything actually changed.
  5993. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5994. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5995. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5996. // to avoid treating these cases as "nothing changed."
  5997. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5998. // Nothing changed.
  5999. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  6000. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  6001. return snap;
  6002. }
  6003. }
  6004. if (optChangeAccumulator != null) {
  6005. if (newChild.isEmpty()) {
  6006. if (snap.hasChild(key)) {
  6007. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6008. }
  6009. else {
  6010. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6011. }
  6012. }
  6013. else if (oldChild.isEmpty()) {
  6014. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6015. }
  6016. else {
  6017. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6018. }
  6019. }
  6020. if (snap.isLeafNode() && newChild.isEmpty()) {
  6021. return snap;
  6022. }
  6023. else {
  6024. // Make sure the node is indexed
  6025. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6026. }
  6027. }
  6028. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6029. if (optChangeAccumulator != null) {
  6030. if (!oldSnap.isLeafNode()) {
  6031. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6032. if (!newSnap.hasChild(key)) {
  6033. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6034. }
  6035. });
  6036. }
  6037. if (!newSnap.isLeafNode()) {
  6038. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6039. if (oldSnap.hasChild(key)) {
  6040. const oldChild = oldSnap.getImmediateChild(key);
  6041. if (!oldChild.equals(childNode)) {
  6042. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6043. }
  6044. }
  6045. else {
  6046. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6047. }
  6048. });
  6049. }
  6050. }
  6051. return newSnap.withIndex(this.index_);
  6052. }
  6053. updatePriority(oldSnap, newPriority) {
  6054. if (oldSnap.isEmpty()) {
  6055. return ChildrenNode.EMPTY_NODE;
  6056. }
  6057. else {
  6058. return oldSnap.updatePriority(newPriority);
  6059. }
  6060. }
  6061. filtersNodes() {
  6062. return false;
  6063. }
  6064. getIndexedFilter() {
  6065. return this;
  6066. }
  6067. getIndex() {
  6068. return this.index_;
  6069. }
  6070. }
  6071. /**
  6072. * @license
  6073. * Copyright 2017 Google LLC
  6074. *
  6075. * Licensed under the Apache License, Version 2.0 (the "License");
  6076. * you may not use this file except in compliance with the License.
  6077. * You may obtain a copy of the License at
  6078. *
  6079. * http://www.apache.org/licenses/LICENSE-2.0
  6080. *
  6081. * Unless required by applicable law or agreed to in writing, software
  6082. * distributed under the License is distributed on an "AS IS" BASIS,
  6083. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6084. * See the License for the specific language governing permissions and
  6085. * limitations under the License.
  6086. */
  6087. /**
  6088. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6089. */
  6090. class RangedFilter {
  6091. constructor(params) {
  6092. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6093. this.index_ = params.getIndex();
  6094. this.startPost_ = RangedFilter.getStartPost_(params);
  6095. this.endPost_ = RangedFilter.getEndPost_(params);
  6096. this.startIsInclusive_ = !params.startAfterSet_;
  6097. this.endIsInclusive_ = !params.endBeforeSet_;
  6098. }
  6099. getStartPost() {
  6100. return this.startPost_;
  6101. }
  6102. getEndPost() {
  6103. return this.endPost_;
  6104. }
  6105. matches(node) {
  6106. const isWithinStart = this.startIsInclusive_
  6107. ? this.index_.compare(this.getStartPost(), node) <= 0
  6108. : this.index_.compare(this.getStartPost(), node) < 0;
  6109. const isWithinEnd = this.endIsInclusive_
  6110. ? this.index_.compare(node, this.getEndPost()) <= 0
  6111. : this.index_.compare(node, this.getEndPost()) < 0;
  6112. return isWithinStart && isWithinEnd;
  6113. }
  6114. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6115. if (!this.matches(new NamedNode(key, newChild))) {
  6116. newChild = ChildrenNode.EMPTY_NODE;
  6117. }
  6118. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6119. }
  6120. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6121. if (newSnap.isLeafNode()) {
  6122. // Make sure we have a children node with the correct index, not a leaf node;
  6123. newSnap = ChildrenNode.EMPTY_NODE;
  6124. }
  6125. let filtered = newSnap.withIndex(this.index_);
  6126. // Don't support priorities on queries
  6127. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6128. const self = this;
  6129. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6130. if (!self.matches(new NamedNode(key, childNode))) {
  6131. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6132. }
  6133. });
  6134. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6135. }
  6136. updatePriority(oldSnap, newPriority) {
  6137. // Don't support priorities on queries
  6138. return oldSnap;
  6139. }
  6140. filtersNodes() {
  6141. return true;
  6142. }
  6143. getIndexedFilter() {
  6144. return this.indexedFilter_;
  6145. }
  6146. getIndex() {
  6147. return this.index_;
  6148. }
  6149. static getStartPost_(params) {
  6150. if (params.hasStart()) {
  6151. const startName = params.getIndexStartName();
  6152. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6153. }
  6154. else {
  6155. return params.getIndex().minPost();
  6156. }
  6157. }
  6158. static getEndPost_(params) {
  6159. if (params.hasEnd()) {
  6160. const endName = params.getIndexEndName();
  6161. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6162. }
  6163. else {
  6164. return params.getIndex().maxPost();
  6165. }
  6166. }
  6167. }
  6168. /**
  6169. * @license
  6170. * Copyright 2017 Google LLC
  6171. *
  6172. * Licensed under the Apache License, Version 2.0 (the "License");
  6173. * you may not use this file except in compliance with the License.
  6174. * You may obtain a copy of the License at
  6175. *
  6176. * http://www.apache.org/licenses/LICENSE-2.0
  6177. *
  6178. * Unless required by applicable law or agreed to in writing, software
  6179. * distributed under the License is distributed on an "AS IS" BASIS,
  6180. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6181. * See the License for the specific language governing permissions and
  6182. * limitations under the License.
  6183. */
  6184. /**
  6185. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6186. */
  6187. class LimitedFilter {
  6188. constructor(params) {
  6189. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6190. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6191. this.withinStartPost = (node) => {
  6192. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6193. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6194. };
  6195. this.withinEndPost = (node) => {
  6196. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6197. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6198. };
  6199. this.rangedFilter_ = new RangedFilter(params);
  6200. this.index_ = params.getIndex();
  6201. this.limit_ = params.getLimit();
  6202. this.reverse_ = !params.isViewFromLeft();
  6203. this.startIsInclusive_ = !params.startAfterSet_;
  6204. this.endIsInclusive_ = !params.endBeforeSet_;
  6205. }
  6206. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6207. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6208. newChild = ChildrenNode.EMPTY_NODE;
  6209. }
  6210. if (snap.getImmediateChild(key).equals(newChild)) {
  6211. // No change
  6212. return snap;
  6213. }
  6214. else if (snap.numChildren() < this.limit_) {
  6215. return this.rangedFilter_
  6216. .getIndexedFilter()
  6217. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6218. }
  6219. else {
  6220. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6221. }
  6222. }
  6223. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6224. let filtered;
  6225. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6226. // Make sure we have a children node with the correct index, not a leaf node;
  6227. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6228. }
  6229. else {
  6230. if (this.limit_ * 2 < newSnap.numChildren() &&
  6231. newSnap.isIndexed(this.index_)) {
  6232. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6233. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6234. // anchor to the startPost, endPost, or last element as appropriate
  6235. let iterator;
  6236. if (this.reverse_) {
  6237. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6238. }
  6239. else {
  6240. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6241. }
  6242. let count = 0;
  6243. while (iterator.hasNext() && count < this.limit_) {
  6244. const next = iterator.getNext();
  6245. if (!this.withinDirectionalStart(next)) {
  6246. // if we have not reached the start, skip to the next element
  6247. continue;
  6248. }
  6249. else if (!this.withinDirectionalEnd(next)) {
  6250. // if we have reached the end, stop adding elements
  6251. break;
  6252. }
  6253. else {
  6254. filtered = filtered.updateImmediateChild(next.name, next.node);
  6255. count++;
  6256. }
  6257. }
  6258. }
  6259. else {
  6260. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6261. filtered = newSnap.withIndex(this.index_);
  6262. // Don't support priorities on queries
  6263. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6264. let iterator;
  6265. if (this.reverse_) {
  6266. iterator = filtered.getReverseIterator(this.index_);
  6267. }
  6268. else {
  6269. iterator = filtered.getIterator(this.index_);
  6270. }
  6271. let count = 0;
  6272. while (iterator.hasNext()) {
  6273. const next = iterator.getNext();
  6274. const inRange = count < this.limit_ &&
  6275. this.withinDirectionalStart(next) &&
  6276. this.withinDirectionalEnd(next);
  6277. if (inRange) {
  6278. count++;
  6279. }
  6280. else {
  6281. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6282. }
  6283. }
  6284. }
  6285. }
  6286. return this.rangedFilter_
  6287. .getIndexedFilter()
  6288. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6289. }
  6290. updatePriority(oldSnap, newPriority) {
  6291. // Don't support priorities on queries
  6292. return oldSnap;
  6293. }
  6294. filtersNodes() {
  6295. return true;
  6296. }
  6297. getIndexedFilter() {
  6298. return this.rangedFilter_.getIndexedFilter();
  6299. }
  6300. getIndex() {
  6301. return this.index_;
  6302. }
  6303. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6304. // TODO: rename all cache stuff etc to general snap terminology
  6305. let cmp;
  6306. if (this.reverse_) {
  6307. const indexCmp = this.index_.getCompare();
  6308. cmp = (a, b) => indexCmp(b, a);
  6309. }
  6310. else {
  6311. cmp = this.index_.getCompare();
  6312. }
  6313. const oldEventCache = snap;
  6314. util.assert(oldEventCache.numChildren() === this.limit_, '');
  6315. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6316. const windowBoundary = this.reverse_
  6317. ? oldEventCache.getFirstChild(this.index_)
  6318. : oldEventCache.getLastChild(this.index_);
  6319. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6320. if (oldEventCache.hasChild(childKey)) {
  6321. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6322. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6323. while (nextChild != null &&
  6324. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6325. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6326. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6327. // the limited filter...
  6328. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6329. }
  6330. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6331. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6332. if (remainsInWindow) {
  6333. if (changeAccumulator != null) {
  6334. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6335. }
  6336. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6337. }
  6338. else {
  6339. if (changeAccumulator != null) {
  6340. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6341. }
  6342. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6343. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6344. if (nextChildInRange) {
  6345. if (changeAccumulator != null) {
  6346. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6347. }
  6348. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6349. }
  6350. else {
  6351. return newEventCache;
  6352. }
  6353. }
  6354. }
  6355. else if (childSnap.isEmpty()) {
  6356. // we're deleting a node, but it was not in the window, so ignore it
  6357. return snap;
  6358. }
  6359. else if (inRange) {
  6360. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6361. if (changeAccumulator != null) {
  6362. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6363. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6364. }
  6365. return oldEventCache
  6366. .updateImmediateChild(childKey, childSnap)
  6367. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6368. }
  6369. else {
  6370. return snap;
  6371. }
  6372. }
  6373. else {
  6374. return snap;
  6375. }
  6376. }
  6377. }
  6378. /**
  6379. * @license
  6380. * Copyright 2017 Google LLC
  6381. *
  6382. * Licensed under the Apache License, Version 2.0 (the "License");
  6383. * you may not use this file except in compliance with the License.
  6384. * You may obtain a copy of the License at
  6385. *
  6386. * http://www.apache.org/licenses/LICENSE-2.0
  6387. *
  6388. * Unless required by applicable law or agreed to in writing, software
  6389. * distributed under the License is distributed on an "AS IS" BASIS,
  6390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6391. * See the License for the specific language governing permissions and
  6392. * limitations under the License.
  6393. */
  6394. /**
  6395. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6396. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6397. * user-facing API level, so it is not done here.
  6398. *
  6399. * @internal
  6400. */
  6401. class QueryParams {
  6402. constructor() {
  6403. this.limitSet_ = false;
  6404. this.startSet_ = false;
  6405. this.startNameSet_ = false;
  6406. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6407. this.endSet_ = false;
  6408. this.endNameSet_ = false;
  6409. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6410. this.limit_ = 0;
  6411. this.viewFrom_ = '';
  6412. this.indexStartValue_ = null;
  6413. this.indexStartName_ = '';
  6414. this.indexEndValue_ = null;
  6415. this.indexEndName_ = '';
  6416. this.index_ = PRIORITY_INDEX;
  6417. }
  6418. hasStart() {
  6419. return this.startSet_;
  6420. }
  6421. /**
  6422. * @returns True if it would return from left.
  6423. */
  6424. isViewFromLeft() {
  6425. if (this.viewFrom_ === '') {
  6426. // limit(), rather than limitToFirst or limitToLast was called.
  6427. // This means that only one of startSet_ and endSet_ is true. Use them
  6428. // to calculate which side of the view to anchor to. If neither is set,
  6429. // anchor to the end.
  6430. return this.startSet_;
  6431. }
  6432. else {
  6433. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6434. }
  6435. }
  6436. /**
  6437. * Only valid to call if hasStart() returns true
  6438. */
  6439. getIndexStartValue() {
  6440. util.assert(this.startSet_, 'Only valid if start has been set');
  6441. return this.indexStartValue_;
  6442. }
  6443. /**
  6444. * Only valid to call if hasStart() returns true.
  6445. * Returns the starting key name for the range defined by these query parameters
  6446. */
  6447. getIndexStartName() {
  6448. util.assert(this.startSet_, 'Only valid if start has been set');
  6449. if (this.startNameSet_) {
  6450. return this.indexStartName_;
  6451. }
  6452. else {
  6453. return MIN_NAME;
  6454. }
  6455. }
  6456. hasEnd() {
  6457. return this.endSet_;
  6458. }
  6459. /**
  6460. * Only valid to call if hasEnd() returns true.
  6461. */
  6462. getIndexEndValue() {
  6463. util.assert(this.endSet_, 'Only valid if end has been set');
  6464. return this.indexEndValue_;
  6465. }
  6466. /**
  6467. * Only valid to call if hasEnd() returns true.
  6468. * Returns the end key name for the range defined by these query parameters
  6469. */
  6470. getIndexEndName() {
  6471. util.assert(this.endSet_, 'Only valid if end has been set');
  6472. if (this.endNameSet_) {
  6473. return this.indexEndName_;
  6474. }
  6475. else {
  6476. return MAX_NAME;
  6477. }
  6478. }
  6479. hasLimit() {
  6480. return this.limitSet_;
  6481. }
  6482. /**
  6483. * @returns True if a limit has been set and it has been explicitly anchored
  6484. */
  6485. hasAnchoredLimit() {
  6486. return this.limitSet_ && this.viewFrom_ !== '';
  6487. }
  6488. /**
  6489. * Only valid to call if hasLimit() returns true
  6490. */
  6491. getLimit() {
  6492. util.assert(this.limitSet_, 'Only valid if limit has been set');
  6493. return this.limit_;
  6494. }
  6495. getIndex() {
  6496. return this.index_;
  6497. }
  6498. loadsAllData() {
  6499. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6500. }
  6501. isDefault() {
  6502. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6503. }
  6504. copy() {
  6505. const copy = new QueryParams();
  6506. copy.limitSet_ = this.limitSet_;
  6507. copy.limit_ = this.limit_;
  6508. copy.startSet_ = this.startSet_;
  6509. copy.startAfterSet_ = this.startAfterSet_;
  6510. copy.indexStartValue_ = this.indexStartValue_;
  6511. copy.startNameSet_ = this.startNameSet_;
  6512. copy.indexStartName_ = this.indexStartName_;
  6513. copy.endSet_ = this.endSet_;
  6514. copy.endBeforeSet_ = this.endBeforeSet_;
  6515. copy.indexEndValue_ = this.indexEndValue_;
  6516. copy.endNameSet_ = this.endNameSet_;
  6517. copy.indexEndName_ = this.indexEndName_;
  6518. copy.index_ = this.index_;
  6519. copy.viewFrom_ = this.viewFrom_;
  6520. return copy;
  6521. }
  6522. }
  6523. function queryParamsGetNodeFilter(queryParams) {
  6524. if (queryParams.loadsAllData()) {
  6525. return new IndexedFilter(queryParams.getIndex());
  6526. }
  6527. else if (queryParams.hasLimit()) {
  6528. return new LimitedFilter(queryParams);
  6529. }
  6530. else {
  6531. return new RangedFilter(queryParams);
  6532. }
  6533. }
  6534. function queryParamsLimitToFirst(queryParams, newLimit) {
  6535. const newParams = queryParams.copy();
  6536. newParams.limitSet_ = true;
  6537. newParams.limit_ = newLimit;
  6538. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6539. return newParams;
  6540. }
  6541. function queryParamsLimitToLast(queryParams, newLimit) {
  6542. const newParams = queryParams.copy();
  6543. newParams.limitSet_ = true;
  6544. newParams.limit_ = newLimit;
  6545. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6546. return newParams;
  6547. }
  6548. function queryParamsStartAt(queryParams, indexValue, key) {
  6549. const newParams = queryParams.copy();
  6550. newParams.startSet_ = true;
  6551. if (indexValue === undefined) {
  6552. indexValue = null;
  6553. }
  6554. newParams.indexStartValue_ = indexValue;
  6555. if (key != null) {
  6556. newParams.startNameSet_ = true;
  6557. newParams.indexStartName_ = key;
  6558. }
  6559. else {
  6560. newParams.startNameSet_ = false;
  6561. newParams.indexStartName_ = '';
  6562. }
  6563. return newParams;
  6564. }
  6565. function queryParamsStartAfter(queryParams, indexValue, key) {
  6566. let params;
  6567. if (queryParams.index_ === KEY_INDEX || !!key) {
  6568. params = queryParamsStartAt(queryParams, indexValue, key);
  6569. }
  6570. else {
  6571. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6572. }
  6573. params.startAfterSet_ = true;
  6574. return params;
  6575. }
  6576. function queryParamsEndAt(queryParams, indexValue, key) {
  6577. const newParams = queryParams.copy();
  6578. newParams.endSet_ = true;
  6579. if (indexValue === undefined) {
  6580. indexValue = null;
  6581. }
  6582. newParams.indexEndValue_ = indexValue;
  6583. if (key !== undefined) {
  6584. newParams.endNameSet_ = true;
  6585. newParams.indexEndName_ = key;
  6586. }
  6587. else {
  6588. newParams.endNameSet_ = false;
  6589. newParams.indexEndName_ = '';
  6590. }
  6591. return newParams;
  6592. }
  6593. function queryParamsEndBefore(queryParams, indexValue, key) {
  6594. let params;
  6595. if (queryParams.index_ === KEY_INDEX || !!key) {
  6596. params = queryParamsEndAt(queryParams, indexValue, key);
  6597. }
  6598. else {
  6599. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6600. }
  6601. params.endBeforeSet_ = true;
  6602. return params;
  6603. }
  6604. function queryParamsOrderBy(queryParams, index) {
  6605. const newParams = queryParams.copy();
  6606. newParams.index_ = index;
  6607. return newParams;
  6608. }
  6609. /**
  6610. * Returns a set of REST query string parameters representing this query.
  6611. *
  6612. * @returns query string parameters
  6613. */
  6614. function queryParamsToRestQueryStringParameters(queryParams) {
  6615. const qs = {};
  6616. if (queryParams.isDefault()) {
  6617. return qs;
  6618. }
  6619. let orderBy;
  6620. if (queryParams.index_ === PRIORITY_INDEX) {
  6621. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6622. }
  6623. else if (queryParams.index_ === VALUE_INDEX) {
  6624. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6625. }
  6626. else if (queryParams.index_ === KEY_INDEX) {
  6627. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6628. }
  6629. else {
  6630. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6631. orderBy = queryParams.index_.toString();
  6632. }
  6633. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  6634. if (queryParams.startSet_) {
  6635. const startParam = queryParams.startAfterSet_
  6636. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6637. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6638. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  6639. if (queryParams.startNameSet_) {
  6640. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  6641. }
  6642. }
  6643. if (queryParams.endSet_) {
  6644. const endParam = queryParams.endBeforeSet_
  6645. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6646. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6647. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  6648. if (queryParams.endNameSet_) {
  6649. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  6650. }
  6651. }
  6652. if (queryParams.limitSet_) {
  6653. if (queryParams.isViewFromLeft()) {
  6654. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6655. }
  6656. else {
  6657. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6658. }
  6659. }
  6660. return qs;
  6661. }
  6662. function queryParamsGetQueryObject(queryParams) {
  6663. const obj = {};
  6664. if (queryParams.startSet_) {
  6665. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6666. queryParams.indexStartValue_;
  6667. if (queryParams.startNameSet_) {
  6668. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6669. queryParams.indexStartName_;
  6670. }
  6671. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6672. !queryParams.startAfterSet_;
  6673. }
  6674. if (queryParams.endSet_) {
  6675. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6676. if (queryParams.endNameSet_) {
  6677. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6678. }
  6679. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6680. !queryParams.endBeforeSet_;
  6681. }
  6682. if (queryParams.limitSet_) {
  6683. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6684. let viewFrom = queryParams.viewFrom_;
  6685. if (viewFrom === '') {
  6686. if (queryParams.isViewFromLeft()) {
  6687. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6688. }
  6689. else {
  6690. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6691. }
  6692. }
  6693. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6694. }
  6695. // For now, priority index is the default, so we only specify if it's some other index
  6696. if (queryParams.index_ !== PRIORITY_INDEX) {
  6697. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6698. }
  6699. return obj;
  6700. }
  6701. /**
  6702. * @license
  6703. * Copyright 2017 Google LLC
  6704. *
  6705. * Licensed under the Apache License, Version 2.0 (the "License");
  6706. * you may not use this file except in compliance with the License.
  6707. * You may obtain a copy of the License at
  6708. *
  6709. * http://www.apache.org/licenses/LICENSE-2.0
  6710. *
  6711. * Unless required by applicable law or agreed to in writing, software
  6712. * distributed under the License is distributed on an "AS IS" BASIS,
  6713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6714. * See the License for the specific language governing permissions and
  6715. * limitations under the License.
  6716. */
  6717. /**
  6718. * An implementation of ServerActions that communicates with the server via REST requests.
  6719. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6720. * persistent connection (using WebSockets or long-polling)
  6721. */
  6722. class ReadonlyRestClient extends ServerActions {
  6723. /**
  6724. * @param repoInfo_ - Data about the namespace we are connecting to
  6725. * @param onDataUpdate_ - A callback for new data from the server
  6726. */
  6727. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6728. super();
  6729. this.repoInfo_ = repoInfo_;
  6730. this.onDataUpdate_ = onDataUpdate_;
  6731. this.authTokenProvider_ = authTokenProvider_;
  6732. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6733. /** @private {function(...[*])} */
  6734. this.log_ = logWrapper('p:rest:');
  6735. /**
  6736. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6737. * that's been removed. :-/
  6738. */
  6739. this.listens_ = {};
  6740. }
  6741. reportStats(stats) {
  6742. throw new Error('Method not implemented.');
  6743. }
  6744. static getListenId_(query, tag) {
  6745. if (tag !== undefined) {
  6746. return 'tag$' + tag;
  6747. }
  6748. else {
  6749. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6750. return query._path.toString();
  6751. }
  6752. }
  6753. /** @inheritDoc */
  6754. listen(query, currentHashFn, tag, onComplete) {
  6755. const pathString = query._path.toString();
  6756. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6757. // Mark this listener so we can tell if it's removed.
  6758. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6759. const thisListen = {};
  6760. this.listens_[listenId] = thisListen;
  6761. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6762. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6763. let data = result;
  6764. if (error === 404) {
  6765. data = null;
  6766. error = null;
  6767. }
  6768. if (error === null) {
  6769. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6770. }
  6771. if (util.safeGet(this.listens_, listenId) === thisListen) {
  6772. let status;
  6773. if (!error) {
  6774. status = 'ok';
  6775. }
  6776. else if (error === 401) {
  6777. status = 'permission_denied';
  6778. }
  6779. else {
  6780. status = 'rest_error:' + error;
  6781. }
  6782. onComplete(status, null);
  6783. }
  6784. });
  6785. }
  6786. /** @inheritDoc */
  6787. unlisten(query, tag) {
  6788. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6789. delete this.listens_[listenId];
  6790. }
  6791. get(query) {
  6792. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6793. const pathString = query._path.toString();
  6794. const deferred = new util.Deferred();
  6795. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6796. let data = result;
  6797. if (error === 404) {
  6798. data = null;
  6799. error = null;
  6800. }
  6801. if (error === null) {
  6802. this.onDataUpdate_(pathString, data,
  6803. /*isMerge=*/ false,
  6804. /*tag=*/ null);
  6805. deferred.resolve(data);
  6806. }
  6807. else {
  6808. deferred.reject(new Error(data));
  6809. }
  6810. });
  6811. return deferred.promise;
  6812. }
  6813. /** @inheritDoc */
  6814. refreshAuthToken(token) {
  6815. // no-op since we just always call getToken.
  6816. }
  6817. /**
  6818. * Performs a REST request to the given path, with the provided query string parameters,
  6819. * and any auth credentials we have.
  6820. */
  6821. restRequest_(pathString, queryStringParameters = {}, callback) {
  6822. queryStringParameters['format'] = 'export';
  6823. return Promise.all([
  6824. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6825. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6826. ]).then(([authToken, appCheckToken]) => {
  6827. if (authToken && authToken.accessToken) {
  6828. queryStringParameters['auth'] = authToken.accessToken;
  6829. }
  6830. if (appCheckToken && appCheckToken.token) {
  6831. queryStringParameters['ac'] = appCheckToken.token;
  6832. }
  6833. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6834. this.repoInfo_.host +
  6835. pathString +
  6836. '?' +
  6837. 'ns=' +
  6838. this.repoInfo_.namespace +
  6839. util.querystring(queryStringParameters);
  6840. this.log_('Sending REST request for ' + url);
  6841. const xhr = new XMLHttpRequest();
  6842. xhr.onreadystatechange = () => {
  6843. if (callback && xhr.readyState === 4) {
  6844. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6845. let res = null;
  6846. if (xhr.status >= 200 && xhr.status < 300) {
  6847. try {
  6848. res = util.jsonEval(xhr.responseText);
  6849. }
  6850. catch (e) {
  6851. warn('Failed to parse JSON response for ' +
  6852. url +
  6853. ': ' +
  6854. xhr.responseText);
  6855. }
  6856. callback(null, res);
  6857. }
  6858. else {
  6859. // 401 and 404 are expected.
  6860. if (xhr.status !== 401 && xhr.status !== 404) {
  6861. warn('Got unsuccessful REST response for ' +
  6862. url +
  6863. ' Status: ' +
  6864. xhr.status);
  6865. }
  6866. callback(xhr.status);
  6867. }
  6868. callback = null;
  6869. }
  6870. };
  6871. xhr.open('GET', url, /*asynchronous=*/ true);
  6872. xhr.send();
  6873. });
  6874. }
  6875. }
  6876. /**
  6877. * @license
  6878. * Copyright 2017 Google LLC
  6879. *
  6880. * Licensed under the Apache License, Version 2.0 (the "License");
  6881. * you may not use this file except in compliance with the License.
  6882. * You may obtain a copy of the License at
  6883. *
  6884. * http://www.apache.org/licenses/LICENSE-2.0
  6885. *
  6886. * Unless required by applicable law or agreed to in writing, software
  6887. * distributed under the License is distributed on an "AS IS" BASIS,
  6888. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6889. * See the License for the specific language governing permissions and
  6890. * limitations under the License.
  6891. */
  6892. /**
  6893. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6894. */
  6895. class SnapshotHolder {
  6896. constructor() {
  6897. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6898. }
  6899. getNode(path) {
  6900. return this.rootNode_.getChild(path);
  6901. }
  6902. updateSnapshot(path, newSnapshotNode) {
  6903. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6904. }
  6905. }
  6906. /**
  6907. * @license
  6908. * Copyright 2017 Google LLC
  6909. *
  6910. * Licensed under the Apache License, Version 2.0 (the "License");
  6911. * you may not use this file except in compliance with the License.
  6912. * You may obtain a copy of the License at
  6913. *
  6914. * http://www.apache.org/licenses/LICENSE-2.0
  6915. *
  6916. * Unless required by applicable law or agreed to in writing, software
  6917. * distributed under the License is distributed on an "AS IS" BASIS,
  6918. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6919. * See the License for the specific language governing permissions and
  6920. * limitations under the License.
  6921. */
  6922. function newSparseSnapshotTree() {
  6923. return {
  6924. value: null,
  6925. children: new Map()
  6926. };
  6927. }
  6928. /**
  6929. * Stores the given node at the specified path. If there is already a node
  6930. * at a shallower path, it merges the new data into that snapshot node.
  6931. *
  6932. * @param path - Path to look up snapshot for.
  6933. * @param data - The new data, or null.
  6934. */
  6935. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6936. if (pathIsEmpty(path)) {
  6937. sparseSnapshotTree.value = data;
  6938. sparseSnapshotTree.children.clear();
  6939. }
  6940. else if (sparseSnapshotTree.value !== null) {
  6941. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6942. }
  6943. else {
  6944. const childKey = pathGetFront(path);
  6945. if (!sparseSnapshotTree.children.has(childKey)) {
  6946. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6947. }
  6948. const child = sparseSnapshotTree.children.get(childKey);
  6949. path = pathPopFront(path);
  6950. sparseSnapshotTreeRemember(child, path, data);
  6951. }
  6952. }
  6953. /**
  6954. * Purge the data at path from the cache.
  6955. *
  6956. * @param path - Path to look up snapshot for.
  6957. * @returns True if this node should now be removed.
  6958. */
  6959. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6960. if (pathIsEmpty(path)) {
  6961. sparseSnapshotTree.value = null;
  6962. sparseSnapshotTree.children.clear();
  6963. return true;
  6964. }
  6965. else {
  6966. if (sparseSnapshotTree.value !== null) {
  6967. if (sparseSnapshotTree.value.isLeafNode()) {
  6968. // We're trying to forget a node that doesn't exist
  6969. return false;
  6970. }
  6971. else {
  6972. const value = sparseSnapshotTree.value;
  6973. sparseSnapshotTree.value = null;
  6974. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6975. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6976. });
  6977. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6978. }
  6979. }
  6980. else if (sparseSnapshotTree.children.size > 0) {
  6981. const childKey = pathGetFront(path);
  6982. path = pathPopFront(path);
  6983. if (sparseSnapshotTree.children.has(childKey)) {
  6984. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6985. if (safeToRemove) {
  6986. sparseSnapshotTree.children.delete(childKey);
  6987. }
  6988. }
  6989. return sparseSnapshotTree.children.size === 0;
  6990. }
  6991. else {
  6992. return true;
  6993. }
  6994. }
  6995. }
  6996. /**
  6997. * Recursively iterates through all of the stored tree and calls the
  6998. * callback on each one.
  6999. *
  7000. * @param prefixPath - Path to look up node for.
  7001. * @param func - The function to invoke for each tree.
  7002. */
  7003. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7004. if (sparseSnapshotTree.value !== null) {
  7005. func(prefixPath, sparseSnapshotTree.value);
  7006. }
  7007. else {
  7008. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  7009. const path = new Path(prefixPath.toString() + '/' + key);
  7010. sparseSnapshotTreeForEachTree(tree, path, func);
  7011. });
  7012. }
  7013. }
  7014. /**
  7015. * Iterates through each immediate child and triggers the callback.
  7016. * Only seems to be used in tests.
  7017. *
  7018. * @param func - The function to invoke for each child.
  7019. */
  7020. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7021. sparseSnapshotTree.children.forEach((tree, key) => {
  7022. func(key, tree);
  7023. });
  7024. }
  7025. /**
  7026. * @license
  7027. * Copyright 2017 Google LLC
  7028. *
  7029. * Licensed under the Apache License, Version 2.0 (the "License");
  7030. * you may not use this file except in compliance with the License.
  7031. * You may obtain a copy of the License at
  7032. *
  7033. * http://www.apache.org/licenses/LICENSE-2.0
  7034. *
  7035. * Unless required by applicable law or agreed to in writing, software
  7036. * distributed under the License is distributed on an "AS IS" BASIS,
  7037. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7038. * See the License for the specific language governing permissions and
  7039. * limitations under the License.
  7040. */
  7041. /**
  7042. * Returns the delta from the previous call to get stats.
  7043. *
  7044. * @param collection_ - The collection to "listen" to.
  7045. */
  7046. class StatsListener {
  7047. constructor(collection_) {
  7048. this.collection_ = collection_;
  7049. this.last_ = null;
  7050. }
  7051. get() {
  7052. const newStats = this.collection_.get();
  7053. const delta = Object.assign({}, newStats);
  7054. if (this.last_) {
  7055. each(this.last_, (stat, value) => {
  7056. delta[stat] = delta[stat] - value;
  7057. });
  7058. }
  7059. this.last_ = newStats;
  7060. return delta;
  7061. }
  7062. }
  7063. /**
  7064. * @license
  7065. * Copyright 2017 Google LLC
  7066. *
  7067. * Licensed under the Apache License, Version 2.0 (the "License");
  7068. * you may not use this file except in compliance with the License.
  7069. * You may obtain a copy of the License at
  7070. *
  7071. * http://www.apache.org/licenses/LICENSE-2.0
  7072. *
  7073. * Unless required by applicable law or agreed to in writing, software
  7074. * distributed under the License is distributed on an "AS IS" BASIS,
  7075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7076. * See the License for the specific language governing permissions and
  7077. * limitations under the License.
  7078. */
  7079. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7080. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7081. // seconds to try to ensure the Firebase connection is established / settled.
  7082. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7083. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7084. // We'll continue to report stats on average every 5 minutes.
  7085. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7086. class StatsReporter {
  7087. constructor(collection, server_) {
  7088. this.server_ = server_;
  7089. this.statsToReport_ = {};
  7090. this.statsListener_ = new StatsListener(collection);
  7091. const timeout = FIRST_STATS_MIN_TIME +
  7092. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7093. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7094. }
  7095. reportStats_() {
  7096. const stats = this.statsListener_.get();
  7097. const reportedStats = {};
  7098. let haveStatsToReport = false;
  7099. each(stats, (stat, value) => {
  7100. if (value > 0 && util.contains(this.statsToReport_, stat)) {
  7101. reportedStats[stat] = value;
  7102. haveStatsToReport = true;
  7103. }
  7104. });
  7105. if (haveStatsToReport) {
  7106. this.server_.reportStats(reportedStats);
  7107. }
  7108. // queue our next run.
  7109. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7110. }
  7111. }
  7112. /**
  7113. * @license
  7114. * Copyright 2017 Google LLC
  7115. *
  7116. * Licensed under the Apache License, Version 2.0 (the "License");
  7117. * you may not use this file except in compliance with the License.
  7118. * You may obtain a copy of the License at
  7119. *
  7120. * http://www.apache.org/licenses/LICENSE-2.0
  7121. *
  7122. * Unless required by applicable law or agreed to in writing, software
  7123. * distributed under the License is distributed on an "AS IS" BASIS,
  7124. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7125. * See the License for the specific language governing permissions and
  7126. * limitations under the License.
  7127. */
  7128. /**
  7129. *
  7130. * @enum
  7131. */
  7132. var OperationType;
  7133. (function (OperationType) {
  7134. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7135. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7136. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7137. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7138. })(OperationType || (OperationType = {}));
  7139. function newOperationSourceUser() {
  7140. return {
  7141. fromUser: true,
  7142. fromServer: false,
  7143. queryId: null,
  7144. tagged: false
  7145. };
  7146. }
  7147. function newOperationSourceServer() {
  7148. return {
  7149. fromUser: false,
  7150. fromServer: true,
  7151. queryId: null,
  7152. tagged: false
  7153. };
  7154. }
  7155. function newOperationSourceServerTaggedQuery(queryId) {
  7156. return {
  7157. fromUser: false,
  7158. fromServer: true,
  7159. queryId,
  7160. tagged: true
  7161. };
  7162. }
  7163. /**
  7164. * @license
  7165. * Copyright 2017 Google LLC
  7166. *
  7167. * Licensed under the Apache License, Version 2.0 (the "License");
  7168. * you may not use this file except in compliance with the License.
  7169. * You may obtain a copy of the License at
  7170. *
  7171. * http://www.apache.org/licenses/LICENSE-2.0
  7172. *
  7173. * Unless required by applicable law or agreed to in writing, software
  7174. * distributed under the License is distributed on an "AS IS" BASIS,
  7175. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7176. * See the License for the specific language governing permissions and
  7177. * limitations under the License.
  7178. */
  7179. class AckUserWrite {
  7180. /**
  7181. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7182. */
  7183. constructor(
  7184. /** @inheritDoc */ path,
  7185. /** @inheritDoc */ affectedTree,
  7186. /** @inheritDoc */ revert) {
  7187. this.path = path;
  7188. this.affectedTree = affectedTree;
  7189. this.revert = revert;
  7190. /** @inheritDoc */
  7191. this.type = OperationType.ACK_USER_WRITE;
  7192. /** @inheritDoc */
  7193. this.source = newOperationSourceUser();
  7194. }
  7195. operationForChild(childName) {
  7196. if (!pathIsEmpty(this.path)) {
  7197. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7198. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7199. }
  7200. else if (this.affectedTree.value != null) {
  7201. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7202. // All child locations are affected as well; just return same operation.
  7203. return this;
  7204. }
  7205. else {
  7206. const childTree = this.affectedTree.subtree(new Path(childName));
  7207. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7208. }
  7209. }
  7210. }
  7211. /**
  7212. * @license
  7213. * Copyright 2017 Google LLC
  7214. *
  7215. * Licensed under the Apache License, Version 2.0 (the "License");
  7216. * you may not use this file except in compliance with the License.
  7217. * You may obtain a copy of the License at
  7218. *
  7219. * http://www.apache.org/licenses/LICENSE-2.0
  7220. *
  7221. * Unless required by applicable law or agreed to in writing, software
  7222. * distributed under the License is distributed on an "AS IS" BASIS,
  7223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7224. * See the License for the specific language governing permissions and
  7225. * limitations under the License.
  7226. */
  7227. class ListenComplete {
  7228. constructor(source, path) {
  7229. this.source = source;
  7230. this.path = path;
  7231. /** @inheritDoc */
  7232. this.type = OperationType.LISTEN_COMPLETE;
  7233. }
  7234. operationForChild(childName) {
  7235. if (pathIsEmpty(this.path)) {
  7236. return new ListenComplete(this.source, newEmptyPath());
  7237. }
  7238. else {
  7239. return new ListenComplete(this.source, pathPopFront(this.path));
  7240. }
  7241. }
  7242. }
  7243. /**
  7244. * @license
  7245. * Copyright 2017 Google LLC
  7246. *
  7247. * Licensed under the Apache License, Version 2.0 (the "License");
  7248. * you may not use this file except in compliance with the License.
  7249. * You may obtain a copy of the License at
  7250. *
  7251. * http://www.apache.org/licenses/LICENSE-2.0
  7252. *
  7253. * Unless required by applicable law or agreed to in writing, software
  7254. * distributed under the License is distributed on an "AS IS" BASIS,
  7255. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7256. * See the License for the specific language governing permissions and
  7257. * limitations under the License.
  7258. */
  7259. class Overwrite {
  7260. constructor(source, path, snap) {
  7261. this.source = source;
  7262. this.path = path;
  7263. this.snap = snap;
  7264. /** @inheritDoc */
  7265. this.type = OperationType.OVERWRITE;
  7266. }
  7267. operationForChild(childName) {
  7268. if (pathIsEmpty(this.path)) {
  7269. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7270. }
  7271. else {
  7272. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7273. }
  7274. }
  7275. }
  7276. /**
  7277. * @license
  7278. * Copyright 2017 Google LLC
  7279. *
  7280. * Licensed under the Apache License, Version 2.0 (the "License");
  7281. * you may not use this file except in compliance with the License.
  7282. * You may obtain a copy of the License at
  7283. *
  7284. * http://www.apache.org/licenses/LICENSE-2.0
  7285. *
  7286. * Unless required by applicable law or agreed to in writing, software
  7287. * distributed under the License is distributed on an "AS IS" BASIS,
  7288. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7289. * See the License for the specific language governing permissions and
  7290. * limitations under the License.
  7291. */
  7292. class Merge {
  7293. constructor(
  7294. /** @inheritDoc */ source,
  7295. /** @inheritDoc */ path,
  7296. /** @inheritDoc */ children) {
  7297. this.source = source;
  7298. this.path = path;
  7299. this.children = children;
  7300. /** @inheritDoc */
  7301. this.type = OperationType.MERGE;
  7302. }
  7303. operationForChild(childName) {
  7304. if (pathIsEmpty(this.path)) {
  7305. const childTree = this.children.subtree(new Path(childName));
  7306. if (childTree.isEmpty()) {
  7307. // This child is unaffected
  7308. return null;
  7309. }
  7310. else if (childTree.value) {
  7311. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7312. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7313. }
  7314. else {
  7315. // This is a merge at a deeper level
  7316. return new Merge(this.source, newEmptyPath(), childTree);
  7317. }
  7318. }
  7319. else {
  7320. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7321. return new Merge(this.source, pathPopFront(this.path), this.children);
  7322. }
  7323. }
  7324. toString() {
  7325. return ('Operation(' +
  7326. this.path +
  7327. ': ' +
  7328. this.source.toString() +
  7329. ' merge: ' +
  7330. this.children.toString() +
  7331. ')');
  7332. }
  7333. }
  7334. /**
  7335. * @license
  7336. * Copyright 2017 Google LLC
  7337. *
  7338. * Licensed under the Apache License, Version 2.0 (the "License");
  7339. * you may not use this file except in compliance with the License.
  7340. * You may obtain a copy of the License at
  7341. *
  7342. * http://www.apache.org/licenses/LICENSE-2.0
  7343. *
  7344. * Unless required by applicable law or agreed to in writing, software
  7345. * distributed under the License is distributed on an "AS IS" BASIS,
  7346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7347. * See the License for the specific language governing permissions and
  7348. * limitations under the License.
  7349. */
  7350. /**
  7351. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7352. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7353. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7354. * whether a node potentially had children removed due to a filter.
  7355. */
  7356. class CacheNode {
  7357. constructor(node_, fullyInitialized_, filtered_) {
  7358. this.node_ = node_;
  7359. this.fullyInitialized_ = fullyInitialized_;
  7360. this.filtered_ = filtered_;
  7361. }
  7362. /**
  7363. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7364. */
  7365. isFullyInitialized() {
  7366. return this.fullyInitialized_;
  7367. }
  7368. /**
  7369. * Returns whether this node is potentially missing children due to a filter applied to the node
  7370. */
  7371. isFiltered() {
  7372. return this.filtered_;
  7373. }
  7374. isCompleteForPath(path) {
  7375. if (pathIsEmpty(path)) {
  7376. return this.isFullyInitialized() && !this.filtered_;
  7377. }
  7378. const childKey = pathGetFront(path);
  7379. return this.isCompleteForChild(childKey);
  7380. }
  7381. isCompleteForChild(key) {
  7382. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7383. }
  7384. getNode() {
  7385. return this.node_;
  7386. }
  7387. }
  7388. /**
  7389. * @license
  7390. * Copyright 2017 Google LLC
  7391. *
  7392. * Licensed under the Apache License, Version 2.0 (the "License");
  7393. * you may not use this file except in compliance with the License.
  7394. * You may obtain a copy of the License at
  7395. *
  7396. * http://www.apache.org/licenses/LICENSE-2.0
  7397. *
  7398. * Unless required by applicable law or agreed to in writing, software
  7399. * distributed under the License is distributed on an "AS IS" BASIS,
  7400. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7401. * See the License for the specific language governing permissions and
  7402. * limitations under the License.
  7403. */
  7404. /**
  7405. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7406. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7407. * for details.
  7408. *
  7409. */
  7410. class EventGenerator {
  7411. constructor(query_) {
  7412. this.query_ = query_;
  7413. this.index_ = this.query_._queryParams.getIndex();
  7414. }
  7415. }
  7416. /**
  7417. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7418. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7419. *
  7420. * Notes:
  7421. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7422. * our index.
  7423. * - prevName will be calculated based on the index ordering.
  7424. */
  7425. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7426. const events = [];
  7427. const moves = [];
  7428. changes.forEach(change => {
  7429. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7430. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7431. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7432. }
  7433. });
  7434. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7435. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7436. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7437. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7438. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7439. return events;
  7440. }
  7441. /**
  7442. * Given changes of a single change type, generate the corresponding events.
  7443. */
  7444. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7445. const filteredChanges = changes.filter(change => change.type === eventType);
  7446. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7447. filteredChanges.forEach(change => {
  7448. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7449. registrations.forEach(registration => {
  7450. if (registration.respondsTo(change.type)) {
  7451. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7452. }
  7453. });
  7454. });
  7455. }
  7456. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7457. if (change.type === 'value' || change.type === 'child_removed') {
  7458. return change;
  7459. }
  7460. else {
  7461. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7462. return change;
  7463. }
  7464. }
  7465. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7466. if (a.childName == null || b.childName == null) {
  7467. throw util.assertionError('Should only compare child_ events.');
  7468. }
  7469. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7470. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7471. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7472. }
  7473. /**
  7474. * @license
  7475. * Copyright 2017 Google LLC
  7476. *
  7477. * Licensed under the Apache License, Version 2.0 (the "License");
  7478. * you may not use this file except in compliance with the License.
  7479. * You may obtain a copy of the License at
  7480. *
  7481. * http://www.apache.org/licenses/LICENSE-2.0
  7482. *
  7483. * Unless required by applicable law or agreed to in writing, software
  7484. * distributed under the License is distributed on an "AS IS" BASIS,
  7485. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7486. * See the License for the specific language governing permissions and
  7487. * limitations under the License.
  7488. */
  7489. function newViewCache(eventCache, serverCache) {
  7490. return { eventCache, serverCache };
  7491. }
  7492. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7493. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7494. }
  7495. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7496. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7497. }
  7498. function viewCacheGetCompleteEventSnap(viewCache) {
  7499. return viewCache.eventCache.isFullyInitialized()
  7500. ? viewCache.eventCache.getNode()
  7501. : null;
  7502. }
  7503. function viewCacheGetCompleteServerSnap(viewCache) {
  7504. return viewCache.serverCache.isFullyInitialized()
  7505. ? viewCache.serverCache.getNode()
  7506. : null;
  7507. }
  7508. /**
  7509. * @license
  7510. * Copyright 2017 Google LLC
  7511. *
  7512. * Licensed under the Apache License, Version 2.0 (the "License");
  7513. * you may not use this file except in compliance with the License.
  7514. * You may obtain a copy of the License at
  7515. *
  7516. * http://www.apache.org/licenses/LICENSE-2.0
  7517. *
  7518. * Unless required by applicable law or agreed to in writing, software
  7519. * distributed under the License is distributed on an "AS IS" BASIS,
  7520. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7521. * See the License for the specific language governing permissions and
  7522. * limitations under the License.
  7523. */
  7524. let emptyChildrenSingleton;
  7525. /**
  7526. * Singleton empty children collection.
  7527. *
  7528. */
  7529. const EmptyChildren = () => {
  7530. if (!emptyChildrenSingleton) {
  7531. emptyChildrenSingleton = new SortedMap(stringCompare);
  7532. }
  7533. return emptyChildrenSingleton;
  7534. };
  7535. /**
  7536. * A tree with immutable elements.
  7537. */
  7538. class ImmutableTree {
  7539. constructor(value, children = EmptyChildren()) {
  7540. this.value = value;
  7541. this.children = children;
  7542. }
  7543. static fromObject(obj) {
  7544. let tree = new ImmutableTree(null);
  7545. each(obj, (childPath, childSnap) => {
  7546. tree = tree.set(new Path(childPath), childSnap);
  7547. });
  7548. return tree;
  7549. }
  7550. /**
  7551. * True if the value is empty and there are no children
  7552. */
  7553. isEmpty() {
  7554. return this.value === null && this.children.isEmpty();
  7555. }
  7556. /**
  7557. * Given a path and predicate, return the first node and the path to that node
  7558. * where the predicate returns true.
  7559. *
  7560. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7561. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7562. *
  7563. * @param relativePath - The remainder of the path
  7564. * @param predicate - The predicate to satisfy to return a node
  7565. */
  7566. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7567. if (this.value != null && predicate(this.value)) {
  7568. return { path: newEmptyPath(), value: this.value };
  7569. }
  7570. else {
  7571. if (pathIsEmpty(relativePath)) {
  7572. return null;
  7573. }
  7574. else {
  7575. const front = pathGetFront(relativePath);
  7576. const child = this.children.get(front);
  7577. if (child !== null) {
  7578. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7579. if (childExistingPathAndValue != null) {
  7580. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7581. return { path: fullPath, value: childExistingPathAndValue.value };
  7582. }
  7583. else {
  7584. return null;
  7585. }
  7586. }
  7587. else {
  7588. return null;
  7589. }
  7590. }
  7591. }
  7592. }
  7593. /**
  7594. * Find, if it exists, the shortest subpath of the given path that points a defined
  7595. * value in the tree
  7596. */
  7597. findRootMostValueAndPath(relativePath) {
  7598. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7599. }
  7600. /**
  7601. * @returns The subtree at the given path
  7602. */
  7603. subtree(relativePath) {
  7604. if (pathIsEmpty(relativePath)) {
  7605. return this;
  7606. }
  7607. else {
  7608. const front = pathGetFront(relativePath);
  7609. const childTree = this.children.get(front);
  7610. if (childTree !== null) {
  7611. return childTree.subtree(pathPopFront(relativePath));
  7612. }
  7613. else {
  7614. return new ImmutableTree(null);
  7615. }
  7616. }
  7617. }
  7618. /**
  7619. * Sets a value at the specified path.
  7620. *
  7621. * @param relativePath - Path to set value at.
  7622. * @param toSet - Value to set.
  7623. * @returns Resulting tree.
  7624. */
  7625. set(relativePath, toSet) {
  7626. if (pathIsEmpty(relativePath)) {
  7627. return new ImmutableTree(toSet, this.children);
  7628. }
  7629. else {
  7630. const front = pathGetFront(relativePath);
  7631. const child = this.children.get(front) || new ImmutableTree(null);
  7632. const newChild = child.set(pathPopFront(relativePath), toSet);
  7633. const newChildren = this.children.insert(front, newChild);
  7634. return new ImmutableTree(this.value, newChildren);
  7635. }
  7636. }
  7637. /**
  7638. * Removes the value at the specified path.
  7639. *
  7640. * @param relativePath - Path to value to remove.
  7641. * @returns Resulting tree.
  7642. */
  7643. remove(relativePath) {
  7644. if (pathIsEmpty(relativePath)) {
  7645. if (this.children.isEmpty()) {
  7646. return new ImmutableTree(null);
  7647. }
  7648. else {
  7649. return new ImmutableTree(null, this.children);
  7650. }
  7651. }
  7652. else {
  7653. const front = pathGetFront(relativePath);
  7654. const child = this.children.get(front);
  7655. if (child) {
  7656. const newChild = child.remove(pathPopFront(relativePath));
  7657. let newChildren;
  7658. if (newChild.isEmpty()) {
  7659. newChildren = this.children.remove(front);
  7660. }
  7661. else {
  7662. newChildren = this.children.insert(front, newChild);
  7663. }
  7664. if (this.value === null && newChildren.isEmpty()) {
  7665. return new ImmutableTree(null);
  7666. }
  7667. else {
  7668. return new ImmutableTree(this.value, newChildren);
  7669. }
  7670. }
  7671. else {
  7672. return this;
  7673. }
  7674. }
  7675. }
  7676. /**
  7677. * Gets a value from the tree.
  7678. *
  7679. * @param relativePath - Path to get value for.
  7680. * @returns Value at path, or null.
  7681. */
  7682. get(relativePath) {
  7683. if (pathIsEmpty(relativePath)) {
  7684. return this.value;
  7685. }
  7686. else {
  7687. const front = pathGetFront(relativePath);
  7688. const child = this.children.get(front);
  7689. if (child) {
  7690. return child.get(pathPopFront(relativePath));
  7691. }
  7692. else {
  7693. return null;
  7694. }
  7695. }
  7696. }
  7697. /**
  7698. * Replace the subtree at the specified path with the given new tree.
  7699. *
  7700. * @param relativePath - Path to replace subtree for.
  7701. * @param newTree - New tree.
  7702. * @returns Resulting tree.
  7703. */
  7704. setTree(relativePath, newTree) {
  7705. if (pathIsEmpty(relativePath)) {
  7706. return newTree;
  7707. }
  7708. else {
  7709. const front = pathGetFront(relativePath);
  7710. const child = this.children.get(front) || new ImmutableTree(null);
  7711. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7712. let newChildren;
  7713. if (newChild.isEmpty()) {
  7714. newChildren = this.children.remove(front);
  7715. }
  7716. else {
  7717. newChildren = this.children.insert(front, newChild);
  7718. }
  7719. return new ImmutableTree(this.value, newChildren);
  7720. }
  7721. }
  7722. /**
  7723. * Performs a depth first fold on this tree. Transforms a tree into a single
  7724. * value, given a function that operates on the path to a node, an optional
  7725. * current value, and a map of child names to folded subtrees
  7726. */
  7727. fold(fn) {
  7728. return this.fold_(newEmptyPath(), fn);
  7729. }
  7730. /**
  7731. * Recursive helper for public-facing fold() method
  7732. */
  7733. fold_(pathSoFar, fn) {
  7734. const accum = {};
  7735. this.children.inorderTraversal((childKey, childTree) => {
  7736. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7737. });
  7738. return fn(pathSoFar, this.value, accum);
  7739. }
  7740. /**
  7741. * Find the first matching value on the given path. Return the result of applying f to it.
  7742. */
  7743. findOnPath(path, f) {
  7744. return this.findOnPath_(path, newEmptyPath(), f);
  7745. }
  7746. findOnPath_(pathToFollow, pathSoFar, f) {
  7747. const result = this.value ? f(pathSoFar, this.value) : false;
  7748. if (result) {
  7749. return result;
  7750. }
  7751. else {
  7752. if (pathIsEmpty(pathToFollow)) {
  7753. return null;
  7754. }
  7755. else {
  7756. const front = pathGetFront(pathToFollow);
  7757. const nextChild = this.children.get(front);
  7758. if (nextChild) {
  7759. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7760. }
  7761. else {
  7762. return null;
  7763. }
  7764. }
  7765. }
  7766. }
  7767. foreachOnPath(path, f) {
  7768. return this.foreachOnPath_(path, newEmptyPath(), f);
  7769. }
  7770. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7771. if (pathIsEmpty(pathToFollow)) {
  7772. return this;
  7773. }
  7774. else {
  7775. if (this.value) {
  7776. f(currentRelativePath, this.value);
  7777. }
  7778. const front = pathGetFront(pathToFollow);
  7779. const nextChild = this.children.get(front);
  7780. if (nextChild) {
  7781. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7782. }
  7783. else {
  7784. return new ImmutableTree(null);
  7785. }
  7786. }
  7787. }
  7788. /**
  7789. * Calls the given function for each node in the tree that has a value.
  7790. *
  7791. * @param f - A function to be called with the path from the root of the tree to
  7792. * a node, and the value at that node. Called in depth-first order.
  7793. */
  7794. foreach(f) {
  7795. this.foreach_(newEmptyPath(), f);
  7796. }
  7797. foreach_(currentRelativePath, f) {
  7798. this.children.inorderTraversal((childName, childTree) => {
  7799. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7800. });
  7801. if (this.value) {
  7802. f(currentRelativePath, this.value);
  7803. }
  7804. }
  7805. foreachChild(f) {
  7806. this.children.inorderTraversal((childName, childTree) => {
  7807. if (childTree.value) {
  7808. f(childName, childTree.value);
  7809. }
  7810. });
  7811. }
  7812. }
  7813. /**
  7814. * @license
  7815. * Copyright 2017 Google LLC
  7816. *
  7817. * Licensed under the Apache License, Version 2.0 (the "License");
  7818. * you may not use this file except in compliance with the License.
  7819. * You may obtain a copy of the License at
  7820. *
  7821. * http://www.apache.org/licenses/LICENSE-2.0
  7822. *
  7823. * Unless required by applicable law or agreed to in writing, software
  7824. * distributed under the License is distributed on an "AS IS" BASIS,
  7825. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7826. * See the License for the specific language governing permissions and
  7827. * limitations under the License.
  7828. */
  7829. /**
  7830. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7831. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7832. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7833. * to reflect the write added.
  7834. */
  7835. class CompoundWrite {
  7836. constructor(writeTree_) {
  7837. this.writeTree_ = writeTree_;
  7838. }
  7839. static empty() {
  7840. return new CompoundWrite(new ImmutableTree(null));
  7841. }
  7842. }
  7843. function compoundWriteAddWrite(compoundWrite, path, node) {
  7844. if (pathIsEmpty(path)) {
  7845. return new CompoundWrite(new ImmutableTree(node));
  7846. }
  7847. else {
  7848. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7849. if (rootmost != null) {
  7850. const rootMostPath = rootmost.path;
  7851. let value = rootmost.value;
  7852. const relativePath = newRelativePath(rootMostPath, path);
  7853. value = value.updateChild(relativePath, node);
  7854. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7855. }
  7856. else {
  7857. const subtree = new ImmutableTree(node);
  7858. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7859. return new CompoundWrite(newWriteTree);
  7860. }
  7861. }
  7862. }
  7863. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7864. let newWrite = compoundWrite;
  7865. each(updates, (childKey, node) => {
  7866. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7867. });
  7868. return newWrite;
  7869. }
  7870. /**
  7871. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7872. * location, which must be removed by calling this method with that path.
  7873. *
  7874. * @param compoundWrite - The CompoundWrite to remove.
  7875. * @param path - The path at which a write and all deeper writes should be removed
  7876. * @returns The new CompoundWrite with the removed path
  7877. */
  7878. function compoundWriteRemoveWrite(compoundWrite, path) {
  7879. if (pathIsEmpty(path)) {
  7880. return CompoundWrite.empty();
  7881. }
  7882. else {
  7883. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7884. return new CompoundWrite(newWriteTree);
  7885. }
  7886. }
  7887. /**
  7888. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7889. * considered "complete".
  7890. *
  7891. * @param compoundWrite - The CompoundWrite to check.
  7892. * @param path - The path to check for
  7893. * @returns Whether there is a complete write at that path
  7894. */
  7895. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7896. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7897. }
  7898. /**
  7899. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7900. * writes from deeper paths, but will return child nodes from a more shallow path.
  7901. *
  7902. * @param compoundWrite - The CompoundWrite to get the node from.
  7903. * @param path - The path to get a complete write
  7904. * @returns The node if complete at that path, or null otherwise.
  7905. */
  7906. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7907. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7908. if (rootmost != null) {
  7909. return compoundWrite.writeTree_
  7910. .get(rootmost.path)
  7911. .getChild(newRelativePath(rootmost.path, path));
  7912. }
  7913. else {
  7914. return null;
  7915. }
  7916. }
  7917. /**
  7918. * Returns all children that are guaranteed to be a complete overwrite.
  7919. *
  7920. * @param compoundWrite - The CompoundWrite to get children from.
  7921. * @returns A list of all complete children.
  7922. */
  7923. function compoundWriteGetCompleteChildren(compoundWrite) {
  7924. const children = [];
  7925. const node = compoundWrite.writeTree_.value;
  7926. if (node != null) {
  7927. // If it's a leaf node, it has no children; so nothing to do.
  7928. if (!node.isLeafNode()) {
  7929. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7930. children.push(new NamedNode(childName, childNode));
  7931. });
  7932. }
  7933. }
  7934. else {
  7935. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7936. if (childTree.value != null) {
  7937. children.push(new NamedNode(childName, childTree.value));
  7938. }
  7939. });
  7940. }
  7941. return children;
  7942. }
  7943. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7944. if (pathIsEmpty(path)) {
  7945. return compoundWrite;
  7946. }
  7947. else {
  7948. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7949. if (shadowingNode != null) {
  7950. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7951. }
  7952. else {
  7953. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7954. }
  7955. }
  7956. }
  7957. /**
  7958. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7959. * @returns Whether this CompoundWrite is empty
  7960. */
  7961. function compoundWriteIsEmpty(compoundWrite) {
  7962. return compoundWrite.writeTree_.isEmpty();
  7963. }
  7964. /**
  7965. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7966. * node
  7967. * @param node - The node to apply this CompoundWrite to
  7968. * @returns The node with all writes applied
  7969. */
  7970. function compoundWriteApply(compoundWrite, node) {
  7971. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7972. }
  7973. function applySubtreeWrite(relativePath, writeTree, node) {
  7974. if (writeTree.value != null) {
  7975. // Since there a write is always a leaf, we're done here
  7976. return node.updateChild(relativePath, writeTree.value);
  7977. }
  7978. else {
  7979. let priorityWrite = null;
  7980. writeTree.children.inorderTraversal((childKey, childTree) => {
  7981. if (childKey === '.priority') {
  7982. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7983. // to apply priorities to empty nodes that are later filled
  7984. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7985. priorityWrite = childTree.value;
  7986. }
  7987. else {
  7988. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7989. }
  7990. });
  7991. // If there was a priority write, we only apply it if the node is not empty
  7992. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7993. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7994. }
  7995. return node;
  7996. }
  7997. }
  7998. /**
  7999. * @license
  8000. * Copyright 2017 Google LLC
  8001. *
  8002. * Licensed under the Apache License, Version 2.0 (the "License");
  8003. * you may not use this file except in compliance with the License.
  8004. * You may obtain a copy of the License at
  8005. *
  8006. * http://www.apache.org/licenses/LICENSE-2.0
  8007. *
  8008. * Unless required by applicable law or agreed to in writing, software
  8009. * distributed under the License is distributed on an "AS IS" BASIS,
  8010. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8011. * See the License for the specific language governing permissions and
  8012. * limitations under the License.
  8013. */
  8014. /**
  8015. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8016. *
  8017. */
  8018. function writeTreeChildWrites(writeTree, path) {
  8019. return newWriteTreeRef(path, writeTree);
  8020. }
  8021. /**
  8022. * Record a new overwrite from user code.
  8023. *
  8024. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8025. */
  8026. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8027. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8028. if (visible === undefined) {
  8029. visible = true;
  8030. }
  8031. writeTree.allWrites.push({
  8032. path,
  8033. snap,
  8034. writeId,
  8035. visible
  8036. });
  8037. if (visible) {
  8038. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8039. }
  8040. writeTree.lastWriteId = writeId;
  8041. }
  8042. /**
  8043. * Record a new merge from user code.
  8044. */
  8045. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8046. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8047. writeTree.allWrites.push({
  8048. path,
  8049. children: changedChildren,
  8050. writeId,
  8051. visible: true
  8052. });
  8053. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8054. writeTree.lastWriteId = writeId;
  8055. }
  8056. function writeTreeGetWrite(writeTree, writeId) {
  8057. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8058. const record = writeTree.allWrites[i];
  8059. if (record.writeId === writeId) {
  8060. return record;
  8061. }
  8062. }
  8063. return null;
  8064. }
  8065. /**
  8066. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8067. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8068. *
  8069. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8070. * events as a result).
  8071. */
  8072. function writeTreeRemoveWrite(writeTree, writeId) {
  8073. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8074. // out of order.
  8075. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8076. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8077. const idx = writeTree.allWrites.findIndex(s => {
  8078. return s.writeId === writeId;
  8079. });
  8080. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8081. const writeToRemove = writeTree.allWrites[idx];
  8082. writeTree.allWrites.splice(idx, 1);
  8083. let removedWriteWasVisible = writeToRemove.visible;
  8084. let removedWriteOverlapsWithOtherWrites = false;
  8085. let i = writeTree.allWrites.length - 1;
  8086. while (removedWriteWasVisible && i >= 0) {
  8087. const currentWrite = writeTree.allWrites[i];
  8088. if (currentWrite.visible) {
  8089. if (i >= idx &&
  8090. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8091. // The removed write was completely shadowed by a subsequent write.
  8092. removedWriteWasVisible = false;
  8093. }
  8094. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8095. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8096. removedWriteOverlapsWithOtherWrites = true;
  8097. }
  8098. }
  8099. i--;
  8100. }
  8101. if (!removedWriteWasVisible) {
  8102. return false;
  8103. }
  8104. else if (removedWriteOverlapsWithOtherWrites) {
  8105. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8106. writeTreeResetTree_(writeTree);
  8107. return true;
  8108. }
  8109. else {
  8110. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8111. if (writeToRemove.snap) {
  8112. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8113. }
  8114. else {
  8115. const children = writeToRemove.children;
  8116. each(children, (childName) => {
  8117. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8118. });
  8119. }
  8120. return true;
  8121. }
  8122. }
  8123. function writeTreeRecordContainsPath_(writeRecord, path) {
  8124. if (writeRecord.snap) {
  8125. return pathContains(writeRecord.path, path);
  8126. }
  8127. else {
  8128. for (const childName in writeRecord.children) {
  8129. if (writeRecord.children.hasOwnProperty(childName) &&
  8130. pathContains(pathChild(writeRecord.path, childName), path)) {
  8131. return true;
  8132. }
  8133. }
  8134. return false;
  8135. }
  8136. }
  8137. /**
  8138. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8139. */
  8140. function writeTreeResetTree_(writeTree) {
  8141. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8142. if (writeTree.allWrites.length > 0) {
  8143. writeTree.lastWriteId =
  8144. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8145. }
  8146. else {
  8147. writeTree.lastWriteId = -1;
  8148. }
  8149. }
  8150. /**
  8151. * The default filter used when constructing the tree. Keep everything that's visible.
  8152. */
  8153. function writeTreeDefaultFilter_(write) {
  8154. return write.visible;
  8155. }
  8156. /**
  8157. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8158. * event data at that path.
  8159. */
  8160. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8161. let compoundWrite = CompoundWrite.empty();
  8162. for (let i = 0; i < writes.length; ++i) {
  8163. const write = writes[i];
  8164. // Theory, a later set will either:
  8165. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8166. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8167. if (filter(write)) {
  8168. const writePath = write.path;
  8169. let relativePath;
  8170. if (write.snap) {
  8171. if (pathContains(treeRoot, writePath)) {
  8172. relativePath = newRelativePath(treeRoot, writePath);
  8173. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8174. }
  8175. else if (pathContains(writePath, treeRoot)) {
  8176. relativePath = newRelativePath(writePath, treeRoot);
  8177. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8178. }
  8179. else ;
  8180. }
  8181. else if (write.children) {
  8182. if (pathContains(treeRoot, writePath)) {
  8183. relativePath = newRelativePath(treeRoot, writePath);
  8184. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8185. }
  8186. else if (pathContains(writePath, treeRoot)) {
  8187. relativePath = newRelativePath(writePath, treeRoot);
  8188. if (pathIsEmpty(relativePath)) {
  8189. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8190. }
  8191. else {
  8192. const child = util.safeGet(write.children, pathGetFront(relativePath));
  8193. if (child) {
  8194. // There exists a child in this node that matches the root path
  8195. const deepNode = child.getChild(pathPopFront(relativePath));
  8196. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8197. }
  8198. }
  8199. }
  8200. else ;
  8201. }
  8202. else {
  8203. throw util.assertionError('WriteRecord should have .snap or .children');
  8204. }
  8205. }
  8206. }
  8207. return compoundWrite;
  8208. }
  8209. /**
  8210. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8211. * writes), attempt to calculate a complete snapshot for the given path
  8212. *
  8213. * @param writeIdsToExclude - An optional set to be excluded
  8214. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8215. */
  8216. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8217. if (!writeIdsToExclude && !includeHiddenWrites) {
  8218. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8219. if (shadowingNode != null) {
  8220. return shadowingNode;
  8221. }
  8222. else {
  8223. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8224. if (compoundWriteIsEmpty(subMerge)) {
  8225. return completeServerCache;
  8226. }
  8227. else if (completeServerCache == null &&
  8228. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8229. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8230. return null;
  8231. }
  8232. else {
  8233. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8234. return compoundWriteApply(subMerge, layeredCache);
  8235. }
  8236. }
  8237. }
  8238. else {
  8239. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8240. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8241. return completeServerCache;
  8242. }
  8243. else {
  8244. // If the server cache is null, and we don't have a complete cache, we need to return null
  8245. if (!includeHiddenWrites &&
  8246. completeServerCache == null &&
  8247. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8248. return null;
  8249. }
  8250. else {
  8251. const filter = function (write) {
  8252. return ((write.visible || includeHiddenWrites) &&
  8253. (!writeIdsToExclude ||
  8254. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8255. (pathContains(write.path, treePath) ||
  8256. pathContains(treePath, write.path)));
  8257. };
  8258. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8259. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8260. return compoundWriteApply(mergeAtPath, layeredCache);
  8261. }
  8262. }
  8263. }
  8264. }
  8265. /**
  8266. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8267. * Used when creating new views, to pre-fill their complete event children snapshot.
  8268. */
  8269. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8270. let completeChildren = ChildrenNode.EMPTY_NODE;
  8271. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8272. if (topLevelSet) {
  8273. if (!topLevelSet.isLeafNode()) {
  8274. // we're shadowing everything. Return the children.
  8275. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8276. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8277. });
  8278. }
  8279. return completeChildren;
  8280. }
  8281. else if (completeServerChildren) {
  8282. // Layer any children we have on top of this
  8283. // We know we don't have a top-level set, so just enumerate existing children
  8284. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8285. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8286. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8287. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8288. });
  8289. // Add any complete children we have from the set
  8290. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8291. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8292. });
  8293. return completeChildren;
  8294. }
  8295. else {
  8296. // We don't have anything to layer on top of. Layer on any children we have
  8297. // Note that we can return an empty snap if we have a defined delete
  8298. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8299. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8300. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8301. });
  8302. return completeChildren;
  8303. }
  8304. }
  8305. /**
  8306. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8307. * applied to the event cache.
  8308. *
  8309. * Possibilities:
  8310. *
  8311. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8312. *
  8313. * 2. Some write is completely shadowing. No events to be raised
  8314. *
  8315. * 3. Is partially shadowed. Events
  8316. *
  8317. * Either existingEventSnap or existingServerSnap must exist
  8318. */
  8319. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8320. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8321. const path = pathChild(treePath, childPath);
  8322. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8323. // At this point we can probably guarantee that we're in case 2, meaning no events
  8324. // May need to check visibility while doing the findRootMostValueAndPath call
  8325. return null;
  8326. }
  8327. else {
  8328. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8329. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8330. if (compoundWriteIsEmpty(childMerge)) {
  8331. // We're not shadowing at all. Case 1
  8332. return existingServerSnap.getChild(childPath);
  8333. }
  8334. else {
  8335. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8336. // However this is tricky to find out, since user updates don't necessary change the server
  8337. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8338. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8339. // only check if the updates change the serverNode.
  8340. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8341. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8342. }
  8343. }
  8344. }
  8345. /**
  8346. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8347. * complete child for this ChildKey.
  8348. */
  8349. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8350. const path = pathChild(treePath, childKey);
  8351. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8352. if (shadowingNode != null) {
  8353. return shadowingNode;
  8354. }
  8355. else {
  8356. if (existingServerSnap.isCompleteForChild(childKey)) {
  8357. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8358. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8359. }
  8360. else {
  8361. return null;
  8362. }
  8363. }
  8364. }
  8365. /**
  8366. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8367. * a higher path, this will return the child of that write relative to the write and this path.
  8368. * Returns null if there is no write at this path.
  8369. */
  8370. function writeTreeShadowingWrite(writeTree, path) {
  8371. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8372. }
  8373. /**
  8374. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8375. * the window, but may now be in the window.
  8376. */
  8377. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8378. let toIterate;
  8379. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8380. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8381. if (shadowingNode != null) {
  8382. toIterate = shadowingNode;
  8383. }
  8384. else if (completeServerData != null) {
  8385. toIterate = compoundWriteApply(merge, completeServerData);
  8386. }
  8387. else {
  8388. // no children to iterate on
  8389. return [];
  8390. }
  8391. toIterate = toIterate.withIndex(index);
  8392. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8393. const nodes = [];
  8394. const cmp = index.getCompare();
  8395. const iter = reverse
  8396. ? toIterate.getReverseIteratorFrom(startPost, index)
  8397. : toIterate.getIteratorFrom(startPost, index);
  8398. let next = iter.getNext();
  8399. while (next && nodes.length < count) {
  8400. if (cmp(next, startPost) !== 0) {
  8401. nodes.push(next);
  8402. }
  8403. next = iter.getNext();
  8404. }
  8405. return nodes;
  8406. }
  8407. else {
  8408. return [];
  8409. }
  8410. }
  8411. function newWriteTree() {
  8412. return {
  8413. visibleWrites: CompoundWrite.empty(),
  8414. allWrites: [],
  8415. lastWriteId: -1
  8416. };
  8417. }
  8418. /**
  8419. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8420. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8421. * can lead to a more expensive calculation.
  8422. *
  8423. * @param writeIdsToExclude - Optional writes to exclude.
  8424. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8425. */
  8426. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8427. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8428. }
  8429. /**
  8430. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8431. * mix of the given server data and write data.
  8432. *
  8433. */
  8434. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8435. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8436. }
  8437. /**
  8438. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8439. * if anything, needs to be applied to the event cache.
  8440. *
  8441. * Possibilities:
  8442. *
  8443. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8444. *
  8445. * 2. Some write is completely shadowing. No events to be raised
  8446. *
  8447. * 3. Is partially shadowed. Events should be raised
  8448. *
  8449. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8450. *
  8451. *
  8452. */
  8453. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8454. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8455. }
  8456. /**
  8457. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8458. * a higher path, this will return the child of that write relative to the write and this path.
  8459. * Returns null if there is no write at this path.
  8460. *
  8461. */
  8462. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8463. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8464. }
  8465. /**
  8466. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8467. * the window, but may now be in the window
  8468. */
  8469. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8470. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8471. }
  8472. /**
  8473. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8474. * complete child for this ChildKey.
  8475. */
  8476. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8477. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8478. }
  8479. /**
  8480. * Return a WriteTreeRef for a child.
  8481. */
  8482. function writeTreeRefChild(writeTreeRef, childName) {
  8483. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8484. }
  8485. function newWriteTreeRef(path, writeTree) {
  8486. return {
  8487. treePath: path,
  8488. writeTree
  8489. };
  8490. }
  8491. /**
  8492. * @license
  8493. * Copyright 2017 Google LLC
  8494. *
  8495. * Licensed under the Apache License, Version 2.0 (the "License");
  8496. * you may not use this file except in compliance with the License.
  8497. * You may obtain a copy of the License at
  8498. *
  8499. * http://www.apache.org/licenses/LICENSE-2.0
  8500. *
  8501. * Unless required by applicable law or agreed to in writing, software
  8502. * distributed under the License is distributed on an "AS IS" BASIS,
  8503. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8504. * See the License for the specific language governing permissions and
  8505. * limitations under the License.
  8506. */
  8507. class ChildChangeAccumulator {
  8508. constructor() {
  8509. this.changeMap = new Map();
  8510. }
  8511. trackChildChange(change) {
  8512. const type = change.type;
  8513. const childKey = change.childName;
  8514. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8515. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8516. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8517. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8518. const oldChange = this.changeMap.get(childKey);
  8519. if (oldChange) {
  8520. const oldType = oldChange.type;
  8521. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8522. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8523. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8524. }
  8525. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8526. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8527. this.changeMap.delete(childKey);
  8528. }
  8529. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8530. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8531. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8532. }
  8533. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8534. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8535. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8536. }
  8537. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8538. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8539. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8540. }
  8541. else {
  8542. throw util.assertionError('Illegal combination of changes: ' +
  8543. change +
  8544. ' occurred after ' +
  8545. oldChange);
  8546. }
  8547. }
  8548. else {
  8549. this.changeMap.set(childKey, change);
  8550. }
  8551. }
  8552. getChanges() {
  8553. return Array.from(this.changeMap.values());
  8554. }
  8555. }
  8556. /**
  8557. * @license
  8558. * Copyright 2017 Google LLC
  8559. *
  8560. * Licensed under the Apache License, Version 2.0 (the "License");
  8561. * you may not use this file except in compliance with the License.
  8562. * You may obtain a copy of the License at
  8563. *
  8564. * http://www.apache.org/licenses/LICENSE-2.0
  8565. *
  8566. * Unless required by applicable law or agreed to in writing, software
  8567. * distributed under the License is distributed on an "AS IS" BASIS,
  8568. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8569. * See the License for the specific language governing permissions and
  8570. * limitations under the License.
  8571. */
  8572. /**
  8573. * An implementation of CompleteChildSource that never returns any additional children
  8574. */
  8575. // eslint-disable-next-line @typescript-eslint/naming-convention
  8576. class NoCompleteChildSource_ {
  8577. getCompleteChild(childKey) {
  8578. return null;
  8579. }
  8580. getChildAfterChild(index, child, reverse) {
  8581. return null;
  8582. }
  8583. }
  8584. /**
  8585. * Singleton instance.
  8586. */
  8587. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8588. /**
  8589. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8590. * old event caches available to calculate complete children.
  8591. */
  8592. class WriteTreeCompleteChildSource {
  8593. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8594. this.writes_ = writes_;
  8595. this.viewCache_ = viewCache_;
  8596. this.optCompleteServerCache_ = optCompleteServerCache_;
  8597. }
  8598. getCompleteChild(childKey) {
  8599. const node = this.viewCache_.eventCache;
  8600. if (node.isCompleteForChild(childKey)) {
  8601. return node.getNode().getImmediateChild(childKey);
  8602. }
  8603. else {
  8604. const serverNode = this.optCompleteServerCache_ != null
  8605. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8606. : this.viewCache_.serverCache;
  8607. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8608. }
  8609. }
  8610. getChildAfterChild(index, child, reverse) {
  8611. const completeServerData = this.optCompleteServerCache_ != null
  8612. ? this.optCompleteServerCache_
  8613. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8614. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8615. if (nodes.length === 0) {
  8616. return null;
  8617. }
  8618. else {
  8619. return nodes[0];
  8620. }
  8621. }
  8622. }
  8623. /**
  8624. * @license
  8625. * Copyright 2017 Google LLC
  8626. *
  8627. * Licensed under the Apache License, Version 2.0 (the "License");
  8628. * you may not use this file except in compliance with the License.
  8629. * You may obtain a copy of the License at
  8630. *
  8631. * http://www.apache.org/licenses/LICENSE-2.0
  8632. *
  8633. * Unless required by applicable law or agreed to in writing, software
  8634. * distributed under the License is distributed on an "AS IS" BASIS,
  8635. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8636. * See the License for the specific language governing permissions and
  8637. * limitations under the License.
  8638. */
  8639. function newViewProcessor(filter) {
  8640. return { filter };
  8641. }
  8642. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8643. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8644. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8645. }
  8646. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8647. const accumulator = new ChildChangeAccumulator();
  8648. let newViewCache, filterServerNode;
  8649. if (operation.type === OperationType.OVERWRITE) {
  8650. const overwrite = operation;
  8651. if (overwrite.source.fromUser) {
  8652. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8653. }
  8654. else {
  8655. util.assert(overwrite.source.fromServer, 'Unknown source.');
  8656. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8657. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8658. // again
  8659. filterServerNode =
  8660. overwrite.source.tagged ||
  8661. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8662. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8663. }
  8664. }
  8665. else if (operation.type === OperationType.MERGE) {
  8666. const merge = operation;
  8667. if (merge.source.fromUser) {
  8668. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8669. }
  8670. else {
  8671. util.assert(merge.source.fromServer, 'Unknown source.');
  8672. // We filter the node if it's a tagged update or the node has been previously filtered
  8673. filterServerNode =
  8674. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8675. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8676. }
  8677. }
  8678. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8679. const ackUserWrite = operation;
  8680. if (!ackUserWrite.revert) {
  8681. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8682. }
  8683. else {
  8684. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8685. }
  8686. }
  8687. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8688. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8689. }
  8690. else {
  8691. throw util.assertionError('Unknown operation type: ' + operation.type);
  8692. }
  8693. const changes = accumulator.getChanges();
  8694. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8695. return { viewCache: newViewCache, changes };
  8696. }
  8697. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8698. const eventSnap = newViewCache.eventCache;
  8699. if (eventSnap.isFullyInitialized()) {
  8700. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8701. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8702. if (accumulator.length > 0 ||
  8703. !oldViewCache.eventCache.isFullyInitialized() ||
  8704. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8705. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8706. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8707. }
  8708. }
  8709. }
  8710. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8711. const oldEventSnap = viewCache.eventCache;
  8712. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8713. // we have a shadowing write, ignore changes
  8714. return viewCache;
  8715. }
  8716. else {
  8717. let newEventCache, serverNode;
  8718. if (pathIsEmpty(changePath)) {
  8719. // TODO: figure out how this plays with "sliding ack windows"
  8720. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8721. if (viewCache.serverCache.isFiltered()) {
  8722. // We need to special case this, because we need to only apply writes to complete children, or
  8723. // we might end up raising events for incomplete children. If the server data is filtered deep
  8724. // writes cannot be guaranteed to be complete
  8725. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8726. const completeChildren = serverCache instanceof ChildrenNode
  8727. ? serverCache
  8728. : ChildrenNode.EMPTY_NODE;
  8729. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8730. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8731. }
  8732. else {
  8733. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8734. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8735. }
  8736. }
  8737. else {
  8738. const childKey = pathGetFront(changePath);
  8739. if (childKey === '.priority') {
  8740. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8741. const oldEventNode = oldEventSnap.getNode();
  8742. serverNode = viewCache.serverCache.getNode();
  8743. // we might have overwrites for this priority
  8744. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8745. if (updatedPriority != null) {
  8746. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8747. }
  8748. else {
  8749. // priority didn't change, keep old node
  8750. newEventCache = oldEventSnap.getNode();
  8751. }
  8752. }
  8753. else {
  8754. const childChangePath = pathPopFront(changePath);
  8755. // update child
  8756. let newEventChild;
  8757. if (oldEventSnap.isCompleteForChild(childKey)) {
  8758. serverNode = viewCache.serverCache.getNode();
  8759. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8760. if (eventChildUpdate != null) {
  8761. newEventChild = oldEventSnap
  8762. .getNode()
  8763. .getImmediateChild(childKey)
  8764. .updateChild(childChangePath, eventChildUpdate);
  8765. }
  8766. else {
  8767. // Nothing changed, just keep the old child
  8768. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8769. }
  8770. }
  8771. else {
  8772. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8773. }
  8774. if (newEventChild != null) {
  8775. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8776. }
  8777. else {
  8778. // no complete child available or no change
  8779. newEventCache = oldEventSnap.getNode();
  8780. }
  8781. }
  8782. }
  8783. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8784. }
  8785. }
  8786. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8787. const oldServerSnap = oldViewCache.serverCache;
  8788. let newServerCache;
  8789. const serverFilter = filterServerNode
  8790. ? viewProcessor.filter
  8791. : viewProcessor.filter.getIndexedFilter();
  8792. if (pathIsEmpty(changePath)) {
  8793. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8794. }
  8795. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8796. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8797. const newServerNode = oldServerSnap
  8798. .getNode()
  8799. .updateChild(changePath, changedSnap);
  8800. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8801. }
  8802. else {
  8803. const childKey = pathGetFront(changePath);
  8804. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8805. pathGetLength(changePath) > 1) {
  8806. // We don't update incomplete nodes with updates intended for other listeners
  8807. return oldViewCache;
  8808. }
  8809. const childChangePath = pathPopFront(changePath);
  8810. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8811. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8812. if (childKey === '.priority') {
  8813. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8814. }
  8815. else {
  8816. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8817. }
  8818. }
  8819. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8820. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8821. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8822. }
  8823. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8824. const oldEventSnap = oldViewCache.eventCache;
  8825. let newViewCache, newEventCache;
  8826. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8827. if (pathIsEmpty(changePath)) {
  8828. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8829. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8830. }
  8831. else {
  8832. const childKey = pathGetFront(changePath);
  8833. if (childKey === '.priority') {
  8834. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8835. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8836. }
  8837. else {
  8838. const childChangePath = pathPopFront(changePath);
  8839. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8840. let newChild;
  8841. if (pathIsEmpty(childChangePath)) {
  8842. // Child overwrite, we can replace the child
  8843. newChild = changedSnap;
  8844. }
  8845. else {
  8846. const childNode = source.getCompleteChild(childKey);
  8847. if (childNode != null) {
  8848. if (pathGetBack(childChangePath) === '.priority' &&
  8849. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8850. // This is a priority update on an empty node. If this node exists on the server, the
  8851. // server will send down the priority in the update, so ignore for now
  8852. newChild = childNode;
  8853. }
  8854. else {
  8855. newChild = childNode.updateChild(childChangePath, changedSnap);
  8856. }
  8857. }
  8858. else {
  8859. // There is no complete child node available
  8860. newChild = ChildrenNode.EMPTY_NODE;
  8861. }
  8862. }
  8863. if (!oldChild.equals(newChild)) {
  8864. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8865. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8866. }
  8867. else {
  8868. newViewCache = oldViewCache;
  8869. }
  8870. }
  8871. }
  8872. return newViewCache;
  8873. }
  8874. function viewProcessorCacheHasChild(viewCache, childKey) {
  8875. return viewCache.eventCache.isCompleteForChild(childKey);
  8876. }
  8877. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8878. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8879. // window leaving room for new items. It's important we process these changes first, so we
  8880. // iterate the changes twice, first processing any that affect items currently in view.
  8881. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8882. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8883. // not the other.
  8884. let curViewCache = viewCache;
  8885. changedChildren.foreach((relativePath, childNode) => {
  8886. const writePath = pathChild(path, relativePath);
  8887. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8888. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8889. }
  8890. });
  8891. changedChildren.foreach((relativePath, childNode) => {
  8892. const writePath = pathChild(path, relativePath);
  8893. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8894. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8895. }
  8896. });
  8897. return curViewCache;
  8898. }
  8899. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8900. merge.foreach((relativePath, childNode) => {
  8901. node = node.updateChild(relativePath, childNode);
  8902. });
  8903. return node;
  8904. }
  8905. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8906. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8907. // wait for the complete data update coming soon.
  8908. if (viewCache.serverCache.getNode().isEmpty() &&
  8909. !viewCache.serverCache.isFullyInitialized()) {
  8910. return viewCache;
  8911. }
  8912. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8913. // window leaving room for new items. It's important we process these changes first, so we
  8914. // iterate the changes twice, first processing any that affect items currently in view.
  8915. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8916. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8917. // not the other.
  8918. let curViewCache = viewCache;
  8919. let viewMergeTree;
  8920. if (pathIsEmpty(path)) {
  8921. viewMergeTree = changedChildren;
  8922. }
  8923. else {
  8924. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8925. }
  8926. const serverNode = viewCache.serverCache.getNode();
  8927. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8928. if (serverNode.hasChild(childKey)) {
  8929. const serverChild = viewCache.serverCache
  8930. .getNode()
  8931. .getImmediateChild(childKey);
  8932. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8933. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8934. }
  8935. });
  8936. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8937. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8938. childMergeTree.value === null;
  8939. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8940. const serverChild = viewCache.serverCache
  8941. .getNode()
  8942. .getImmediateChild(childKey);
  8943. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8944. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8945. }
  8946. });
  8947. return curViewCache;
  8948. }
  8949. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8950. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8951. return viewCache;
  8952. }
  8953. // Only filter server node if it is currently filtered
  8954. const filterServerNode = viewCache.serverCache.isFiltered();
  8955. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8956. // now that it won't be shadowed.
  8957. const serverCache = viewCache.serverCache;
  8958. if (affectedTree.value != null) {
  8959. // This is an overwrite.
  8960. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8961. serverCache.isCompleteForPath(ackPath)) {
  8962. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8963. }
  8964. else if (pathIsEmpty(ackPath)) {
  8965. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8966. // should just re-apply whatever we have in our cache as a merge.
  8967. let changedChildren = new ImmutableTree(null);
  8968. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8969. changedChildren = changedChildren.set(new Path(name), node);
  8970. });
  8971. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8972. }
  8973. else {
  8974. return viewCache;
  8975. }
  8976. }
  8977. else {
  8978. // This is a merge.
  8979. let changedChildren = new ImmutableTree(null);
  8980. affectedTree.foreach((mergePath, value) => {
  8981. const serverCachePath = pathChild(ackPath, mergePath);
  8982. if (serverCache.isCompleteForPath(serverCachePath)) {
  8983. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8984. }
  8985. });
  8986. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8987. }
  8988. }
  8989. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8990. const oldServerNode = viewCache.serverCache;
  8991. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8992. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8993. }
  8994. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8995. let complete;
  8996. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8997. return viewCache;
  8998. }
  8999. else {
  9000. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  9001. const oldEventCache = viewCache.eventCache.getNode();
  9002. let newEventCache;
  9003. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9004. let newNode;
  9005. if (viewCache.serverCache.isFullyInitialized()) {
  9006. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9007. }
  9008. else {
  9009. const serverChildren = viewCache.serverCache.getNode();
  9010. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9011. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9012. }
  9013. newNode = newNode;
  9014. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9015. }
  9016. else {
  9017. const childKey = pathGetFront(path);
  9018. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9019. if (newChild == null &&
  9020. viewCache.serverCache.isCompleteForChild(childKey)) {
  9021. newChild = oldEventCache.getImmediateChild(childKey);
  9022. }
  9023. if (newChild != null) {
  9024. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9025. }
  9026. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9027. // No complete child available, delete the existing one, if any
  9028. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9029. }
  9030. else {
  9031. newEventCache = oldEventCache;
  9032. }
  9033. if (newEventCache.isEmpty() &&
  9034. viewCache.serverCache.isFullyInitialized()) {
  9035. // We might have reverted all child writes. Maybe the old event was a leaf node
  9036. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9037. if (complete.isLeafNode()) {
  9038. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9039. }
  9040. }
  9041. }
  9042. complete =
  9043. viewCache.serverCache.isFullyInitialized() ||
  9044. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9045. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9046. }
  9047. }
  9048. /**
  9049. * @license
  9050. * Copyright 2017 Google LLC
  9051. *
  9052. * Licensed under the Apache License, Version 2.0 (the "License");
  9053. * you may not use this file except in compliance with the License.
  9054. * You may obtain a copy of the License at
  9055. *
  9056. * http://www.apache.org/licenses/LICENSE-2.0
  9057. *
  9058. * Unless required by applicable law or agreed to in writing, software
  9059. * distributed under the License is distributed on an "AS IS" BASIS,
  9060. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9061. * See the License for the specific language governing permissions and
  9062. * limitations under the License.
  9063. */
  9064. /**
  9065. * A view represents a specific location and query that has 1 or more event registrations.
  9066. *
  9067. * It does several things:
  9068. * - Maintains the list of event registrations for this location/query.
  9069. * - Maintains a cache of the data visible for this location/query.
  9070. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9071. * registrations returns the set of events to be raised.
  9072. */
  9073. class View {
  9074. constructor(query_, initialViewCache) {
  9075. this.query_ = query_;
  9076. this.eventRegistrations_ = [];
  9077. const params = this.query_._queryParams;
  9078. const indexFilter = new IndexedFilter(params.getIndex());
  9079. const filter = queryParamsGetNodeFilter(params);
  9080. this.processor_ = newViewProcessor(filter);
  9081. const initialServerCache = initialViewCache.serverCache;
  9082. const initialEventCache = initialViewCache.eventCache;
  9083. // Don't filter server node with other filter than index, wait for tagged listen
  9084. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9085. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9086. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9087. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9088. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9089. this.eventGenerator_ = new EventGenerator(this.query_);
  9090. }
  9091. get query() {
  9092. return this.query_;
  9093. }
  9094. }
  9095. function viewGetServerCache(view) {
  9096. return view.viewCache_.serverCache.getNode();
  9097. }
  9098. function viewGetCompleteNode(view) {
  9099. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9100. }
  9101. function viewGetCompleteServerCache(view, path) {
  9102. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9103. if (cache) {
  9104. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9105. // we need to see if it contains the child we're interested in.
  9106. if (view.query._queryParams.loadsAllData() ||
  9107. (!pathIsEmpty(path) &&
  9108. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9109. return cache.getChild(path);
  9110. }
  9111. }
  9112. return null;
  9113. }
  9114. function viewIsEmpty(view) {
  9115. return view.eventRegistrations_.length === 0;
  9116. }
  9117. function viewAddEventRegistration(view, eventRegistration) {
  9118. view.eventRegistrations_.push(eventRegistration);
  9119. }
  9120. /**
  9121. * @param eventRegistration - If null, remove all callbacks.
  9122. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9123. * @returns Cancel events, if cancelError was provided.
  9124. */
  9125. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9126. const cancelEvents = [];
  9127. if (cancelError) {
  9128. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9129. const path = view.query._path;
  9130. view.eventRegistrations_.forEach(registration => {
  9131. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9132. if (maybeEvent) {
  9133. cancelEvents.push(maybeEvent);
  9134. }
  9135. });
  9136. }
  9137. if (eventRegistration) {
  9138. let remaining = [];
  9139. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9140. const existing = view.eventRegistrations_[i];
  9141. if (!existing.matches(eventRegistration)) {
  9142. remaining.push(existing);
  9143. }
  9144. else if (eventRegistration.hasAnyCallback()) {
  9145. // We're removing just this one
  9146. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9147. break;
  9148. }
  9149. }
  9150. view.eventRegistrations_ = remaining;
  9151. }
  9152. else {
  9153. view.eventRegistrations_ = [];
  9154. }
  9155. return cancelEvents;
  9156. }
  9157. /**
  9158. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9159. */
  9160. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9161. if (operation.type === OperationType.MERGE &&
  9162. operation.source.queryId !== null) {
  9163. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9164. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9165. }
  9166. const oldViewCache = view.viewCache_;
  9167. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9168. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9169. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  9170. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9171. view.viewCache_ = result.viewCache;
  9172. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9173. }
  9174. function viewGetInitialEvents(view, registration) {
  9175. const eventSnap = view.viewCache_.eventCache;
  9176. const initialChanges = [];
  9177. if (!eventSnap.getNode().isLeafNode()) {
  9178. const eventNode = eventSnap.getNode();
  9179. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9180. initialChanges.push(changeChildAdded(key, childNode));
  9181. });
  9182. }
  9183. if (eventSnap.isFullyInitialized()) {
  9184. initialChanges.push(changeValue(eventSnap.getNode()));
  9185. }
  9186. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9187. }
  9188. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9189. const registrations = eventRegistration
  9190. ? [eventRegistration]
  9191. : view.eventRegistrations_;
  9192. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9193. }
  9194. /**
  9195. * @license
  9196. * Copyright 2017 Google LLC
  9197. *
  9198. * Licensed under the Apache License, Version 2.0 (the "License");
  9199. * you may not use this file except in compliance with the License.
  9200. * You may obtain a copy of the License at
  9201. *
  9202. * http://www.apache.org/licenses/LICENSE-2.0
  9203. *
  9204. * Unless required by applicable law or agreed to in writing, software
  9205. * distributed under the License is distributed on an "AS IS" BASIS,
  9206. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9207. * See the License for the specific language governing permissions and
  9208. * limitations under the License.
  9209. */
  9210. let referenceConstructor$1;
  9211. /**
  9212. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9213. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9214. * and user writes (set, transaction, update).
  9215. *
  9216. * It's responsible for:
  9217. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9218. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9219. * applyUserOverwrite, etc.)
  9220. */
  9221. class SyncPoint {
  9222. constructor() {
  9223. /**
  9224. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9225. * queryId and the value is the View for that query.
  9226. *
  9227. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9228. */
  9229. this.views = new Map();
  9230. }
  9231. }
  9232. function syncPointSetReferenceConstructor(val) {
  9233. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9234. referenceConstructor$1 = val;
  9235. }
  9236. function syncPointGetReferenceConstructor() {
  9237. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9238. return referenceConstructor$1;
  9239. }
  9240. function syncPointIsEmpty(syncPoint) {
  9241. return syncPoint.views.size === 0;
  9242. }
  9243. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9244. const queryId = operation.source.queryId;
  9245. if (queryId !== null) {
  9246. const view = syncPoint.views.get(queryId);
  9247. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9248. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9249. }
  9250. else {
  9251. let events = [];
  9252. for (const view of syncPoint.views.values()) {
  9253. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9254. }
  9255. return events;
  9256. }
  9257. }
  9258. /**
  9259. * Get a view for the specified query.
  9260. *
  9261. * @param query - The query to return a view for
  9262. * @param writesCache
  9263. * @param serverCache
  9264. * @param serverCacheComplete
  9265. * @returns Events to raise.
  9266. */
  9267. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9268. const queryId = query._queryIdentifier;
  9269. const view = syncPoint.views.get(queryId);
  9270. if (!view) {
  9271. // TODO: make writesCache take flag for complete server node
  9272. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9273. let eventCacheComplete = false;
  9274. if (eventCache) {
  9275. eventCacheComplete = true;
  9276. }
  9277. else if (serverCache instanceof ChildrenNode) {
  9278. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9279. eventCacheComplete = false;
  9280. }
  9281. else {
  9282. eventCache = ChildrenNode.EMPTY_NODE;
  9283. eventCacheComplete = false;
  9284. }
  9285. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9286. return new View(query, viewCache);
  9287. }
  9288. return view;
  9289. }
  9290. /**
  9291. * Add an event callback for the specified query.
  9292. *
  9293. * @param query
  9294. * @param eventRegistration
  9295. * @param writesCache
  9296. * @param serverCache - Complete server cache, if we have it.
  9297. * @param serverCacheComplete
  9298. * @returns Events to raise.
  9299. */
  9300. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9301. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9302. if (!syncPoint.views.has(query._queryIdentifier)) {
  9303. syncPoint.views.set(query._queryIdentifier, view);
  9304. }
  9305. // This is guaranteed to exist now, we just created anything that was missing
  9306. viewAddEventRegistration(view, eventRegistration);
  9307. return viewGetInitialEvents(view, eventRegistration);
  9308. }
  9309. /**
  9310. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9311. *
  9312. * If query is the default query, we'll check all views for the specified eventRegistration.
  9313. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9314. *
  9315. * @param eventRegistration - If null, remove all callbacks.
  9316. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9317. * @returns removed queries and any cancel events
  9318. */
  9319. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9320. const queryId = query._queryIdentifier;
  9321. const removed = [];
  9322. let cancelEvents = [];
  9323. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9324. if (queryId === 'default') {
  9325. // When you do ref.off(...), we search all views for the registration to remove.
  9326. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9327. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9328. if (viewIsEmpty(view)) {
  9329. syncPoint.views.delete(viewQueryId);
  9330. // We'll deal with complete views later.
  9331. if (!view.query._queryParams.loadsAllData()) {
  9332. removed.push(view.query);
  9333. }
  9334. }
  9335. }
  9336. }
  9337. else {
  9338. // remove the callback from the specific view.
  9339. const view = syncPoint.views.get(queryId);
  9340. if (view) {
  9341. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9342. if (viewIsEmpty(view)) {
  9343. syncPoint.views.delete(queryId);
  9344. // We'll deal with complete views later.
  9345. if (!view.query._queryParams.loadsAllData()) {
  9346. removed.push(view.query);
  9347. }
  9348. }
  9349. }
  9350. }
  9351. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9352. // We removed our last complete view.
  9353. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9354. }
  9355. return { removed, events: cancelEvents };
  9356. }
  9357. function syncPointGetQueryViews(syncPoint) {
  9358. const result = [];
  9359. for (const view of syncPoint.views.values()) {
  9360. if (!view.query._queryParams.loadsAllData()) {
  9361. result.push(view);
  9362. }
  9363. }
  9364. return result;
  9365. }
  9366. /**
  9367. * @param path - The path to the desired complete snapshot
  9368. * @returns A complete cache, if it exists
  9369. */
  9370. function syncPointGetCompleteServerCache(syncPoint, path) {
  9371. let serverCache = null;
  9372. for (const view of syncPoint.views.values()) {
  9373. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9374. }
  9375. return serverCache;
  9376. }
  9377. function syncPointViewForQuery(syncPoint, query) {
  9378. const params = query._queryParams;
  9379. if (params.loadsAllData()) {
  9380. return syncPointGetCompleteView(syncPoint);
  9381. }
  9382. else {
  9383. const queryId = query._queryIdentifier;
  9384. return syncPoint.views.get(queryId);
  9385. }
  9386. }
  9387. function syncPointViewExistsForQuery(syncPoint, query) {
  9388. return syncPointViewForQuery(syncPoint, query) != null;
  9389. }
  9390. function syncPointHasCompleteView(syncPoint) {
  9391. return syncPointGetCompleteView(syncPoint) != null;
  9392. }
  9393. function syncPointGetCompleteView(syncPoint) {
  9394. for (const view of syncPoint.views.values()) {
  9395. if (view.query._queryParams.loadsAllData()) {
  9396. return view;
  9397. }
  9398. }
  9399. return null;
  9400. }
  9401. /**
  9402. * @license
  9403. * Copyright 2017 Google LLC
  9404. *
  9405. * Licensed under the Apache License, Version 2.0 (the "License");
  9406. * you may not use this file except in compliance with the License.
  9407. * You may obtain a copy of the License at
  9408. *
  9409. * http://www.apache.org/licenses/LICENSE-2.0
  9410. *
  9411. * Unless required by applicable law or agreed to in writing, software
  9412. * distributed under the License is distributed on an "AS IS" BASIS,
  9413. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9414. * See the License for the specific language governing permissions and
  9415. * limitations under the License.
  9416. */
  9417. let referenceConstructor;
  9418. function syncTreeSetReferenceConstructor(val) {
  9419. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9420. referenceConstructor = val;
  9421. }
  9422. function syncTreeGetReferenceConstructor() {
  9423. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  9424. return referenceConstructor;
  9425. }
  9426. /**
  9427. * Static tracker for next query tag.
  9428. */
  9429. let syncTreeNextQueryTag_ = 1;
  9430. /**
  9431. * SyncTree is the central class for managing event callback registration, data caching, views
  9432. * (query processing), and event generation. There are typically two SyncTree instances for
  9433. * each Repo, one for the normal Firebase data, and one for the .info data.
  9434. *
  9435. * It has a number of responsibilities, including:
  9436. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9437. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9438. * (applyUserOverwrite(), applyUserMerge()).
  9439. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9440. * applyServerMerge()).
  9441. * - Generating user-facing events for server and user changes (all of the apply* methods
  9442. * return the set of events that need to be raised as a result).
  9443. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9444. * to the correct set of paths and queries to satisfy the current set of user event
  9445. * callbacks (listens are started/stopped using the provided listenProvider).
  9446. *
  9447. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9448. * events are returned to the caller rather than raised synchronously.
  9449. *
  9450. */
  9451. class SyncTree {
  9452. /**
  9453. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9454. * to server data.
  9455. */
  9456. constructor(listenProvider_) {
  9457. this.listenProvider_ = listenProvider_;
  9458. /**
  9459. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9460. */
  9461. this.syncPointTree_ = new ImmutableTree(null);
  9462. /**
  9463. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9464. */
  9465. this.pendingWriteTree_ = newWriteTree();
  9466. this.tagToQueryMap = new Map();
  9467. this.queryToTagMap = new Map();
  9468. }
  9469. }
  9470. /**
  9471. * Apply the data changes for a user-generated set() or transaction() call.
  9472. *
  9473. * @returns Events to raise.
  9474. */
  9475. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9476. // Record pending write.
  9477. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9478. if (!visible) {
  9479. return [];
  9480. }
  9481. else {
  9482. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9483. }
  9484. }
  9485. /**
  9486. * Apply the data from a user-generated update() call
  9487. *
  9488. * @returns Events to raise.
  9489. */
  9490. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9491. // Record pending merge.
  9492. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9493. const changeTree = ImmutableTree.fromObject(changedChildren);
  9494. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9495. }
  9496. /**
  9497. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9498. *
  9499. * @param revert - True if the given write failed and needs to be reverted
  9500. * @returns Events to raise.
  9501. */
  9502. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9503. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9504. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9505. if (!needToReevaluate) {
  9506. return [];
  9507. }
  9508. else {
  9509. let affectedTree = new ImmutableTree(null);
  9510. if (write.snap != null) {
  9511. // overwrite
  9512. affectedTree = affectedTree.set(newEmptyPath(), true);
  9513. }
  9514. else {
  9515. each(write.children, (pathString) => {
  9516. affectedTree = affectedTree.set(new Path(pathString), true);
  9517. });
  9518. }
  9519. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9520. }
  9521. }
  9522. /**
  9523. * Apply new server data for the specified path..
  9524. *
  9525. * @returns Events to raise.
  9526. */
  9527. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9528. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9529. }
  9530. /**
  9531. * Apply new server data to be merged in at the specified path.
  9532. *
  9533. * @returns Events to raise.
  9534. */
  9535. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9536. const changeTree = ImmutableTree.fromObject(changedChildren);
  9537. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9538. }
  9539. /**
  9540. * Apply a listen complete for a query
  9541. *
  9542. * @returns Events to raise.
  9543. */
  9544. function syncTreeApplyListenComplete(syncTree, path) {
  9545. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9546. }
  9547. /**
  9548. * Apply a listen complete for a tagged query
  9549. *
  9550. * @returns Events to raise.
  9551. */
  9552. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9553. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9554. if (queryKey) {
  9555. const r = syncTreeParseQueryKey_(queryKey);
  9556. const queryPath = r.path, queryId = r.queryId;
  9557. const relativePath = newRelativePath(queryPath, path);
  9558. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9559. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9560. }
  9561. else {
  9562. // We've already removed the query. No big deal, ignore the update
  9563. return [];
  9564. }
  9565. }
  9566. /**
  9567. * Remove event callback(s).
  9568. *
  9569. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9570. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9571. *
  9572. * @param eventRegistration - If null, all callbacks are removed.
  9573. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9574. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9575. * deduping needs to take place. This flag allows toggling of that behavior
  9576. * @returns Cancel events, if cancelError was provided.
  9577. */
  9578. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9579. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9580. const path = query._path;
  9581. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9582. let cancelEvents = [];
  9583. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9584. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9585. // not loadsAllData().
  9586. if (maybeSyncPoint &&
  9587. (query._queryIdentifier === 'default' ||
  9588. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9589. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9590. if (syncPointIsEmpty(maybeSyncPoint)) {
  9591. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9592. }
  9593. const removed = removedAndEvents.removed;
  9594. cancelEvents = removedAndEvents.events;
  9595. if (!skipListenerDedup) {
  9596. /**
  9597. * We may have just removed one of many listeners and can short-circuit this whole process
  9598. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9599. * properly set up.
  9600. */
  9601. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9602. // queryId === 'default'
  9603. const removingDefault = -1 !==
  9604. removed.findIndex(query => {
  9605. return query._queryParams.loadsAllData();
  9606. });
  9607. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9608. if (removingDefault && !covered) {
  9609. const subtree = syncTree.syncPointTree_.subtree(path);
  9610. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9611. // removal
  9612. if (!subtree.isEmpty()) {
  9613. // We need to fold over our subtree and collect the listeners to send
  9614. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9615. // Ok, we've collected all the listens we need. Set them up.
  9616. for (let i = 0; i < newViews.length; ++i) {
  9617. const view = newViews[i], newQuery = view.query;
  9618. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9619. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9620. }
  9621. }
  9622. // Otherwise there's nothing below us, so nothing we need to start listening on
  9623. }
  9624. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9625. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9626. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9627. if (!covered && removed.length > 0 && !cancelError) {
  9628. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9629. // default. Otherwise, we need to iterate through and cancel each individual query
  9630. if (removingDefault) {
  9631. // We don't tag default listeners
  9632. const defaultTag = null;
  9633. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9634. }
  9635. else {
  9636. removed.forEach((queryToRemove) => {
  9637. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9638. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9639. });
  9640. }
  9641. }
  9642. }
  9643. // Now, clear all of the tags we're tracking for the removed listens
  9644. syncTreeRemoveTags_(syncTree, removed);
  9645. }
  9646. return cancelEvents;
  9647. }
  9648. /**
  9649. * Apply new server data for the specified tagged query.
  9650. *
  9651. * @returns Events to raise.
  9652. */
  9653. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9654. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9655. if (queryKey != null) {
  9656. const r = syncTreeParseQueryKey_(queryKey);
  9657. const queryPath = r.path, queryId = r.queryId;
  9658. const relativePath = newRelativePath(queryPath, path);
  9659. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9660. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9661. }
  9662. else {
  9663. // Query must have been removed already
  9664. return [];
  9665. }
  9666. }
  9667. /**
  9668. * Apply server data to be merged in for the specified tagged query.
  9669. *
  9670. * @returns Events to raise.
  9671. */
  9672. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9673. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9674. if (queryKey) {
  9675. const r = syncTreeParseQueryKey_(queryKey);
  9676. const queryPath = r.path, queryId = r.queryId;
  9677. const relativePath = newRelativePath(queryPath, path);
  9678. const changeTree = ImmutableTree.fromObject(changedChildren);
  9679. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9680. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9681. }
  9682. else {
  9683. // We've already removed the query. No big deal, ignore the update
  9684. return [];
  9685. }
  9686. }
  9687. /**
  9688. * Add an event callback for the specified query.
  9689. *
  9690. * @returns Events to raise.
  9691. */
  9692. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9693. const path = query._path;
  9694. let serverCache = null;
  9695. let foundAncestorDefaultView = false;
  9696. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9697. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9698. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9699. const relativePath = newRelativePath(pathToSyncPoint, path);
  9700. serverCache =
  9701. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9702. foundAncestorDefaultView =
  9703. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9704. });
  9705. let syncPoint = syncTree.syncPointTree_.get(path);
  9706. if (!syncPoint) {
  9707. syncPoint = new SyncPoint();
  9708. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9709. }
  9710. else {
  9711. foundAncestorDefaultView =
  9712. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9713. serverCache =
  9714. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9715. }
  9716. let serverCacheComplete;
  9717. if (serverCache != null) {
  9718. serverCacheComplete = true;
  9719. }
  9720. else {
  9721. serverCacheComplete = false;
  9722. serverCache = ChildrenNode.EMPTY_NODE;
  9723. const subtree = syncTree.syncPointTree_.subtree(path);
  9724. subtree.foreachChild((childName, childSyncPoint) => {
  9725. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9726. if (completeCache) {
  9727. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9728. }
  9729. });
  9730. }
  9731. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9732. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9733. // We need to track a tag for this query
  9734. const queryKey = syncTreeMakeQueryKey_(query);
  9735. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9736. const tag = syncTreeGetNextQueryTag_();
  9737. syncTree.queryToTagMap.set(queryKey, tag);
  9738. syncTree.tagToQueryMap.set(tag, queryKey);
  9739. }
  9740. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9741. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9742. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9743. const view = syncPointViewForQuery(syncPoint, query);
  9744. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9745. }
  9746. return events;
  9747. }
  9748. /**
  9749. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9750. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9751. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9752. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9753. *
  9754. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9755. *
  9756. * @param path - The path to the data we want
  9757. * @param writeIdsToExclude - A specific set to be excluded
  9758. */
  9759. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9760. const includeHiddenSets = true;
  9761. const writeTree = syncTree.pendingWriteTree_;
  9762. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9763. const relativePath = newRelativePath(pathSoFar, path);
  9764. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9765. if (serverCache) {
  9766. return serverCache;
  9767. }
  9768. });
  9769. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9770. }
  9771. function syncTreeGetServerValue(syncTree, query) {
  9772. const path = query._path;
  9773. let serverCache = null;
  9774. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9775. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9776. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9777. const relativePath = newRelativePath(pathToSyncPoint, path);
  9778. serverCache =
  9779. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9780. });
  9781. let syncPoint = syncTree.syncPointTree_.get(path);
  9782. if (!syncPoint) {
  9783. syncPoint = new SyncPoint();
  9784. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9785. }
  9786. else {
  9787. serverCache =
  9788. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9789. }
  9790. const serverCacheComplete = serverCache != null;
  9791. const serverCacheNode = serverCacheComplete
  9792. ? new CacheNode(serverCache, true, false)
  9793. : null;
  9794. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9795. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9796. return viewGetCompleteNode(view);
  9797. }
  9798. /**
  9799. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9800. *
  9801. * NOTES:
  9802. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9803. *
  9804. * - We call applyOperation() on each SyncPoint passing three things:
  9805. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9806. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9807. * 3. A snapshot Node with cached server data, if we have it.
  9808. *
  9809. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9810. */
  9811. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9812. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9813. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9814. }
  9815. /**
  9816. * Recursive helper for applyOperationToSyncPoints_
  9817. */
  9818. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9819. if (pathIsEmpty(operation.path)) {
  9820. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9821. }
  9822. else {
  9823. const syncPoint = syncPointTree.get(newEmptyPath());
  9824. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9825. if (serverCache == null && syncPoint != null) {
  9826. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9827. }
  9828. let events = [];
  9829. const childName = pathGetFront(operation.path);
  9830. const childOperation = operation.operationForChild(childName);
  9831. const childTree = syncPointTree.children.get(childName);
  9832. if (childTree && childOperation) {
  9833. const childServerCache = serverCache
  9834. ? serverCache.getImmediateChild(childName)
  9835. : null;
  9836. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9837. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9838. }
  9839. if (syncPoint) {
  9840. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9841. }
  9842. return events;
  9843. }
  9844. }
  9845. /**
  9846. * Recursive helper for applyOperationToSyncPoints_
  9847. */
  9848. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9849. const syncPoint = syncPointTree.get(newEmptyPath());
  9850. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9851. if (serverCache == null && syncPoint != null) {
  9852. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9853. }
  9854. let events = [];
  9855. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9856. const childServerCache = serverCache
  9857. ? serverCache.getImmediateChild(childName)
  9858. : null;
  9859. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9860. const childOperation = operation.operationForChild(childName);
  9861. if (childOperation) {
  9862. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9863. }
  9864. });
  9865. if (syncPoint) {
  9866. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9867. }
  9868. return events;
  9869. }
  9870. function syncTreeCreateListenerForView_(syncTree, view) {
  9871. const query = view.query;
  9872. const tag = syncTreeTagForQuery(syncTree, query);
  9873. return {
  9874. hashFn: () => {
  9875. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9876. return cache.hash();
  9877. },
  9878. onComplete: (status) => {
  9879. if (status === 'ok') {
  9880. if (tag) {
  9881. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9882. }
  9883. else {
  9884. return syncTreeApplyListenComplete(syncTree, query._path);
  9885. }
  9886. }
  9887. else {
  9888. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9889. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9890. const error = errorForServerCode(status, query);
  9891. return syncTreeRemoveEventRegistration(syncTree, query,
  9892. /*eventRegistration*/ null, error);
  9893. }
  9894. }
  9895. };
  9896. }
  9897. /**
  9898. * Return the tag associated with the given query.
  9899. */
  9900. function syncTreeTagForQuery(syncTree, query) {
  9901. const queryKey = syncTreeMakeQueryKey_(query);
  9902. return syncTree.queryToTagMap.get(queryKey);
  9903. }
  9904. /**
  9905. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9906. */
  9907. function syncTreeMakeQueryKey_(query) {
  9908. return query._path.toString() + '$' + query._queryIdentifier;
  9909. }
  9910. /**
  9911. * Return the query associated with the given tag, if we have one
  9912. */
  9913. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9914. return syncTree.tagToQueryMap.get(tag);
  9915. }
  9916. /**
  9917. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9918. */
  9919. function syncTreeParseQueryKey_(queryKey) {
  9920. const splitIndex = queryKey.indexOf('$');
  9921. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9922. return {
  9923. queryId: queryKey.substr(splitIndex + 1),
  9924. path: new Path(queryKey.substr(0, splitIndex))
  9925. };
  9926. }
  9927. /**
  9928. * A helper method to apply tagged operations
  9929. */
  9930. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9931. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9932. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9933. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9934. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9935. }
  9936. /**
  9937. * This collapses multiple unfiltered views into a single view, since we only need a single
  9938. * listener for them.
  9939. */
  9940. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9941. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9942. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9943. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9944. return [completeView];
  9945. }
  9946. else {
  9947. // No complete view here, flatten any deeper listens into an array
  9948. let views = [];
  9949. if (maybeChildSyncPoint) {
  9950. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9951. }
  9952. each(childMap, (_key, childViews) => {
  9953. views = views.concat(childViews);
  9954. });
  9955. return views;
  9956. }
  9957. });
  9958. }
  9959. /**
  9960. * Normalizes a query to a query we send the server for listening
  9961. *
  9962. * @returns The normalized query
  9963. */
  9964. function syncTreeQueryForListening_(query) {
  9965. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9966. // We treat queries that load all data as default queries
  9967. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9968. // from Query
  9969. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9970. }
  9971. else {
  9972. return query;
  9973. }
  9974. }
  9975. function syncTreeRemoveTags_(syncTree, queries) {
  9976. for (let j = 0; j < queries.length; ++j) {
  9977. const removedQuery = queries[j];
  9978. if (!removedQuery._queryParams.loadsAllData()) {
  9979. // We should have a tag for this
  9980. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9981. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9982. syncTree.queryToTagMap.delete(removedQueryKey);
  9983. syncTree.tagToQueryMap.delete(removedQueryTag);
  9984. }
  9985. }
  9986. }
  9987. /**
  9988. * Static accessor for query tags.
  9989. */
  9990. function syncTreeGetNextQueryTag_() {
  9991. return syncTreeNextQueryTag_++;
  9992. }
  9993. /**
  9994. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9995. *
  9996. * @returns This method can return events to support synchronous data sources
  9997. */
  9998. function syncTreeSetupListener_(syncTree, query, view) {
  9999. const path = query._path;
  10000. const tag = syncTreeTagForQuery(syncTree, query);
  10001. const listener = syncTreeCreateListenerForView_(syncTree, view);
  10002. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10003. const subtree = syncTree.syncPointTree_.subtree(path);
  10004. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10005. // may need to shadow other listens as well.
  10006. if (tag) {
  10007. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10008. }
  10009. else {
  10010. // Shadow everything at or below this location, this is a default listener.
  10011. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  10012. if (!pathIsEmpty(relativePath) &&
  10013. maybeChildSyncPoint &&
  10014. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10015. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10016. }
  10017. else {
  10018. // No default listener here, flatten any deeper queries into an array
  10019. let queries = [];
  10020. if (maybeChildSyncPoint) {
  10021. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10022. }
  10023. each(childMap, (_key, childQueries) => {
  10024. queries = queries.concat(childQueries);
  10025. });
  10026. return queries;
  10027. }
  10028. });
  10029. for (let i = 0; i < queriesToStop.length; ++i) {
  10030. const queryToStop = queriesToStop[i];
  10031. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10032. }
  10033. }
  10034. return events;
  10035. }
  10036. /**
  10037. * @license
  10038. * Copyright 2017 Google LLC
  10039. *
  10040. * Licensed under the Apache License, Version 2.0 (the "License");
  10041. * you may not use this file except in compliance with the License.
  10042. * You may obtain a copy of the License at
  10043. *
  10044. * http://www.apache.org/licenses/LICENSE-2.0
  10045. *
  10046. * Unless required by applicable law or agreed to in writing, software
  10047. * distributed under the License is distributed on an "AS IS" BASIS,
  10048. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10049. * See the License for the specific language governing permissions and
  10050. * limitations under the License.
  10051. */
  10052. class ExistingValueProvider {
  10053. constructor(node_) {
  10054. this.node_ = node_;
  10055. }
  10056. getImmediateChild(childName) {
  10057. const child = this.node_.getImmediateChild(childName);
  10058. return new ExistingValueProvider(child);
  10059. }
  10060. node() {
  10061. return this.node_;
  10062. }
  10063. }
  10064. class DeferredValueProvider {
  10065. constructor(syncTree, path) {
  10066. this.syncTree_ = syncTree;
  10067. this.path_ = path;
  10068. }
  10069. getImmediateChild(childName) {
  10070. const childPath = pathChild(this.path_, childName);
  10071. return new DeferredValueProvider(this.syncTree_, childPath);
  10072. }
  10073. node() {
  10074. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10075. }
  10076. }
  10077. /**
  10078. * Generate placeholders for deferred values.
  10079. */
  10080. const generateWithValues = function (values) {
  10081. values = values || {};
  10082. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10083. return values;
  10084. };
  10085. /**
  10086. * Value to use when firing local events. When writing server values, fire
  10087. * local events with an approximate value, otherwise return value as-is.
  10088. */
  10089. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10090. if (!value || typeof value !== 'object') {
  10091. return value;
  10092. }
  10093. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10094. if (typeof value['.sv'] === 'string') {
  10095. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10096. }
  10097. else if (typeof value['.sv'] === 'object') {
  10098. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10099. }
  10100. else {
  10101. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10102. }
  10103. };
  10104. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10105. switch (op) {
  10106. case 'timestamp':
  10107. return serverValues['timestamp'];
  10108. default:
  10109. util.assert(false, 'Unexpected server value: ' + op);
  10110. }
  10111. };
  10112. const resolveComplexDeferredValue = function (op, existing, unused) {
  10113. if (!op.hasOwnProperty('increment')) {
  10114. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10115. }
  10116. const delta = op['increment'];
  10117. if (typeof delta !== 'number') {
  10118. util.assert(false, 'Unexpected increment value: ' + delta);
  10119. }
  10120. const existingNode = existing.node();
  10121. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10122. // Incrementing a non-number sets the value to the incremented amount
  10123. if (!existingNode.isLeafNode()) {
  10124. return delta;
  10125. }
  10126. const leaf = existingNode;
  10127. const existingVal = leaf.getValue();
  10128. if (typeof existingVal !== 'number') {
  10129. return delta;
  10130. }
  10131. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10132. return existingVal + delta;
  10133. };
  10134. /**
  10135. * Recursively replace all deferred values and priorities in the tree with the
  10136. * specified generated replacement values.
  10137. * @param path - path to which write is relative
  10138. * @param node - new data written at path
  10139. * @param syncTree - current data
  10140. */
  10141. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10142. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10143. };
  10144. /**
  10145. * Recursively replace all deferred values and priorities in the node with the
  10146. * specified generated replacement values. If there are no server values in the node,
  10147. * it'll be returned as-is.
  10148. */
  10149. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10150. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10151. };
  10152. function resolveDeferredValue(node, existingVal, serverValues) {
  10153. const rawPri = node.getPriority().val();
  10154. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10155. let newNode;
  10156. if (node.isLeafNode()) {
  10157. const leafNode = node;
  10158. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10159. if (value !== leafNode.getValue() ||
  10160. priority !== leafNode.getPriority().val()) {
  10161. return new LeafNode(value, nodeFromJSON(priority));
  10162. }
  10163. else {
  10164. return node;
  10165. }
  10166. }
  10167. else {
  10168. const childrenNode = node;
  10169. newNode = childrenNode;
  10170. if (priority !== childrenNode.getPriority().val()) {
  10171. newNode = newNode.updatePriority(new LeafNode(priority));
  10172. }
  10173. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10174. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10175. if (newChildNode !== childNode) {
  10176. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10177. }
  10178. });
  10179. return newNode;
  10180. }
  10181. }
  10182. /**
  10183. * @license
  10184. * Copyright 2017 Google LLC
  10185. *
  10186. * Licensed under the Apache License, Version 2.0 (the "License");
  10187. * you may not use this file except in compliance with the License.
  10188. * You may obtain a copy of the License at
  10189. *
  10190. * http://www.apache.org/licenses/LICENSE-2.0
  10191. *
  10192. * Unless required by applicable law or agreed to in writing, software
  10193. * distributed under the License is distributed on an "AS IS" BASIS,
  10194. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10195. * See the License for the specific language governing permissions and
  10196. * limitations under the License.
  10197. */
  10198. /**
  10199. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10200. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10201. * children.
  10202. */
  10203. class Tree {
  10204. /**
  10205. * @param name - Optional name of the node.
  10206. * @param parent - Optional parent node.
  10207. * @param node - Optional node to wrap.
  10208. */
  10209. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10210. this.name = name;
  10211. this.parent = parent;
  10212. this.node = node;
  10213. }
  10214. }
  10215. /**
  10216. * Returns a sub-Tree for the given path.
  10217. *
  10218. * @param pathObj - Path to look up.
  10219. * @returns Tree for path.
  10220. */
  10221. function treeSubTree(tree, pathObj) {
  10222. // TODO: Require pathObj to be Path?
  10223. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10224. let child = tree, next = pathGetFront(path);
  10225. while (next !== null) {
  10226. const childNode = util.safeGet(child.node.children, next) || {
  10227. children: {},
  10228. childCount: 0
  10229. };
  10230. child = new Tree(next, child, childNode);
  10231. path = pathPopFront(path);
  10232. next = pathGetFront(path);
  10233. }
  10234. return child;
  10235. }
  10236. /**
  10237. * Returns the data associated with this tree node.
  10238. *
  10239. * @returns The data or null if no data exists.
  10240. */
  10241. function treeGetValue(tree) {
  10242. return tree.node.value;
  10243. }
  10244. /**
  10245. * Sets data to this tree node.
  10246. *
  10247. * @param value - Value to set.
  10248. */
  10249. function treeSetValue(tree, value) {
  10250. tree.node.value = value;
  10251. treeUpdateParents(tree);
  10252. }
  10253. /**
  10254. * @returns Whether the tree has any children.
  10255. */
  10256. function treeHasChildren(tree) {
  10257. return tree.node.childCount > 0;
  10258. }
  10259. /**
  10260. * @returns Whether the tree is empty (no value or children).
  10261. */
  10262. function treeIsEmpty(tree) {
  10263. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10264. }
  10265. /**
  10266. * Calls action for each child of this tree node.
  10267. *
  10268. * @param action - Action to be called for each child.
  10269. */
  10270. function treeForEachChild(tree, action) {
  10271. each(tree.node.children, (child, childTree) => {
  10272. action(new Tree(child, tree, childTree));
  10273. });
  10274. }
  10275. /**
  10276. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10277. *
  10278. * @param action - Action to be called for each child.
  10279. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10280. * false.
  10281. * @param childrenFirst - Whether to call action on children before calling it on
  10282. * parent.
  10283. */
  10284. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10285. if (includeSelf && !childrenFirst) {
  10286. action(tree);
  10287. }
  10288. treeForEachChild(tree, child => {
  10289. treeForEachDescendant(child, action, true, childrenFirst);
  10290. });
  10291. if (includeSelf && childrenFirst) {
  10292. action(tree);
  10293. }
  10294. }
  10295. /**
  10296. * Calls action on each ancestor node.
  10297. *
  10298. * @param action - Action to be called on each parent; return
  10299. * true to abort.
  10300. * @param includeSelf - Whether to call action on this node as well.
  10301. * @returns true if the action callback returned true.
  10302. */
  10303. function treeForEachAncestor(tree, action, includeSelf) {
  10304. let node = includeSelf ? tree : tree.parent;
  10305. while (node !== null) {
  10306. if (action(node)) {
  10307. return true;
  10308. }
  10309. node = node.parent;
  10310. }
  10311. return false;
  10312. }
  10313. /**
  10314. * @returns The path of this tree node, as a Path.
  10315. */
  10316. function treeGetPath(tree) {
  10317. return new Path(tree.parent === null
  10318. ? tree.name
  10319. : treeGetPath(tree.parent) + '/' + tree.name);
  10320. }
  10321. /**
  10322. * Adds or removes this child from its parent based on whether it's empty or not.
  10323. */
  10324. function treeUpdateParents(tree) {
  10325. if (tree.parent !== null) {
  10326. treeUpdateChild(tree.parent, tree.name, tree);
  10327. }
  10328. }
  10329. /**
  10330. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10331. *
  10332. * @param childName - The name of the child to update.
  10333. * @param child - The child to update.
  10334. */
  10335. function treeUpdateChild(tree, childName, child) {
  10336. const childEmpty = treeIsEmpty(child);
  10337. const childExists = util.contains(tree.node.children, childName);
  10338. if (childEmpty && childExists) {
  10339. delete tree.node.children[childName];
  10340. tree.node.childCount--;
  10341. treeUpdateParents(tree);
  10342. }
  10343. else if (!childEmpty && !childExists) {
  10344. tree.node.children[childName] = child.node;
  10345. tree.node.childCount++;
  10346. treeUpdateParents(tree);
  10347. }
  10348. }
  10349. /**
  10350. * @license
  10351. * Copyright 2017 Google LLC
  10352. *
  10353. * Licensed under the Apache License, Version 2.0 (the "License");
  10354. * you may not use this file except in compliance with the License.
  10355. * You may obtain a copy of the License at
  10356. *
  10357. * http://www.apache.org/licenses/LICENSE-2.0
  10358. *
  10359. * Unless required by applicable law or agreed to in writing, software
  10360. * distributed under the License is distributed on an "AS IS" BASIS,
  10361. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10362. * See the License for the specific language governing permissions and
  10363. * limitations under the License.
  10364. */
  10365. /**
  10366. * True for invalid Firebase keys
  10367. */
  10368. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10369. /**
  10370. * True for invalid Firebase paths.
  10371. * Allows '/' in paths.
  10372. */
  10373. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10374. /**
  10375. * Maximum number of characters to allow in leaf value
  10376. */
  10377. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10378. const isValidKey = function (key) {
  10379. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10380. };
  10381. const isValidPathString = function (pathString) {
  10382. return (typeof pathString === 'string' &&
  10383. pathString.length !== 0 &&
  10384. !INVALID_PATH_REGEX_.test(pathString));
  10385. };
  10386. const isValidRootPathString = function (pathString) {
  10387. if (pathString) {
  10388. // Allow '/.info/' at the beginning.
  10389. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10390. }
  10391. return isValidPathString(pathString);
  10392. };
  10393. const isValidPriority = function (priority) {
  10394. return (priority === null ||
  10395. typeof priority === 'string' ||
  10396. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10397. (priority &&
  10398. typeof priority === 'object' &&
  10399. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10400. util.contains(priority, '.sv')));
  10401. };
  10402. /**
  10403. * Pre-validate a datum passed as an argument to Firebase function.
  10404. */
  10405. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10406. if (optional && value === undefined) {
  10407. return;
  10408. }
  10409. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  10410. };
  10411. /**
  10412. * Validate a data object client-side before sending to server.
  10413. */
  10414. const validateFirebaseData = function (errorPrefix, data, path_) {
  10415. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10416. if (data === undefined) {
  10417. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10418. }
  10419. if (typeof data === 'function') {
  10420. throw new Error(errorPrefix +
  10421. 'contains a function ' +
  10422. validationPathToErrorString(path) +
  10423. ' with contents = ' +
  10424. data.toString());
  10425. }
  10426. if (isInvalidJSONNumber(data)) {
  10427. throw new Error(errorPrefix +
  10428. 'contains ' +
  10429. data.toString() +
  10430. ' ' +
  10431. validationPathToErrorString(path));
  10432. }
  10433. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10434. if (typeof data === 'string' &&
  10435. data.length > MAX_LEAF_SIZE_ / 3 &&
  10436. util.stringLength(data) > MAX_LEAF_SIZE_) {
  10437. throw new Error(errorPrefix +
  10438. 'contains a string greater than ' +
  10439. MAX_LEAF_SIZE_ +
  10440. ' utf8 bytes ' +
  10441. validationPathToErrorString(path) +
  10442. " ('" +
  10443. data.substring(0, 50) +
  10444. "...')");
  10445. }
  10446. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10447. // to save extra walking of large objects.
  10448. if (data && typeof data === 'object') {
  10449. let hasDotValue = false;
  10450. let hasActualChild = false;
  10451. each(data, (key, value) => {
  10452. if (key === '.value') {
  10453. hasDotValue = true;
  10454. }
  10455. else if (key !== '.priority' && key !== '.sv') {
  10456. hasActualChild = true;
  10457. if (!isValidKey(key)) {
  10458. throw new Error(errorPrefix +
  10459. ' contains an invalid key (' +
  10460. key +
  10461. ') ' +
  10462. validationPathToErrorString(path) +
  10463. '. Keys must be non-empty strings ' +
  10464. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10465. }
  10466. }
  10467. validationPathPush(path, key);
  10468. validateFirebaseData(errorPrefix, value, path);
  10469. validationPathPop(path);
  10470. });
  10471. if (hasDotValue && hasActualChild) {
  10472. throw new Error(errorPrefix +
  10473. ' contains ".value" child ' +
  10474. validationPathToErrorString(path) +
  10475. ' in addition to actual children.');
  10476. }
  10477. }
  10478. };
  10479. /**
  10480. * Pre-validate paths passed in the firebase function.
  10481. */
  10482. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10483. let i, curPath;
  10484. for (i = 0; i < mergePaths.length; i++) {
  10485. curPath = mergePaths[i];
  10486. const keys = pathSlice(curPath);
  10487. for (let j = 0; j < keys.length; j++) {
  10488. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10489. else if (!isValidKey(keys[j])) {
  10490. throw new Error(errorPrefix +
  10491. 'contains an invalid key (' +
  10492. keys[j] +
  10493. ') in path ' +
  10494. curPath.toString() +
  10495. '. Keys must be non-empty strings ' +
  10496. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10497. }
  10498. }
  10499. }
  10500. // Check that update keys are not descendants of each other.
  10501. // We rely on the property that sorting guarantees that ancestors come
  10502. // right before descendants.
  10503. mergePaths.sort(pathCompare);
  10504. let prevPath = null;
  10505. for (i = 0; i < mergePaths.length; i++) {
  10506. curPath = mergePaths[i];
  10507. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10508. throw new Error(errorPrefix +
  10509. 'contains a path ' +
  10510. prevPath.toString() +
  10511. ' that is ancestor of another path ' +
  10512. curPath.toString());
  10513. }
  10514. prevPath = curPath;
  10515. }
  10516. };
  10517. /**
  10518. * pre-validate an object passed as an argument to firebase function (
  10519. * must be an object - e.g. for firebase.update()).
  10520. */
  10521. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10522. if (optional && data === undefined) {
  10523. return;
  10524. }
  10525. const errorPrefix = util.errorPrefix(fnName, 'values');
  10526. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10527. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  10528. }
  10529. const mergePaths = [];
  10530. each(data, (key, value) => {
  10531. const curPath = new Path(key);
  10532. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  10533. if (pathGetBack(curPath) === '.priority') {
  10534. if (!isValidPriority(value)) {
  10535. throw new Error(errorPrefix +
  10536. "contains an invalid value for '" +
  10537. curPath.toString() +
  10538. "', which must be a valid " +
  10539. 'Firebase priority (a string, finite number, server value, or null).');
  10540. }
  10541. }
  10542. mergePaths.push(curPath);
  10543. });
  10544. validateFirebaseMergePaths(errorPrefix, mergePaths);
  10545. };
  10546. const validatePriority = function (fnName, priority, optional) {
  10547. if (optional && priority === undefined) {
  10548. return;
  10549. }
  10550. if (isInvalidJSONNumber(priority)) {
  10551. throw new Error(util.errorPrefix(fnName, 'priority') +
  10552. 'is ' +
  10553. priority.toString() +
  10554. ', but must be a valid Firebase priority (a string, finite number, ' +
  10555. 'server value, or null).');
  10556. }
  10557. // Special case to allow importing data with a .sv.
  10558. if (!isValidPriority(priority)) {
  10559. throw new Error(util.errorPrefix(fnName, 'priority') +
  10560. 'must be a valid Firebase priority ' +
  10561. '(a string, finite number, server value, or null).');
  10562. }
  10563. };
  10564. const validateKey = function (fnName, argumentName, key, optional) {
  10565. if (optional && key === undefined) {
  10566. return;
  10567. }
  10568. if (!isValidKey(key)) {
  10569. throw new Error(util.errorPrefix(fnName, argumentName) +
  10570. 'was an invalid key = "' +
  10571. key +
  10572. '". Firebase keys must be non-empty strings and ' +
  10573. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10574. }
  10575. };
  10576. /**
  10577. * @internal
  10578. */
  10579. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10580. if (optional && pathString === undefined) {
  10581. return;
  10582. }
  10583. if (!isValidPathString(pathString)) {
  10584. throw new Error(util.errorPrefix(fnName, argumentName) +
  10585. 'was an invalid path = "' +
  10586. pathString +
  10587. '". Paths must be non-empty strings and ' +
  10588. 'can\'t contain ".", "#", "$", "[", or "]"');
  10589. }
  10590. };
  10591. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10592. if (pathString) {
  10593. // Allow '/.info/' at the beginning.
  10594. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10595. }
  10596. validatePathString(fnName, argumentName, pathString, optional);
  10597. };
  10598. /**
  10599. * @internal
  10600. */
  10601. const validateWritablePath = function (fnName, path) {
  10602. if (pathGetFront(path) === '.info') {
  10603. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10604. }
  10605. };
  10606. const validateUrl = function (fnName, parsedUrl) {
  10607. // TODO = Validate server better.
  10608. const pathString = parsedUrl.path.toString();
  10609. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10610. parsedUrl.repoInfo.host.length === 0 ||
  10611. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10612. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10613. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10614. throw new Error(util.errorPrefix(fnName, 'url') +
  10615. 'must be a valid firebase URL and ' +
  10616. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10617. }
  10618. };
  10619. /**
  10620. * @license
  10621. * Copyright 2017 Google LLC
  10622. *
  10623. * Licensed under the Apache License, Version 2.0 (the "License");
  10624. * you may not use this file except in compliance with the License.
  10625. * You may obtain a copy of the License at
  10626. *
  10627. * http://www.apache.org/licenses/LICENSE-2.0
  10628. *
  10629. * Unless required by applicable law or agreed to in writing, software
  10630. * distributed under the License is distributed on an "AS IS" BASIS,
  10631. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10632. * See the License for the specific language governing permissions and
  10633. * limitations under the License.
  10634. */
  10635. /**
  10636. * The event queue serves a few purposes:
  10637. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10638. * events being queued.
  10639. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10640. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10641. * left off, ensuring that the events are still raised synchronously and in order.
  10642. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10643. * events are raised synchronously.
  10644. *
  10645. * NOTE: This can all go away if/when we move to async events.
  10646. *
  10647. */
  10648. class EventQueue {
  10649. constructor() {
  10650. this.eventLists_ = [];
  10651. /**
  10652. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10653. */
  10654. this.recursionDepth_ = 0;
  10655. }
  10656. }
  10657. /**
  10658. * @param eventDataList - The new events to queue.
  10659. */
  10660. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10661. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10662. let currList = null;
  10663. for (let i = 0; i < eventDataList.length; i++) {
  10664. const data = eventDataList[i];
  10665. const path = data.getPath();
  10666. if (currList !== null && !pathEquals(path, currList.path)) {
  10667. eventQueue.eventLists_.push(currList);
  10668. currList = null;
  10669. }
  10670. if (currList === null) {
  10671. currList = { events: [], path };
  10672. }
  10673. currList.events.push(data);
  10674. }
  10675. if (currList) {
  10676. eventQueue.eventLists_.push(currList);
  10677. }
  10678. }
  10679. /**
  10680. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10681. * for the specified path.
  10682. *
  10683. * It is assumed that the new events are all for the specified path.
  10684. *
  10685. * @param path - The path to raise events for.
  10686. * @param eventDataList - The new events to raise.
  10687. */
  10688. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10689. eventQueueQueueEvents(eventQueue, eventDataList);
  10690. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10691. }
  10692. /**
  10693. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10694. * locations related to the specified change path (i.e. all ancestors and descendants).
  10695. *
  10696. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10697. *
  10698. * @param changedPath - The path to raise events for.
  10699. * @param eventDataList - The events to raise
  10700. */
  10701. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10702. eventQueueQueueEvents(eventQueue, eventDataList);
  10703. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10704. pathContains(changedPath, eventPath));
  10705. }
  10706. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10707. eventQueue.recursionDepth_++;
  10708. let sentAll = true;
  10709. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10710. const eventList = eventQueue.eventLists_[i];
  10711. if (eventList) {
  10712. const eventPath = eventList.path;
  10713. if (predicate(eventPath)) {
  10714. eventListRaise(eventQueue.eventLists_[i]);
  10715. eventQueue.eventLists_[i] = null;
  10716. }
  10717. else {
  10718. sentAll = false;
  10719. }
  10720. }
  10721. }
  10722. if (sentAll) {
  10723. eventQueue.eventLists_ = [];
  10724. }
  10725. eventQueue.recursionDepth_--;
  10726. }
  10727. /**
  10728. * Iterates through the list and raises each event
  10729. */
  10730. function eventListRaise(eventList) {
  10731. for (let i = 0; i < eventList.events.length; i++) {
  10732. const eventData = eventList.events[i];
  10733. if (eventData !== null) {
  10734. eventList.events[i] = null;
  10735. const eventFn = eventData.getEventRunner();
  10736. if (logger) {
  10737. log('event: ' + eventData.toString());
  10738. }
  10739. exceptionGuard(eventFn);
  10740. }
  10741. }
  10742. }
  10743. /**
  10744. * @license
  10745. * Copyright 2017 Google LLC
  10746. *
  10747. * Licensed under the Apache License, Version 2.0 (the "License");
  10748. * you may not use this file except in compliance with the License.
  10749. * You may obtain a copy of the License at
  10750. *
  10751. * http://www.apache.org/licenses/LICENSE-2.0
  10752. *
  10753. * Unless required by applicable law or agreed to in writing, software
  10754. * distributed under the License is distributed on an "AS IS" BASIS,
  10755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10756. * See the License for the specific language governing permissions and
  10757. * limitations under the License.
  10758. */
  10759. const INTERRUPT_REASON = 'repo_interrupt';
  10760. /**
  10761. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10762. * things this ensure that if there's ever a bug causing a mismatch between
  10763. * client / server hashes for some data, we won't retry indefinitely.
  10764. */
  10765. const MAX_TRANSACTION_RETRIES = 25;
  10766. /**
  10767. * A connection to a single data repository.
  10768. */
  10769. class Repo {
  10770. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10771. this.repoInfo_ = repoInfo_;
  10772. this.forceRestClient_ = forceRestClient_;
  10773. this.authTokenProvider_ = authTokenProvider_;
  10774. this.appCheckProvider_ = appCheckProvider_;
  10775. this.dataUpdateCount = 0;
  10776. this.statsListener_ = null;
  10777. this.eventQueue_ = new EventQueue();
  10778. this.nextWriteId_ = 1;
  10779. this.interceptServerDataCallback_ = null;
  10780. /** A list of data pieces and paths to be set when this client disconnects. */
  10781. this.onDisconnect_ = newSparseSnapshotTree();
  10782. /** Stores queues of outstanding transactions for Firebase locations. */
  10783. this.transactionQueueTree_ = new Tree();
  10784. // TODO: This should be @private but it's used by test_access.js and internal.js
  10785. this.persistentConnection_ = null;
  10786. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10787. this.key = this.repoInfo_.toURLString();
  10788. }
  10789. /**
  10790. * @returns The URL corresponding to the root of this Firebase.
  10791. */
  10792. toString() {
  10793. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10794. }
  10795. }
  10796. function repoStart(repo, appId, authOverride) {
  10797. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10798. if (repo.forceRestClient_ || beingCrawled()) {
  10799. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10800. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10801. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10802. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10803. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10804. }
  10805. else {
  10806. // Validate authOverride
  10807. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10808. if (typeof authOverride !== 'object') {
  10809. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10810. }
  10811. try {
  10812. util.stringify(authOverride);
  10813. }
  10814. catch (e) {
  10815. throw new Error('Invalid authOverride provided: ' + e);
  10816. }
  10817. }
  10818. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10819. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10820. }, (connectStatus) => {
  10821. repoOnConnectStatus(repo, connectStatus);
  10822. }, (updates) => {
  10823. repoOnServerInfoUpdate(repo, updates);
  10824. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10825. repo.server_ = repo.persistentConnection_;
  10826. }
  10827. repo.authTokenProvider_.addTokenChangeListener(token => {
  10828. repo.server_.refreshAuthToken(token);
  10829. });
  10830. repo.appCheckProvider_.addTokenChangeListener(result => {
  10831. repo.server_.refreshAppCheckToken(result.token);
  10832. });
  10833. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10834. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10835. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10836. // Used for .info.
  10837. repo.infoData_ = new SnapshotHolder();
  10838. repo.infoSyncTree_ = new SyncTree({
  10839. startListening: (query, tag, currentHashFn, onComplete) => {
  10840. let infoEvents = [];
  10841. const node = repo.infoData_.getNode(query._path);
  10842. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10843. // on initial data...
  10844. if (!node.isEmpty()) {
  10845. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10846. setTimeout(() => {
  10847. onComplete('ok');
  10848. }, 0);
  10849. }
  10850. return infoEvents;
  10851. },
  10852. stopListening: () => { }
  10853. });
  10854. repoUpdateInfo(repo, 'connected', false);
  10855. repo.serverSyncTree_ = new SyncTree({
  10856. startListening: (query, tag, currentHashFn, onComplete) => {
  10857. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10858. const events = onComplete(status, data);
  10859. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10860. });
  10861. // No synchronous events for network-backed sync trees
  10862. return [];
  10863. },
  10864. stopListening: (query, tag) => {
  10865. repo.server_.unlisten(query, tag);
  10866. }
  10867. });
  10868. }
  10869. /**
  10870. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10871. */
  10872. function repoServerTime(repo) {
  10873. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10874. const offset = offsetNode.val() || 0;
  10875. return new Date().getTime() + offset;
  10876. }
  10877. /**
  10878. * Generate ServerValues using some variables from the repo object.
  10879. */
  10880. function repoGenerateServerValues(repo) {
  10881. return generateWithValues({
  10882. timestamp: repoServerTime(repo)
  10883. });
  10884. }
  10885. /**
  10886. * Called by realtime when we get new messages from the server.
  10887. */
  10888. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10889. // For testing.
  10890. repo.dataUpdateCount++;
  10891. const path = new Path(pathString);
  10892. data = repo.interceptServerDataCallback_
  10893. ? repo.interceptServerDataCallback_(pathString, data)
  10894. : data;
  10895. let events = [];
  10896. if (tag) {
  10897. if (isMerge) {
  10898. const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  10899. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10900. }
  10901. else {
  10902. const taggedSnap = nodeFromJSON(data);
  10903. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10904. }
  10905. }
  10906. else if (isMerge) {
  10907. const changedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  10908. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10909. }
  10910. else {
  10911. const snap = nodeFromJSON(data);
  10912. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10913. }
  10914. let affectedPath = path;
  10915. if (events.length > 0) {
  10916. // Since we have a listener outstanding for each transaction, receiving any events
  10917. // is a proxy for some change having occurred.
  10918. affectedPath = repoRerunTransactions(repo, path);
  10919. }
  10920. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10921. }
  10922. function repoOnConnectStatus(repo, connectStatus) {
  10923. repoUpdateInfo(repo, 'connected', connectStatus);
  10924. if (connectStatus === false) {
  10925. repoRunOnDisconnectEvents(repo);
  10926. }
  10927. }
  10928. function repoOnServerInfoUpdate(repo, updates) {
  10929. each(updates, (key, value) => {
  10930. repoUpdateInfo(repo, key, value);
  10931. });
  10932. }
  10933. function repoUpdateInfo(repo, pathString, value) {
  10934. const path = new Path('/.info/' + pathString);
  10935. const newNode = nodeFromJSON(value);
  10936. repo.infoData_.updateSnapshot(path, newNode);
  10937. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10938. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10939. }
  10940. function repoGetNextWriteId(repo) {
  10941. return repo.nextWriteId_++;
  10942. }
  10943. /**
  10944. * The purpose of `getValue` is to return the latest known value
  10945. * satisfying `query`.
  10946. *
  10947. * This method will first check for in-memory cached values
  10948. * belonging to active listeners. If they are found, such values
  10949. * are considered to be the most up-to-date.
  10950. *
  10951. * If the client is not connected, this method will wait until the
  10952. * repo has established a connection and then request the value for `query`.
  10953. * If the client is not able to retrieve the query result for another reason,
  10954. * it reports an error.
  10955. *
  10956. * @param query - The query to surface a value for.
  10957. */
  10958. function repoGetValue(repo, query, eventRegistration) {
  10959. // Only active queries are cached. There is no persisted cache.
  10960. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10961. if (cached != null) {
  10962. return Promise.resolve(cached);
  10963. }
  10964. return repo.server_.get(query).then(payload => {
  10965. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10966. /**
  10967. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10968. * Add an event registration,
  10969. * Update data at the path,
  10970. * Raise any events,
  10971. * Cleanup the SyncTree
  10972. */
  10973. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10974. let events;
  10975. if (query._queryParams.loadsAllData()) {
  10976. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10977. }
  10978. else {
  10979. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10980. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10981. }
  10982. /*
  10983. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10984. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10985. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10986. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10987. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10988. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10989. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10990. * ensure the corresponding child events will get fired.
  10991. */
  10992. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10993. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10994. return node;
  10995. }, err => {
  10996. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  10997. return Promise.reject(new Error(err));
  10998. });
  10999. }
  11000. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  11001. repoLog(repo, 'set', {
  11002. path: path.toString(),
  11003. value: newVal,
  11004. priority: newPriority
  11005. });
  11006. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11007. // (b) store unresolved paths on JSON parse
  11008. const serverValues = repoGenerateServerValues(repo);
  11009. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11010. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11011. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11012. const writeId = repoGetNextWriteId(repo);
  11013. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11014. eventQueueQueueEvents(repo.eventQueue_, events);
  11015. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11016. const success = status === 'ok';
  11017. if (!success) {
  11018. warn('set at ' + path + ' failed: ' + status);
  11019. }
  11020. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11021. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11022. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11023. });
  11024. const affectedPath = repoAbortTransactions(repo, path);
  11025. repoRerunTransactions(repo, affectedPath);
  11026. // We queued the events above, so just flush the queue here
  11027. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11028. }
  11029. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11030. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11031. // Start with our existing data and merge each child into it.
  11032. let empty = true;
  11033. const serverValues = repoGenerateServerValues(repo);
  11034. const changedChildren = {};
  11035. each(childrenToMerge, (changedKey, changedValue) => {
  11036. empty = false;
  11037. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11038. });
  11039. if (!empty) {
  11040. const writeId = repoGetNextWriteId(repo);
  11041. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11042. eventQueueQueueEvents(repo.eventQueue_, events);
  11043. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11044. const success = status === 'ok';
  11045. if (!success) {
  11046. warn('update at ' + path + ' failed: ' + status);
  11047. }
  11048. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11049. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11050. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11051. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11052. });
  11053. each(childrenToMerge, (changedPath) => {
  11054. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11055. repoRerunTransactions(repo, affectedPath);
  11056. });
  11057. // We queued the events above, so just flush the queue here
  11058. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11059. }
  11060. else {
  11061. log("update() called with empty data. Don't do anything.");
  11062. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11063. }
  11064. }
  11065. /**
  11066. * Applies all of the changes stored up in the onDisconnect_ tree.
  11067. */
  11068. function repoRunOnDisconnectEvents(repo) {
  11069. repoLog(repo, 'onDisconnectEvents');
  11070. const serverValues = repoGenerateServerValues(repo);
  11071. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11072. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11073. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11074. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11075. });
  11076. let events = [];
  11077. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11078. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11079. const affectedPath = repoAbortTransactions(repo, path);
  11080. repoRerunTransactions(repo, affectedPath);
  11081. });
  11082. repo.onDisconnect_ = newSparseSnapshotTree();
  11083. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11084. }
  11085. function repoOnDisconnectCancel(repo, path, onComplete) {
  11086. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11087. if (status === 'ok') {
  11088. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11089. }
  11090. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11091. });
  11092. }
  11093. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11094. const newNode = nodeFromJSON(value);
  11095. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11096. if (status === 'ok') {
  11097. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11098. }
  11099. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11100. });
  11101. }
  11102. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11103. const newNode = nodeFromJSON(value, priority);
  11104. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11105. if (status === 'ok') {
  11106. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11107. }
  11108. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11109. });
  11110. }
  11111. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11112. if (util.isEmpty(childrenToMerge)) {
  11113. log("onDisconnect().update() called with empty data. Don't do anything.");
  11114. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11115. return;
  11116. }
  11117. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11118. if (status === 'ok') {
  11119. each(childrenToMerge, (childName, childNode) => {
  11120. const newChildNode = nodeFromJSON(childNode);
  11121. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11122. });
  11123. }
  11124. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11125. });
  11126. }
  11127. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11128. let events;
  11129. if (pathGetFront(query._path) === '.info') {
  11130. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11131. }
  11132. else {
  11133. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11134. }
  11135. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11136. }
  11137. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11138. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11139. // a little bit by handling the return values anyways.
  11140. let events;
  11141. if (pathGetFront(query._path) === '.info') {
  11142. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11143. }
  11144. else {
  11145. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11146. }
  11147. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11148. }
  11149. function repoInterrupt(repo) {
  11150. if (repo.persistentConnection_) {
  11151. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11152. }
  11153. }
  11154. function repoResume(repo) {
  11155. if (repo.persistentConnection_) {
  11156. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11157. }
  11158. }
  11159. function repoLog(repo, ...varArgs) {
  11160. let prefix = '';
  11161. if (repo.persistentConnection_) {
  11162. prefix = repo.persistentConnection_.id + ':';
  11163. }
  11164. log(prefix, ...varArgs);
  11165. }
  11166. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11167. if (callback) {
  11168. exceptionGuard(() => {
  11169. if (status === 'ok') {
  11170. callback(null);
  11171. }
  11172. else {
  11173. const code = (status || 'error').toUpperCase();
  11174. let message = code;
  11175. if (errorReason) {
  11176. message += ': ' + errorReason;
  11177. }
  11178. const error = new Error(message);
  11179. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11180. error.code = code;
  11181. callback(error);
  11182. }
  11183. });
  11184. }
  11185. }
  11186. /**
  11187. * Creates a new transaction, adds it to the transactions we're tracking, and
  11188. * sends it to the server if possible.
  11189. *
  11190. * @param path - Path at which to do transaction.
  11191. * @param transactionUpdate - Update callback.
  11192. * @param onComplete - Completion callback.
  11193. * @param unwatcher - Function that will be called when the transaction no longer
  11194. * need data updates for `path`.
  11195. * @param applyLocally - Whether or not to make intermediate results visible
  11196. */
  11197. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11198. repoLog(repo, 'transaction on ' + path);
  11199. // Initialize transaction.
  11200. const transaction = {
  11201. path,
  11202. update: transactionUpdate,
  11203. onComplete,
  11204. // One of TransactionStatus enums.
  11205. status: null,
  11206. // Used when combining transactions at different locations to figure out
  11207. // which one goes first.
  11208. order: LUIDGenerator(),
  11209. // Whether to raise local events for this transaction.
  11210. applyLocally,
  11211. // Count of how many times we've retried the transaction.
  11212. retryCount: 0,
  11213. // Function to call to clean up our .on() listener.
  11214. unwatcher,
  11215. // Stores why a transaction was aborted.
  11216. abortReason: null,
  11217. currentWriteId: null,
  11218. currentInputSnapshot: null,
  11219. currentOutputSnapshotRaw: null,
  11220. currentOutputSnapshotResolved: null
  11221. };
  11222. // Run transaction initially.
  11223. const currentState = repoGetLatestState(repo, path, undefined);
  11224. transaction.currentInputSnapshot = currentState;
  11225. const newVal = transaction.update(currentState.val());
  11226. if (newVal === undefined) {
  11227. // Abort transaction.
  11228. transaction.unwatcher();
  11229. transaction.currentOutputSnapshotRaw = null;
  11230. transaction.currentOutputSnapshotResolved = null;
  11231. if (transaction.onComplete) {
  11232. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11233. }
  11234. }
  11235. else {
  11236. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11237. // Mark as run and add to our queue.
  11238. transaction.status = 0 /* TransactionStatus.RUN */;
  11239. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11240. const nodeQueue = treeGetValue(queueNode) || [];
  11241. nodeQueue.push(transaction);
  11242. treeSetValue(queueNode, nodeQueue);
  11243. // Update visibleData and raise events
  11244. // Note: We intentionally raise events after updating all of our
  11245. // transaction state, since the user could start new transactions from the
  11246. // event callbacks.
  11247. let priorityForNode;
  11248. if (typeof newVal === 'object' &&
  11249. newVal !== null &&
  11250. util.contains(newVal, '.priority')) {
  11251. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11252. priorityForNode = util.safeGet(newVal, '.priority');
  11253. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11254. 'Priority must be a valid string, finite number, server value, or null.');
  11255. }
  11256. else {
  11257. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11258. ChildrenNode.EMPTY_NODE;
  11259. priorityForNode = currentNode.getPriority().val();
  11260. }
  11261. const serverValues = repoGenerateServerValues(repo);
  11262. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11263. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11264. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11265. transaction.currentOutputSnapshotResolved = newNode;
  11266. transaction.currentWriteId = repoGetNextWriteId(repo);
  11267. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11268. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11269. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11270. }
  11271. }
  11272. /**
  11273. * @param excludeSets - A specific set to exclude
  11274. */
  11275. function repoGetLatestState(repo, path, excludeSets) {
  11276. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11277. ChildrenNode.EMPTY_NODE);
  11278. }
  11279. /**
  11280. * Sends any already-run transactions that aren't waiting for outstanding
  11281. * transactions to complete.
  11282. *
  11283. * Externally it's called with no arguments, but it calls itself recursively
  11284. * with a particular transactionQueueTree node to recurse through the tree.
  11285. *
  11286. * @param node - transactionQueueTree node to start at.
  11287. */
  11288. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11289. // Before recursing, make sure any completed transactions are removed.
  11290. if (!node) {
  11291. repoPruneCompletedTransactionsBelowNode(repo, node);
  11292. }
  11293. if (treeGetValue(node)) {
  11294. const queue = repoBuildTransactionQueue(repo, node);
  11295. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  11296. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11297. // If they're all run (and not sent), we can send them. Else, we must wait.
  11298. if (allRun) {
  11299. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11300. }
  11301. }
  11302. else if (treeHasChildren(node)) {
  11303. treeForEachChild(node, childNode => {
  11304. repoSendReadyTransactions(repo, childNode);
  11305. });
  11306. }
  11307. }
  11308. /**
  11309. * Given a list of run transactions, send them to the server and then handle
  11310. * the result (success or failure).
  11311. *
  11312. * @param path - The location of the queue.
  11313. * @param queue - Queue of transactions under the specified location.
  11314. */
  11315. function repoSendTransactionQueue(repo, path, queue) {
  11316. // Mark transactions as sent and increment retry count!
  11317. const setsToIgnore = queue.map(txn => {
  11318. return txn.currentWriteId;
  11319. });
  11320. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11321. let snapToSend = latestState;
  11322. const latestHash = latestState.hash();
  11323. for (let i = 0; i < queue.length; i++) {
  11324. const txn = queue[i];
  11325. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11326. txn.status = 1 /* TransactionStatus.SENT */;
  11327. txn.retryCount++;
  11328. const relativePath = newRelativePath(path, txn.path);
  11329. // If we've gotten to this point, the output snapshot must be defined.
  11330. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11331. }
  11332. const dataToSend = snapToSend.val(true);
  11333. const pathToSend = path;
  11334. // Send the put.
  11335. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11336. repoLog(repo, 'transaction put response', {
  11337. path: pathToSend.toString(),
  11338. status
  11339. });
  11340. let events = [];
  11341. if (status === 'ok') {
  11342. // Queue up the callbacks and fire them after cleaning up all of our
  11343. // transaction state, since the callback could trigger more
  11344. // transactions or sets.
  11345. const callbacks = [];
  11346. for (let i = 0; i < queue.length; i++) {
  11347. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11348. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11349. if (queue[i].onComplete) {
  11350. // We never unset the output snapshot, and given that this
  11351. // transaction is complete, it should be set
  11352. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11353. }
  11354. queue[i].unwatcher();
  11355. }
  11356. // Now remove the completed transactions.
  11357. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11358. // There may be pending transactions that we can now send.
  11359. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11360. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11361. // Finally, trigger onComplete callbacks.
  11362. for (let i = 0; i < callbacks.length; i++) {
  11363. exceptionGuard(callbacks[i]);
  11364. }
  11365. }
  11366. else {
  11367. // transactions are no longer sent. Update their status appropriately.
  11368. if (status === 'datastale') {
  11369. for (let i = 0; i < queue.length; i++) {
  11370. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11371. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11372. }
  11373. else {
  11374. queue[i].status = 0 /* TransactionStatus.RUN */;
  11375. }
  11376. }
  11377. }
  11378. else {
  11379. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11380. for (let i = 0; i < queue.length; i++) {
  11381. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11382. queue[i].abortReason = status;
  11383. }
  11384. }
  11385. repoRerunTransactions(repo, path);
  11386. }
  11387. }, latestHash);
  11388. }
  11389. /**
  11390. * Finds all transactions dependent on the data at changedPath and reruns them.
  11391. *
  11392. * Should be called any time cached data changes.
  11393. *
  11394. * Return the highest path that was affected by rerunning transactions. This
  11395. * is the path at which events need to be raised for.
  11396. *
  11397. * @param changedPath - The path in mergedData that changed.
  11398. * @returns The rootmost path that was affected by rerunning transactions.
  11399. */
  11400. function repoRerunTransactions(repo, changedPath) {
  11401. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11402. const path = treeGetPath(rootMostTransactionNode);
  11403. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11404. repoRerunTransactionQueue(repo, queue, path);
  11405. return path;
  11406. }
  11407. /**
  11408. * Does all the work of rerunning transactions (as well as cleans up aborted
  11409. * transactions and whatnot).
  11410. *
  11411. * @param queue - The queue of transactions to run.
  11412. * @param path - The path the queue is for.
  11413. */
  11414. function repoRerunTransactionQueue(repo, queue, path) {
  11415. if (queue.length === 0) {
  11416. return; // Nothing to do!
  11417. }
  11418. // Queue up the callbacks and fire them after cleaning up all of our
  11419. // transaction state, since the callback could trigger more transactions or
  11420. // sets.
  11421. const callbacks = [];
  11422. let events = [];
  11423. // Ignore all of the sets we're going to re-run.
  11424. const txnsToRerun = queue.filter(q => {
  11425. return q.status === 0 /* TransactionStatus.RUN */;
  11426. });
  11427. const setsToIgnore = txnsToRerun.map(q => {
  11428. return q.currentWriteId;
  11429. });
  11430. for (let i = 0; i < queue.length; i++) {
  11431. const transaction = queue[i];
  11432. const relativePath = newRelativePath(path, transaction.path);
  11433. let abortTransaction = false, abortReason;
  11434. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11435. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11436. abortTransaction = true;
  11437. abortReason = transaction.abortReason;
  11438. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11439. }
  11440. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11441. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11442. abortTransaction = true;
  11443. abortReason = 'maxretry';
  11444. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11445. }
  11446. else {
  11447. // This code reruns a transaction
  11448. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11449. transaction.currentInputSnapshot = currentNode;
  11450. const newData = queue[i].update(currentNode.val());
  11451. if (newData !== undefined) {
  11452. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11453. let newDataNode = nodeFromJSON(newData);
  11454. const hasExplicitPriority = typeof newData === 'object' &&
  11455. newData != null &&
  11456. util.contains(newData, '.priority');
  11457. if (!hasExplicitPriority) {
  11458. // Keep the old priority if there wasn't a priority explicitly specified.
  11459. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11460. }
  11461. const oldWriteId = transaction.currentWriteId;
  11462. const serverValues = repoGenerateServerValues(repo);
  11463. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11464. transaction.currentOutputSnapshotRaw = newDataNode;
  11465. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11466. transaction.currentWriteId = repoGetNextWriteId(repo);
  11467. // Mutates setsToIgnore in place
  11468. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11469. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11470. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11471. }
  11472. else {
  11473. abortTransaction = true;
  11474. abortReason = 'nodata';
  11475. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11476. }
  11477. }
  11478. }
  11479. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11480. events = [];
  11481. if (abortTransaction) {
  11482. // Abort.
  11483. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11484. // Removing a listener can trigger pruning which can muck with
  11485. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11486. // until we're done.
  11487. (function (unwatcher) {
  11488. setTimeout(unwatcher, Math.floor(0));
  11489. })(queue[i].unwatcher);
  11490. if (queue[i].onComplete) {
  11491. if (abortReason === 'nodata') {
  11492. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11493. }
  11494. else {
  11495. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11496. }
  11497. }
  11498. }
  11499. }
  11500. // Clean up completed transactions.
  11501. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11502. // Now fire callbacks, now that we're in a good, known state.
  11503. for (let i = 0; i < callbacks.length; i++) {
  11504. exceptionGuard(callbacks[i]);
  11505. }
  11506. // Try to send the transaction result to the server.
  11507. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11508. }
  11509. /**
  11510. * Returns the rootmost ancestor node of the specified path that has a pending
  11511. * transaction on it, or just returns the node for the given path if there are
  11512. * no pending transactions on any ancestor.
  11513. *
  11514. * @param path - The location to start at.
  11515. * @returns The rootmost node with a transaction.
  11516. */
  11517. function repoGetAncestorTransactionNode(repo, path) {
  11518. let front;
  11519. // Start at the root and walk deeper into the tree towards path until we
  11520. // find a node with pending transactions.
  11521. let transactionNode = repo.transactionQueueTree_;
  11522. front = pathGetFront(path);
  11523. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11524. transactionNode = treeSubTree(transactionNode, front);
  11525. path = pathPopFront(path);
  11526. front = pathGetFront(path);
  11527. }
  11528. return transactionNode;
  11529. }
  11530. /**
  11531. * Builds the queue of all transactions at or below the specified
  11532. * transactionNode.
  11533. *
  11534. * @param transactionNode
  11535. * @returns The generated queue.
  11536. */
  11537. function repoBuildTransactionQueue(repo, transactionNode) {
  11538. // Walk any child transaction queues and aggregate them into a single queue.
  11539. const transactionQueue = [];
  11540. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11541. // Sort them by the order the transactions were created.
  11542. transactionQueue.sort((a, b) => a.order - b.order);
  11543. return transactionQueue;
  11544. }
  11545. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11546. const nodeQueue = treeGetValue(node);
  11547. if (nodeQueue) {
  11548. for (let i = 0; i < nodeQueue.length; i++) {
  11549. queue.push(nodeQueue[i]);
  11550. }
  11551. }
  11552. treeForEachChild(node, child => {
  11553. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11554. });
  11555. }
  11556. /**
  11557. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11558. */
  11559. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11560. const queue = treeGetValue(node);
  11561. if (queue) {
  11562. let to = 0;
  11563. for (let from = 0; from < queue.length; from++) {
  11564. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11565. queue[to] = queue[from];
  11566. to++;
  11567. }
  11568. }
  11569. queue.length = to;
  11570. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11571. }
  11572. treeForEachChild(node, childNode => {
  11573. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11574. });
  11575. }
  11576. /**
  11577. * Aborts all transactions on ancestors or descendants of the specified path.
  11578. * Called when doing a set() or update() since we consider them incompatible
  11579. * with transactions.
  11580. *
  11581. * @param path - Path for which we want to abort related transactions.
  11582. */
  11583. function repoAbortTransactions(repo, path) {
  11584. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11585. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11586. treeForEachAncestor(transactionNode, (node) => {
  11587. repoAbortTransactionsOnNode(repo, node);
  11588. });
  11589. repoAbortTransactionsOnNode(repo, transactionNode);
  11590. treeForEachDescendant(transactionNode, (node) => {
  11591. repoAbortTransactionsOnNode(repo, node);
  11592. });
  11593. return affectedPath;
  11594. }
  11595. /**
  11596. * Abort transactions stored in this transaction queue node.
  11597. *
  11598. * @param node - Node to abort transactions for.
  11599. */
  11600. function repoAbortTransactionsOnNode(repo, node) {
  11601. const queue = treeGetValue(node);
  11602. if (queue) {
  11603. // Queue up the callbacks and fire them after cleaning up all of our
  11604. // transaction state, since the callback could trigger more transactions
  11605. // or sets.
  11606. const callbacks = [];
  11607. // Go through queue. Any already-sent transactions must be marked for
  11608. // abort, while the unsent ones can be immediately aborted and removed.
  11609. let events = [];
  11610. let lastSent = -1;
  11611. for (let i = 0; i < queue.length; i++) {
  11612. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11613. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11614. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11615. lastSent = i;
  11616. // Mark transaction for abort when it comes back.
  11617. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11618. queue[i].abortReason = 'set';
  11619. }
  11620. else {
  11621. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11622. // We can abort it immediately.
  11623. queue[i].unwatcher();
  11624. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11625. if (queue[i].onComplete) {
  11626. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11627. }
  11628. }
  11629. }
  11630. if (lastSent === -1) {
  11631. // We're not waiting for any sent transactions. We can clear the queue.
  11632. treeSetValue(node, undefined);
  11633. }
  11634. else {
  11635. // Remove the transactions we aborted.
  11636. queue.length = lastSent + 1;
  11637. }
  11638. // Now fire the callbacks.
  11639. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11640. for (let i = 0; i < callbacks.length; i++) {
  11641. exceptionGuard(callbacks[i]);
  11642. }
  11643. }
  11644. }
  11645. /**
  11646. * @license
  11647. * Copyright 2017 Google LLC
  11648. *
  11649. * Licensed under the Apache License, Version 2.0 (the "License");
  11650. * you may not use this file except in compliance with the License.
  11651. * You may obtain a copy of the License at
  11652. *
  11653. * http://www.apache.org/licenses/LICENSE-2.0
  11654. *
  11655. * Unless required by applicable law or agreed to in writing, software
  11656. * distributed under the License is distributed on an "AS IS" BASIS,
  11657. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11658. * See the License for the specific language governing permissions and
  11659. * limitations under the License.
  11660. */
  11661. function decodePath(pathString) {
  11662. let pathStringDecoded = '';
  11663. const pieces = pathString.split('/');
  11664. for (let i = 0; i < pieces.length; i++) {
  11665. if (pieces[i].length > 0) {
  11666. let piece = pieces[i];
  11667. try {
  11668. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11669. }
  11670. catch (e) { }
  11671. pathStringDecoded += '/' + piece;
  11672. }
  11673. }
  11674. return pathStringDecoded;
  11675. }
  11676. /**
  11677. * @returns key value hash
  11678. */
  11679. function decodeQuery(queryString) {
  11680. const results = {};
  11681. if (queryString.charAt(0) === '?') {
  11682. queryString = queryString.substring(1);
  11683. }
  11684. for (const segment of queryString.split('&')) {
  11685. if (segment.length === 0) {
  11686. continue;
  11687. }
  11688. const kv = segment.split('=');
  11689. if (kv.length === 2) {
  11690. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11691. }
  11692. else {
  11693. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11694. }
  11695. }
  11696. return results;
  11697. }
  11698. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11699. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11700. if (parsedUrl.domain === 'firebase.com') {
  11701. fatal(parsedUrl.host +
  11702. ' is no longer supported. ' +
  11703. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11704. }
  11705. // Catch common error of uninitialized namespace value.
  11706. if ((!namespace || namespace === 'undefined') &&
  11707. parsedUrl.domain !== 'localhost') {
  11708. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11709. }
  11710. if (!parsedUrl.secure) {
  11711. warnIfPageIsSecure();
  11712. }
  11713. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11714. return {
  11715. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11716. /*persistenceKey=*/ '',
  11717. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11718. path: new Path(parsedUrl.pathString)
  11719. };
  11720. };
  11721. const parseDatabaseURL = function (dataURL) {
  11722. // Default to empty strings in the event of a malformed string.
  11723. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11724. // Always default to SSL, unless otherwise specified.
  11725. let secure = true, scheme = 'https', port = 443;
  11726. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11727. if (typeof dataURL === 'string') {
  11728. // Parse scheme.
  11729. let colonInd = dataURL.indexOf('//');
  11730. if (colonInd >= 0) {
  11731. scheme = dataURL.substring(0, colonInd - 1);
  11732. dataURL = dataURL.substring(colonInd + 2);
  11733. }
  11734. // Parse host, path, and query string.
  11735. let slashInd = dataURL.indexOf('/');
  11736. if (slashInd === -1) {
  11737. slashInd = dataURL.length;
  11738. }
  11739. let questionMarkInd = dataURL.indexOf('?');
  11740. if (questionMarkInd === -1) {
  11741. questionMarkInd = dataURL.length;
  11742. }
  11743. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11744. if (slashInd < questionMarkInd) {
  11745. // For pathString, questionMarkInd will always come after slashInd
  11746. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11747. }
  11748. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11749. // If we have a port, use scheme for determining if it's secure.
  11750. colonInd = host.indexOf(':');
  11751. if (colonInd >= 0) {
  11752. secure = scheme === 'https' || scheme === 'wss';
  11753. port = parseInt(host.substring(colonInd + 1), 10);
  11754. }
  11755. else {
  11756. colonInd = host.length;
  11757. }
  11758. const hostWithoutPort = host.slice(0, colonInd);
  11759. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11760. domain = 'localhost';
  11761. }
  11762. else if (hostWithoutPort.split('.').length <= 2) {
  11763. domain = hostWithoutPort;
  11764. }
  11765. else {
  11766. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11767. const dotInd = host.indexOf('.');
  11768. subdomain = host.substring(0, dotInd).toLowerCase();
  11769. domain = host.substring(dotInd + 1);
  11770. // Normalize namespaces to lowercase to share storage / connection.
  11771. namespace = subdomain;
  11772. }
  11773. // Always treat the value of the `ns` as the namespace name if it is present.
  11774. if ('ns' in queryParams) {
  11775. namespace = queryParams['ns'];
  11776. }
  11777. }
  11778. return {
  11779. host,
  11780. port,
  11781. domain,
  11782. subdomain,
  11783. secure,
  11784. scheme,
  11785. pathString,
  11786. namespace
  11787. };
  11788. };
  11789. /**
  11790. * @license
  11791. * Copyright 2017 Google LLC
  11792. *
  11793. * Licensed under the Apache License, Version 2.0 (the "License");
  11794. * you may not use this file except in compliance with the License.
  11795. * You may obtain a copy of the License at
  11796. *
  11797. * http://www.apache.org/licenses/LICENSE-2.0
  11798. *
  11799. * Unless required by applicable law or agreed to in writing, software
  11800. * distributed under the License is distributed on an "AS IS" BASIS,
  11801. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11802. * See the License for the specific language governing permissions and
  11803. * limitations under the License.
  11804. */
  11805. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11806. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11807. /**
  11808. * Fancy ID generator that creates 20-character string identifiers with the
  11809. * following properties:
  11810. *
  11811. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11812. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11813. * collide with other clients' IDs.
  11814. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11815. * that will sort properly).
  11816. * 4. They're monotonically increasing. Even if you generate more than one in
  11817. * the same timestamp, the latter ones will sort after the former ones. We do
  11818. * this by using the previous random bits but "incrementing" them by 1 (only
  11819. * in the case of a timestamp collision).
  11820. */
  11821. const nextPushId = (function () {
  11822. // Timestamp of last push, used to prevent local collisions if you push twice
  11823. // in one ms.
  11824. let lastPushTime = 0;
  11825. // We generate 72-bits of randomness which get turned into 12 characters and
  11826. // appended to the timestamp to prevent collisions with other clients. We
  11827. // store the last characters we generated because in the event of a collision,
  11828. // we'll use those same characters except "incremented" by one.
  11829. const lastRandChars = [];
  11830. return function (now) {
  11831. const duplicateTime = now === lastPushTime;
  11832. lastPushTime = now;
  11833. let i;
  11834. const timeStampChars = new Array(8);
  11835. for (i = 7; i >= 0; i--) {
  11836. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11837. // NOTE: Can't use << here because javascript will convert to int and lose
  11838. // the upper bits.
  11839. now = Math.floor(now / 64);
  11840. }
  11841. util.assert(now === 0, 'Cannot push at time == 0');
  11842. let id = timeStampChars.join('');
  11843. if (!duplicateTime) {
  11844. for (i = 0; i < 12; i++) {
  11845. lastRandChars[i] = Math.floor(Math.random() * 64);
  11846. }
  11847. }
  11848. else {
  11849. // If the timestamp hasn't changed since last push, use the same random
  11850. // number, except incremented by 1.
  11851. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11852. lastRandChars[i] = 0;
  11853. }
  11854. lastRandChars[i]++;
  11855. }
  11856. for (i = 0; i < 12; i++) {
  11857. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11858. }
  11859. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  11860. return id;
  11861. };
  11862. })();
  11863. /**
  11864. * @license
  11865. * Copyright 2017 Google LLC
  11866. *
  11867. * Licensed under the Apache License, Version 2.0 (the "License");
  11868. * you may not use this file except in compliance with the License.
  11869. * You may obtain a copy of the License at
  11870. *
  11871. * http://www.apache.org/licenses/LICENSE-2.0
  11872. *
  11873. * Unless required by applicable law or agreed to in writing, software
  11874. * distributed under the License is distributed on an "AS IS" BASIS,
  11875. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11876. * See the License for the specific language governing permissions and
  11877. * limitations under the License.
  11878. */
  11879. /**
  11880. * Encapsulates the data needed to raise an event
  11881. */
  11882. class DataEvent {
  11883. /**
  11884. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11885. * @param eventRegistration - The function to call to with the event data. User provided
  11886. * @param snapshot - The data backing the event
  11887. * @param prevName - Optional, the name of the previous child for child_* events.
  11888. */
  11889. constructor(eventType, eventRegistration, snapshot, prevName) {
  11890. this.eventType = eventType;
  11891. this.eventRegistration = eventRegistration;
  11892. this.snapshot = snapshot;
  11893. this.prevName = prevName;
  11894. }
  11895. getPath() {
  11896. const ref = this.snapshot.ref;
  11897. if (this.eventType === 'value') {
  11898. return ref._path;
  11899. }
  11900. else {
  11901. return ref.parent._path;
  11902. }
  11903. }
  11904. getEventType() {
  11905. return this.eventType;
  11906. }
  11907. getEventRunner() {
  11908. return this.eventRegistration.getEventRunner(this);
  11909. }
  11910. toString() {
  11911. return (this.getPath().toString() +
  11912. ':' +
  11913. this.eventType +
  11914. ':' +
  11915. util.stringify(this.snapshot.exportVal()));
  11916. }
  11917. }
  11918. class CancelEvent {
  11919. constructor(eventRegistration, error, path) {
  11920. this.eventRegistration = eventRegistration;
  11921. this.error = error;
  11922. this.path = path;
  11923. }
  11924. getPath() {
  11925. return this.path;
  11926. }
  11927. getEventType() {
  11928. return 'cancel';
  11929. }
  11930. getEventRunner() {
  11931. return this.eventRegistration.getEventRunner(this);
  11932. }
  11933. toString() {
  11934. return this.path.toString() + ':cancel';
  11935. }
  11936. }
  11937. /**
  11938. * @license
  11939. * Copyright 2017 Google LLC
  11940. *
  11941. * Licensed under the Apache License, Version 2.0 (the "License");
  11942. * you may not use this file except in compliance with the License.
  11943. * You may obtain a copy of the License at
  11944. *
  11945. * http://www.apache.org/licenses/LICENSE-2.0
  11946. *
  11947. * Unless required by applicable law or agreed to in writing, software
  11948. * distributed under the License is distributed on an "AS IS" BASIS,
  11949. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11950. * See the License for the specific language governing permissions and
  11951. * limitations under the License.
  11952. */
  11953. /**
  11954. * A wrapper class that converts events from the database@exp SDK to the legacy
  11955. * Database SDK. Events are not converted directly as event registration relies
  11956. * on reference comparison of the original user callback (see `matches()`) and
  11957. * relies on equality of the legacy SDK's `context` object.
  11958. */
  11959. class CallbackContext {
  11960. constructor(snapshotCallback, cancelCallback) {
  11961. this.snapshotCallback = snapshotCallback;
  11962. this.cancelCallback = cancelCallback;
  11963. }
  11964. onValue(expDataSnapshot, previousChildName) {
  11965. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11966. }
  11967. onCancel(error) {
  11968. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11969. return this.cancelCallback.call(null, error);
  11970. }
  11971. get hasCancelCallback() {
  11972. return !!this.cancelCallback;
  11973. }
  11974. matches(other) {
  11975. return (this.snapshotCallback === other.snapshotCallback ||
  11976. (this.snapshotCallback.userCallback !== undefined &&
  11977. this.snapshotCallback.userCallback ===
  11978. other.snapshotCallback.userCallback &&
  11979. this.snapshotCallback.context === other.snapshotCallback.context));
  11980. }
  11981. }
  11982. /**
  11983. * @license
  11984. * Copyright 2021 Google LLC
  11985. *
  11986. * Licensed under the Apache License, Version 2.0 (the "License");
  11987. * you may not use this file except in compliance with the License.
  11988. * You may obtain a copy of the License at
  11989. *
  11990. * http://www.apache.org/licenses/LICENSE-2.0
  11991. *
  11992. * Unless required by applicable law or agreed to in writing, software
  11993. * distributed under the License is distributed on an "AS IS" BASIS,
  11994. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11995. * See the License for the specific language governing permissions and
  11996. * limitations under the License.
  11997. */
  11998. /**
  11999. * The `onDisconnect` class allows you to write or clear data when your client
  12000. * disconnects from the Database server. These updates occur whether your
  12001. * client disconnects cleanly or not, so you can rely on them to clean up data
  12002. * even if a connection is dropped or a client crashes.
  12003. *
  12004. * The `onDisconnect` class is most commonly used to manage presence in
  12005. * applications where it is useful to detect how many clients are connected and
  12006. * when other clients disconnect. See
  12007. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12008. * for more information.
  12009. *
  12010. * To avoid problems when a connection is dropped before the requests can be
  12011. * transferred to the Database server, these functions should be called before
  12012. * writing any data.
  12013. *
  12014. * Note that `onDisconnect` operations are only triggered once. If you want an
  12015. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12016. * the `onDisconnect` operations each time you reconnect.
  12017. */
  12018. class OnDisconnect {
  12019. /** @hideconstructor */
  12020. constructor(_repo, _path) {
  12021. this._repo = _repo;
  12022. this._path = _path;
  12023. }
  12024. /**
  12025. * Cancels all previously queued `onDisconnect()` set or update events for this
  12026. * location and all children.
  12027. *
  12028. * If a write has been queued for this location via a `set()` or `update()` at a
  12029. * parent location, the write at this location will be canceled, though writes
  12030. * to sibling locations will still occur.
  12031. *
  12032. * @returns Resolves when synchronization to the server is complete.
  12033. */
  12034. cancel() {
  12035. const deferred = new util.Deferred();
  12036. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12037. return deferred.promise;
  12038. }
  12039. /**
  12040. * Ensures the data at this location is deleted when the client is disconnected
  12041. * (due to closing the browser, navigating to a new page, or network issues).
  12042. *
  12043. * @returns Resolves when synchronization to the server is complete.
  12044. */
  12045. remove() {
  12046. validateWritablePath('OnDisconnect.remove', this._path);
  12047. const deferred = new util.Deferred();
  12048. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12049. return deferred.promise;
  12050. }
  12051. /**
  12052. * Ensures the data at this location is set to the specified value when the
  12053. * client is disconnected (due to closing the browser, navigating to a new page,
  12054. * or network issues).
  12055. *
  12056. * `set()` is especially useful for implementing "presence" systems, where a
  12057. * value should be changed or cleared when a user disconnects so that they
  12058. * appear "offline" to other users. See
  12059. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12060. * for more information.
  12061. *
  12062. * Note that `onDisconnect` operations are only triggered once. If you want an
  12063. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12064. * the `onDisconnect` operations each time.
  12065. *
  12066. * @param value - The value to be written to this location on disconnect (can
  12067. * be an object, array, string, number, boolean, or null).
  12068. * @returns Resolves when synchronization to the Database is complete.
  12069. */
  12070. set(value) {
  12071. validateWritablePath('OnDisconnect.set', this._path);
  12072. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12073. const deferred = new util.Deferred();
  12074. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12075. return deferred.promise;
  12076. }
  12077. /**
  12078. * Ensures the data at this location is set to the specified value and priority
  12079. * when the client is disconnected (due to closing the browser, navigating to a
  12080. * new page, or network issues).
  12081. *
  12082. * @param value - The value to be written to this location on disconnect (can
  12083. * be an object, array, string, number, boolean, or null).
  12084. * @param priority - The priority to be written (string, number, or null).
  12085. * @returns Resolves when synchronization to the Database is complete.
  12086. */
  12087. setWithPriority(value, priority) {
  12088. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12089. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12090. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12091. const deferred = new util.Deferred();
  12092. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12093. return deferred.promise;
  12094. }
  12095. /**
  12096. * Writes multiple values at this location when the client is disconnected (due
  12097. * to closing the browser, navigating to a new page, or network issues).
  12098. *
  12099. * The `values` argument contains multiple property-value pairs that will be
  12100. * written to the Database together. Each child property can either be a simple
  12101. * property (for example, "name") or a relative path (for example, "name/first")
  12102. * from the current location to the data to update.
  12103. *
  12104. * As opposed to the `set()` method, `update()` can be use to selectively update
  12105. * only the referenced properties at the current location (instead of replacing
  12106. * all the child properties at the current location).
  12107. *
  12108. * @param values - Object containing multiple values.
  12109. * @returns Resolves when synchronization to the Database is complete.
  12110. */
  12111. update(values) {
  12112. validateWritablePath('OnDisconnect.update', this._path);
  12113. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12114. const deferred = new util.Deferred();
  12115. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12116. return deferred.promise;
  12117. }
  12118. }
  12119. /**
  12120. * @license
  12121. * Copyright 2020 Google LLC
  12122. *
  12123. * Licensed under the Apache License, Version 2.0 (the "License");
  12124. * you may not use this file except in compliance with the License.
  12125. * You may obtain a copy of the License at
  12126. *
  12127. * http://www.apache.org/licenses/LICENSE-2.0
  12128. *
  12129. * Unless required by applicable law or agreed to in writing, software
  12130. * distributed under the License is distributed on an "AS IS" BASIS,
  12131. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12132. * See the License for the specific language governing permissions and
  12133. * limitations under the License.
  12134. */
  12135. /**
  12136. * @internal
  12137. */
  12138. class QueryImpl {
  12139. /**
  12140. * @hideconstructor
  12141. */
  12142. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12143. this._repo = _repo;
  12144. this._path = _path;
  12145. this._queryParams = _queryParams;
  12146. this._orderByCalled = _orderByCalled;
  12147. }
  12148. get key() {
  12149. if (pathIsEmpty(this._path)) {
  12150. return null;
  12151. }
  12152. else {
  12153. return pathGetBack(this._path);
  12154. }
  12155. }
  12156. get ref() {
  12157. return new ReferenceImpl(this._repo, this._path);
  12158. }
  12159. get _queryIdentifier() {
  12160. const obj = queryParamsGetQueryObject(this._queryParams);
  12161. const id = ObjectToUniqueKey(obj);
  12162. return id === '{}' ? 'default' : id;
  12163. }
  12164. /**
  12165. * An object representation of the query parameters used by this Query.
  12166. */
  12167. get _queryObject() {
  12168. return queryParamsGetQueryObject(this._queryParams);
  12169. }
  12170. isEqual(other) {
  12171. other = util.getModularInstance(other);
  12172. if (!(other instanceof QueryImpl)) {
  12173. return false;
  12174. }
  12175. const sameRepo = this._repo === other._repo;
  12176. const samePath = pathEquals(this._path, other._path);
  12177. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12178. return sameRepo && samePath && sameQueryIdentifier;
  12179. }
  12180. toJSON() {
  12181. return this.toString();
  12182. }
  12183. toString() {
  12184. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12185. }
  12186. }
  12187. /**
  12188. * Validates that no other order by call has been made
  12189. */
  12190. function validateNoPreviousOrderByCall(query, fnName) {
  12191. if (query._orderByCalled === true) {
  12192. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12193. }
  12194. }
  12195. /**
  12196. * Validates start/end values for queries.
  12197. */
  12198. function validateQueryEndpoints(params) {
  12199. let startNode = null;
  12200. let endNode = null;
  12201. if (params.hasStart()) {
  12202. startNode = params.getIndexStartValue();
  12203. }
  12204. if (params.hasEnd()) {
  12205. endNode = params.getIndexEndValue();
  12206. }
  12207. if (params.getIndex() === KEY_INDEX) {
  12208. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12209. 'startAt(), endAt(), or equalTo().';
  12210. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12211. 'endAt(), endBefore(), or equalTo() must be a string.';
  12212. if (params.hasStart()) {
  12213. const startName = params.getIndexStartName();
  12214. if (startName !== MIN_NAME) {
  12215. throw new Error(tooManyArgsError);
  12216. }
  12217. else if (typeof startNode !== 'string') {
  12218. throw new Error(wrongArgTypeError);
  12219. }
  12220. }
  12221. if (params.hasEnd()) {
  12222. const endName = params.getIndexEndName();
  12223. if (endName !== MAX_NAME) {
  12224. throw new Error(tooManyArgsError);
  12225. }
  12226. else if (typeof endNode !== 'string') {
  12227. throw new Error(wrongArgTypeError);
  12228. }
  12229. }
  12230. }
  12231. else if (params.getIndex() === PRIORITY_INDEX) {
  12232. if ((startNode != null && !isValidPriority(startNode)) ||
  12233. (endNode != null && !isValidPriority(endNode))) {
  12234. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12235. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12236. '(null, a number, or a string).');
  12237. }
  12238. }
  12239. else {
  12240. util.assert(params.getIndex() instanceof PathIndex ||
  12241. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12242. if ((startNode != null && typeof startNode === 'object') ||
  12243. (endNode != null && typeof endNode === 'object')) {
  12244. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12245. 'equalTo() cannot be an object.');
  12246. }
  12247. }
  12248. }
  12249. /**
  12250. * Validates that limit* has been called with the correct combination of parameters
  12251. */
  12252. function validateLimit(params) {
  12253. if (params.hasStart() &&
  12254. params.hasEnd() &&
  12255. params.hasLimit() &&
  12256. !params.hasAnchoredLimit()) {
  12257. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12258. 'limitToFirst() or limitToLast() instead.');
  12259. }
  12260. }
  12261. /**
  12262. * @internal
  12263. */
  12264. class ReferenceImpl extends QueryImpl {
  12265. /** @hideconstructor */
  12266. constructor(repo, path) {
  12267. super(repo, path, new QueryParams(), false);
  12268. }
  12269. get parent() {
  12270. const parentPath = pathParent(this._path);
  12271. return parentPath === null
  12272. ? null
  12273. : new ReferenceImpl(this._repo, parentPath);
  12274. }
  12275. get root() {
  12276. let ref = this;
  12277. while (ref.parent !== null) {
  12278. ref = ref.parent;
  12279. }
  12280. return ref;
  12281. }
  12282. }
  12283. /**
  12284. * A `DataSnapshot` contains data from a Database location.
  12285. *
  12286. * Any time you read data from the Database, you receive the data as a
  12287. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12288. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12289. * JavaScript object by calling the `val()` method. Alternatively, you can
  12290. * traverse into the snapshot by calling `child()` to return child snapshots
  12291. * (which you could then call `val()` on).
  12292. *
  12293. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12294. * a Database location. It cannot be modified and will never change (to modify
  12295. * data, you always call the `set()` method on a `Reference` directly).
  12296. */
  12297. class DataSnapshot {
  12298. /**
  12299. * @param _node - A SnapshotNode to wrap.
  12300. * @param ref - The location this snapshot came from.
  12301. * @param _index - The iteration order for this snapshot
  12302. * @hideconstructor
  12303. */
  12304. constructor(_node,
  12305. /**
  12306. * The location of this DataSnapshot.
  12307. */
  12308. ref, _index) {
  12309. this._node = _node;
  12310. this.ref = ref;
  12311. this._index = _index;
  12312. }
  12313. /**
  12314. * Gets the priority value of the data in this `DataSnapshot`.
  12315. *
  12316. * Applications need not use priority but can order collections by
  12317. * ordinary properties (see
  12318. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12319. * ).
  12320. */
  12321. get priority() {
  12322. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12323. return this._node.getPriority().val();
  12324. }
  12325. /**
  12326. * The key (last part of the path) of the location of this `DataSnapshot`.
  12327. *
  12328. * The last token in a Database location is considered its key. For example,
  12329. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12330. * `DataSnapshot` will return the key for the location that generated it.
  12331. * However, accessing the key on the root URL of a Database will return
  12332. * `null`.
  12333. */
  12334. get key() {
  12335. return this.ref.key;
  12336. }
  12337. /** Returns the number of child properties of this `DataSnapshot`. */
  12338. get size() {
  12339. return this._node.numChildren();
  12340. }
  12341. /**
  12342. * Gets another `DataSnapshot` for the location at the specified relative path.
  12343. *
  12344. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12345. * another `DataSnapshot` for the location at the specified relative path. The
  12346. * relative path can either be a simple child name (for example, "ada") or a
  12347. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12348. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12349. * whose value is `null`) is returned.
  12350. *
  12351. * @param path - A relative path to the location of child data.
  12352. */
  12353. child(path) {
  12354. const childPath = new Path(path);
  12355. const childRef = child(this.ref, path);
  12356. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12357. }
  12358. /**
  12359. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12360. * efficient than using `snapshot.val() !== null`.
  12361. */
  12362. exists() {
  12363. return !this._node.isEmpty();
  12364. }
  12365. /**
  12366. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12367. *
  12368. * The `exportVal()` method is similar to `val()`, except priority information
  12369. * is included (if available), making it suitable for backing up your data.
  12370. *
  12371. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12372. * Array, string, number, boolean, or `null`).
  12373. */
  12374. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12375. exportVal() {
  12376. return this._node.val(true);
  12377. }
  12378. /**
  12379. * Enumerates the top-level children in the `IteratedDataSnapshot`.
  12380. *
  12381. * Because of the way JavaScript objects work, the ordering of data in the
  12382. * JavaScript object returned by `val()` is not guaranteed to match the
  12383. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12384. * where `forEach()` comes in handy. It guarantees the children of a
  12385. * `DataSnapshot` will be iterated in their query order.
  12386. *
  12387. * If no explicit `orderBy*()` method is used, results are returned
  12388. * ordered by key (unless priorities are used, in which case, results are
  12389. * returned by priority).
  12390. *
  12391. * @param action - A function that will be called for each child DataSnapshot.
  12392. * The callback can return true to cancel further enumeration.
  12393. * @returns true if enumeration was canceled due to your callback returning
  12394. * true.
  12395. */
  12396. forEach(action) {
  12397. if (this._node.isLeafNode()) {
  12398. return false;
  12399. }
  12400. const childrenNode = this._node;
  12401. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12402. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12403. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12404. });
  12405. }
  12406. /**
  12407. * Returns true if the specified child path has (non-null) data.
  12408. *
  12409. * @param path - A relative path to the location of a potential child.
  12410. * @returns `true` if data exists at the specified child path; else
  12411. * `false`.
  12412. */
  12413. hasChild(path) {
  12414. const childPath = new Path(path);
  12415. return !this._node.getChild(childPath).isEmpty();
  12416. }
  12417. /**
  12418. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12419. * properties.
  12420. *
  12421. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12422. * children. If it does, you can enumerate them using `forEach()`. If it
  12423. * doesn't, then either this snapshot contains a primitive value (which can be
  12424. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12425. * `null`).
  12426. *
  12427. * @returns true if this snapshot has any children; else false.
  12428. */
  12429. hasChildren() {
  12430. if (this._node.isLeafNode()) {
  12431. return false;
  12432. }
  12433. else {
  12434. return !this._node.isEmpty();
  12435. }
  12436. }
  12437. /**
  12438. * Returns a JSON-serializable representation of this object.
  12439. */
  12440. toJSON() {
  12441. return this.exportVal();
  12442. }
  12443. /**
  12444. * Extracts a JavaScript value from a `DataSnapshot`.
  12445. *
  12446. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12447. * scalar type (string, number, or boolean), an array, or an object. It may
  12448. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12449. * data).
  12450. *
  12451. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12452. * Array, string, number, boolean, or `null`).
  12453. */
  12454. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12455. val() {
  12456. return this._node.val();
  12457. }
  12458. }
  12459. /**
  12460. *
  12461. * Returns a `Reference` representing the location in the Database
  12462. * corresponding to the provided path. If no path is provided, the `Reference`
  12463. * will point to the root of the Database.
  12464. *
  12465. * @param db - The database instance to obtain a reference for.
  12466. * @param path - Optional path representing the location the returned
  12467. * `Reference` will point. If not provided, the returned `Reference` will
  12468. * point to the root of the Database.
  12469. * @returns If a path is provided, a `Reference`
  12470. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12471. * root of the Database.
  12472. */
  12473. function ref(db, path) {
  12474. db = util.getModularInstance(db);
  12475. db._checkNotDeleted('ref');
  12476. return path !== undefined ? child(db._root, path) : db._root;
  12477. }
  12478. /**
  12479. * Returns a `Reference` representing the location in the Database
  12480. * corresponding to the provided Firebase URL.
  12481. *
  12482. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12483. * has a different domain than the current `Database` instance.
  12484. *
  12485. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12486. * and are not applied to the returned `Reference`.
  12487. *
  12488. * @param db - The database instance to obtain a reference for.
  12489. * @param url - The Firebase URL at which the returned `Reference` will
  12490. * point.
  12491. * @returns A `Reference` pointing to the provided
  12492. * Firebase URL.
  12493. */
  12494. function refFromURL(db, url) {
  12495. db = util.getModularInstance(db);
  12496. db._checkNotDeleted('refFromURL');
  12497. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12498. validateUrl('refFromURL', parsedURL);
  12499. const repoInfo = parsedURL.repoInfo;
  12500. if (!db._repo.repoInfo_.isCustomHost() &&
  12501. repoInfo.host !== db._repo.repoInfo_.host) {
  12502. fatal('refFromURL' +
  12503. ': Host name does not match the current database: ' +
  12504. '(found ' +
  12505. repoInfo.host +
  12506. ' but expected ' +
  12507. db._repo.repoInfo_.host +
  12508. ')');
  12509. }
  12510. return ref(db, parsedURL.path.toString());
  12511. }
  12512. /**
  12513. * Gets a `Reference` for the location at the specified relative path.
  12514. *
  12515. * The relative path can either be a simple child name (for example, "ada") or
  12516. * a deeper slash-separated path (for example, "ada/name/first").
  12517. *
  12518. * @param parent - The parent location.
  12519. * @param path - A relative path from this location to the desired child
  12520. * location.
  12521. * @returns The specified child location.
  12522. */
  12523. function child(parent, path) {
  12524. parent = util.getModularInstance(parent);
  12525. if (pathGetFront(parent._path) === null) {
  12526. validateRootPathString('child', 'path', path, false);
  12527. }
  12528. else {
  12529. validatePathString('child', 'path', path, false);
  12530. }
  12531. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12532. }
  12533. /**
  12534. * Returns an `OnDisconnect` object - see
  12535. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12536. * for more information on how to use it.
  12537. *
  12538. * @param ref - The reference to add OnDisconnect triggers for.
  12539. */
  12540. function onDisconnect(ref) {
  12541. ref = util.getModularInstance(ref);
  12542. return new OnDisconnect(ref._repo, ref._path);
  12543. }
  12544. /**
  12545. * Generates a new child location using a unique key and returns its
  12546. * `Reference`.
  12547. *
  12548. * This is the most common pattern for adding data to a collection of items.
  12549. *
  12550. * If you provide a value to `push()`, the value is written to the
  12551. * generated location. If you don't pass a value, nothing is written to the
  12552. * database and the child remains empty (but you can use the `Reference`
  12553. * elsewhere).
  12554. *
  12555. * The unique keys generated by `push()` are ordered by the current time, so the
  12556. * resulting list of items is chronologically sorted. The keys are also
  12557. * designed to be unguessable (they contain 72 random bits of entropy).
  12558. *
  12559. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12560. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12561. *
  12562. * @param parent - The parent location.
  12563. * @param value - Optional value to be written at the generated location.
  12564. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12565. * but can be used immediately as the `Reference` to the child location.
  12566. */
  12567. function push(parent, value) {
  12568. parent = util.getModularInstance(parent);
  12569. validateWritablePath('push', parent._path);
  12570. validateFirebaseDataArg('push', value, parent._path, true);
  12571. const now = repoServerTime(parent._repo);
  12572. const name = nextPushId(now);
  12573. // push() returns a ThennableReference whose promise is fulfilled with a
  12574. // regular Reference. We use child() to create handles to two different
  12575. // references. The first is turned into a ThennableReference below by adding
  12576. // then() and catch() methods and is used as the return value of push(). The
  12577. // second remains a regular Reference and is used as the fulfilled value of
  12578. // the first ThennableReference.
  12579. const thenablePushRef = child(parent, name);
  12580. const pushRef = child(parent, name);
  12581. let promise;
  12582. if (value != null) {
  12583. promise = set(pushRef, value).then(() => pushRef);
  12584. }
  12585. else {
  12586. promise = Promise.resolve(pushRef);
  12587. }
  12588. thenablePushRef.then = promise.then.bind(promise);
  12589. thenablePushRef.catch = promise.then.bind(promise, undefined);
  12590. return thenablePushRef;
  12591. }
  12592. /**
  12593. * Removes the data at this Database location.
  12594. *
  12595. * Any data at child locations will also be deleted.
  12596. *
  12597. * The effect of the remove will be visible immediately and the corresponding
  12598. * event 'value' will be triggered. Synchronization of the remove to the
  12599. * Firebase servers will also be started, and the returned Promise will resolve
  12600. * when complete. If provided, the onComplete callback will be called
  12601. * asynchronously after synchronization has finished.
  12602. *
  12603. * @param ref - The location to remove.
  12604. * @returns Resolves when remove on server is complete.
  12605. */
  12606. function remove(ref) {
  12607. validateWritablePath('remove', ref._path);
  12608. return set(ref, null);
  12609. }
  12610. /**
  12611. * Writes data to this Database location.
  12612. *
  12613. * This will overwrite any data at this location and all child locations.
  12614. *
  12615. * The effect of the write will be visible immediately, and the corresponding
  12616. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12617. * the data to the Firebase servers will also be started, and the returned
  12618. * Promise will resolve when complete. If provided, the `onComplete` callback
  12619. * will be called asynchronously after synchronization has finished.
  12620. *
  12621. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12622. * all data at this location and all child locations will be deleted.
  12623. *
  12624. * `set()` will remove any priority stored at this location, so if priority is
  12625. * meant to be preserved, you need to use `setWithPriority()` instead.
  12626. *
  12627. * Note that modifying data with `set()` will cancel any pending transactions
  12628. * at that location, so extreme care should be taken if mixing `set()` and
  12629. * `transaction()` to modify the same data.
  12630. *
  12631. * A single `set()` will generate a single "value" event at the location where
  12632. * the `set()` was performed.
  12633. *
  12634. * @param ref - The location to write to.
  12635. * @param value - The value to be written (string, number, boolean, object,
  12636. * array, or null).
  12637. * @returns Resolves when write to server is complete.
  12638. */
  12639. function set(ref, value) {
  12640. ref = util.getModularInstance(ref);
  12641. validateWritablePath('set', ref._path);
  12642. validateFirebaseDataArg('set', value, ref._path, false);
  12643. const deferred = new util.Deferred();
  12644. repoSetWithPriority(ref._repo, ref._path, value,
  12645. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12646. return deferred.promise;
  12647. }
  12648. /**
  12649. * Sets a priority for the data at this Database location.
  12650. *
  12651. * Applications need not use priority but can order collections by
  12652. * ordinary properties (see
  12653. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12654. * ).
  12655. *
  12656. * @param ref - The location to write to.
  12657. * @param priority - The priority to be written (string, number, or null).
  12658. * @returns Resolves when write to server is complete.
  12659. */
  12660. function setPriority(ref, priority) {
  12661. ref = util.getModularInstance(ref);
  12662. validateWritablePath('setPriority', ref._path);
  12663. validatePriority('setPriority', priority, false);
  12664. const deferred = new util.Deferred();
  12665. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12666. return deferred.promise;
  12667. }
  12668. /**
  12669. * Writes data the Database location. Like `set()` but also specifies the
  12670. * priority for that data.
  12671. *
  12672. * Applications need not use priority but can order collections by
  12673. * ordinary properties (see
  12674. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12675. * ).
  12676. *
  12677. * @param ref - The location to write to.
  12678. * @param value - The value to be written (string, number, boolean, object,
  12679. * array, or null).
  12680. * @param priority - The priority to be written (string, number, or null).
  12681. * @returns Resolves when write to server is complete.
  12682. */
  12683. function setWithPriority(ref, value, priority) {
  12684. validateWritablePath('setWithPriority', ref._path);
  12685. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12686. validatePriority('setWithPriority', priority, false);
  12687. if (ref.key === '.length' || ref.key === '.keys') {
  12688. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12689. }
  12690. const deferred = new util.Deferred();
  12691. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12692. return deferred.promise;
  12693. }
  12694. /**
  12695. * Writes multiple values to the Database at once.
  12696. *
  12697. * The `values` argument contains multiple property-value pairs that will be
  12698. * written to the Database together. Each child property can either be a simple
  12699. * property (for example, "name") or a relative path (for example,
  12700. * "name/first") from the current location to the data to update.
  12701. *
  12702. * As opposed to the `set()` method, `update()` can be use to selectively update
  12703. * only the referenced properties at the current location (instead of replacing
  12704. * all the child properties at the current location).
  12705. *
  12706. * The effect of the write will be visible immediately, and the corresponding
  12707. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12708. * the data to the Firebase servers will also be started, and the returned
  12709. * Promise will resolve when complete. If provided, the `onComplete` callback
  12710. * will be called asynchronously after synchronization has finished.
  12711. *
  12712. * A single `update()` will generate a single "value" event at the location
  12713. * where the `update()` was performed, regardless of how many children were
  12714. * modified.
  12715. *
  12716. * Note that modifying data with `update()` will cancel any pending
  12717. * transactions at that location, so extreme care should be taken if mixing
  12718. * `update()` and `transaction()` to modify the same data.
  12719. *
  12720. * Passing `null` to `update()` will remove the data at this location.
  12721. *
  12722. * See
  12723. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12724. *
  12725. * @param ref - The location to write to.
  12726. * @param values - Object containing multiple values.
  12727. * @returns Resolves when update on server is complete.
  12728. */
  12729. function update(ref, values) {
  12730. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12731. const deferred = new util.Deferred();
  12732. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12733. return deferred.promise;
  12734. }
  12735. /**
  12736. * Gets the most up-to-date result for this query.
  12737. *
  12738. * @param query - The query to run.
  12739. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12740. * available, or rejects if the client is unable to return a value (e.g., if the
  12741. * server is unreachable and there is nothing cached).
  12742. */
  12743. function get(query) {
  12744. query = util.getModularInstance(query);
  12745. const callbackContext = new CallbackContext(() => { });
  12746. const container = new ValueEventRegistration(callbackContext);
  12747. return repoGetValue(query._repo, query, container).then(node => {
  12748. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12749. });
  12750. }
  12751. /**
  12752. * Represents registration for 'value' events.
  12753. */
  12754. class ValueEventRegistration {
  12755. constructor(callbackContext) {
  12756. this.callbackContext = callbackContext;
  12757. }
  12758. respondsTo(eventType) {
  12759. return eventType === 'value';
  12760. }
  12761. createEvent(change, query) {
  12762. const index = query._queryParams.getIndex();
  12763. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12764. }
  12765. getEventRunner(eventData) {
  12766. if (eventData.getEventType() === 'cancel') {
  12767. return () => this.callbackContext.onCancel(eventData.error);
  12768. }
  12769. else {
  12770. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12771. }
  12772. }
  12773. createCancelEvent(error, path) {
  12774. if (this.callbackContext.hasCancelCallback) {
  12775. return new CancelEvent(this, error, path);
  12776. }
  12777. else {
  12778. return null;
  12779. }
  12780. }
  12781. matches(other) {
  12782. if (!(other instanceof ValueEventRegistration)) {
  12783. return false;
  12784. }
  12785. else if (!other.callbackContext || !this.callbackContext) {
  12786. // If no callback specified, we consider it to match any callback.
  12787. return true;
  12788. }
  12789. else {
  12790. return other.callbackContext.matches(this.callbackContext);
  12791. }
  12792. }
  12793. hasAnyCallback() {
  12794. return this.callbackContext !== null;
  12795. }
  12796. }
  12797. /**
  12798. * Represents the registration of a child_x event.
  12799. */
  12800. class ChildEventRegistration {
  12801. constructor(eventType, callbackContext) {
  12802. this.eventType = eventType;
  12803. this.callbackContext = callbackContext;
  12804. }
  12805. respondsTo(eventType) {
  12806. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12807. eventToCheck =
  12808. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12809. return this.eventType === eventToCheck;
  12810. }
  12811. createCancelEvent(error, path) {
  12812. if (this.callbackContext.hasCancelCallback) {
  12813. return new CancelEvent(this, error, path);
  12814. }
  12815. else {
  12816. return null;
  12817. }
  12818. }
  12819. createEvent(change, query) {
  12820. util.assert(change.childName != null, 'Child events should have a childName.');
  12821. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12822. const index = query._queryParams.getIndex();
  12823. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12824. }
  12825. getEventRunner(eventData) {
  12826. if (eventData.getEventType() === 'cancel') {
  12827. return () => this.callbackContext.onCancel(eventData.error);
  12828. }
  12829. else {
  12830. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12831. }
  12832. }
  12833. matches(other) {
  12834. if (other instanceof ChildEventRegistration) {
  12835. return (this.eventType === other.eventType &&
  12836. (!this.callbackContext ||
  12837. !other.callbackContext ||
  12838. this.callbackContext.matches(other.callbackContext)));
  12839. }
  12840. return false;
  12841. }
  12842. hasAnyCallback() {
  12843. return !!this.callbackContext;
  12844. }
  12845. }
  12846. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12847. let cancelCallback;
  12848. if (typeof cancelCallbackOrListenOptions === 'object') {
  12849. cancelCallback = undefined;
  12850. options = cancelCallbackOrListenOptions;
  12851. }
  12852. if (typeof cancelCallbackOrListenOptions === 'function') {
  12853. cancelCallback = cancelCallbackOrListenOptions;
  12854. }
  12855. if (options && options.onlyOnce) {
  12856. const userCallback = callback;
  12857. const onceCallback = (dataSnapshot, previousChildName) => {
  12858. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12859. userCallback(dataSnapshot, previousChildName);
  12860. };
  12861. onceCallback.userCallback = callback.userCallback;
  12862. onceCallback.context = callback.context;
  12863. callback = onceCallback;
  12864. }
  12865. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12866. const container = eventType === 'value'
  12867. ? new ValueEventRegistration(callbackContext)
  12868. : new ChildEventRegistration(eventType, callbackContext);
  12869. repoAddEventCallbackForQuery(query._repo, query, container);
  12870. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12871. }
  12872. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12873. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12874. }
  12875. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12876. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12877. }
  12878. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12879. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12880. }
  12881. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12882. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12883. }
  12884. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12885. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12886. }
  12887. /**
  12888. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12889. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12890. * the respective `on*` callbacks.
  12891. *
  12892. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12893. * will not automatically remove listeners registered on child nodes, `off()`
  12894. * must also be called on any child listeners to remove the callback.
  12895. *
  12896. * If a callback is not specified, all callbacks for the specified eventType
  12897. * will be removed. Similarly, if no eventType is specified, all callbacks
  12898. * for the `Reference` will be removed.
  12899. *
  12900. * Individual listeners can also be removed by invoking their unsubscribe
  12901. * callbacks.
  12902. *
  12903. * @param query - The query that the listener was registered with.
  12904. * @param eventType - One of the following strings: "value", "child_added",
  12905. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12906. * for the `Reference` will be removed.
  12907. * @param callback - The callback function that was passed to `on()` or
  12908. * `undefined` to remove all callbacks.
  12909. */
  12910. function off(query, eventType, callback) {
  12911. let container = null;
  12912. const expCallback = callback ? new CallbackContext(callback) : null;
  12913. if (eventType === 'value') {
  12914. container = new ValueEventRegistration(expCallback);
  12915. }
  12916. else if (eventType) {
  12917. container = new ChildEventRegistration(eventType, expCallback);
  12918. }
  12919. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12920. }
  12921. /**
  12922. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12923. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12924. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12925. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12926. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12927. * {@link orderByValue} or {@link equalTo} and
  12928. * can then be passed to {@link query} to create a new query instance that
  12929. * also contains this `QueryConstraint`.
  12930. */
  12931. class QueryConstraint {
  12932. }
  12933. class QueryEndAtConstraint extends QueryConstraint {
  12934. constructor(_value, _key) {
  12935. super();
  12936. this._value = _value;
  12937. this._key = _key;
  12938. this.type = 'endAt';
  12939. }
  12940. _apply(query) {
  12941. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12942. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12943. validateLimit(newParams);
  12944. validateQueryEndpoints(newParams);
  12945. if (query._queryParams.hasEnd()) {
  12946. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12947. 'endBefore or equalTo).');
  12948. }
  12949. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12950. }
  12951. }
  12952. /**
  12953. * Creates a `QueryConstraint` with the specified ending point.
  12954. *
  12955. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12956. * allows you to choose arbitrary starting and ending points for your queries.
  12957. *
  12958. * The ending point is inclusive, so children with exactly the specified value
  12959. * will be included in the query. The optional key argument can be used to
  12960. * further limit the range of the query. If it is specified, then children that
  12961. * have exactly the specified value must also have a key name less than or equal
  12962. * to the specified key.
  12963. *
  12964. * You can read more about `endAt()` in
  12965. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12966. *
  12967. * @param value - The value to end at. The argument type depends on which
  12968. * `orderBy*()` function was used in this query. Specify a value that matches
  12969. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12970. * value must be a string.
  12971. * @param key - The child key to end at, among the children with the previously
  12972. * specified priority. This argument is only allowed if ordering by child,
  12973. * value, or priority.
  12974. */
  12975. function endAt(value, key) {
  12976. validateKey('endAt', 'key', key, true);
  12977. return new QueryEndAtConstraint(value, key);
  12978. }
  12979. class QueryEndBeforeConstraint extends QueryConstraint {
  12980. constructor(_value, _key) {
  12981. super();
  12982. this._value = _value;
  12983. this._key = _key;
  12984. this.type = 'endBefore';
  12985. }
  12986. _apply(query) {
  12987. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12988. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12989. validateLimit(newParams);
  12990. validateQueryEndpoints(newParams);
  12991. if (query._queryParams.hasEnd()) {
  12992. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12993. 'endBefore or equalTo).');
  12994. }
  12995. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12996. }
  12997. }
  12998. /**
  12999. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  13000. *
  13001. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13002. * allows you to choose arbitrary starting and ending points for your queries.
  13003. *
  13004. * The ending point is exclusive. If only a value is provided, children
  13005. * with a value less than the specified value will be included in the query.
  13006. * If a key is specified, then children must have a value less than or equal
  13007. * to the specified value and a key name less than the specified key.
  13008. *
  13009. * @param value - The value to end before. The argument type depends on which
  13010. * `orderBy*()` function was used in this query. Specify a value that matches
  13011. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13012. * value must be a string.
  13013. * @param key - The child key to end before, among the children with the
  13014. * previously specified priority. This argument is only allowed if ordering by
  13015. * child, value, or priority.
  13016. */
  13017. function endBefore(value, key) {
  13018. validateKey('endBefore', 'key', key, true);
  13019. return new QueryEndBeforeConstraint(value, key);
  13020. }
  13021. class QueryStartAtConstraint extends QueryConstraint {
  13022. constructor(_value, _key) {
  13023. super();
  13024. this._value = _value;
  13025. this._key = _key;
  13026. this.type = 'startAt';
  13027. }
  13028. _apply(query) {
  13029. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13030. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13031. validateLimit(newParams);
  13032. validateQueryEndpoints(newParams);
  13033. if (query._queryParams.hasStart()) {
  13034. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13035. 'startBefore or equalTo).');
  13036. }
  13037. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13038. }
  13039. }
  13040. /**
  13041. * Creates a `QueryConstraint` with the specified starting point.
  13042. *
  13043. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13044. * allows you to choose arbitrary starting and ending points for your queries.
  13045. *
  13046. * The starting point is inclusive, so children with exactly the specified value
  13047. * will be included in the query. The optional key argument can be used to
  13048. * further limit the range of the query. If it is specified, then children that
  13049. * have exactly the specified value must also have a key name greater than or
  13050. * equal to the specified key.
  13051. *
  13052. * You can read more about `startAt()` in
  13053. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13054. *
  13055. * @param value - The value to start at. The argument type depends on which
  13056. * `orderBy*()` function was used in this query. Specify a value that matches
  13057. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13058. * value must be a string.
  13059. * @param key - The child key to start at. This argument is only allowed if
  13060. * ordering by child, value, or priority.
  13061. */
  13062. function startAt(value = null, key) {
  13063. validateKey('startAt', 'key', key, true);
  13064. return new QueryStartAtConstraint(value, key);
  13065. }
  13066. class QueryStartAfterConstraint extends QueryConstraint {
  13067. constructor(_value, _key) {
  13068. super();
  13069. this._value = _value;
  13070. this._key = _key;
  13071. this.type = 'startAfter';
  13072. }
  13073. _apply(query) {
  13074. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13075. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13076. validateLimit(newParams);
  13077. validateQueryEndpoints(newParams);
  13078. if (query._queryParams.hasStart()) {
  13079. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13080. 'startAfter, or equalTo).');
  13081. }
  13082. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13083. }
  13084. }
  13085. /**
  13086. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13087. *
  13088. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13089. * allows you to choose arbitrary starting and ending points for your queries.
  13090. *
  13091. * The starting point is exclusive. If only a value is provided, children
  13092. * with a value greater than the specified value will be included in the query.
  13093. * If a key is specified, then children must have a value greater than or equal
  13094. * to the specified value and a a key name greater than the specified key.
  13095. *
  13096. * @param value - The value to start after. The argument type depends on which
  13097. * `orderBy*()` function was used in this query. Specify a value that matches
  13098. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13099. * value must be a string.
  13100. * @param key - The child key to start after. This argument is only allowed if
  13101. * ordering by child, value, or priority.
  13102. */
  13103. function startAfter(value, key) {
  13104. validateKey('startAfter', 'key', key, true);
  13105. return new QueryStartAfterConstraint(value, key);
  13106. }
  13107. class QueryLimitToFirstConstraint extends QueryConstraint {
  13108. constructor(_limit) {
  13109. super();
  13110. this._limit = _limit;
  13111. this.type = 'limitToFirst';
  13112. }
  13113. _apply(query) {
  13114. if (query._queryParams.hasLimit()) {
  13115. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13116. 'or limitToLast).');
  13117. }
  13118. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13119. }
  13120. }
  13121. /**
  13122. * Creates a new `QueryConstraint` that if limited to the first specific number
  13123. * of children.
  13124. *
  13125. * The `limitToFirst()` method is used to set a maximum number of children to be
  13126. * synced for a given callback. If we set a limit of 100, we will initially only
  13127. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13128. * stored in our Database, a `child_added` event will fire for each message.
  13129. * However, if we have over 100 messages, we will only receive a `child_added`
  13130. * event for the first 100 ordered messages. As items change, we will receive
  13131. * `child_removed` events for each item that drops out of the active list so
  13132. * that the total number stays at 100.
  13133. *
  13134. * You can read more about `limitToFirst()` in
  13135. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13136. *
  13137. * @param limit - The maximum number of nodes to include in this query.
  13138. */
  13139. function limitToFirst(limit) {
  13140. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13141. throw new Error('limitToFirst: First argument must be a positive integer.');
  13142. }
  13143. return new QueryLimitToFirstConstraint(limit);
  13144. }
  13145. class QueryLimitToLastConstraint extends QueryConstraint {
  13146. constructor(_limit) {
  13147. super();
  13148. this._limit = _limit;
  13149. this.type = 'limitToLast';
  13150. }
  13151. _apply(query) {
  13152. if (query._queryParams.hasLimit()) {
  13153. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13154. 'or limitToLast).');
  13155. }
  13156. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13157. }
  13158. }
  13159. /**
  13160. * Creates a new `QueryConstraint` that is limited to return only the last
  13161. * specified number of children.
  13162. *
  13163. * The `limitToLast()` method is used to set a maximum number of children to be
  13164. * synced for a given callback. If we set a limit of 100, we will initially only
  13165. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13166. * stored in our Database, a `child_added` event will fire for each message.
  13167. * However, if we have over 100 messages, we will only receive a `child_added`
  13168. * event for the last 100 ordered messages. As items change, we will receive
  13169. * `child_removed` events for each item that drops out of the active list so
  13170. * that the total number stays at 100.
  13171. *
  13172. * You can read more about `limitToLast()` in
  13173. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13174. *
  13175. * @param limit - The maximum number of nodes to include in this query.
  13176. */
  13177. function limitToLast(limit) {
  13178. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13179. throw new Error('limitToLast: First argument must be a positive integer.');
  13180. }
  13181. return new QueryLimitToLastConstraint(limit);
  13182. }
  13183. class QueryOrderByChildConstraint extends QueryConstraint {
  13184. constructor(_path) {
  13185. super();
  13186. this._path = _path;
  13187. this.type = 'orderByChild';
  13188. }
  13189. _apply(query) {
  13190. validateNoPreviousOrderByCall(query, 'orderByChild');
  13191. const parsedPath = new Path(this._path);
  13192. if (pathIsEmpty(parsedPath)) {
  13193. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13194. }
  13195. const index = new PathIndex(parsedPath);
  13196. const newParams = queryParamsOrderBy(query._queryParams, index);
  13197. validateQueryEndpoints(newParams);
  13198. return new QueryImpl(query._repo, query._path, newParams,
  13199. /*orderByCalled=*/ true);
  13200. }
  13201. }
  13202. /**
  13203. * Creates a new `QueryConstraint` that orders by the specified child key.
  13204. *
  13205. * Queries can only order by one key at a time. Calling `orderByChild()`
  13206. * multiple times on the same query is an error.
  13207. *
  13208. * Firebase queries allow you to order your data by any child key on the fly.
  13209. * However, if you know in advance what your indexes will be, you can define
  13210. * them via the .indexOn rule in your Security Rules for better performance. See
  13211. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13212. * rule for more information.
  13213. *
  13214. * You can read more about `orderByChild()` in
  13215. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13216. *
  13217. * @param path - The path to order by.
  13218. */
  13219. function orderByChild(path) {
  13220. if (path === '$key') {
  13221. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13222. }
  13223. else if (path === '$priority') {
  13224. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13225. }
  13226. else if (path === '$value') {
  13227. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13228. }
  13229. validatePathString('orderByChild', 'path', path, false);
  13230. return new QueryOrderByChildConstraint(path);
  13231. }
  13232. class QueryOrderByKeyConstraint extends QueryConstraint {
  13233. constructor() {
  13234. super(...arguments);
  13235. this.type = 'orderByKey';
  13236. }
  13237. _apply(query) {
  13238. validateNoPreviousOrderByCall(query, 'orderByKey');
  13239. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13240. validateQueryEndpoints(newParams);
  13241. return new QueryImpl(query._repo, query._path, newParams,
  13242. /*orderByCalled=*/ true);
  13243. }
  13244. }
  13245. /**
  13246. * Creates a new `QueryConstraint` that orders by the key.
  13247. *
  13248. * Sorts the results of a query by their (ascending) key values.
  13249. *
  13250. * You can read more about `orderByKey()` in
  13251. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13252. */
  13253. function orderByKey() {
  13254. return new QueryOrderByKeyConstraint();
  13255. }
  13256. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13257. constructor() {
  13258. super(...arguments);
  13259. this.type = 'orderByPriority';
  13260. }
  13261. _apply(query) {
  13262. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13263. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13264. validateQueryEndpoints(newParams);
  13265. return new QueryImpl(query._repo, query._path, newParams,
  13266. /*orderByCalled=*/ true);
  13267. }
  13268. }
  13269. /**
  13270. * Creates a new `QueryConstraint` that orders by priority.
  13271. *
  13272. * Applications need not use priority but can order collections by
  13273. * ordinary properties (see
  13274. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13275. * for alternatives to priority.
  13276. */
  13277. function orderByPriority() {
  13278. return new QueryOrderByPriorityConstraint();
  13279. }
  13280. class QueryOrderByValueConstraint extends QueryConstraint {
  13281. constructor() {
  13282. super(...arguments);
  13283. this.type = 'orderByValue';
  13284. }
  13285. _apply(query) {
  13286. validateNoPreviousOrderByCall(query, 'orderByValue');
  13287. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13288. validateQueryEndpoints(newParams);
  13289. return new QueryImpl(query._repo, query._path, newParams,
  13290. /*orderByCalled=*/ true);
  13291. }
  13292. }
  13293. /**
  13294. * Creates a new `QueryConstraint` that orders by value.
  13295. *
  13296. * If the children of a query are all scalar values (string, number, or
  13297. * boolean), you can order the results by their (ascending) values.
  13298. *
  13299. * You can read more about `orderByValue()` in
  13300. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13301. */
  13302. function orderByValue() {
  13303. return new QueryOrderByValueConstraint();
  13304. }
  13305. class QueryEqualToValueConstraint extends QueryConstraint {
  13306. constructor(_value, _key) {
  13307. super();
  13308. this._value = _value;
  13309. this._key = _key;
  13310. this.type = 'equalTo';
  13311. }
  13312. _apply(query) {
  13313. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13314. if (query._queryParams.hasStart()) {
  13315. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13316. 'equalTo).');
  13317. }
  13318. if (query._queryParams.hasEnd()) {
  13319. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13320. 'equalTo).');
  13321. }
  13322. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13323. }
  13324. }
  13325. /**
  13326. * Creates a `QueryConstraint` that includes children that match the specified
  13327. * value.
  13328. *
  13329. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13330. * allows you to choose arbitrary starting and ending points for your queries.
  13331. *
  13332. * The optional key argument can be used to further limit the range of the
  13333. * query. If it is specified, then children that have exactly the specified
  13334. * value must also have exactly the specified key as their key name. This can be
  13335. * used to filter result sets with many matches for the same value.
  13336. *
  13337. * You can read more about `equalTo()` in
  13338. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13339. *
  13340. * @param value - The value to match for. The argument type depends on which
  13341. * `orderBy*()` function was used in this query. Specify a value that matches
  13342. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13343. * value must be a string.
  13344. * @param key - The child key to start at, among the children with the
  13345. * previously specified priority. This argument is only allowed if ordering by
  13346. * child, value, or priority.
  13347. */
  13348. function equalTo(value, key) {
  13349. validateKey('equalTo', 'key', key, true);
  13350. return new QueryEqualToValueConstraint(value, key);
  13351. }
  13352. /**
  13353. * Creates a new immutable instance of `Query` that is extended to also include
  13354. * additional query constraints.
  13355. *
  13356. * @param query - The Query instance to use as a base for the new constraints.
  13357. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13358. * @throws if any of the provided query constraints cannot be combined with the
  13359. * existing or new constraints.
  13360. */
  13361. function query(query, ...queryConstraints) {
  13362. let queryImpl = util.getModularInstance(query);
  13363. for (const constraint of queryConstraints) {
  13364. queryImpl = constraint._apply(queryImpl);
  13365. }
  13366. return queryImpl;
  13367. }
  13368. /**
  13369. * Define reference constructor in various modules
  13370. *
  13371. * We are doing this here to avoid several circular
  13372. * dependency issues
  13373. */
  13374. syncPointSetReferenceConstructor(ReferenceImpl);
  13375. syncTreeSetReferenceConstructor(ReferenceImpl);
  13376. /**
  13377. * @license
  13378. * Copyright 2020 Google LLC
  13379. *
  13380. * Licensed under the Apache License, Version 2.0 (the "License");
  13381. * you may not use this file except in compliance with the License.
  13382. * You may obtain a copy of the License at
  13383. *
  13384. * http://www.apache.org/licenses/LICENSE-2.0
  13385. *
  13386. * Unless required by applicable law or agreed to in writing, software
  13387. * distributed under the License is distributed on an "AS IS" BASIS,
  13388. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13389. * See the License for the specific language governing permissions and
  13390. * limitations under the License.
  13391. */
  13392. /**
  13393. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13394. * modifying this definition, consult the definition in:
  13395. *
  13396. * https://github.com/firebase/firebase-admin-node
  13397. *
  13398. * and make sure the two are consistent.
  13399. */
  13400. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13401. /**
  13402. * Creates and caches `Repo` instances.
  13403. */
  13404. const repos = {};
  13405. /**
  13406. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13407. */
  13408. let useRestClient = false;
  13409. /**
  13410. * Update an existing `Repo` in place to point to a new host/port.
  13411. */
  13412. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13413. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13414. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13415. /*isUsingEmulator=*/ true);
  13416. if (tokenProvider) {
  13417. repo.authTokenProvider_ = tokenProvider;
  13418. }
  13419. }
  13420. /**
  13421. * This function should only ever be called to CREATE a new database instance.
  13422. * @internal
  13423. */
  13424. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13425. let dbUrl = url || app.options.databaseURL;
  13426. if (dbUrl === undefined) {
  13427. if (!app.options.projectId) {
  13428. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13429. ' a Project ID when calling firebase.initializeApp().');
  13430. }
  13431. log('Using default host for project ', app.options.projectId);
  13432. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13433. }
  13434. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13435. let repoInfo = parsedUrl.repoInfo;
  13436. let isEmulator;
  13437. let dbEmulatorHost = undefined;
  13438. if (typeof process !== 'undefined' && process.env) {
  13439. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13440. }
  13441. if (dbEmulatorHost) {
  13442. isEmulator = true;
  13443. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13444. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13445. repoInfo = parsedUrl.repoInfo;
  13446. }
  13447. else {
  13448. isEmulator = !parsedUrl.repoInfo.secure;
  13449. }
  13450. const authTokenProvider = nodeAdmin && isEmulator
  13451. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13452. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13453. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13454. if (!pathIsEmpty(parsedUrl.path)) {
  13455. fatal('Database URL must point to the root of a Firebase Database ' +
  13456. '(not including a child path).');
  13457. }
  13458. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13459. return new Database(repo, app);
  13460. }
  13461. /**
  13462. * Remove the repo and make sure it is disconnected.
  13463. *
  13464. */
  13465. function repoManagerDeleteRepo(repo, appName) {
  13466. const appRepos = repos[appName];
  13467. // This should never happen...
  13468. if (!appRepos || appRepos[repo.key] !== repo) {
  13469. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13470. }
  13471. repoInterrupt(repo);
  13472. delete appRepos[repo.key];
  13473. }
  13474. /**
  13475. * Ensures a repo doesn't already exist and then creates one using the
  13476. * provided app.
  13477. *
  13478. * @param repoInfo - The metadata about the Repo
  13479. * @returns The Repo object for the specified server / repoName.
  13480. */
  13481. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13482. let appRepos = repos[app.name];
  13483. if (!appRepos) {
  13484. appRepos = {};
  13485. repos[app.name] = appRepos;
  13486. }
  13487. let repo = appRepos[repoInfo.toURLString()];
  13488. if (repo) {
  13489. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13490. }
  13491. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13492. appRepos[repoInfo.toURLString()] = repo;
  13493. return repo;
  13494. }
  13495. /**
  13496. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13497. */
  13498. function repoManagerForceRestClient(forceRestClient) {
  13499. useRestClient = forceRestClient;
  13500. }
  13501. /**
  13502. * Class representing a Firebase Realtime Database.
  13503. */
  13504. class Database {
  13505. /** @hideconstructor */
  13506. constructor(_repoInternal,
  13507. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13508. app) {
  13509. this._repoInternal = _repoInternal;
  13510. this.app = app;
  13511. /** Represents a `Database` instance. */
  13512. this['type'] = 'database';
  13513. /** Track if the instance has been used (root or repo accessed) */
  13514. this._instanceStarted = false;
  13515. }
  13516. get _repo() {
  13517. if (!this._instanceStarted) {
  13518. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13519. this._instanceStarted = true;
  13520. }
  13521. return this._repoInternal;
  13522. }
  13523. get _root() {
  13524. if (!this._rootInternal) {
  13525. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13526. }
  13527. return this._rootInternal;
  13528. }
  13529. _delete() {
  13530. if (this._rootInternal !== null) {
  13531. repoManagerDeleteRepo(this._repo, this.app.name);
  13532. this._repoInternal = null;
  13533. this._rootInternal = null;
  13534. }
  13535. return Promise.resolve();
  13536. }
  13537. _checkNotDeleted(apiName) {
  13538. if (this._rootInternal === null) {
  13539. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13540. }
  13541. }
  13542. }
  13543. function checkTransportInit() {
  13544. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13545. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13546. }
  13547. }
  13548. /**
  13549. * Force the use of websockets instead of longPolling.
  13550. */
  13551. function forceWebSockets() {
  13552. checkTransportInit();
  13553. BrowserPollConnection.forceDisallow();
  13554. }
  13555. /**
  13556. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13557. */
  13558. function forceLongPolling() {
  13559. checkTransportInit();
  13560. WebSocketConnection.forceDisallow();
  13561. BrowserPollConnection.forceAllow();
  13562. }
  13563. /**
  13564. * Returns the instance of the Realtime Database SDK that is associated with the provided
  13565. * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if
  13566. * no instance exists or if the existing instance uses a custom database URL.
  13567. *
  13568. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  13569. * Database instance is associated with.
  13570. * @param url - The URL of the Realtime Database instance to connect to. If not
  13571. * provided, the SDK connects to the default instance of the Firebase App.
  13572. * @returns The `Database` instance of the provided app.
  13573. */
  13574. function getDatabase(app$1 = app.getApp(), url) {
  13575. const db = app._getProvider(app$1, 'database').getImmediate({
  13576. identifier: url
  13577. });
  13578. if (!db._instanceStarted) {
  13579. const emulator = util.getDefaultEmulatorHostnameAndPort('database');
  13580. if (emulator) {
  13581. connectDatabaseEmulator(db, ...emulator);
  13582. }
  13583. }
  13584. return db;
  13585. }
  13586. /**
  13587. * Modify the provided instance to communicate with the Realtime Database
  13588. * emulator.
  13589. *
  13590. * <p>Note: This method must be called before performing any other operation.
  13591. *
  13592. * @param db - The instance to modify.
  13593. * @param host - The emulator host (ex: localhost)
  13594. * @param port - The emulator port (ex: 8080)
  13595. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13596. */
  13597. function connectDatabaseEmulator(db, host, port, options = {}) {
  13598. db = util.getModularInstance(db);
  13599. db._checkNotDeleted('useEmulator');
  13600. if (db._instanceStarted) {
  13601. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13602. }
  13603. const repo = db._repoInternal;
  13604. let tokenProvider = undefined;
  13605. if (repo.repoInfo_.nodeAdmin) {
  13606. if (options.mockUserToken) {
  13607. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13608. }
  13609. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13610. }
  13611. else if (options.mockUserToken) {
  13612. const token = typeof options.mockUserToken === 'string'
  13613. ? options.mockUserToken
  13614. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13615. tokenProvider = new EmulatorTokenProvider(token);
  13616. }
  13617. // Modify the repo to apply emulator settings
  13618. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13619. }
  13620. /**
  13621. * Disconnects from the server (all Database operations will be completed
  13622. * offline).
  13623. *
  13624. * The client automatically maintains a persistent connection to the Database
  13625. * server, which will remain active indefinitely and reconnect when
  13626. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13627. * to control the client connection in cases where a persistent connection is
  13628. * undesirable.
  13629. *
  13630. * While offline, the client will no longer receive data updates from the
  13631. * Database. However, all Database operations performed locally will continue to
  13632. * immediately fire events, allowing your application to continue behaving
  13633. * normally. Additionally, each operation performed locally will automatically
  13634. * be queued and retried upon reconnection to the Database server.
  13635. *
  13636. * To reconnect to the Database and begin receiving remote events, see
  13637. * `goOnline()`.
  13638. *
  13639. * @param db - The instance to disconnect.
  13640. */
  13641. function goOffline(db) {
  13642. db = util.getModularInstance(db);
  13643. db._checkNotDeleted('goOffline');
  13644. repoInterrupt(db._repo);
  13645. }
  13646. /**
  13647. * Reconnects to the server and synchronizes the offline Database state
  13648. * with the server state.
  13649. *
  13650. * This method should be used after disabling the active connection with
  13651. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13652. * and fire the appropriate events so that your client "catches up"
  13653. * automatically.
  13654. *
  13655. * @param db - The instance to reconnect.
  13656. */
  13657. function goOnline(db) {
  13658. db = util.getModularInstance(db);
  13659. db._checkNotDeleted('goOnline');
  13660. repoResume(db._repo);
  13661. }
  13662. function enableLogging(logger, persistent) {
  13663. enableLogging$1(logger, persistent);
  13664. }
  13665. /**
  13666. * @license
  13667. * Copyright 2021 Google LLC
  13668. *
  13669. * Licensed under the Apache License, Version 2.0 (the "License");
  13670. * you may not use this file except in compliance with the License.
  13671. * You may obtain a copy of the License at
  13672. *
  13673. * http://www.apache.org/licenses/LICENSE-2.0
  13674. *
  13675. * Unless required by applicable law or agreed to in writing, software
  13676. * distributed under the License is distributed on an "AS IS" BASIS,
  13677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13678. * See the License for the specific language governing permissions and
  13679. * limitations under the License.
  13680. */
  13681. function registerDatabase(variant) {
  13682. setSDKVersion(app.SDK_VERSION);
  13683. app._registerComponent(new component.Component('database', (container, { instanceIdentifier: url }) => {
  13684. const app = container.getProvider('app').getImmediate();
  13685. const authProvider = container.getProvider('auth-internal');
  13686. const appCheckProvider = container.getProvider('app-check-internal');
  13687. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  13688. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  13689. app.registerVersion(name, version, variant);
  13690. // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
  13691. app.registerVersion(name, version, 'cjs2017');
  13692. }
  13693. /**
  13694. * @license
  13695. * Copyright 2020 Google LLC
  13696. *
  13697. * Licensed under the Apache License, Version 2.0 (the "License");
  13698. * you may not use this file except in compliance with the License.
  13699. * You may obtain a copy of the License at
  13700. *
  13701. * http://www.apache.org/licenses/LICENSE-2.0
  13702. *
  13703. * Unless required by applicable law or agreed to in writing, software
  13704. * distributed under the License is distributed on an "AS IS" BASIS,
  13705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13706. * See the License for the specific language governing permissions and
  13707. * limitations under the License.
  13708. */
  13709. const SERVER_TIMESTAMP = {
  13710. '.sv': 'timestamp'
  13711. };
  13712. /**
  13713. * Returns a placeholder value for auto-populating the current timestamp (time
  13714. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13715. * servers.
  13716. */
  13717. function serverTimestamp() {
  13718. return SERVER_TIMESTAMP;
  13719. }
  13720. /**
  13721. * Returns a placeholder value that can be used to atomically increment the
  13722. * current database value by the provided delta.
  13723. *
  13724. * @param delta - the amount to modify the current value atomically.
  13725. * @returns A placeholder value for modifying data atomically server-side.
  13726. */
  13727. function increment(delta) {
  13728. return {
  13729. '.sv': {
  13730. 'increment': delta
  13731. }
  13732. };
  13733. }
  13734. /**
  13735. * @license
  13736. * Copyright 2020 Google LLC
  13737. *
  13738. * Licensed under the Apache License, Version 2.0 (the "License");
  13739. * you may not use this file except in compliance with the License.
  13740. * You may obtain a copy of the License at
  13741. *
  13742. * http://www.apache.org/licenses/LICENSE-2.0
  13743. *
  13744. * Unless required by applicable law or agreed to in writing, software
  13745. * distributed under the License is distributed on an "AS IS" BASIS,
  13746. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13747. * See the License for the specific language governing permissions and
  13748. * limitations under the License.
  13749. */
  13750. /**
  13751. * A type for the resolve value of {@link runTransaction}.
  13752. */
  13753. class TransactionResult {
  13754. /** @hideconstructor */
  13755. constructor(
  13756. /** Whether the transaction was successfully committed. */
  13757. committed,
  13758. /** The resulting data snapshot. */
  13759. snapshot) {
  13760. this.committed = committed;
  13761. this.snapshot = snapshot;
  13762. }
  13763. /** Returns a JSON-serializable representation of this object. */
  13764. toJSON() {
  13765. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13766. }
  13767. }
  13768. /**
  13769. * Atomically modifies the data at this location.
  13770. *
  13771. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13772. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13773. * used to modify the existing value to a new value, ensuring there are no
  13774. * conflicts with other clients writing to the same location at the same time.
  13775. *
  13776. * To accomplish this, you pass `runTransaction()` an update function which is
  13777. * used to transform the current value into a new value. If another client
  13778. * writes to the location before your new value is successfully written, your
  13779. * update function will be called again with the new current value, and the
  13780. * write will be retried. This will happen repeatedly until your write succeeds
  13781. * without conflict or you abort the transaction by not returning a value from
  13782. * your update function.
  13783. *
  13784. * Note: Modifying data with `set()` will cancel any pending transactions at
  13785. * that location, so extreme care should be taken if mixing `set()` and
  13786. * `runTransaction()` to update the same data.
  13787. *
  13788. * Note: When using transactions with Security and Firebase Rules in place, be
  13789. * aware that a client needs `.read` access in addition to `.write` access in
  13790. * order to perform a transaction. This is because the client-side nature of
  13791. * transactions requires the client to read the data in order to transactionally
  13792. * update it.
  13793. *
  13794. * @param ref - The location to atomically modify.
  13795. * @param transactionUpdate - A developer-supplied function which will be passed
  13796. * the current data stored at this location (as a JavaScript object). The
  13797. * function should return the new value it would like written (as a JavaScript
  13798. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13799. * transaction will be aborted and the data at this location will not be
  13800. * modified.
  13801. * @param options - An options object to configure transactions.
  13802. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13803. * callback to handle success and failure.
  13804. */
  13805. function runTransaction(ref,
  13806. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13807. transactionUpdate, options) {
  13808. var _a;
  13809. ref = util.getModularInstance(ref);
  13810. validateWritablePath('Reference.transaction', ref._path);
  13811. if (ref.key === '.length' || ref.key === '.keys') {
  13812. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13813. }
  13814. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13815. const deferred = new util.Deferred();
  13816. const promiseComplete = (error, committed, node) => {
  13817. let dataSnapshot = null;
  13818. if (error) {
  13819. deferred.reject(error);
  13820. }
  13821. else {
  13822. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13823. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13824. }
  13825. };
  13826. // Add a watch to make sure we get server updates.
  13827. const unwatcher = onValue(ref, () => { });
  13828. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13829. return deferred.promise;
  13830. }
  13831. /**
  13832. * @license
  13833. * Copyright 2017 Google LLC
  13834. *
  13835. * Licensed under the Apache License, Version 2.0 (the "License");
  13836. * you may not use this file except in compliance with the License.
  13837. * You may obtain a copy of the License at
  13838. *
  13839. * http://www.apache.org/licenses/LICENSE-2.0
  13840. *
  13841. * Unless required by applicable law or agreed to in writing, software
  13842. * distributed under the License is distributed on an "AS IS" BASIS,
  13843. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13844. * See the License for the specific language governing permissions and
  13845. * limitations under the License.
  13846. */
  13847. PersistentConnection;
  13848. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13849. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13850. this.sendRequest('q', { p: pathString }, onComplete);
  13851. };
  13852. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13853. PersistentConnection.prototype.echo = function (data, onEcho) {
  13854. this.sendRequest('echo', { d: data }, onEcho);
  13855. };
  13856. // RealTimeConnection properties that we use in tests.
  13857. Connection;
  13858. /**
  13859. * @internal
  13860. */
  13861. const hijackHash = function (newHash) {
  13862. const oldPut = PersistentConnection.prototype.put;
  13863. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13864. if (hash !== undefined) {
  13865. hash = newHash();
  13866. }
  13867. oldPut.call(this, pathString, data, onComplete, hash);
  13868. };
  13869. return function () {
  13870. PersistentConnection.prototype.put = oldPut;
  13871. };
  13872. };
  13873. RepoInfo;
  13874. /**
  13875. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13876. * @internal
  13877. */
  13878. const forceRestClient = function (forceRestClient) {
  13879. repoManagerForceRestClient(forceRestClient);
  13880. };
  13881. /**
  13882. * @license
  13883. * Copyright 2023 Google LLC
  13884. *
  13885. * Licensed under the Apache License, Version 2.0 (the "License");
  13886. * you may not use this file except in compliance with the License.
  13887. * You may obtain a copy of the License at
  13888. *
  13889. * http://www.apache.org/licenses/LICENSE-2.0
  13890. *
  13891. * Unless required by applicable law or agreed to in writing, software
  13892. * distributed under the License is distributed on an "AS IS" BASIS,
  13893. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13894. * See the License for the specific language governing permissions and
  13895. * limitations under the License.
  13896. */
  13897. /**
  13898. * Used by console to create a database based on the app,
  13899. * passed database URL and a custom auth implementation.
  13900. * @internal
  13901. * @param app - A valid FirebaseApp-like object
  13902. * @param url - A valid Firebase databaseURL
  13903. * @param version - custom version e.g. firebase-admin version
  13904. * @param customAppCheckImpl - custom app check implementation
  13905. * @param customAuthImpl - custom auth implementation
  13906. */
  13907. function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {
  13908. setSDKVersion(version);
  13909. /**
  13910. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  13911. * any actual function.
  13912. */
  13913. const componentContainer = new component.ComponentContainer('database-standalone');
  13914. const authProvider = new component.Provider('auth-internal', componentContainer);
  13915. let appCheckProvider;
  13916. if (customAppCheckImpl) {
  13917. appCheckProvider = new component.Provider('app-check-internal', componentContainer);
  13918. appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13919. }
  13920. authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13921. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);
  13922. }
  13923. /**
  13924. * @license
  13925. * Copyright 2021 Google LLC
  13926. *
  13927. * Licensed under the Apache License, Version 2.0 (the "License");
  13928. * you may not use this file except in compliance with the License.
  13929. * You may obtain a copy of the License at
  13930. *
  13931. * http://www.apache.org/licenses/LICENSE-2.0
  13932. *
  13933. * Unless required by applicable law or agreed to in writing, software
  13934. * distributed under the License is distributed on an "AS IS" BASIS,
  13935. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13936. * See the License for the specific language governing permissions and
  13937. * limitations under the License.
  13938. */
  13939. setWebSocketImpl(Websocket__default["default"].Client);
  13940. registerDatabase('node');
  13941. exports.DataSnapshot = DataSnapshot;
  13942. exports.Database = Database;
  13943. exports.OnDisconnect = OnDisconnect;
  13944. exports.QueryConstraint = QueryConstraint;
  13945. exports.TransactionResult = TransactionResult;
  13946. exports._QueryImpl = QueryImpl;
  13947. exports._QueryParams = QueryParams;
  13948. exports._ReferenceImpl = ReferenceImpl;
  13949. exports._TEST_ACCESS_forceRestClient = forceRestClient;
  13950. exports._TEST_ACCESS_hijackHash = hijackHash;
  13951. exports._initStandalone = _initStandalone;
  13952. exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  13953. exports._setSDKVersion = setSDKVersion;
  13954. exports._validatePathString = validatePathString;
  13955. exports._validateWritablePath = validateWritablePath;
  13956. exports.child = child;
  13957. exports.connectDatabaseEmulator = connectDatabaseEmulator;
  13958. exports.enableLogging = enableLogging;
  13959. exports.endAt = endAt;
  13960. exports.endBefore = endBefore;
  13961. exports.equalTo = equalTo;
  13962. exports.forceLongPolling = forceLongPolling;
  13963. exports.forceWebSockets = forceWebSockets;
  13964. exports.get = get;
  13965. exports.getDatabase = getDatabase;
  13966. exports.goOffline = goOffline;
  13967. exports.goOnline = goOnline;
  13968. exports.increment = increment;
  13969. exports.limitToFirst = limitToFirst;
  13970. exports.limitToLast = limitToLast;
  13971. exports.off = off;
  13972. exports.onChildAdded = onChildAdded;
  13973. exports.onChildChanged = onChildChanged;
  13974. exports.onChildMoved = onChildMoved;
  13975. exports.onChildRemoved = onChildRemoved;
  13976. exports.onDisconnect = onDisconnect;
  13977. exports.onValue = onValue;
  13978. exports.orderByChild = orderByChild;
  13979. exports.orderByKey = orderByKey;
  13980. exports.orderByPriority = orderByPriority;
  13981. exports.orderByValue = orderByValue;
  13982. exports.push = push;
  13983. exports.query = query;
  13984. exports.ref = ref;
  13985. exports.refFromURL = refFromURL;
  13986. exports.remove = remove;
  13987. exports.runTransaction = runTransaction;
  13988. exports.serverTimestamp = serverTimestamp;
  13989. exports.set = set;
  13990. exports.setPriority = setPriority;
  13991. exports.setWithPriority = setWithPriority;
  13992. exports.startAfter = startAfter;
  13993. exports.startAt = startAt;
  13994. exports.update = update;
  13995. //# sourceMappingURL=index.node.cjs.js.map