index.standalone.js 664 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var require$$2 = require('util');
  4. var require$$0 = require('buffer');
  5. var require$$1 = require('events');
  6. var require$$0$1 = require('stream');
  7. var require$$1$1 = require('crypto');
  8. var require$$2$1 = require('url');
  9. var require$$0$2 = require('assert');
  10. var require$$1$2 = require('net');
  11. var require$$2$2 = require('tls');
  12. var require$$1$3 = require('@firebase/util');
  13. var require$$2$3 = require('@firebase/logger');
  14. var require$$3 = require('@firebase/component');
  15. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  16. var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
  17. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  18. var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
  19. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
  20. var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
  21. var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
  22. var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
  23. var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
  24. var require$$2__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$2$2);
  25. var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3);
  26. var require$$2__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$2$3);
  27. var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3);
  28. var index_standalone = {};
  29. var safeBuffer = {exports: {}};
  30. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  31. (function (module, exports) {
  32. /* eslint-disable node/no-deprecated-api */
  33. var buffer = require$$0__default["default"];
  34. var Buffer = buffer.Buffer;
  35. // alternative to using Object.keys for old browsers
  36. function copyProps (src, dst) {
  37. for (var key in src) {
  38. dst[key] = src[key];
  39. }
  40. }
  41. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  42. module.exports = buffer;
  43. } else {
  44. // Copy properties from require('buffer')
  45. copyProps(buffer, exports);
  46. exports.Buffer = SafeBuffer;
  47. }
  48. function SafeBuffer (arg, encodingOrOffset, length) {
  49. return Buffer(arg, encodingOrOffset, length)
  50. }
  51. SafeBuffer.prototype = Object.create(Buffer.prototype);
  52. // Copy static methods from Buffer
  53. copyProps(Buffer, SafeBuffer);
  54. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  55. if (typeof arg === 'number') {
  56. throw new TypeError('Argument must not be a number')
  57. }
  58. return Buffer(arg, encodingOrOffset, length)
  59. };
  60. SafeBuffer.alloc = function (size, fill, encoding) {
  61. if (typeof size !== 'number') {
  62. throw new TypeError('Argument must be a number')
  63. }
  64. var buf = Buffer(size);
  65. if (fill !== undefined) {
  66. if (typeof encoding === 'string') {
  67. buf.fill(fill, encoding);
  68. } else {
  69. buf.fill(fill);
  70. }
  71. } else {
  72. buf.fill(0);
  73. }
  74. return buf
  75. };
  76. SafeBuffer.allocUnsafe = function (size) {
  77. if (typeof size !== 'number') {
  78. throw new TypeError('Argument must be a number')
  79. }
  80. return Buffer(size)
  81. };
  82. SafeBuffer.allocUnsafeSlow = function (size) {
  83. if (typeof size !== 'number') {
  84. throw new TypeError('Argument must be a number')
  85. }
  86. return buffer.SlowBuffer(size)
  87. };
  88. }(safeBuffer, safeBuffer.exports));
  89. var streams$1 = {};
  90. /**
  91. Streams in a WebSocket connection
  92. ---------------------------------
  93. We model a WebSocket as two duplex streams: one stream is for the wire protocol
  94. over an I/O socket, and the other is for incoming/outgoing messages.
  95. +----------+ +---------+ +----------+
  96. [1] write(chunk) -->| ~~~~~~~~ +----->| parse() +----->| ~~~~~~~~ +--> emit('data') [2]
  97. | | +----+----+ | |
  98. | | | | |
  99. | IO | | [5] | Messages |
  100. | | V | |
  101. | | +---------+ | |
  102. [4] emit('data') <--+ ~~~~~~~~ |<-----+ frame() |<-----+ ~~~~~~~~ |<-- write(chunk) [3]
  103. +----------+ +---------+ +----------+
  104. Message transfer in each direction is simple: IO receives a byte stream [1] and
  105. sends this stream for parsing. The parser will periodically emit a complete
  106. message text on the Messages stream [2]. Similarly, when messages are written
  107. to the Messages stream [3], they are framed using the WebSocket wire format and
  108. emitted via IO [4].
  109. There is a feedback loop via [5] since some input from [1] will be things like
  110. ping, pong and close frames. In these cases the protocol responds by emitting
  111. responses directly back to [4] rather than emitting messages via [2].
  112. For the purposes of flow control, we consider the sources of each Readable
  113. stream to be as follows:
  114. * [2] receives input from [1]
  115. * [4] receives input from [1] and [3]
  116. The classes below express the relationships described above without prescribing
  117. anything about how parse() and frame() work, other than assuming they emit
  118. 'data' events to the IO and Messages streams. They will work with any protocol
  119. driver having these two methods.
  120. **/
  121. var Stream$3 = require$$0__default$1["default"].Stream,
  122. util$c = require$$2__default["default"];
  123. var IO = function(driver) {
  124. this.readable = this.writable = true;
  125. this._paused = false;
  126. this._driver = driver;
  127. };
  128. util$c.inherits(IO, Stream$3);
  129. // The IO pause() and resume() methods will be called when the socket we are
  130. // piping to gets backed up and drains. Since IO output [4] comes from IO input
  131. // [1] and Messages input [3], we need to tell both of those to return false
  132. // from write() when this stream is paused.
  133. IO.prototype.pause = function() {
  134. this._paused = true;
  135. this._driver.messages._paused = true;
  136. };
  137. IO.prototype.resume = function() {
  138. this._paused = false;
  139. this.emit('drain');
  140. var messages = this._driver.messages;
  141. messages._paused = false;
  142. messages.emit('drain');
  143. };
  144. // When we receive input from a socket, send it to the parser and tell the
  145. // source whether to back off.
  146. IO.prototype.write = function(chunk) {
  147. if (!this.writable) return false;
  148. this._driver.parse(chunk);
  149. return !this._paused;
  150. };
  151. // The IO end() method will be called when the socket piping into it emits
  152. // 'close' or 'end', i.e. the socket is closed. In this situation the Messages
  153. // stream will not emit any more data so we emit 'end'.
  154. IO.prototype.end = function(chunk) {
  155. if (!this.writable) return;
  156. if (chunk !== undefined) this.write(chunk);
  157. this.writable = false;
  158. var messages = this._driver.messages;
  159. if (messages.readable) {
  160. messages.readable = messages.writable = false;
  161. messages.emit('end');
  162. }
  163. };
  164. IO.prototype.destroy = function() {
  165. this.end();
  166. };
  167. var Messages = function(driver) {
  168. this.readable = this.writable = true;
  169. this._paused = false;
  170. this._driver = driver;
  171. };
  172. util$c.inherits(Messages, Stream$3);
  173. // The Messages pause() and resume() methods will be called when the app that's
  174. // processing the messages gets backed up and drains. If we're emitting
  175. // messages too fast we should tell the source to slow down. Message output [2]
  176. // comes from IO input [1].
  177. Messages.prototype.pause = function() {
  178. this._driver.io._paused = true;
  179. };
  180. Messages.prototype.resume = function() {
  181. this._driver.io._paused = false;
  182. this._driver.io.emit('drain');
  183. };
  184. // When we receive messages from the user, send them to the formatter and tell
  185. // the source whether to back off.
  186. Messages.prototype.write = function(message) {
  187. if (!this.writable) return false;
  188. if (typeof message === 'string') this._driver.text(message);
  189. else this._driver.binary(message);
  190. return !this._paused;
  191. };
  192. // The Messages end() method will be called when a stream piping into it emits
  193. // 'end'. Many streams may be piped into the WebSocket and one of them ending
  194. // does not mean the whole socket is done, so just process the input and move
  195. // on leaving the socket open.
  196. Messages.prototype.end = function(message) {
  197. if (message !== undefined) this.write(message);
  198. };
  199. Messages.prototype.destroy = function() {};
  200. streams$1.IO = IO;
  201. streams$1.Messages = Messages;
  202. var Headers$3 = function() {
  203. this.clear();
  204. };
  205. Headers$3.prototype.ALLOWED_DUPLICATES = ['set-cookie', 'set-cookie2', 'warning', 'www-authenticate'];
  206. Headers$3.prototype.clear = function() {
  207. this._sent = {};
  208. this._lines = [];
  209. };
  210. Headers$3.prototype.set = function(name, value) {
  211. if (value === undefined) return;
  212. name = this._strip(name);
  213. value = this._strip(value);
  214. var key = name.toLowerCase();
  215. if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) {
  216. this._sent[key] = true;
  217. this._lines.push(name + ': ' + value + '\r\n');
  218. }
  219. };
  220. Headers$3.prototype.toString = function() {
  221. return this._lines.join('');
  222. };
  223. Headers$3.prototype._strip = function(string) {
  224. return string.toString().replace(/^ */, '').replace(/ *$/, '');
  225. };
  226. var headers = Headers$3;
  227. var Buffer$9 = safeBuffer.exports.Buffer;
  228. var StreamReader = function() {
  229. this._queue = [];
  230. this._queueSize = 0;
  231. this._offset = 0;
  232. };
  233. StreamReader.prototype.put = function(buffer) {
  234. if (!buffer || buffer.length === 0) return;
  235. if (!Buffer$9.isBuffer(buffer)) buffer = Buffer$9.from(buffer);
  236. this._queue.push(buffer);
  237. this._queueSize += buffer.length;
  238. };
  239. StreamReader.prototype.read = function(length) {
  240. if (length > this._queueSize) return null;
  241. if (length === 0) return Buffer$9.alloc(0);
  242. this._queueSize -= length;
  243. var queue = this._queue,
  244. remain = length,
  245. first = queue[0],
  246. buffers, buffer;
  247. if (first.length >= length) {
  248. if (first.length === length) {
  249. return queue.shift();
  250. } else {
  251. buffer = first.slice(0, length);
  252. queue[0] = first.slice(length);
  253. return buffer;
  254. }
  255. }
  256. for (var i = 0, n = queue.length; i < n; i++) {
  257. if (remain < queue[i].length) break;
  258. remain -= queue[i].length;
  259. }
  260. buffers = queue.splice(0, i);
  261. if (remain > 0 && queue.length > 0) {
  262. buffers.push(queue[0].slice(0, remain));
  263. queue[0] = queue[0].slice(remain);
  264. }
  265. return Buffer$9.concat(buffers, length);
  266. };
  267. StreamReader.prototype.eachByte = function(callback, context) {
  268. var buffer, n, index;
  269. while (this._queue.length > 0) {
  270. buffer = this._queue[0];
  271. n = buffer.length;
  272. while (this._offset < n) {
  273. index = this._offset;
  274. this._offset += 1;
  275. callback.call(context, buffer[index]);
  276. }
  277. this._offset = 0;
  278. this._queue.shift();
  279. }
  280. };
  281. var stream_reader = StreamReader;
  282. var Buffer$8 = safeBuffer.exports.Buffer,
  283. Emitter = require$$1__default["default"].EventEmitter,
  284. util$b = require$$2__default["default"],
  285. streams = streams$1,
  286. Headers$2 = headers,
  287. Reader = stream_reader;
  288. var Base$7 = function(request, url, options) {
  289. Emitter.call(this);
  290. Base$7.validateOptions(options || {}, ['maxLength', 'masking', 'requireMasking', 'protocols']);
  291. this._request = request;
  292. this._reader = new Reader();
  293. this._options = options || {};
  294. this._maxLength = this._options.maxLength || this.MAX_LENGTH;
  295. this._headers = new Headers$2();
  296. this.__queue = [];
  297. this.readyState = 0;
  298. this.url = url;
  299. this.io = new streams.IO(this);
  300. this.messages = new streams.Messages(this);
  301. this._bindEventListeners();
  302. };
  303. util$b.inherits(Base$7, Emitter);
  304. Base$7.isWebSocket = function(request) {
  305. var connection = request.headers.connection || '',
  306. upgrade = request.headers.upgrade || '';
  307. return request.method === 'GET' &&
  308. connection.toLowerCase().split(/ *, */).indexOf('upgrade') >= 0 &&
  309. upgrade.toLowerCase() === 'websocket';
  310. };
  311. Base$7.validateOptions = function(options, validKeys) {
  312. for (var key in options) {
  313. if (validKeys.indexOf(key) < 0)
  314. throw new Error('Unrecognized option: ' + key);
  315. }
  316. };
  317. var instance$b = {
  318. // This is 64MB, small enough for an average VPS to handle without
  319. // crashing from process out of memory
  320. MAX_LENGTH: 0x3ffffff,
  321. STATES: ['connecting', 'open', 'closing', 'closed'],
  322. _bindEventListeners: function() {
  323. var self = this;
  324. // Protocol errors are informational and do not have to be handled
  325. this.messages.on('error', function() {});
  326. this.on('message', function(event) {
  327. var messages = self.messages;
  328. if (messages.readable) messages.emit('data', event.data);
  329. });
  330. this.on('error', function(error) {
  331. var messages = self.messages;
  332. if (messages.readable) messages.emit('error', error);
  333. });
  334. this.on('close', function() {
  335. var messages = self.messages;
  336. if (!messages.readable) return;
  337. messages.readable = messages.writable = false;
  338. messages.emit('end');
  339. });
  340. },
  341. getState: function() {
  342. return this.STATES[this.readyState] || null;
  343. },
  344. addExtension: function(extension) {
  345. return false;
  346. },
  347. setHeader: function(name, value) {
  348. if (this.readyState > 0) return false;
  349. this._headers.set(name, value);
  350. return true;
  351. },
  352. start: function() {
  353. if (this.readyState !== 0) return false;
  354. if (!Base$7.isWebSocket(this._request))
  355. return this._failHandshake(new Error('Not a WebSocket request'));
  356. var response;
  357. try {
  358. response = this._handshakeResponse();
  359. } catch (error) {
  360. return this._failHandshake(error);
  361. }
  362. this._write(response);
  363. if (this._stage !== -1) this._open();
  364. return true;
  365. },
  366. _failHandshake: function(error) {
  367. var headers = new Headers$2();
  368. headers.set('Content-Type', 'text/plain');
  369. headers.set('Content-Length', Buffer$8.byteLength(error.message, 'utf8'));
  370. headers = ['HTTP/1.1 400 Bad Request', headers.toString(), error.message];
  371. this._write(Buffer$8.from(headers.join('\r\n'), 'utf8'));
  372. this._fail('protocol_error', error.message);
  373. return false;
  374. },
  375. text: function(message) {
  376. return this.frame(message);
  377. },
  378. binary: function(message) {
  379. return false;
  380. },
  381. ping: function() {
  382. return false;
  383. },
  384. pong: function() {
  385. return false;
  386. },
  387. close: function(reason, code) {
  388. if (this.readyState !== 1) return false;
  389. this.readyState = 3;
  390. this.emit('close', new Base$7.CloseEvent(null, null));
  391. return true;
  392. },
  393. _open: function() {
  394. this.readyState = 1;
  395. this.__queue.forEach(function(args) { this.frame.apply(this, args); }, this);
  396. this.__queue = [];
  397. this.emit('open', new Base$7.OpenEvent());
  398. },
  399. _queue: function(message) {
  400. this.__queue.push(message);
  401. return true;
  402. },
  403. _write: function(chunk) {
  404. var io = this.io;
  405. if (io.readable) io.emit('data', chunk);
  406. },
  407. _fail: function(type, message) {
  408. this.readyState = 2;
  409. this.emit('error', new Error(message));
  410. this.close();
  411. }
  412. };
  413. for (var key$b in instance$b)
  414. Base$7.prototype[key$b] = instance$b[key$b];
  415. Base$7.ConnectEvent = function() {};
  416. Base$7.OpenEvent = function() {};
  417. Base$7.CloseEvent = function(code, reason) {
  418. this.code = code;
  419. this.reason = reason;
  420. };
  421. Base$7.MessageEvent = function(data) {
  422. this.data = data;
  423. };
  424. Base$7.PingEvent = function(data) {
  425. this.data = data;
  426. };
  427. Base$7.PongEvent = function(data) {
  428. this.data = data;
  429. };
  430. var base = Base$7;
  431. var httpParser = {};
  432. /*jshint node:true */
  433. var assert = require$$0__default$2["default"];
  434. httpParser.HTTPParser = HTTPParser;
  435. function HTTPParser(type) {
  436. assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE || type === undefined);
  437. if (type === undefined) ; else {
  438. this.initialize(type);
  439. }
  440. }
  441. HTTPParser.prototype.initialize = function (type, async_resource) {
  442. assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE);
  443. this.type = type;
  444. this.state = type + '_LINE';
  445. this.info = {
  446. headers: [],
  447. upgrade: false
  448. };
  449. this.trailers = [];
  450. this.line = '';
  451. this.isChunked = false;
  452. this.connection = '';
  453. this.headerSize = 0; // for preventing too big headers
  454. this.body_bytes = null;
  455. this.isUserCall = false;
  456. this.hadError = false;
  457. };
  458. HTTPParser.encoding = 'ascii';
  459. HTTPParser.maxHeaderSize = 80 * 1024; // maxHeaderSize (in bytes) is configurable, but 80kb by default;
  460. HTTPParser.REQUEST = 'REQUEST';
  461. HTTPParser.RESPONSE = 'RESPONSE';
  462. // Note: *not* starting with kOnHeaders=0 line the Node parser, because any
  463. // newly added constants (kOnTimeout in Node v12.19.0) will overwrite 0!
  464. var kOnHeaders = HTTPParser.kOnHeaders = 1;
  465. var kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 2;
  466. var kOnBody = HTTPParser.kOnBody = 3;
  467. var kOnMessageComplete = HTTPParser.kOnMessageComplete = 4;
  468. // Some handler stubs, needed for compatibility
  469. HTTPParser.prototype[kOnHeaders] =
  470. HTTPParser.prototype[kOnHeadersComplete] =
  471. HTTPParser.prototype[kOnBody] =
  472. HTTPParser.prototype[kOnMessageComplete] = function () {};
  473. var compatMode0_12 = true;
  474. Object.defineProperty(HTTPParser, 'kOnExecute', {
  475. get: function () {
  476. // hack for backward compatibility
  477. compatMode0_12 = false;
  478. return 99;
  479. }
  480. });
  481. var methods = httpParser.methods = HTTPParser.methods = [
  482. 'DELETE',
  483. 'GET',
  484. 'HEAD',
  485. 'POST',
  486. 'PUT',
  487. 'CONNECT',
  488. 'OPTIONS',
  489. 'TRACE',
  490. 'COPY',
  491. 'LOCK',
  492. 'MKCOL',
  493. 'MOVE',
  494. 'PROPFIND',
  495. 'PROPPATCH',
  496. 'SEARCH',
  497. 'UNLOCK',
  498. 'BIND',
  499. 'REBIND',
  500. 'UNBIND',
  501. 'ACL',
  502. 'REPORT',
  503. 'MKACTIVITY',
  504. 'CHECKOUT',
  505. 'MERGE',
  506. 'M-SEARCH',
  507. 'NOTIFY',
  508. 'SUBSCRIBE',
  509. 'UNSUBSCRIBE',
  510. 'PATCH',
  511. 'PURGE',
  512. 'MKCALENDAR',
  513. 'LINK',
  514. 'UNLINK'
  515. ];
  516. var method_connect = methods.indexOf('CONNECT');
  517. HTTPParser.prototype.reinitialize = HTTPParser;
  518. HTTPParser.prototype.close =
  519. HTTPParser.prototype.pause =
  520. HTTPParser.prototype.resume =
  521. HTTPParser.prototype.free = function () {};
  522. HTTPParser.prototype._compatMode0_11 = false;
  523. HTTPParser.prototype.getAsyncId = function() { return 0; };
  524. var headerState = {
  525. REQUEST_LINE: true,
  526. RESPONSE_LINE: true,
  527. HEADER: true
  528. };
  529. HTTPParser.prototype.execute = function (chunk, start, length) {
  530. if (!(this instanceof HTTPParser)) {
  531. throw new TypeError('not a HTTPParser');
  532. }
  533. // backward compat to node < 0.11.4
  534. // Note: the start and length params were removed in newer version
  535. start = start || 0;
  536. length = typeof length === 'number' ? length : chunk.length;
  537. this.chunk = chunk;
  538. this.offset = start;
  539. var end = this.end = start + length;
  540. try {
  541. while (this.offset < end) {
  542. if (this[this.state]()) {
  543. break;
  544. }
  545. }
  546. } catch (err) {
  547. if (this.isUserCall) {
  548. throw err;
  549. }
  550. this.hadError = true;
  551. return err;
  552. }
  553. this.chunk = null;
  554. length = this.offset - start;
  555. if (headerState[this.state]) {
  556. this.headerSize += length;
  557. if (this.headerSize > HTTPParser.maxHeaderSize) {
  558. return new Error('max header size exceeded');
  559. }
  560. }
  561. return length;
  562. };
  563. var stateFinishAllowed = {
  564. REQUEST_LINE: true,
  565. RESPONSE_LINE: true,
  566. BODY_RAW: true
  567. };
  568. HTTPParser.prototype.finish = function () {
  569. if (this.hadError) {
  570. return;
  571. }
  572. if (!stateFinishAllowed[this.state]) {
  573. return new Error('invalid state for EOF');
  574. }
  575. if (this.state === 'BODY_RAW') {
  576. this.userCall()(this[kOnMessageComplete]());
  577. }
  578. };
  579. // These three methods are used for an internal speed optimization, and it also
  580. // works if theses are noops. Basically consume() asks us to read the bytes
  581. // ourselves, but if we don't do it we get them through execute().
  582. HTTPParser.prototype.consume =
  583. HTTPParser.prototype.unconsume =
  584. HTTPParser.prototype.getCurrentBuffer = function () {};
  585. //For correct error handling - see HTTPParser#execute
  586. //Usage: this.userCall()(userFunction('arg'));
  587. HTTPParser.prototype.userCall = function () {
  588. this.isUserCall = true;
  589. var self = this;
  590. return function (ret) {
  591. self.isUserCall = false;
  592. return ret;
  593. };
  594. };
  595. HTTPParser.prototype.nextRequest = function () {
  596. this.userCall()(this[kOnMessageComplete]());
  597. this.reinitialize(this.type);
  598. };
  599. HTTPParser.prototype.consumeLine = function () {
  600. var end = this.end,
  601. chunk = this.chunk;
  602. for (var i = this.offset; i < end; i++) {
  603. if (chunk[i] === 0x0a) { // \n
  604. var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i);
  605. if (line.charAt(line.length - 1) === '\r') {
  606. line = line.substr(0, line.length - 1);
  607. }
  608. this.line = '';
  609. this.offset = i + 1;
  610. return line;
  611. }
  612. }
  613. //line split over multiple chunks
  614. this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end);
  615. this.offset = this.end;
  616. };
  617. var headerExp = /^([^: \t]+):[ \t]*((?:.*[^ \t])|)/;
  618. var headerContinueExp = /^[ \t]+(.*[^ \t])/;
  619. HTTPParser.prototype.parseHeader = function (line, headers) {
  620. if (line.indexOf('\r') !== -1) {
  621. throw parseErrorCode('HPE_LF_EXPECTED');
  622. }
  623. var match = headerExp.exec(line);
  624. var k = match && match[1];
  625. if (k) { // skip empty string (malformed header)
  626. headers.push(k);
  627. headers.push(match[2]);
  628. } else {
  629. var matchContinue = headerContinueExp.exec(line);
  630. if (matchContinue && headers.length) {
  631. if (headers[headers.length - 1]) {
  632. headers[headers.length - 1] += ' ';
  633. }
  634. headers[headers.length - 1] += matchContinue[1];
  635. }
  636. }
  637. };
  638. var requestExp = /^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;
  639. HTTPParser.prototype.REQUEST_LINE = function () {
  640. var line = this.consumeLine();
  641. if (!line) {
  642. return;
  643. }
  644. var match = requestExp.exec(line);
  645. if (match === null) {
  646. throw parseErrorCode('HPE_INVALID_CONSTANT');
  647. }
  648. this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]);
  649. if (this.info.method === -1) {
  650. throw new Error('invalid request method');
  651. }
  652. this.info.url = match[2];
  653. this.info.versionMajor = +match[3];
  654. this.info.versionMinor = +match[4];
  655. this.body_bytes = 0;
  656. this.state = 'HEADER';
  657. };
  658. var responseExp = /^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;
  659. HTTPParser.prototype.RESPONSE_LINE = function () {
  660. var line = this.consumeLine();
  661. if (!line) {
  662. return;
  663. }
  664. var match = responseExp.exec(line);
  665. if (match === null) {
  666. throw parseErrorCode('HPE_INVALID_CONSTANT');
  667. }
  668. this.info.versionMajor = +match[1];
  669. this.info.versionMinor = +match[2];
  670. var statusCode = this.info.statusCode = +match[3];
  671. this.info.statusMessage = match[4];
  672. // Implied zero length.
  673. if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) {
  674. this.body_bytes = 0;
  675. }
  676. this.state = 'HEADER';
  677. };
  678. HTTPParser.prototype.shouldKeepAlive = function () {
  679. if (this.info.versionMajor > 0 && this.info.versionMinor > 0) {
  680. if (this.connection.indexOf('close') !== -1) {
  681. return false;
  682. }
  683. } else if (this.connection.indexOf('keep-alive') === -1) {
  684. return false;
  685. }
  686. if (this.body_bytes !== null || this.isChunked) { // || skipBody
  687. return true;
  688. }
  689. return false;
  690. };
  691. HTTPParser.prototype.HEADER = function () {
  692. var line = this.consumeLine();
  693. if (line === undefined) {
  694. return;
  695. }
  696. var info = this.info;
  697. if (line) {
  698. this.parseHeader(line, info.headers);
  699. } else {
  700. var headers = info.headers;
  701. var hasContentLength = false;
  702. var currentContentLengthValue;
  703. var hasUpgradeHeader = false;
  704. for (var i = 0; i < headers.length; i += 2) {
  705. switch (headers[i].toLowerCase()) {
  706. case 'transfer-encoding':
  707. this.isChunked = headers[i + 1].toLowerCase() === 'chunked';
  708. break;
  709. case 'content-length':
  710. currentContentLengthValue = +headers[i + 1];
  711. if (hasContentLength) {
  712. // Fix duplicate Content-Length header with same values.
  713. // Throw error only if values are different.
  714. // Known issues:
  715. // https://github.com/request/request/issues/2091#issuecomment-328715113
  716. // https://github.com/nodejs/node/issues/6517#issuecomment-216263771
  717. if (currentContentLengthValue !== this.body_bytes) {
  718. throw parseErrorCode('HPE_UNEXPECTED_CONTENT_LENGTH');
  719. }
  720. } else {
  721. hasContentLength = true;
  722. this.body_bytes = currentContentLengthValue;
  723. }
  724. break;
  725. case 'connection':
  726. this.connection += headers[i + 1].toLowerCase();
  727. break;
  728. case 'upgrade':
  729. hasUpgradeHeader = true;
  730. break;
  731. }
  732. }
  733. // if both isChunked and hasContentLength, isChunked wins
  734. // This is required so the body is parsed using the chunked method, and matches
  735. // Chrome's behavior. We could, maybe, ignore them both (would get chunked
  736. // encoding into the body), and/or disable shouldKeepAlive to be more
  737. // resilient.
  738. if (this.isChunked && hasContentLength) {
  739. hasContentLength = false;
  740. this.body_bytes = null;
  741. }
  742. // Logic from https://github.com/nodejs/http-parser/blob/921d5585515a153fa00e411cf144280c59b41f90/http_parser.c#L1727-L1737
  743. // "For responses, "Upgrade: foo" and "Connection: upgrade" are
  744. // mandatory only when it is a 101 Switching Protocols response,
  745. // otherwise it is purely informational, to announce support.
  746. if (hasUpgradeHeader && this.connection.indexOf('upgrade') != -1) {
  747. info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101;
  748. } else {
  749. info.upgrade = info.method === method_connect;
  750. }
  751. if (this.isChunked && info.upgrade) {
  752. this.isChunked = false;
  753. }
  754. info.shouldKeepAlive = this.shouldKeepAlive();
  755. //problem which also exists in original node: we should know skipBody before calling onHeadersComplete
  756. var skipBody;
  757. if (compatMode0_12) {
  758. skipBody = this.userCall()(this[kOnHeadersComplete](info));
  759. } else {
  760. skipBody = this.userCall()(this[kOnHeadersComplete](info.versionMajor,
  761. info.versionMinor, info.headers, info.method, info.url, info.statusCode,
  762. info.statusMessage, info.upgrade, info.shouldKeepAlive));
  763. }
  764. if (skipBody === 2) {
  765. this.nextRequest();
  766. return true;
  767. } else if (this.isChunked && !skipBody) {
  768. this.state = 'BODY_CHUNKHEAD';
  769. } else if (skipBody || this.body_bytes === 0) {
  770. this.nextRequest();
  771. // For older versions of node (v6.x and older?), that return skipBody=1 or skipBody=true,
  772. // need this "return true;" if it's an upgrade request.
  773. return info.upgrade;
  774. } else if (this.body_bytes === null) {
  775. this.state = 'BODY_RAW';
  776. } else {
  777. this.state = 'BODY_SIZED';
  778. }
  779. }
  780. };
  781. HTTPParser.prototype.BODY_CHUNKHEAD = function () {
  782. var line = this.consumeLine();
  783. if (line === undefined) {
  784. return;
  785. }
  786. this.body_bytes = parseInt(line, 16);
  787. if (!this.body_bytes) {
  788. this.state = 'BODY_CHUNKTRAILERS';
  789. } else {
  790. this.state = 'BODY_CHUNK';
  791. }
  792. };
  793. HTTPParser.prototype.BODY_CHUNK = function () {
  794. var length = Math.min(this.end - this.offset, this.body_bytes);
  795. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  796. this.offset += length;
  797. this.body_bytes -= length;
  798. if (!this.body_bytes) {
  799. this.state = 'BODY_CHUNKEMPTYLINE';
  800. }
  801. };
  802. HTTPParser.prototype.BODY_CHUNKEMPTYLINE = function () {
  803. var line = this.consumeLine();
  804. if (line === undefined) {
  805. return;
  806. }
  807. assert.equal(line, '');
  808. this.state = 'BODY_CHUNKHEAD';
  809. };
  810. HTTPParser.prototype.BODY_CHUNKTRAILERS = function () {
  811. var line = this.consumeLine();
  812. if (line === undefined) {
  813. return;
  814. }
  815. if (line) {
  816. this.parseHeader(line, this.trailers);
  817. } else {
  818. if (this.trailers.length) {
  819. this.userCall()(this[kOnHeaders](this.trailers, ''));
  820. }
  821. this.nextRequest();
  822. }
  823. };
  824. HTTPParser.prototype.BODY_RAW = function () {
  825. var length = this.end - this.offset;
  826. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  827. this.offset = this.end;
  828. };
  829. HTTPParser.prototype.BODY_SIZED = function () {
  830. var length = Math.min(this.end - this.offset, this.body_bytes);
  831. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  832. this.offset += length;
  833. this.body_bytes -= length;
  834. if (!this.body_bytes) {
  835. this.nextRequest();
  836. }
  837. };
  838. // backward compat to node < 0.11.6
  839. ['Headers', 'HeadersComplete', 'Body', 'MessageComplete'].forEach(function (name) {
  840. var k = HTTPParser['kOn' + name];
  841. Object.defineProperty(HTTPParser.prototype, 'on' + name, {
  842. get: function () {
  843. return this[k];
  844. },
  845. set: function (to) {
  846. // hack for backward compatibility
  847. this._compatMode0_11 = true;
  848. method_connect = 'CONNECT';
  849. return (this[k] = to);
  850. }
  851. });
  852. });
  853. function parseErrorCode(code) {
  854. var err = new Error('Parse Error');
  855. err.code = code;
  856. return err;
  857. }
  858. var NodeHTTPParser = httpParser.HTTPParser,
  859. Buffer$7 = safeBuffer.exports.Buffer;
  860. var TYPES = {
  861. request: NodeHTTPParser.REQUEST || 'request',
  862. response: NodeHTTPParser.RESPONSE || 'response'
  863. };
  864. var HttpParser$3 = function(type) {
  865. this._type = type;
  866. this._parser = new NodeHTTPParser(TYPES[type]);
  867. this._complete = false;
  868. this.headers = {};
  869. var current = null,
  870. self = this;
  871. this._parser.onHeaderField = function(b, start, length) {
  872. current = b.toString('utf8', start, start + length).toLowerCase();
  873. };
  874. this._parser.onHeaderValue = function(b, start, length) {
  875. var value = b.toString('utf8', start, start + length);
  876. if (self.headers.hasOwnProperty(current))
  877. self.headers[current] += ', ' + value;
  878. else
  879. self.headers[current] = value;
  880. };
  881. this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] =
  882. function(majorVersion, minorVersion, headers, method, pathname, statusCode) {
  883. var info = arguments[0];
  884. if (typeof info === 'object') {
  885. method = info.method;
  886. pathname = info.url;
  887. statusCode = info.statusCode;
  888. headers = info.headers;
  889. }
  890. self.method = (typeof method === 'number') ? HttpParser$3.METHODS[method] : method;
  891. self.statusCode = statusCode;
  892. self.url = pathname;
  893. if (!headers) return;
  894. for (var i = 0, n = headers.length, key, value; i < n; i += 2) {
  895. key = headers[i].toLowerCase();
  896. value = headers[i+1];
  897. if (self.headers.hasOwnProperty(key))
  898. self.headers[key] += ', ' + value;
  899. else
  900. self.headers[key] = value;
  901. }
  902. self._complete = true;
  903. };
  904. };
  905. HttpParser$3.METHODS = {
  906. 0: 'DELETE',
  907. 1: 'GET',
  908. 2: 'HEAD',
  909. 3: 'POST',
  910. 4: 'PUT',
  911. 5: 'CONNECT',
  912. 6: 'OPTIONS',
  913. 7: 'TRACE',
  914. 8: 'COPY',
  915. 9: 'LOCK',
  916. 10: 'MKCOL',
  917. 11: 'MOVE',
  918. 12: 'PROPFIND',
  919. 13: 'PROPPATCH',
  920. 14: 'SEARCH',
  921. 15: 'UNLOCK',
  922. 16: 'BIND',
  923. 17: 'REBIND',
  924. 18: 'UNBIND',
  925. 19: 'ACL',
  926. 20: 'REPORT',
  927. 21: 'MKACTIVITY',
  928. 22: 'CHECKOUT',
  929. 23: 'MERGE',
  930. 24: 'M-SEARCH',
  931. 25: 'NOTIFY',
  932. 26: 'SUBSCRIBE',
  933. 27: 'UNSUBSCRIBE',
  934. 28: 'PATCH',
  935. 29: 'PURGE',
  936. 30: 'MKCALENDAR',
  937. 31: 'LINK',
  938. 32: 'UNLINK'
  939. };
  940. var VERSION = process.version
  941. ? process.version.match(/[0-9]+/g).map(function(n) { return parseInt(n, 10) })
  942. : [];
  943. if (VERSION[0] === 0 && VERSION[1] === 12) {
  944. HttpParser$3.METHODS[16] = 'REPORT';
  945. HttpParser$3.METHODS[17] = 'MKACTIVITY';
  946. HttpParser$3.METHODS[18] = 'CHECKOUT';
  947. HttpParser$3.METHODS[19] = 'MERGE';
  948. HttpParser$3.METHODS[20] = 'M-SEARCH';
  949. HttpParser$3.METHODS[21] = 'NOTIFY';
  950. HttpParser$3.METHODS[22] = 'SUBSCRIBE';
  951. HttpParser$3.METHODS[23] = 'UNSUBSCRIBE';
  952. HttpParser$3.METHODS[24] = 'PATCH';
  953. HttpParser$3.METHODS[25] = 'PURGE';
  954. }
  955. HttpParser$3.prototype.isComplete = function() {
  956. return this._complete;
  957. };
  958. HttpParser$3.prototype.parse = function(chunk) {
  959. var consumed = this._parser.execute(chunk, 0, chunk.length);
  960. if (typeof consumed !== 'number') {
  961. this.error = consumed;
  962. this._complete = true;
  963. return;
  964. }
  965. if (this._complete)
  966. this.body = (consumed < chunk.length)
  967. ? chunk.slice(consumed)
  968. : Buffer$7.alloc(0);
  969. };
  970. var http_parser = HttpParser$3;
  971. var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/,
  972. NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g,
  973. QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/,
  974. PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'),
  975. EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'),
  976. EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'),
  977. NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/;
  978. var hasOwnProperty = Object.prototype.hasOwnProperty;
  979. var Parser$1 = {
  980. parseHeader: function(header) {
  981. var offers = new Offers();
  982. if (header === '' || header === undefined) return offers;
  983. if (!EXT_LIST.test(header))
  984. throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header);
  985. var values = header.match(EXT);
  986. values.forEach(function(value) {
  987. var params = value.match(new RegExp(PARAM.source, 'g')),
  988. name = params.shift(),
  989. offer = {};
  990. params.forEach(function(param) {
  991. var args = param.match(PARAM), key = args[1], data;
  992. if (args[2] !== undefined) {
  993. data = args[2];
  994. } else if (args[3] !== undefined) {
  995. data = args[3].replace(/\\/g, '');
  996. } else {
  997. data = true;
  998. }
  999. if (NUMBER.test(data)) data = parseFloat(data);
  1000. if (hasOwnProperty.call(offer, key)) {
  1001. offer[key] = [].concat(offer[key]);
  1002. offer[key].push(data);
  1003. } else {
  1004. offer[key] = data;
  1005. }
  1006. }, this);
  1007. offers.push(name, offer);
  1008. }, this);
  1009. return offers;
  1010. },
  1011. serializeParams: function(name, params) {
  1012. var values = [];
  1013. var print = function(key, value) {
  1014. if (value instanceof Array) {
  1015. value.forEach(function(v) { print(key, v); });
  1016. } else if (value === true) {
  1017. values.push(key);
  1018. } else if (typeof value === 'number') {
  1019. values.push(key + '=' + value);
  1020. } else if (NOTOKEN.test(value)) {
  1021. values.push(key + '="' + value.replace(/"/g, '\\"') + '"');
  1022. } else {
  1023. values.push(key + '=' + value);
  1024. }
  1025. };
  1026. for (var key in params) print(key, params[key]);
  1027. return [name].concat(values).join('; ');
  1028. }
  1029. };
  1030. var Offers = function() {
  1031. this._byName = {};
  1032. this._inOrder = [];
  1033. };
  1034. Offers.prototype.push = function(name, params) {
  1035. if (!hasOwnProperty.call(this._byName, name))
  1036. this._byName[name] = [];
  1037. this._byName[name].push(params);
  1038. this._inOrder.push({ name: name, params: params });
  1039. };
  1040. Offers.prototype.eachOffer = function(callback, context) {
  1041. var list = this._inOrder;
  1042. for (var i = 0, n = list.length; i < n; i++)
  1043. callback.call(context, list[i].name, list[i].params);
  1044. };
  1045. Offers.prototype.byName = function(name) {
  1046. return this._byName[name] || [];
  1047. };
  1048. Offers.prototype.toArray = function() {
  1049. return this._inOrder.slice();
  1050. };
  1051. var parser = Parser$1;
  1052. var RingBuffer$2 = function(bufferSize) {
  1053. this._bufferSize = bufferSize;
  1054. this.clear();
  1055. };
  1056. RingBuffer$2.prototype.clear = function() {
  1057. this._buffer = new Array(this._bufferSize);
  1058. this._ringOffset = 0;
  1059. this._ringSize = this._bufferSize;
  1060. this._head = 0;
  1061. this._tail = 0;
  1062. this.length = 0;
  1063. };
  1064. RingBuffer$2.prototype.push = function(value) {
  1065. var expandBuffer = false,
  1066. expandRing = false;
  1067. if (this._ringSize < this._bufferSize) {
  1068. expandBuffer = (this._tail === 0);
  1069. } else if (this._ringOffset === this._ringSize) {
  1070. expandBuffer = true;
  1071. expandRing = (this._tail === 0);
  1072. }
  1073. if (expandBuffer) {
  1074. this._tail = this._bufferSize;
  1075. this._buffer = this._buffer.concat(new Array(this._bufferSize));
  1076. this._bufferSize = this._buffer.length;
  1077. if (expandRing)
  1078. this._ringSize = this._bufferSize;
  1079. }
  1080. this._buffer[this._tail] = value;
  1081. this.length += 1;
  1082. if (this._tail < this._ringSize) this._ringOffset += 1;
  1083. this._tail = (this._tail + 1) % this._bufferSize;
  1084. };
  1085. RingBuffer$2.prototype.peek = function() {
  1086. if (this.length === 0) return void 0;
  1087. return this._buffer[this._head];
  1088. };
  1089. RingBuffer$2.prototype.shift = function() {
  1090. if (this.length === 0) return void 0;
  1091. var value = this._buffer[this._head];
  1092. this._buffer[this._head] = void 0;
  1093. this.length -= 1;
  1094. this._ringOffset -= 1;
  1095. if (this._ringOffset === 0 && this.length > 0) {
  1096. this._head = this._ringSize;
  1097. this._ringOffset = this.length;
  1098. this._ringSize = this._bufferSize;
  1099. } else {
  1100. this._head = (this._head + 1) % this._ringSize;
  1101. }
  1102. return value;
  1103. };
  1104. var ring_buffer = RingBuffer$2;
  1105. var RingBuffer$1 = ring_buffer;
  1106. var Functor$1 = function(session, method) {
  1107. this._session = session;
  1108. this._method = method;
  1109. this._queue = new RingBuffer$1(Functor$1.QUEUE_SIZE);
  1110. this._stopped = false;
  1111. this.pending = 0;
  1112. };
  1113. Functor$1.QUEUE_SIZE = 8;
  1114. Functor$1.prototype.call = function(error, message, callback, context) {
  1115. if (this._stopped) return;
  1116. var record = { error: error, message: message, callback: callback, context: context, done: false },
  1117. called = false,
  1118. self = this;
  1119. this._queue.push(record);
  1120. if (record.error) {
  1121. record.done = true;
  1122. this._stop();
  1123. return this._flushQueue();
  1124. }
  1125. var handler = function(err, msg) {
  1126. if (!(called ^ (called = true))) return;
  1127. if (err) {
  1128. self._stop();
  1129. record.error = err;
  1130. record.message = null;
  1131. } else {
  1132. record.message = msg;
  1133. }
  1134. record.done = true;
  1135. self._flushQueue();
  1136. };
  1137. try {
  1138. this._session[this._method](message, handler);
  1139. } catch (err) {
  1140. handler(err);
  1141. }
  1142. };
  1143. Functor$1.prototype._stop = function() {
  1144. this.pending = this._queue.length;
  1145. this._stopped = true;
  1146. };
  1147. Functor$1.prototype._flushQueue = function() {
  1148. var queue = this._queue, record;
  1149. while (queue.length > 0 && queue.peek().done) {
  1150. record = queue.shift();
  1151. if (record.error) {
  1152. this.pending = 0;
  1153. queue.clear();
  1154. } else {
  1155. this.pending -= 1;
  1156. }
  1157. record.callback.call(record.context, record.error, record.message);
  1158. }
  1159. };
  1160. var functor = Functor$1;
  1161. var RingBuffer = ring_buffer;
  1162. var Pledge$2 = function() {
  1163. this._complete = false;
  1164. this._callbacks = new RingBuffer(Pledge$2.QUEUE_SIZE);
  1165. };
  1166. Pledge$2.QUEUE_SIZE = 4;
  1167. Pledge$2.all = function(list) {
  1168. var pledge = new Pledge$2(),
  1169. pending = list.length,
  1170. n = pending;
  1171. if (pending === 0) pledge.done();
  1172. while (n--) list[n].then(function() {
  1173. pending -= 1;
  1174. if (pending === 0) pledge.done();
  1175. });
  1176. return pledge;
  1177. };
  1178. Pledge$2.prototype.then = function(callback) {
  1179. if (this._complete) callback();
  1180. else this._callbacks.push(callback);
  1181. };
  1182. Pledge$2.prototype.done = function() {
  1183. this._complete = true;
  1184. var callbacks = this._callbacks, callback;
  1185. while (callback = callbacks.shift()) callback();
  1186. };
  1187. var pledge = Pledge$2;
  1188. var Functor = functor,
  1189. Pledge$1 = pledge;
  1190. var Cell$1 = function(tuple) {
  1191. this._ext = tuple[0];
  1192. this._session = tuple[1];
  1193. this._functors = {
  1194. incoming: new Functor(this._session, 'processIncomingMessage'),
  1195. outgoing: new Functor(this._session, 'processOutgoingMessage')
  1196. };
  1197. };
  1198. Cell$1.prototype.pending = function(direction) {
  1199. var functor = this._functors[direction];
  1200. if (!functor._stopped) functor.pending += 1;
  1201. };
  1202. Cell$1.prototype.incoming = function(error, message, callback, context) {
  1203. this._exec('incoming', error, message, callback, context);
  1204. };
  1205. Cell$1.prototype.outgoing = function(error, message, callback, context) {
  1206. this._exec('outgoing', error, message, callback, context);
  1207. };
  1208. Cell$1.prototype.close = function() {
  1209. this._closed = this._closed || new Pledge$1();
  1210. this._doClose();
  1211. return this._closed;
  1212. };
  1213. Cell$1.prototype._exec = function(direction, error, message, callback, context) {
  1214. this._functors[direction].call(error, message, function(err, msg) {
  1215. if (err) err.message = this._ext.name + ': ' + err.message;
  1216. callback.call(context, err, msg);
  1217. this._doClose();
  1218. }, this);
  1219. };
  1220. Cell$1.prototype._doClose = function() {
  1221. var fin = this._functors.incoming,
  1222. fout = this._functors.outgoing;
  1223. if (!this._closed || fin.pending + fout.pending !== 0) return;
  1224. if (this._session) this._session.close();
  1225. this._session = null;
  1226. this._closed.done();
  1227. };
  1228. var cell = Cell$1;
  1229. var Cell = cell,
  1230. Pledge = pledge;
  1231. var Pipeline$1 = function(sessions) {
  1232. this._cells = sessions.map(function(session) { return new Cell(session) });
  1233. this._stopped = { incoming: false, outgoing: false };
  1234. };
  1235. Pipeline$1.prototype.processIncomingMessage = function(message, callback, context) {
  1236. if (this._stopped.incoming) return;
  1237. this._loop('incoming', this._cells.length - 1, -1, -1, message, callback, context);
  1238. };
  1239. Pipeline$1.prototype.processOutgoingMessage = function(message, callback, context) {
  1240. if (this._stopped.outgoing) return;
  1241. this._loop('outgoing', 0, this._cells.length, 1, message, callback, context);
  1242. };
  1243. Pipeline$1.prototype.close = function(callback, context) {
  1244. this._stopped = { incoming: true, outgoing: true };
  1245. var closed = this._cells.map(function(a) { return a.close() });
  1246. if (callback)
  1247. Pledge.all(closed).then(function() { callback.call(context); });
  1248. };
  1249. Pipeline$1.prototype._loop = function(direction, start, end, step, message, callback, context) {
  1250. var cells = this._cells,
  1251. n = cells.length,
  1252. self = this;
  1253. while (n--) cells[n].pending(direction);
  1254. var pipe = function(index, error, msg) {
  1255. if (index === end) return callback.call(context, error, msg);
  1256. cells[index][direction](error, msg, function(err, m) {
  1257. if (err) self._stopped[direction] = true;
  1258. pipe(index + step, err, m);
  1259. });
  1260. };
  1261. pipe(start, null, message);
  1262. };
  1263. var pipeline = Pipeline$1;
  1264. var Parser = parser,
  1265. Pipeline = pipeline;
  1266. var Extensions$1 = function() {
  1267. this._rsv1 = this._rsv2 = this._rsv3 = null;
  1268. this._byName = {};
  1269. this._inOrder = [];
  1270. this._sessions = [];
  1271. this._index = {};
  1272. };
  1273. Extensions$1.MESSAGE_OPCODES = [1, 2];
  1274. var instance$a = {
  1275. add: function(ext) {
  1276. if (typeof ext.name !== 'string') throw new TypeError('extension.name must be a string');
  1277. if (ext.type !== 'permessage') throw new TypeError('extension.type must be "permessage"');
  1278. if (typeof ext.rsv1 !== 'boolean') throw new TypeError('extension.rsv1 must be true or false');
  1279. if (typeof ext.rsv2 !== 'boolean') throw new TypeError('extension.rsv2 must be true or false');
  1280. if (typeof ext.rsv3 !== 'boolean') throw new TypeError('extension.rsv3 must be true or false');
  1281. if (this._byName.hasOwnProperty(ext.name))
  1282. throw new TypeError('An extension with name "' + ext.name + '" is already registered');
  1283. this._byName[ext.name] = ext;
  1284. this._inOrder.push(ext);
  1285. },
  1286. generateOffer: function() {
  1287. var sessions = [],
  1288. offer = [],
  1289. index = {};
  1290. this._inOrder.forEach(function(ext) {
  1291. var session = ext.createClientSession();
  1292. if (!session) return;
  1293. var record = [ext, session];
  1294. sessions.push(record);
  1295. index[ext.name] = record;
  1296. var offers = session.generateOffer();
  1297. offers = offers ? [].concat(offers) : [];
  1298. offers.forEach(function(off) {
  1299. offer.push(Parser.serializeParams(ext.name, off));
  1300. }, this);
  1301. }, this);
  1302. this._sessions = sessions;
  1303. this._index = index;
  1304. return offer.length > 0 ? offer.join(', ') : null;
  1305. },
  1306. activate: function(header) {
  1307. var responses = Parser.parseHeader(header),
  1308. sessions = [];
  1309. responses.eachOffer(function(name, params) {
  1310. var record = this._index[name];
  1311. if (!record)
  1312. throw new Error('Server sent an extension response for unknown extension "' + name + '"');
  1313. var ext = record[0],
  1314. session = record[1],
  1315. reserved = this._reserved(ext);
  1316. if (reserved)
  1317. throw new Error('Server sent two extension responses that use the RSV' +
  1318. reserved[0] + ' bit: "' +
  1319. reserved[1] + '" and "' + ext.name + '"');
  1320. if (session.activate(params) !== true)
  1321. throw new Error('Server sent unacceptable extension parameters: ' +
  1322. Parser.serializeParams(name, params));
  1323. this._reserve(ext);
  1324. sessions.push(record);
  1325. }, this);
  1326. this._sessions = sessions;
  1327. this._pipeline = new Pipeline(sessions);
  1328. },
  1329. generateResponse: function(header) {
  1330. var sessions = [],
  1331. response = [],
  1332. offers = Parser.parseHeader(header);
  1333. this._inOrder.forEach(function(ext) {
  1334. var offer = offers.byName(ext.name);
  1335. if (offer.length === 0 || this._reserved(ext)) return;
  1336. var session = ext.createServerSession(offer);
  1337. if (!session) return;
  1338. this._reserve(ext);
  1339. sessions.push([ext, session]);
  1340. response.push(Parser.serializeParams(ext.name, session.generateResponse()));
  1341. }, this);
  1342. this._sessions = sessions;
  1343. this._pipeline = new Pipeline(sessions);
  1344. return response.length > 0 ? response.join(', ') : null;
  1345. },
  1346. validFrameRsv: function(frame) {
  1347. var allowed = { rsv1: false, rsv2: false, rsv3: false },
  1348. ext;
  1349. if (Extensions$1.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) {
  1350. for (var i = 0, n = this._sessions.length; i < n; i++) {
  1351. ext = this._sessions[i][0];
  1352. allowed.rsv1 = allowed.rsv1 || ext.rsv1;
  1353. allowed.rsv2 = allowed.rsv2 || ext.rsv2;
  1354. allowed.rsv3 = allowed.rsv3 || ext.rsv3;
  1355. }
  1356. }
  1357. return (allowed.rsv1 || !frame.rsv1) &&
  1358. (allowed.rsv2 || !frame.rsv2) &&
  1359. (allowed.rsv3 || !frame.rsv3);
  1360. },
  1361. processIncomingMessage: function(message, callback, context) {
  1362. this._pipeline.processIncomingMessage(message, callback, context);
  1363. },
  1364. processOutgoingMessage: function(message, callback, context) {
  1365. this._pipeline.processOutgoingMessage(message, callback, context);
  1366. },
  1367. close: function(callback, context) {
  1368. if (!this._pipeline) return callback.call(context);
  1369. this._pipeline.close(callback, context);
  1370. },
  1371. _reserve: function(ext) {
  1372. this._rsv1 = this._rsv1 || (ext.rsv1 && ext.name);
  1373. this._rsv2 = this._rsv2 || (ext.rsv2 && ext.name);
  1374. this._rsv3 = this._rsv3 || (ext.rsv3 && ext.name);
  1375. },
  1376. _reserved: function(ext) {
  1377. if (this._rsv1 && ext.rsv1) return [1, this._rsv1];
  1378. if (this._rsv2 && ext.rsv2) return [2, this._rsv2];
  1379. if (this._rsv3 && ext.rsv3) return [3, this._rsv3];
  1380. return false;
  1381. }
  1382. };
  1383. for (var key$a in instance$a)
  1384. Extensions$1.prototype[key$a] = instance$a[key$a];
  1385. var websocket_extensions = Extensions$1;
  1386. var Frame$1 = function() {};
  1387. var instance$9 = {
  1388. final: false,
  1389. rsv1: false,
  1390. rsv2: false,
  1391. rsv3: false,
  1392. opcode: null,
  1393. masked: false,
  1394. maskingKey: null,
  1395. lengthBytes: 1,
  1396. length: 0,
  1397. payload: null
  1398. };
  1399. for (var key$9 in instance$9)
  1400. Frame$1.prototype[key$9] = instance$9[key$9];
  1401. var frame = Frame$1;
  1402. var Buffer$6 = safeBuffer.exports.Buffer;
  1403. var Message$1 = function() {
  1404. this.rsv1 = false;
  1405. this.rsv2 = false;
  1406. this.rsv3 = false;
  1407. this.opcode = null;
  1408. this.length = 0;
  1409. this._chunks = [];
  1410. };
  1411. var instance$8 = {
  1412. read: function() {
  1413. return this.data = this.data || Buffer$6.concat(this._chunks, this.length);
  1414. },
  1415. pushFrame: function(frame) {
  1416. this.rsv1 = this.rsv1 || frame.rsv1;
  1417. this.rsv2 = this.rsv2 || frame.rsv2;
  1418. this.rsv3 = this.rsv3 || frame.rsv3;
  1419. if (this.opcode === null) this.opcode = frame.opcode;
  1420. this._chunks.push(frame.payload);
  1421. this.length += frame.length;
  1422. }
  1423. };
  1424. for (var key$8 in instance$8)
  1425. Message$1.prototype[key$8] = instance$8[key$8];
  1426. var message = Message$1;
  1427. var Buffer$5 = safeBuffer.exports.Buffer,
  1428. crypto$2 = require$$1__default$1["default"],
  1429. util$a = require$$2__default["default"],
  1430. Extensions = websocket_extensions,
  1431. Base$6 = base,
  1432. Frame = frame,
  1433. Message = message;
  1434. var Hybi$2 = function(request, url, options) {
  1435. Base$6.apply(this, arguments);
  1436. this._extensions = new Extensions();
  1437. this._stage = 0;
  1438. this._masking = this._options.masking;
  1439. this._protocols = this._options.protocols || [];
  1440. this._requireMasking = this._options.requireMasking;
  1441. this._pingCallbacks = {};
  1442. if (typeof this._protocols === 'string')
  1443. this._protocols = this._protocols.split(/ *, */);
  1444. if (!this._request) return;
  1445. var protos = this._request.headers['sec-websocket-protocol'],
  1446. supported = this._protocols;
  1447. if (protos !== undefined) {
  1448. if (typeof protos === 'string') protos = protos.split(/ *, */);
  1449. this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0];
  1450. }
  1451. this.version = 'hybi-' + Hybi$2.VERSION;
  1452. };
  1453. util$a.inherits(Hybi$2, Base$6);
  1454. Hybi$2.VERSION = '13';
  1455. Hybi$2.mask = function(payload, mask, offset) {
  1456. if (!mask || mask.length === 0) return payload;
  1457. offset = offset || 0;
  1458. for (var i = 0, n = payload.length - offset; i < n; i++) {
  1459. payload[offset + i] = payload[offset + i] ^ mask[i % 4];
  1460. }
  1461. return payload;
  1462. };
  1463. Hybi$2.generateAccept = function(key) {
  1464. var sha1 = crypto$2.createHash('sha1');
  1465. sha1.update(key + Hybi$2.GUID);
  1466. return sha1.digest('base64');
  1467. };
  1468. Hybi$2.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  1469. var instance$7 = {
  1470. FIN: 0x80,
  1471. MASK: 0x80,
  1472. RSV1: 0x40,
  1473. RSV2: 0x20,
  1474. RSV3: 0x10,
  1475. OPCODE: 0x0F,
  1476. LENGTH: 0x7F,
  1477. OPCODES: {
  1478. continuation: 0,
  1479. text: 1,
  1480. binary: 2,
  1481. close: 8,
  1482. ping: 9,
  1483. pong: 10
  1484. },
  1485. OPCODE_CODES: [0, 1, 2, 8, 9, 10],
  1486. MESSAGE_OPCODES: [0, 1, 2],
  1487. OPENING_OPCODES: [1, 2],
  1488. ERRORS: {
  1489. normal_closure: 1000,
  1490. going_away: 1001,
  1491. protocol_error: 1002,
  1492. unacceptable: 1003,
  1493. encoding_error: 1007,
  1494. policy_violation: 1008,
  1495. too_large: 1009,
  1496. extension_error: 1010,
  1497. unexpected_condition: 1011
  1498. },
  1499. ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011],
  1500. DEFAULT_ERROR_CODE: 1000,
  1501. MIN_RESERVED_ERROR: 3000,
  1502. MAX_RESERVED_ERROR: 4999,
  1503. // http://www.w3.org/International/questions/qa-forms-utf-8.en.php
  1504. UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/,
  1505. addExtension: function(extension) {
  1506. this._extensions.add(extension);
  1507. return true;
  1508. },
  1509. parse: function(chunk) {
  1510. this._reader.put(chunk);
  1511. var buffer = true;
  1512. while (buffer) {
  1513. switch (this._stage) {
  1514. case 0:
  1515. buffer = this._reader.read(1);
  1516. if (buffer) this._parseOpcode(buffer[0]);
  1517. break;
  1518. case 1:
  1519. buffer = this._reader.read(1);
  1520. if (buffer) this._parseLength(buffer[0]);
  1521. break;
  1522. case 2:
  1523. buffer = this._reader.read(this._frame.lengthBytes);
  1524. if (buffer) this._parseExtendedLength(buffer);
  1525. break;
  1526. case 3:
  1527. buffer = this._reader.read(4);
  1528. if (buffer) {
  1529. this._stage = 4;
  1530. this._frame.maskingKey = buffer;
  1531. }
  1532. break;
  1533. case 4:
  1534. buffer = this._reader.read(this._frame.length);
  1535. if (buffer) {
  1536. this._stage = 0;
  1537. this._emitFrame(buffer);
  1538. }
  1539. break;
  1540. default:
  1541. buffer = null;
  1542. }
  1543. }
  1544. },
  1545. text: function(message) {
  1546. if (this.readyState > 1) return false;
  1547. return this.frame(message, 'text');
  1548. },
  1549. binary: function(message) {
  1550. if (this.readyState > 1) return false;
  1551. return this.frame(message, 'binary');
  1552. },
  1553. ping: function(message, callback) {
  1554. if (this.readyState > 1) return false;
  1555. message = message || '';
  1556. if (callback) this._pingCallbacks[message] = callback;
  1557. return this.frame(message, 'ping');
  1558. },
  1559. pong: function(message) {
  1560. if (this.readyState > 1) return false;
  1561. message = message ||'';
  1562. return this.frame(message, 'pong');
  1563. },
  1564. close: function(reason, code) {
  1565. reason = reason || '';
  1566. code = code || this.ERRORS.normal_closure;
  1567. if (this.readyState <= 0) {
  1568. this.readyState = 3;
  1569. this.emit('close', new Base$6.CloseEvent(code, reason));
  1570. return true;
  1571. } else if (this.readyState === 1) {
  1572. this.readyState = 2;
  1573. this._extensions.close(function() { this.frame(reason, 'close', code); }, this);
  1574. return true;
  1575. } else {
  1576. return false;
  1577. }
  1578. },
  1579. frame: function(buffer, type, code) {
  1580. if (this.readyState <= 0) return this._queue([buffer, type, code]);
  1581. if (this.readyState > 2) return false;
  1582. if (buffer instanceof Array) buffer = Buffer$5.from(buffer);
  1583. if (typeof buffer === 'number') buffer = buffer.toString();
  1584. var message = new Message(),
  1585. isText = (typeof buffer === 'string'),
  1586. payload, copy;
  1587. message.rsv1 = message.rsv2 = message.rsv3 = false;
  1588. message.opcode = this.OPCODES[type || (isText ? 'text' : 'binary')];
  1589. payload = isText ? Buffer$5.from(buffer, 'utf8') : buffer;
  1590. if (code) {
  1591. copy = payload;
  1592. payload = Buffer$5.allocUnsafe(2 + copy.length);
  1593. payload.writeUInt16BE(code, 0);
  1594. copy.copy(payload, 2);
  1595. }
  1596. message.data = payload;
  1597. var onMessageReady = function(message) {
  1598. var frame = new Frame();
  1599. frame.final = true;
  1600. frame.rsv1 = message.rsv1;
  1601. frame.rsv2 = message.rsv2;
  1602. frame.rsv3 = message.rsv3;
  1603. frame.opcode = message.opcode;
  1604. frame.masked = !!this._masking;
  1605. frame.length = message.data.length;
  1606. frame.payload = message.data;
  1607. if (frame.masked) frame.maskingKey = crypto$2.randomBytes(4);
  1608. this._sendFrame(frame);
  1609. };
  1610. if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0)
  1611. this._extensions.processOutgoingMessage(message, function(error, message) {
  1612. if (error) return this._fail('extension_error', error.message);
  1613. onMessageReady.call(this, message);
  1614. }, this);
  1615. else
  1616. onMessageReady.call(this, message);
  1617. return true;
  1618. },
  1619. _sendFrame: function(frame) {
  1620. var length = frame.length,
  1621. header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10),
  1622. offset = header + (frame.masked ? 4 : 0),
  1623. buffer = Buffer$5.allocUnsafe(offset + length),
  1624. masked = frame.masked ? this.MASK : 0;
  1625. buffer[0] = (frame.final ? this.FIN : 0) |
  1626. (frame.rsv1 ? this.RSV1 : 0) |
  1627. (frame.rsv2 ? this.RSV2 : 0) |
  1628. (frame.rsv3 ? this.RSV3 : 0) |
  1629. frame.opcode;
  1630. if (length <= 125) {
  1631. buffer[1] = masked | length;
  1632. } else if (length <= 65535) {
  1633. buffer[1] = masked | 126;
  1634. buffer.writeUInt16BE(length, 2);
  1635. } else {
  1636. buffer[1] = masked | 127;
  1637. buffer.writeUInt32BE(Math.floor(length / 0x100000000), 2);
  1638. buffer.writeUInt32BE(length % 0x100000000, 6);
  1639. }
  1640. frame.payload.copy(buffer, offset);
  1641. if (frame.masked) {
  1642. frame.maskingKey.copy(buffer, header);
  1643. Hybi$2.mask(buffer, frame.maskingKey, offset);
  1644. }
  1645. this._write(buffer);
  1646. },
  1647. _handshakeResponse: function() {
  1648. var secKey = this._request.headers['sec-websocket-key'],
  1649. version = this._request.headers['sec-websocket-version'];
  1650. if (version !== Hybi$2.VERSION)
  1651. throw new Error('Unsupported WebSocket version: ' + version);
  1652. if (typeof secKey !== 'string')
  1653. throw new Error('Missing handshake request header: Sec-WebSocket-Key');
  1654. this._headers.set('Upgrade', 'websocket');
  1655. this._headers.set('Connection', 'Upgrade');
  1656. this._headers.set('Sec-WebSocket-Accept', Hybi$2.generateAccept(secKey));
  1657. if (this.protocol) this._headers.set('Sec-WebSocket-Protocol', this.protocol);
  1658. var extensions = this._extensions.generateResponse(this._request.headers['sec-websocket-extensions']);
  1659. if (extensions) this._headers.set('Sec-WebSocket-Extensions', extensions);
  1660. var start = 'HTTP/1.1 101 Switching Protocols',
  1661. headers = [start, this._headers.toString(), ''];
  1662. return Buffer$5.from(headers.join('\r\n'), 'utf8');
  1663. },
  1664. _shutdown: function(code, reason, error) {
  1665. delete this._frame;
  1666. delete this._message;
  1667. this._stage = 5;
  1668. var sendCloseFrame = (this.readyState === 1);
  1669. this.readyState = 2;
  1670. this._extensions.close(function() {
  1671. if (sendCloseFrame) this.frame(reason, 'close', code);
  1672. this.readyState = 3;
  1673. if (error) this.emit('error', new Error(reason));
  1674. this.emit('close', new Base$6.CloseEvent(code, reason));
  1675. }, this);
  1676. },
  1677. _fail: function(type, message) {
  1678. if (this.readyState > 1) return;
  1679. this._shutdown(this.ERRORS[type], message, true);
  1680. },
  1681. _parseOpcode: function(octet) {
  1682. var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) {
  1683. return (octet & rsv) === rsv;
  1684. });
  1685. var frame = this._frame = new Frame();
  1686. frame.final = (octet & this.FIN) === this.FIN;
  1687. frame.rsv1 = rsvs[0];
  1688. frame.rsv2 = rsvs[1];
  1689. frame.rsv3 = rsvs[2];
  1690. frame.opcode = (octet & this.OPCODE);
  1691. this._stage = 1;
  1692. if (!this._extensions.validFrameRsv(frame))
  1693. return this._fail('protocol_error',
  1694. 'One or more reserved bits are on: reserved1 = ' + (frame.rsv1 ? 1 : 0) +
  1695. ', reserved2 = ' + (frame.rsv2 ? 1 : 0) +
  1696. ', reserved3 = ' + (frame.rsv3 ? 1 : 0));
  1697. if (this.OPCODE_CODES.indexOf(frame.opcode) < 0)
  1698. return this._fail('protocol_error', 'Unrecognized frame opcode: ' + frame.opcode);
  1699. if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final)
  1700. return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + frame.opcode);
  1701. if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0)
  1702. return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished');
  1703. },
  1704. _parseLength: function(octet) {
  1705. var frame = this._frame;
  1706. frame.masked = (octet & this.MASK) === this.MASK;
  1707. frame.length = (octet & this.LENGTH);
  1708. if (frame.length >= 0 && frame.length <= 125) {
  1709. this._stage = frame.masked ? 3 : 4;
  1710. if (!this._checkFrameLength()) return;
  1711. } else {
  1712. this._stage = 2;
  1713. frame.lengthBytes = (frame.length === 126 ? 2 : 8);
  1714. }
  1715. if (this._requireMasking && !frame.masked)
  1716. return this._fail('unacceptable', 'Received unmasked frame but masking is required');
  1717. },
  1718. _parseExtendedLength: function(buffer) {
  1719. var frame = this._frame;
  1720. frame.length = this._readUInt(buffer);
  1721. this._stage = frame.masked ? 3 : 4;
  1722. if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125)
  1723. return this._fail('protocol_error', 'Received control frame having too long payload: ' + frame.length);
  1724. if (!this._checkFrameLength()) return;
  1725. },
  1726. _checkFrameLength: function() {
  1727. var length = this._message ? this._message.length : 0;
  1728. if (length + this._frame.length > this._maxLength) {
  1729. this._fail('too_large', 'WebSocket frame length too large');
  1730. return false;
  1731. } else {
  1732. return true;
  1733. }
  1734. },
  1735. _emitFrame: function(buffer) {
  1736. var frame = this._frame,
  1737. payload = frame.payload = Hybi$2.mask(buffer, frame.maskingKey),
  1738. opcode = frame.opcode,
  1739. message,
  1740. code, reason,
  1741. callbacks, callback;
  1742. delete this._frame;
  1743. if (opcode === this.OPCODES.continuation) {
  1744. if (!this._message) return this._fail('protocol_error', 'Received unexpected continuation frame');
  1745. this._message.pushFrame(frame);
  1746. }
  1747. if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) {
  1748. this._message = new Message();
  1749. this._message.pushFrame(frame);
  1750. }
  1751. if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0)
  1752. return this._emitMessage(this._message);
  1753. if (opcode === this.OPCODES.close) {
  1754. code = (payload.length >= 2) ? payload.readUInt16BE(0) : null;
  1755. reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null;
  1756. if (!(payload.length === 0) &&
  1757. !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) &&
  1758. this.ERROR_CODES.indexOf(code) < 0)
  1759. code = this.ERRORS.protocol_error;
  1760. if (payload.length > 125 || (payload.length > 2 && !reason))
  1761. code = this.ERRORS.protocol_error;
  1762. this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || '');
  1763. }
  1764. if (opcode === this.OPCODES.ping) {
  1765. this.frame(payload, 'pong');
  1766. this.emit('ping', new Base$6.PingEvent(payload.toString()));
  1767. }
  1768. if (opcode === this.OPCODES.pong) {
  1769. callbacks = this._pingCallbacks;
  1770. message = this._encode(payload);
  1771. callback = callbacks[message];
  1772. delete callbacks[message];
  1773. if (callback) callback();
  1774. this.emit('pong', new Base$6.PongEvent(payload.toString()));
  1775. }
  1776. },
  1777. _emitMessage: function(message) {
  1778. var message = this._message;
  1779. message.read();
  1780. delete this._message;
  1781. this._extensions.processIncomingMessage(message, function(error, message) {
  1782. if (error) return this._fail('extension_error', error.message);
  1783. var payload = message.data;
  1784. if (message.opcode === this.OPCODES.text) payload = this._encode(payload);
  1785. if (payload === null)
  1786. return this._fail('encoding_error', 'Could not decode a text frame as UTF-8');
  1787. else
  1788. this.emit('message', new Base$6.MessageEvent(payload));
  1789. }, this);
  1790. },
  1791. _encode: function(buffer) {
  1792. try {
  1793. var string = buffer.toString('binary', 0, buffer.length);
  1794. if (!this.UTF8_MATCH.test(string)) return null;
  1795. } catch (e) {}
  1796. return buffer.toString('utf8', 0, buffer.length);
  1797. },
  1798. _readUInt: function(buffer) {
  1799. if (buffer.length === 2) return buffer.readUInt16BE(0);
  1800. return buffer.readUInt32BE(0) * 0x100000000 +
  1801. buffer.readUInt32BE(4);
  1802. }
  1803. };
  1804. for (var key$7 in instance$7)
  1805. Hybi$2.prototype[key$7] = instance$7[key$7];
  1806. var hybi = Hybi$2;
  1807. var Buffer$4 = safeBuffer.exports.Buffer,
  1808. Stream$2 = require$$0__default$1["default"].Stream,
  1809. url$2 = require$$2__default$1["default"],
  1810. util$9 = require$$2__default["default"],
  1811. Base$5 = base,
  1812. Headers$1 = headers,
  1813. HttpParser$2 = http_parser;
  1814. var PORTS = { 'ws:': 80, 'wss:': 443 };
  1815. var Proxy$1 = function(client, origin, options) {
  1816. this._client = client;
  1817. this._http = new HttpParser$2('response');
  1818. this._origin = (typeof client.url === 'object') ? client.url : url$2.parse(client.url);
  1819. this._url = (typeof origin === 'object') ? origin : url$2.parse(origin);
  1820. this._options = options || {};
  1821. this._state = 0;
  1822. this.readable = this.writable = true;
  1823. this._paused = false;
  1824. this._headers = new Headers$1();
  1825. this._headers.set('Host', this._origin.host);
  1826. this._headers.set('Connection', 'keep-alive');
  1827. this._headers.set('Proxy-Connection', 'keep-alive');
  1828. var auth = this._url.auth && Buffer$4.from(this._url.auth, 'utf8').toString('base64');
  1829. if (auth) this._headers.set('Proxy-Authorization', 'Basic ' + auth);
  1830. };
  1831. util$9.inherits(Proxy$1, Stream$2);
  1832. var instance$6 = {
  1833. setHeader: function(name, value) {
  1834. if (this._state !== 0) return false;
  1835. this._headers.set(name, value);
  1836. return true;
  1837. },
  1838. start: function() {
  1839. if (this._state !== 0) return false;
  1840. this._state = 1;
  1841. var origin = this._origin,
  1842. port = origin.port || PORTS[origin.protocol],
  1843. start = 'CONNECT ' + origin.hostname + ':' + port + ' HTTP/1.1';
  1844. var headers = [start, this._headers.toString(), ''];
  1845. this.emit('data', Buffer$4.from(headers.join('\r\n'), 'utf8'));
  1846. return true;
  1847. },
  1848. pause: function() {
  1849. this._paused = true;
  1850. },
  1851. resume: function() {
  1852. this._paused = false;
  1853. this.emit('drain');
  1854. },
  1855. write: function(chunk) {
  1856. if (!this.writable) return false;
  1857. this._http.parse(chunk);
  1858. if (!this._http.isComplete()) return !this._paused;
  1859. this.statusCode = this._http.statusCode;
  1860. this.headers = this._http.headers;
  1861. if (this.statusCode === 200) {
  1862. this.emit('connect', new Base$5.ConnectEvent());
  1863. } else {
  1864. var message = "Can't establish a connection to the server at " + this._origin.href;
  1865. this.emit('error', new Error(message));
  1866. }
  1867. this.end();
  1868. return !this._paused;
  1869. },
  1870. end: function(chunk) {
  1871. if (!this.writable) return;
  1872. if (chunk !== undefined) this.write(chunk);
  1873. this.readable = this.writable = false;
  1874. this.emit('close');
  1875. this.emit('end');
  1876. },
  1877. destroy: function() {
  1878. this.end();
  1879. }
  1880. };
  1881. for (var key$6 in instance$6)
  1882. Proxy$1.prototype[key$6] = instance$6[key$6];
  1883. var proxy = Proxy$1;
  1884. var Buffer$3 = safeBuffer.exports.Buffer,
  1885. crypto$1 = require$$1__default$1["default"],
  1886. url$1 = require$$2__default$1["default"],
  1887. util$8 = require$$2__default["default"],
  1888. HttpParser$1 = http_parser,
  1889. Base$4 = base,
  1890. Hybi$1 = hybi,
  1891. Proxy = proxy;
  1892. var Client$2 = function(_url, options) {
  1893. this.version = 'hybi-' + Hybi$1.VERSION;
  1894. Hybi$1.call(this, null, _url, options);
  1895. this.readyState = -1;
  1896. this._key = Client$2.generateKey();
  1897. this._accept = Hybi$1.generateAccept(this._key);
  1898. this._http = new HttpParser$1('response');
  1899. var uri = url$1.parse(this.url),
  1900. auth = uri.auth && Buffer$3.from(uri.auth, 'utf8').toString('base64');
  1901. if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0)
  1902. throw new Error(this.url + ' is not a valid WebSocket URL');
  1903. this._pathname = (uri.pathname || '/') + (uri.search || '');
  1904. this._headers.set('Host', uri.host);
  1905. this._headers.set('Upgrade', 'websocket');
  1906. this._headers.set('Connection', 'Upgrade');
  1907. this._headers.set('Sec-WebSocket-Key', this._key);
  1908. this._headers.set('Sec-WebSocket-Version', Hybi$1.VERSION);
  1909. if (this._protocols.length > 0)
  1910. this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', '));
  1911. if (auth)
  1912. this._headers.set('Authorization', 'Basic ' + auth);
  1913. };
  1914. util$8.inherits(Client$2, Hybi$1);
  1915. Client$2.generateKey = function() {
  1916. return crypto$1.randomBytes(16).toString('base64');
  1917. };
  1918. var instance$5 = {
  1919. VALID_PROTOCOLS: ['ws:', 'wss:'],
  1920. proxy: function(origin, options) {
  1921. return new Proxy(this, origin, options);
  1922. },
  1923. start: function() {
  1924. if (this.readyState !== -1) return false;
  1925. this._write(this._handshakeRequest());
  1926. this.readyState = 0;
  1927. return true;
  1928. },
  1929. parse: function(chunk) {
  1930. if (this.readyState === 3) return;
  1931. if (this.readyState > 0) return Hybi$1.prototype.parse.call(this, chunk);
  1932. this._http.parse(chunk);
  1933. if (!this._http.isComplete()) return;
  1934. this._validateHandshake();
  1935. if (this.readyState === 3) return;
  1936. this._open();
  1937. this.parse(this._http.body);
  1938. },
  1939. _handshakeRequest: function() {
  1940. var extensions = this._extensions.generateOffer();
  1941. if (extensions)
  1942. this._headers.set('Sec-WebSocket-Extensions', extensions);
  1943. var start = 'GET ' + this._pathname + ' HTTP/1.1',
  1944. headers = [start, this._headers.toString(), ''];
  1945. return Buffer$3.from(headers.join('\r\n'), 'utf8');
  1946. },
  1947. _failHandshake: function(message) {
  1948. message = 'Error during WebSocket handshake: ' + message;
  1949. this.readyState = 3;
  1950. this.emit('error', new Error(message));
  1951. this.emit('close', new Base$4.CloseEvent(this.ERRORS.protocol_error, message));
  1952. },
  1953. _validateHandshake: function() {
  1954. this.statusCode = this._http.statusCode;
  1955. this.headers = this._http.headers;
  1956. if (this._http.error)
  1957. return this._failHandshake(this._http.error.message);
  1958. if (this._http.statusCode !== 101)
  1959. return this._failHandshake('Unexpected response code: ' + this._http.statusCode);
  1960. var headers = this._http.headers,
  1961. upgrade = headers['upgrade'] || '',
  1962. connection = headers['connection'] || '',
  1963. accept = headers['sec-websocket-accept'] || '',
  1964. protocol = headers['sec-websocket-protocol'] || '';
  1965. if (upgrade === '')
  1966. return this._failHandshake("'Upgrade' header is missing");
  1967. if (upgrade.toLowerCase() !== 'websocket')
  1968. return this._failHandshake("'Upgrade' header value is not 'WebSocket'");
  1969. if (connection === '')
  1970. return this._failHandshake("'Connection' header is missing");
  1971. if (connection.toLowerCase() !== 'upgrade')
  1972. return this._failHandshake("'Connection' header value is not 'Upgrade'");
  1973. if (accept !== this._accept)
  1974. return this._failHandshake('Sec-WebSocket-Accept mismatch');
  1975. this.protocol = null;
  1976. if (protocol !== '') {
  1977. if (this._protocols.indexOf(protocol) < 0)
  1978. return this._failHandshake('Sec-WebSocket-Protocol mismatch');
  1979. else
  1980. this.protocol = protocol;
  1981. }
  1982. try {
  1983. this._extensions.activate(this.headers['sec-websocket-extensions']);
  1984. } catch (e) {
  1985. return this._failHandshake(e.message);
  1986. }
  1987. }
  1988. };
  1989. for (var key$5 in instance$5)
  1990. Client$2.prototype[key$5] = instance$5[key$5];
  1991. var client$1 = Client$2;
  1992. var Buffer$2 = safeBuffer.exports.Buffer,
  1993. Base$3 = base,
  1994. util$7 = require$$2__default["default"];
  1995. var Draft75$2 = function(request, url, options) {
  1996. Base$3.apply(this, arguments);
  1997. this._stage = 0;
  1998. this.version = 'hixie-75';
  1999. this._headers.set('Upgrade', 'WebSocket');
  2000. this._headers.set('Connection', 'Upgrade');
  2001. this._headers.set('WebSocket-Origin', this._request.headers.origin);
  2002. this._headers.set('WebSocket-Location', this.url);
  2003. };
  2004. util$7.inherits(Draft75$2, Base$3);
  2005. var instance$4 = {
  2006. close: function() {
  2007. if (this.readyState === 3) return false;
  2008. this.readyState = 3;
  2009. this.emit('close', new Base$3.CloseEvent(null, null));
  2010. return true;
  2011. },
  2012. parse: function(chunk) {
  2013. if (this.readyState > 1) return;
  2014. this._reader.put(chunk);
  2015. this._reader.eachByte(function(octet) {
  2016. var message;
  2017. switch (this._stage) {
  2018. case -1:
  2019. this._body.push(octet);
  2020. this._sendHandshakeBody();
  2021. break;
  2022. case 0:
  2023. this._parseLeadingByte(octet);
  2024. break;
  2025. case 1:
  2026. this._length = (octet & 0x7F) + 128 * this._length;
  2027. if (this._closing && this._length === 0) {
  2028. return this.close();
  2029. }
  2030. else if ((octet & 0x80) !== 0x80) {
  2031. if (this._length === 0) {
  2032. this._stage = 0;
  2033. }
  2034. else {
  2035. this._skipped = 0;
  2036. this._stage = 2;
  2037. }
  2038. }
  2039. break;
  2040. case 2:
  2041. if (octet === 0xFF) {
  2042. this._stage = 0;
  2043. message = Buffer$2.from(this._buffer).toString('utf8', 0, this._buffer.length);
  2044. this.emit('message', new Base$3.MessageEvent(message));
  2045. }
  2046. else {
  2047. if (this._length) {
  2048. this._skipped += 1;
  2049. if (this._skipped === this._length)
  2050. this._stage = 0;
  2051. } else {
  2052. this._buffer.push(octet);
  2053. if (this._buffer.length > this._maxLength) return this.close();
  2054. }
  2055. }
  2056. break;
  2057. }
  2058. }, this);
  2059. },
  2060. frame: function(buffer) {
  2061. if (this.readyState === 0) return this._queue([buffer]);
  2062. if (this.readyState > 1) return false;
  2063. if (typeof buffer !== 'string') buffer = buffer.toString();
  2064. var length = Buffer$2.byteLength(buffer),
  2065. frame = Buffer$2.allocUnsafe(length + 2);
  2066. frame[0] = 0x00;
  2067. frame.write(buffer, 1);
  2068. frame[frame.length - 1] = 0xFF;
  2069. this._write(frame);
  2070. return true;
  2071. },
  2072. _handshakeResponse: function() {
  2073. var start = 'HTTP/1.1 101 Web Socket Protocol Handshake',
  2074. headers = [start, this._headers.toString(), ''];
  2075. return Buffer$2.from(headers.join('\r\n'), 'utf8');
  2076. },
  2077. _parseLeadingByte: function(octet) {
  2078. if ((octet & 0x80) === 0x80) {
  2079. this._length = 0;
  2080. this._stage = 1;
  2081. } else {
  2082. delete this._length;
  2083. delete this._skipped;
  2084. this._buffer = [];
  2085. this._stage = 2;
  2086. }
  2087. }
  2088. };
  2089. for (var key$4 in instance$4)
  2090. Draft75$2.prototype[key$4] = instance$4[key$4];
  2091. var draft75 = Draft75$2;
  2092. var Buffer$1 = safeBuffer.exports.Buffer,
  2093. Base$2 = base,
  2094. Draft75$1 = draft75,
  2095. crypto = require$$1__default$1["default"],
  2096. util$6 = require$$2__default["default"];
  2097. var numberFromKey = function(key) {
  2098. return parseInt((key.match(/[0-9]/g) || []).join(''), 10);
  2099. };
  2100. var spacesInKey = function(key) {
  2101. return (key.match(/ /g) || []).length;
  2102. };
  2103. var Draft76$1 = function(request, url, options) {
  2104. Draft75$1.apply(this, arguments);
  2105. this._stage = -1;
  2106. this._body = [];
  2107. this.version = 'hixie-76';
  2108. this._headers.clear();
  2109. this._headers.set('Upgrade', 'WebSocket');
  2110. this._headers.set('Connection', 'Upgrade');
  2111. this._headers.set('Sec-WebSocket-Origin', this._request.headers.origin);
  2112. this._headers.set('Sec-WebSocket-Location', this.url);
  2113. };
  2114. util$6.inherits(Draft76$1, Draft75$1);
  2115. var instance$3 = {
  2116. BODY_SIZE: 8,
  2117. start: function() {
  2118. if (!Draft75$1.prototype.start.call(this)) return false;
  2119. this._started = true;
  2120. this._sendHandshakeBody();
  2121. return true;
  2122. },
  2123. close: function() {
  2124. if (this.readyState === 3) return false;
  2125. if (this.readyState === 1) this._write(Buffer$1.from([0xFF, 0x00]));
  2126. this.readyState = 3;
  2127. this.emit('close', new Base$2.CloseEvent(null, null));
  2128. return true;
  2129. },
  2130. _handshakeResponse: function() {
  2131. var headers = this._request.headers,
  2132. key1 = headers['sec-websocket-key1'],
  2133. key2 = headers['sec-websocket-key2'];
  2134. if (!key1) throw new Error('Missing required header: Sec-WebSocket-Key1');
  2135. if (!key2) throw new Error('Missing required header: Sec-WebSocket-Key2');
  2136. var number1 = numberFromKey(key1),
  2137. spaces1 = spacesInKey(key1),
  2138. number2 = numberFromKey(key2),
  2139. spaces2 = spacesInKey(key2);
  2140. if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0)
  2141. throw new Error('Client sent invalid Sec-WebSocket-Key headers');
  2142. this._keyValues = [number1 / spaces1, number2 / spaces2];
  2143. var start = 'HTTP/1.1 101 WebSocket Protocol Handshake',
  2144. headers = [start, this._headers.toString(), ''];
  2145. return Buffer$1.from(headers.join('\r\n'), 'binary');
  2146. },
  2147. _handshakeSignature: function() {
  2148. if (this._body.length < this.BODY_SIZE) return null;
  2149. var md5 = crypto.createHash('md5'),
  2150. buffer = Buffer$1.allocUnsafe(8 + this.BODY_SIZE);
  2151. buffer.writeUInt32BE(this._keyValues[0], 0);
  2152. buffer.writeUInt32BE(this._keyValues[1], 4);
  2153. Buffer$1.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE);
  2154. md5.update(buffer);
  2155. return Buffer$1.from(md5.digest('binary'), 'binary');
  2156. },
  2157. _sendHandshakeBody: function() {
  2158. if (!this._started) return;
  2159. var signature = this._handshakeSignature();
  2160. if (!signature) return;
  2161. this._write(signature);
  2162. this._stage = 0;
  2163. this._open();
  2164. if (this._body.length > this.BODY_SIZE)
  2165. this.parse(this._body.slice(this.BODY_SIZE));
  2166. },
  2167. _parseLeadingByte: function(octet) {
  2168. if (octet !== 0xFF)
  2169. return Draft75$1.prototype._parseLeadingByte.call(this, octet);
  2170. this._closing = true;
  2171. this._length = 0;
  2172. this._stage = 1;
  2173. }
  2174. };
  2175. for (var key$3 in instance$3)
  2176. Draft76$1.prototype[key$3] = instance$3[key$3];
  2177. var draft76 = Draft76$1;
  2178. var util$5 = require$$2__default["default"],
  2179. HttpParser = http_parser,
  2180. Base$1 = base,
  2181. Draft75 = draft75,
  2182. Draft76 = draft76,
  2183. Hybi = hybi;
  2184. var Server$1 = function(options) {
  2185. Base$1.call(this, null, null, options);
  2186. this._http = new HttpParser('request');
  2187. };
  2188. util$5.inherits(Server$1, Base$1);
  2189. var instance$2 = {
  2190. EVENTS: ['open', 'message', 'error', 'close', 'ping', 'pong'],
  2191. _bindEventListeners: function() {
  2192. this.messages.on('error', function() {});
  2193. this.on('error', function() {});
  2194. },
  2195. parse: function(chunk) {
  2196. if (this._delegate) return this._delegate.parse(chunk);
  2197. this._http.parse(chunk);
  2198. if (!this._http.isComplete()) return;
  2199. this.method = this._http.method;
  2200. this.url = this._http.url;
  2201. this.headers = this._http.headers;
  2202. this.body = this._http.body;
  2203. var self = this;
  2204. this._delegate = Server$1.http(this, this._options);
  2205. this._delegate.messages = this.messages;
  2206. this._delegate.io = this.io;
  2207. this._open();
  2208. this.EVENTS.forEach(function(event) {
  2209. this._delegate.on(event, function(e) { self.emit(event, e); });
  2210. }, this);
  2211. this.protocol = this._delegate.protocol;
  2212. this.version = this._delegate.version;
  2213. this.parse(this._http.body);
  2214. this.emit('connect', new Base$1.ConnectEvent());
  2215. },
  2216. _open: function() {
  2217. this.__queue.forEach(function(msg) {
  2218. this._delegate[msg[0]].apply(this._delegate, msg[1]);
  2219. }, this);
  2220. this.__queue = [];
  2221. }
  2222. };
  2223. ['addExtension', 'setHeader', 'start', 'frame', 'text', 'binary', 'ping', 'close'].forEach(function(method) {
  2224. instance$2[method] = function() {
  2225. if (this._delegate) {
  2226. return this._delegate[method].apply(this._delegate, arguments);
  2227. } else {
  2228. this.__queue.push([method, arguments]);
  2229. return true;
  2230. }
  2231. };
  2232. });
  2233. for (var key$2 in instance$2)
  2234. Server$1.prototype[key$2] = instance$2[key$2];
  2235. Server$1.isSecureRequest = function(request) {
  2236. if (request.connection && request.connection.authorized !== undefined) return true;
  2237. if (request.socket && request.socket.secure) return true;
  2238. var headers = request.headers;
  2239. if (!headers) return false;
  2240. if (headers['https'] === 'on') return true;
  2241. if (headers['x-forwarded-ssl'] === 'on') return true;
  2242. if (headers['x-forwarded-scheme'] === 'https') return true;
  2243. if (headers['x-forwarded-proto'] === 'https') return true;
  2244. return false;
  2245. };
  2246. Server$1.determineUrl = function(request) {
  2247. var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:';
  2248. return scheme + '//' + request.headers.host + request.url;
  2249. };
  2250. Server$1.http = function(request, options) {
  2251. options = options || {};
  2252. if (options.requireMasking === undefined) options.requireMasking = true;
  2253. var headers = request.headers,
  2254. version = headers['sec-websocket-version'],
  2255. key = headers['sec-websocket-key'],
  2256. key1 = headers['sec-websocket-key1'],
  2257. key2 = headers['sec-websocket-key2'],
  2258. url = this.determineUrl(request);
  2259. if (version || key)
  2260. return new Hybi(request, url, options);
  2261. else if (key1 || key2)
  2262. return new Draft76(request, url, options);
  2263. else
  2264. return new Draft75(request, url, options);
  2265. };
  2266. var server = Server$1;
  2267. // Protocol references:
  2268. //
  2269. // * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75
  2270. // * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
  2271. // * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17
  2272. var Base = base,
  2273. Client$1 = client$1,
  2274. Server = server;
  2275. var Driver = {
  2276. client: function(url, options) {
  2277. options = options || {};
  2278. if (options.masking === undefined) options.masking = true;
  2279. return new Client$1(url, options);
  2280. },
  2281. server: function(options) {
  2282. options = options || {};
  2283. if (options.requireMasking === undefined) options.requireMasking = true;
  2284. return new Server(options);
  2285. },
  2286. http: function() {
  2287. return Server.http.apply(Server, arguments);
  2288. },
  2289. isSecureRequest: function(request) {
  2290. return Server.isSecureRequest(request);
  2291. },
  2292. isWebSocket: function(request) {
  2293. return Base.isWebSocket(request);
  2294. },
  2295. validateOptions: function(options, validKeys) {
  2296. Base.validateOptions(options, validKeys);
  2297. }
  2298. };
  2299. var driver$4 = Driver;
  2300. var Event$3 = function(eventType, options) {
  2301. this.type = eventType;
  2302. for (var key in options)
  2303. this[key] = options[key];
  2304. };
  2305. Event$3.prototype.initEvent = function(eventType, canBubble, cancelable) {
  2306. this.type = eventType;
  2307. this.bubbles = canBubble;
  2308. this.cancelable = cancelable;
  2309. };
  2310. Event$3.prototype.stopPropagation = function() {};
  2311. Event$3.prototype.preventDefault = function() {};
  2312. Event$3.CAPTURING_PHASE = 1;
  2313. Event$3.AT_TARGET = 2;
  2314. Event$3.BUBBLING_PHASE = 3;
  2315. var event = Event$3;
  2316. var Event$2 = event;
  2317. var EventTarget$2 = {
  2318. onopen: null,
  2319. onmessage: null,
  2320. onerror: null,
  2321. onclose: null,
  2322. addEventListener: function(eventType, listener, useCapture) {
  2323. this.on(eventType, listener);
  2324. },
  2325. removeEventListener: function(eventType, listener, useCapture) {
  2326. this.removeListener(eventType, listener);
  2327. },
  2328. dispatchEvent: function(event) {
  2329. event.target = event.currentTarget = this;
  2330. event.eventPhase = Event$2.AT_TARGET;
  2331. if (this['on' + event.type])
  2332. this['on' + event.type](event);
  2333. this.emit(event.type, event);
  2334. }
  2335. };
  2336. var event_target = EventTarget$2;
  2337. var Stream$1 = require$$0__default$1["default"].Stream,
  2338. util$4 = require$$2__default["default"],
  2339. driver$3 = driver$4,
  2340. EventTarget$1 = event_target,
  2341. Event$1 = event;
  2342. var API$3 = function(options) {
  2343. options = options || {};
  2344. driver$3.validateOptions(options, ['headers', 'extensions', 'maxLength', 'ping', 'proxy', 'tls', 'ca']);
  2345. this.readable = this.writable = true;
  2346. var headers = options.headers;
  2347. if (headers) {
  2348. for (var name in headers) this._driver.setHeader(name, headers[name]);
  2349. }
  2350. var extensions = options.extensions;
  2351. if (extensions) {
  2352. [].concat(extensions).forEach(this._driver.addExtension, this._driver);
  2353. }
  2354. this._ping = options.ping;
  2355. this._pingId = 0;
  2356. this.readyState = API$3.CONNECTING;
  2357. this.bufferedAmount = 0;
  2358. this.protocol = '';
  2359. this.url = this._driver.url;
  2360. this.version = this._driver.version;
  2361. var self = this;
  2362. this._driver.on('open', function(e) { self._open(); });
  2363. this._driver.on('message', function(e) { self._receiveMessage(e.data); });
  2364. this._driver.on('close', function(e) { self._beginClose(e.reason, e.code); });
  2365. this._driver.on('error', function(error) {
  2366. self._emitError(error.message);
  2367. });
  2368. this.on('error', function() {});
  2369. this._driver.messages.on('drain', function() {
  2370. self.emit('drain');
  2371. });
  2372. if (this._ping)
  2373. this._pingTimer = setInterval(function() {
  2374. self._pingId += 1;
  2375. self.ping(self._pingId.toString());
  2376. }, this._ping * 1000);
  2377. this._configureStream();
  2378. if (!this._proxy) {
  2379. this._stream.pipe(this._driver.io);
  2380. this._driver.io.pipe(this._stream);
  2381. }
  2382. };
  2383. util$4.inherits(API$3, Stream$1);
  2384. API$3.CONNECTING = 0;
  2385. API$3.OPEN = 1;
  2386. API$3.CLOSING = 2;
  2387. API$3.CLOSED = 3;
  2388. API$3.CLOSE_TIMEOUT = 30000;
  2389. var instance$1 = {
  2390. write: function(data) {
  2391. return this.send(data);
  2392. },
  2393. end: function(data) {
  2394. if (data !== undefined) this.send(data);
  2395. this.close();
  2396. },
  2397. pause: function() {
  2398. return this._driver.messages.pause();
  2399. },
  2400. resume: function() {
  2401. return this._driver.messages.resume();
  2402. },
  2403. send: function(data) {
  2404. if (this.readyState > API$3.OPEN) return false;
  2405. if (!(data instanceof Buffer)) data = String(data);
  2406. return this._driver.messages.write(data);
  2407. },
  2408. ping: function(message, callback) {
  2409. if (this.readyState > API$3.OPEN) return false;
  2410. return this._driver.ping(message, callback);
  2411. },
  2412. close: function(code, reason) {
  2413. if (code === undefined) code = 1000;
  2414. if (reason === undefined) reason = '';
  2415. if (code !== 1000 && (code < 3000 || code > 4999))
  2416. throw new Error("Failed to execute 'close' on WebSocket: " +
  2417. "The code must be either 1000, or between 3000 and 4999. " +
  2418. code + " is neither.");
  2419. if (this.readyState < API$3.CLOSING) {
  2420. var self = this;
  2421. this._closeTimer = setTimeout(function() {
  2422. self._beginClose('', 1006);
  2423. }, API$3.CLOSE_TIMEOUT);
  2424. }
  2425. if (this.readyState !== API$3.CLOSED) this.readyState = API$3.CLOSING;
  2426. this._driver.close(reason, code);
  2427. },
  2428. _configureStream: function() {
  2429. var self = this;
  2430. this._stream.setTimeout(0);
  2431. this._stream.setNoDelay(true);
  2432. ['close', 'end'].forEach(function(event) {
  2433. this._stream.on(event, function() { self._finalizeClose(); });
  2434. }, this);
  2435. this._stream.on('error', function(error) {
  2436. self._emitError('Network error: ' + self.url + ': ' + error.message);
  2437. self._finalizeClose();
  2438. });
  2439. },
  2440. _open: function() {
  2441. if (this.readyState !== API$3.CONNECTING) return;
  2442. this.readyState = API$3.OPEN;
  2443. this.protocol = this._driver.protocol || '';
  2444. var event = new Event$1('open');
  2445. event.initEvent('open', false, false);
  2446. this.dispatchEvent(event);
  2447. },
  2448. _receiveMessage: function(data) {
  2449. if (this.readyState > API$3.OPEN) return false;
  2450. if (this.readable) this.emit('data', data);
  2451. var event = new Event$1('message', { data: data });
  2452. event.initEvent('message', false, false);
  2453. this.dispatchEvent(event);
  2454. },
  2455. _emitError: function(message) {
  2456. if (this.readyState >= API$3.CLOSING) return;
  2457. var event = new Event$1('error', { message: message });
  2458. event.initEvent('error', false, false);
  2459. this.dispatchEvent(event);
  2460. },
  2461. _beginClose: function(reason, code) {
  2462. if (this.readyState === API$3.CLOSED) return;
  2463. this.readyState = API$3.CLOSING;
  2464. this._closeParams = [reason, code];
  2465. if (this._stream) {
  2466. this._stream.destroy();
  2467. if (!this._stream.readable) this._finalizeClose();
  2468. }
  2469. },
  2470. _finalizeClose: function() {
  2471. if (this.readyState === API$3.CLOSED) return;
  2472. this.readyState = API$3.CLOSED;
  2473. if (this._closeTimer) clearTimeout(this._closeTimer);
  2474. if (this._pingTimer) clearInterval(this._pingTimer);
  2475. if (this._stream) this._stream.end();
  2476. if (this.readable) this.emit('end');
  2477. this.readable = this.writable = false;
  2478. var reason = this._closeParams ? this._closeParams[0] : '',
  2479. code = this._closeParams ? this._closeParams[1] : 1006;
  2480. var event = new Event$1('close', { code: code, reason: reason });
  2481. event.initEvent('close', false, false);
  2482. this.dispatchEvent(event);
  2483. }
  2484. };
  2485. for (var method$1 in instance$1) API$3.prototype[method$1] = instance$1[method$1];
  2486. for (var key$1 in EventTarget$1) API$3.prototype[key$1] = EventTarget$1[key$1];
  2487. var api = API$3;
  2488. var util$3 = require$$2__default["default"],
  2489. net = require$$1__default$2["default"],
  2490. tls = require$$2__default$2["default"],
  2491. url = require$$2__default$1["default"],
  2492. driver$2 = driver$4,
  2493. API$2 = api;
  2494. var DEFAULT_PORTS = { 'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443 },
  2495. SECURE_PROTOCOLS = ['https:', 'wss:'];
  2496. var Client = function(_url, protocols, options) {
  2497. options = options || {};
  2498. this.url = _url;
  2499. this._driver = driver$2.client(this.url, { maxLength: options.maxLength, protocols: protocols });
  2500. ['open', 'error'].forEach(function(event) {
  2501. this._driver.on(event, function() {
  2502. self.headers = self._driver.headers;
  2503. self.statusCode = self._driver.statusCode;
  2504. });
  2505. }, this);
  2506. var proxy = options.proxy || {},
  2507. endpoint = url.parse(proxy.origin || this.url),
  2508. port = endpoint.port || DEFAULT_PORTS[endpoint.protocol],
  2509. secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0,
  2510. onConnect = function() { self._onConnect(); },
  2511. netOptions = options.net || {},
  2512. originTLS = options.tls || {},
  2513. socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS,
  2514. self = this;
  2515. netOptions.host = socketTLS.host = endpoint.hostname;
  2516. netOptions.port = socketTLS.port = port;
  2517. originTLS.ca = originTLS.ca || options.ca;
  2518. socketTLS.servername = socketTLS.servername || endpoint.hostname;
  2519. this._stream = secure
  2520. ? tls.connect(socketTLS, onConnect)
  2521. : net.connect(netOptions, onConnect);
  2522. if (proxy.origin) this._configureProxy(proxy, originTLS);
  2523. API$2.call(this, options);
  2524. };
  2525. util$3.inherits(Client, API$2);
  2526. Client.prototype._onConnect = function() {
  2527. var worker = this._proxy || this._driver;
  2528. worker.start();
  2529. };
  2530. Client.prototype._configureProxy = function(proxy, originTLS) {
  2531. var uri = url.parse(this.url),
  2532. secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0,
  2533. self = this,
  2534. name;
  2535. this._proxy = this._driver.proxy(proxy.origin);
  2536. if (proxy.headers) {
  2537. for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]);
  2538. }
  2539. this._proxy.pipe(this._stream, { end: false });
  2540. this._stream.pipe(this._proxy);
  2541. this._proxy.on('connect', function() {
  2542. if (secure) {
  2543. var options = { socket: self._stream, servername: uri.hostname };
  2544. for (name in originTLS) options[name] = originTLS[name];
  2545. self._stream = tls.connect(options);
  2546. self._configureStream();
  2547. }
  2548. self._driver.io.pipe(self._stream);
  2549. self._stream.pipe(self._driver.io);
  2550. self._driver.start();
  2551. });
  2552. this._proxy.on('error', function(error) {
  2553. self._driver.emit('error', error);
  2554. });
  2555. };
  2556. var client = Client;
  2557. var Stream = require$$0__default$1["default"].Stream,
  2558. util$2 = require$$2__default["default"],
  2559. driver$1 = driver$4,
  2560. Headers = headers,
  2561. API$1 = api,
  2562. EventTarget = event_target,
  2563. Event = event;
  2564. var EventSource = function(request, response, options) {
  2565. this.writable = true;
  2566. options = options || {};
  2567. this._stream = response.socket;
  2568. this._ping = options.ping || this.DEFAULT_PING;
  2569. this._retry = options.retry || this.DEFAULT_RETRY;
  2570. var scheme = driver$1.isSecureRequest(request) ? 'https:' : 'http:';
  2571. this.url = scheme + '//' + request.headers.host + request.url;
  2572. this.lastEventId = request.headers['last-event-id'] || '';
  2573. this.readyState = API$1.CONNECTING;
  2574. var headers = new Headers(),
  2575. self = this;
  2576. if (options.headers) {
  2577. for (var key in options.headers) headers.set(key, options.headers[key]);
  2578. }
  2579. if (!this._stream || !this._stream.writable) return;
  2580. process.nextTick(function() { self._open(); });
  2581. this._stream.setTimeout(0);
  2582. this._stream.setNoDelay(true);
  2583. var handshake = 'HTTP/1.1 200 OK\r\n' +
  2584. 'Content-Type: text/event-stream\r\n' +
  2585. 'Cache-Control: no-cache, no-store\r\n' +
  2586. 'Connection: close\r\n' +
  2587. headers.toString() +
  2588. '\r\n' +
  2589. 'retry: ' + Math.floor(this._retry * 1000) + '\r\n\r\n';
  2590. this._write(handshake);
  2591. this._stream.on('drain', function() { self.emit('drain'); });
  2592. if (this._ping)
  2593. this._pingTimer = setInterval(function() { self.ping(); }, this._ping * 1000);
  2594. ['error', 'end'].forEach(function(event) {
  2595. self._stream.on(event, function() { self.close(); });
  2596. });
  2597. };
  2598. util$2.inherits(EventSource, Stream);
  2599. EventSource.isEventSource = function(request) {
  2600. if (request.method !== 'GET') return false;
  2601. var accept = (request.headers.accept || '').split(/\s*,\s*/);
  2602. return accept.indexOf('text/event-stream') >= 0;
  2603. };
  2604. var instance = {
  2605. DEFAULT_PING: 10,
  2606. DEFAULT_RETRY: 5,
  2607. _write: function(chunk) {
  2608. if (!this.writable) return false;
  2609. try {
  2610. return this._stream.write(chunk, 'utf8');
  2611. } catch (e) {
  2612. return false;
  2613. }
  2614. },
  2615. _open: function() {
  2616. if (this.readyState !== API$1.CONNECTING) return;
  2617. this.readyState = API$1.OPEN;
  2618. var event = new Event('open');
  2619. event.initEvent('open', false, false);
  2620. this.dispatchEvent(event);
  2621. },
  2622. write: function(message) {
  2623. return this.send(message);
  2624. },
  2625. end: function(message) {
  2626. if (message !== undefined) this.write(message);
  2627. this.close();
  2628. },
  2629. send: function(message, options) {
  2630. if (this.readyState > API$1.OPEN) return false;
  2631. message = String(message).replace(/(\r\n|\r|\n)/g, '$1data: ');
  2632. options = options || {};
  2633. var frame = '';
  2634. if (options.event) frame += 'event: ' + options.event + '\r\n';
  2635. if (options.id) frame += 'id: ' + options.id + '\r\n';
  2636. frame += 'data: ' + message + '\r\n\r\n';
  2637. return this._write(frame);
  2638. },
  2639. ping: function() {
  2640. return this._write(':\r\n\r\n');
  2641. },
  2642. close: function() {
  2643. if (this.readyState > API$1.OPEN) return false;
  2644. this.readyState = API$1.CLOSED;
  2645. this.writable = false;
  2646. if (this._pingTimer) clearInterval(this._pingTimer);
  2647. if (this._stream) this._stream.end();
  2648. var event = new Event('close');
  2649. event.initEvent('close', false, false);
  2650. this.dispatchEvent(event);
  2651. return true;
  2652. }
  2653. };
  2654. for (var method in instance) EventSource.prototype[method] = instance[method];
  2655. for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key];
  2656. var eventsource = EventSource;
  2657. var util$1 = require$$2__default["default"],
  2658. driver = driver$4,
  2659. API = api;
  2660. var WebSocket$1 = function(request, socket, body, protocols, options) {
  2661. options = options || {};
  2662. this._stream = socket;
  2663. this._driver = driver.http(request, { maxLength: options.maxLength, protocols: protocols });
  2664. var self = this;
  2665. if (!this._stream || !this._stream.writable) return;
  2666. if (!this._stream.readable) return this._stream.end();
  2667. var catchup = function() { self._stream.removeListener('data', catchup); };
  2668. this._stream.on('data', catchup);
  2669. API.call(this, options);
  2670. process.nextTick(function() {
  2671. self._driver.start();
  2672. self._driver.io.write(body);
  2673. });
  2674. };
  2675. util$1.inherits(WebSocket$1, API);
  2676. WebSocket$1.isWebSocket = function(request) {
  2677. return driver.isWebSocket(request);
  2678. };
  2679. WebSocket$1.validateOptions = function(options, validKeys) {
  2680. driver.validateOptions(options, validKeys);
  2681. };
  2682. WebSocket$1.WebSocket = WebSocket$1;
  2683. WebSocket$1.Client = client;
  2684. WebSocket$1.EventSource = eventsource;
  2685. var websocket = WebSocket$1;
  2686. Object.defineProperty(index_standalone, '__esModule', { value: true });
  2687. var Websocket = websocket;
  2688. var util = require$$1__default$3["default"];
  2689. var logger$1 = require$$2__default$3["default"];
  2690. var component = require$$3__default["default"];
  2691. function _interopDefaultLegacy$1 (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  2692. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy$1(Websocket);
  2693. /**
  2694. * @license
  2695. * Copyright 2017 Google LLC
  2696. *
  2697. * Licensed under the Apache License, Version 2.0 (the "License");
  2698. * you may not use this file except in compliance with the License.
  2699. * You may obtain a copy of the License at
  2700. *
  2701. * http://www.apache.org/licenses/LICENSE-2.0
  2702. *
  2703. * Unless required by applicable law or agreed to in writing, software
  2704. * distributed under the License is distributed on an "AS IS" BASIS,
  2705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2706. * See the License for the specific language governing permissions and
  2707. * limitations under the License.
  2708. */
  2709. const PROTOCOL_VERSION = '5';
  2710. const VERSION_PARAM = 'v';
  2711. const TRANSPORT_SESSION_PARAM = 's';
  2712. const REFERER_PARAM = 'r';
  2713. const FORGE_REF = 'f';
  2714. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  2715. // firebase.corp.google.com
  2716. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  2717. const LAST_SESSION_PARAM = 'ls';
  2718. const APPLICATION_ID_PARAM = 'p';
  2719. const APP_CHECK_TOKEN_PARAM = 'ac';
  2720. const WEBSOCKET = 'websocket';
  2721. const LONG_POLLING = 'long_polling';
  2722. /**
  2723. * @license
  2724. * Copyright 2017 Google LLC
  2725. *
  2726. * Licensed under the Apache License, Version 2.0 (the "License");
  2727. * you may not use this file except in compliance with the License.
  2728. * You may obtain a copy of the License at
  2729. *
  2730. * http://www.apache.org/licenses/LICENSE-2.0
  2731. *
  2732. * Unless required by applicable law or agreed to in writing, software
  2733. * distributed under the License is distributed on an "AS IS" BASIS,
  2734. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2735. * See the License for the specific language governing permissions and
  2736. * limitations under the License.
  2737. */
  2738. /**
  2739. * Wraps a DOM Storage object and:
  2740. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  2741. * - prefixes names with "firebase:" to avoid collisions with app data.
  2742. *
  2743. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  2744. * and one for localStorage.
  2745. *
  2746. */
  2747. class DOMStorageWrapper {
  2748. /**
  2749. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  2750. */
  2751. constructor(domStorage_) {
  2752. this.domStorage_ = domStorage_;
  2753. // Use a prefix to avoid collisions with other stuff saved by the app.
  2754. this.prefix_ = 'firebase:';
  2755. }
  2756. /**
  2757. * @param key - The key to save the value under
  2758. * @param value - The value being stored, or null to remove the key.
  2759. */
  2760. set(key, value) {
  2761. if (value == null) {
  2762. this.domStorage_.removeItem(this.prefixedName_(key));
  2763. }
  2764. else {
  2765. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  2766. }
  2767. }
  2768. /**
  2769. * @returns The value that was stored under this key, or null
  2770. */
  2771. get(key) {
  2772. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  2773. if (storedVal == null) {
  2774. return null;
  2775. }
  2776. else {
  2777. return util.jsonEval(storedVal);
  2778. }
  2779. }
  2780. remove(key) {
  2781. this.domStorage_.removeItem(this.prefixedName_(key));
  2782. }
  2783. prefixedName_(name) {
  2784. return this.prefix_ + name;
  2785. }
  2786. toString() {
  2787. return this.domStorage_.toString();
  2788. }
  2789. }
  2790. /**
  2791. * @license
  2792. * Copyright 2017 Google LLC
  2793. *
  2794. * Licensed under the Apache License, Version 2.0 (the "License");
  2795. * you may not use this file except in compliance with the License.
  2796. * You may obtain a copy of the License at
  2797. *
  2798. * http://www.apache.org/licenses/LICENSE-2.0
  2799. *
  2800. * Unless required by applicable law or agreed to in writing, software
  2801. * distributed under the License is distributed on an "AS IS" BASIS,
  2802. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2803. * See the License for the specific language governing permissions and
  2804. * limitations under the License.
  2805. */
  2806. /**
  2807. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  2808. * (TODO: create interface for both to implement).
  2809. */
  2810. class MemoryStorage {
  2811. constructor() {
  2812. this.cache_ = {};
  2813. this.isInMemoryStorage = true;
  2814. }
  2815. set(key, value) {
  2816. if (value == null) {
  2817. delete this.cache_[key];
  2818. }
  2819. else {
  2820. this.cache_[key] = value;
  2821. }
  2822. }
  2823. get(key) {
  2824. if (util.contains(this.cache_, key)) {
  2825. return this.cache_[key];
  2826. }
  2827. return null;
  2828. }
  2829. remove(key) {
  2830. delete this.cache_[key];
  2831. }
  2832. }
  2833. /**
  2834. * @license
  2835. * Copyright 2017 Google LLC
  2836. *
  2837. * Licensed under the Apache License, Version 2.0 (the "License");
  2838. * you may not use this file except in compliance with the License.
  2839. * You may obtain a copy of the License at
  2840. *
  2841. * http://www.apache.org/licenses/LICENSE-2.0
  2842. *
  2843. * Unless required by applicable law or agreed to in writing, software
  2844. * distributed under the License is distributed on an "AS IS" BASIS,
  2845. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2846. * See the License for the specific language governing permissions and
  2847. * limitations under the License.
  2848. */
  2849. /**
  2850. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  2851. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  2852. * to reflect this type
  2853. *
  2854. * @param domStorageName - Name of the underlying storage object
  2855. * (e.g. 'localStorage' or 'sessionStorage').
  2856. * @returns Turning off type information until a common interface is defined.
  2857. */
  2858. const createStoragefor = function (domStorageName) {
  2859. try {
  2860. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  2861. // so it must be inside the try/catch.
  2862. if (typeof window !== 'undefined' &&
  2863. typeof window[domStorageName] !== 'undefined') {
  2864. // Need to test cache. Just because it's here doesn't mean it works
  2865. const domStorage = window[domStorageName];
  2866. domStorage.setItem('firebase:sentinel', 'cache');
  2867. domStorage.removeItem('firebase:sentinel');
  2868. return new DOMStorageWrapper(domStorage);
  2869. }
  2870. }
  2871. catch (e) { }
  2872. // Failed to create wrapper. Just return in-memory storage.
  2873. // TODO: log?
  2874. return new MemoryStorage();
  2875. };
  2876. /** A storage object that lasts across sessions */
  2877. const PersistentStorage = createStoragefor('localStorage');
  2878. /** A storage object that only lasts one session */
  2879. const SessionStorage = createStoragefor('sessionStorage');
  2880. /**
  2881. * @license
  2882. * Copyright 2017 Google LLC
  2883. *
  2884. * Licensed under the Apache License, Version 2.0 (the "License");
  2885. * you may not use this file except in compliance with the License.
  2886. * You may obtain a copy of the License at
  2887. *
  2888. * http://www.apache.org/licenses/LICENSE-2.0
  2889. *
  2890. * Unless required by applicable law or agreed to in writing, software
  2891. * distributed under the License is distributed on an "AS IS" BASIS,
  2892. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2893. * See the License for the specific language governing permissions and
  2894. * limitations under the License.
  2895. */
  2896. const logClient$1 = new logger$1.Logger('@firebase/database');
  2897. /**
  2898. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  2899. */
  2900. const LUIDGenerator = (function () {
  2901. let id = 1;
  2902. return function () {
  2903. return id++;
  2904. };
  2905. })();
  2906. /**
  2907. * Sha1 hash of the input string
  2908. * @param str - The string to hash
  2909. * @returns {!string} The resulting hash
  2910. */
  2911. const sha1 = function (str) {
  2912. const utf8Bytes = util.stringToByteArray(str);
  2913. const sha1 = new util.Sha1();
  2914. sha1.update(utf8Bytes);
  2915. const sha1Bytes = sha1.digest();
  2916. return util.base64.encodeByteArray(sha1Bytes);
  2917. };
  2918. const buildLogMessage_ = function (...varArgs) {
  2919. let message = '';
  2920. for (let i = 0; i < varArgs.length; i++) {
  2921. const arg = varArgs[i];
  2922. if (Array.isArray(arg) ||
  2923. (arg &&
  2924. typeof arg === 'object' &&
  2925. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2926. typeof arg.length === 'number')) {
  2927. message += buildLogMessage_.apply(null, arg);
  2928. }
  2929. else if (typeof arg === 'object') {
  2930. message += util.stringify(arg);
  2931. }
  2932. else {
  2933. message += arg;
  2934. }
  2935. message += ' ';
  2936. }
  2937. return message;
  2938. };
  2939. /**
  2940. * Use this for all debug messages in Firebase.
  2941. */
  2942. let logger = null;
  2943. /**
  2944. * Flag to check for log availability on first log message
  2945. */
  2946. let firstLog_ = true;
  2947. /**
  2948. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  2949. * @param logger_ - A flag to turn on logging, or a custom logger
  2950. * @param persistent - Whether or not to persist logging settings across refreshes
  2951. */
  2952. const enableLogging$1 = function (logger_, persistent) {
  2953. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  2954. if (logger_ === true) {
  2955. logClient$1.logLevel = logger$1.LogLevel.VERBOSE;
  2956. logger = logClient$1.log.bind(logClient$1);
  2957. if (persistent) {
  2958. SessionStorage.set('logging_enabled', true);
  2959. }
  2960. }
  2961. else if (typeof logger_ === 'function') {
  2962. logger = logger_;
  2963. }
  2964. else {
  2965. logger = null;
  2966. SessionStorage.remove('logging_enabled');
  2967. }
  2968. };
  2969. const log = function (...varArgs) {
  2970. if (firstLog_ === true) {
  2971. firstLog_ = false;
  2972. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  2973. enableLogging$1(true);
  2974. }
  2975. }
  2976. if (logger) {
  2977. const message = buildLogMessage_.apply(null, varArgs);
  2978. logger(message);
  2979. }
  2980. };
  2981. const logWrapper = function (prefix) {
  2982. return function (...varArgs) {
  2983. log(prefix, ...varArgs);
  2984. };
  2985. };
  2986. const error = function (...varArgs) {
  2987. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  2988. logClient$1.error(message);
  2989. };
  2990. const fatal = function (...varArgs) {
  2991. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  2992. logClient$1.error(message);
  2993. throw new Error(message);
  2994. };
  2995. const warn$1 = function (...varArgs) {
  2996. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  2997. logClient$1.warn(message);
  2998. };
  2999. /**
  3000. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  3001. * does not use https.
  3002. */
  3003. const warnIfPageIsSecure = function () {
  3004. // Be very careful accessing browser globals. Who knows what may or may not exist.
  3005. if (typeof window !== 'undefined' &&
  3006. window.location &&
  3007. window.location.protocol &&
  3008. window.location.protocol.indexOf('https:') !== -1) {
  3009. warn$1('Insecure Firebase access from a secure page. ' +
  3010. 'Please use https in calls to new Firebase().');
  3011. }
  3012. };
  3013. /**
  3014. * Returns true if data is NaN, or +/- Infinity.
  3015. */
  3016. const isInvalidJSONNumber = function (data) {
  3017. return (typeof data === 'number' &&
  3018. (data !== data || // NaN
  3019. data === Number.POSITIVE_INFINITY ||
  3020. data === Number.NEGATIVE_INFINITY));
  3021. };
  3022. const executeWhenDOMReady = function (fn) {
  3023. if (util.isNodeSdk() || document.readyState === 'complete') {
  3024. fn();
  3025. }
  3026. else {
  3027. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  3028. // fire before onload), but fall back to onload.
  3029. let called = false;
  3030. const wrappedFn = function () {
  3031. if (!document.body) {
  3032. setTimeout(wrappedFn, Math.floor(10));
  3033. return;
  3034. }
  3035. if (!called) {
  3036. called = true;
  3037. fn();
  3038. }
  3039. };
  3040. if (document.addEventListener) {
  3041. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  3042. // fallback to onload.
  3043. window.addEventListener('load', wrappedFn, false);
  3044. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3045. }
  3046. else if (document.attachEvent) {
  3047. // IE.
  3048. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3049. document.attachEvent('onreadystatechange', () => {
  3050. if (document.readyState === 'complete') {
  3051. wrappedFn();
  3052. }
  3053. });
  3054. // fallback to onload.
  3055. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3056. window.attachEvent('onload', wrappedFn);
  3057. // jQuery has an extra hack for IE that we could employ (based on
  3058. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  3059. // I'm hoping we don't need it.
  3060. }
  3061. }
  3062. };
  3063. /**
  3064. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  3065. */
  3066. const MIN_NAME = '[MIN_NAME]';
  3067. /**
  3068. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  3069. */
  3070. const MAX_NAME = '[MAX_NAME]';
  3071. /**
  3072. * Compares valid Firebase key names, plus min and max name
  3073. */
  3074. const nameCompare = function (a, b) {
  3075. if (a === b) {
  3076. return 0;
  3077. }
  3078. else if (a === MIN_NAME || b === MAX_NAME) {
  3079. return -1;
  3080. }
  3081. else if (b === MIN_NAME || a === MAX_NAME) {
  3082. return 1;
  3083. }
  3084. else {
  3085. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  3086. if (aAsInt !== null) {
  3087. if (bAsInt !== null) {
  3088. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  3089. }
  3090. else {
  3091. return -1;
  3092. }
  3093. }
  3094. else if (bAsInt !== null) {
  3095. return 1;
  3096. }
  3097. else {
  3098. return a < b ? -1 : 1;
  3099. }
  3100. }
  3101. };
  3102. /**
  3103. * @returns {!number} comparison result.
  3104. */
  3105. const stringCompare = function (a, b) {
  3106. if (a === b) {
  3107. return 0;
  3108. }
  3109. else if (a < b) {
  3110. return -1;
  3111. }
  3112. else {
  3113. return 1;
  3114. }
  3115. };
  3116. const requireKey = function (key, obj) {
  3117. if (obj && key in obj) {
  3118. return obj[key];
  3119. }
  3120. else {
  3121. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  3122. }
  3123. };
  3124. const ObjectToUniqueKey = function (obj) {
  3125. if (typeof obj !== 'object' || obj === null) {
  3126. return util.stringify(obj);
  3127. }
  3128. const keys = [];
  3129. // eslint-disable-next-line guard-for-in
  3130. for (const k in obj) {
  3131. keys.push(k);
  3132. }
  3133. // Export as json, but with the keys sorted.
  3134. keys.sort();
  3135. let key = '{';
  3136. for (let i = 0; i < keys.length; i++) {
  3137. if (i !== 0) {
  3138. key += ',';
  3139. }
  3140. key += util.stringify(keys[i]);
  3141. key += ':';
  3142. key += ObjectToUniqueKey(obj[keys[i]]);
  3143. }
  3144. key += '}';
  3145. return key;
  3146. };
  3147. /**
  3148. * Splits a string into a number of smaller segments of maximum size
  3149. * @param str - The string
  3150. * @param segsize - The maximum number of chars in the string.
  3151. * @returns The string, split into appropriately-sized chunks
  3152. */
  3153. const splitStringBySize = function (str, segsize) {
  3154. const len = str.length;
  3155. if (len <= segsize) {
  3156. return [str];
  3157. }
  3158. const dataSegs = [];
  3159. for (let c = 0; c < len; c += segsize) {
  3160. if (c + segsize > len) {
  3161. dataSegs.push(str.substring(c, len));
  3162. }
  3163. else {
  3164. dataSegs.push(str.substring(c, c + segsize));
  3165. }
  3166. }
  3167. return dataSegs;
  3168. };
  3169. /**
  3170. * Apply a function to each (key, value) pair in an object or
  3171. * apply a function to each (index, value) pair in an array
  3172. * @param obj - The object or array to iterate over
  3173. * @param fn - The function to apply
  3174. */
  3175. function each(obj, fn) {
  3176. for (const key in obj) {
  3177. if (obj.hasOwnProperty(key)) {
  3178. fn(key, obj[key]);
  3179. }
  3180. }
  3181. }
  3182. /**
  3183. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  3184. * I made one modification at the end and removed the NaN / Infinity
  3185. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  3186. * @param v - A double
  3187. *
  3188. */
  3189. const doubleToIEEE754String = function (v) {
  3190. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  3191. const ebits = 11, fbits = 52;
  3192. const bias = (1 << (ebits - 1)) - 1;
  3193. let s, e, f, ln, i;
  3194. // Compute sign, exponent, fraction
  3195. // Skip NaN / Infinity handling --MJL.
  3196. if (v === 0) {
  3197. e = 0;
  3198. f = 0;
  3199. s = 1 / v === -Infinity ? 1 : 0;
  3200. }
  3201. else {
  3202. s = v < 0;
  3203. v = Math.abs(v);
  3204. if (v >= Math.pow(2, 1 - bias)) {
  3205. // Normalized
  3206. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  3207. e = ln + bias;
  3208. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  3209. }
  3210. else {
  3211. // Denormalized
  3212. e = 0;
  3213. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  3214. }
  3215. }
  3216. // Pack sign, exponent, fraction
  3217. const bits = [];
  3218. for (i = fbits; i; i -= 1) {
  3219. bits.push(f % 2 ? 1 : 0);
  3220. f = Math.floor(f / 2);
  3221. }
  3222. for (i = ebits; i; i -= 1) {
  3223. bits.push(e % 2 ? 1 : 0);
  3224. e = Math.floor(e / 2);
  3225. }
  3226. bits.push(s ? 1 : 0);
  3227. bits.reverse();
  3228. const str = bits.join('');
  3229. // Return the data as a hex string. --MJL
  3230. let hexByteString = '';
  3231. for (i = 0; i < 64; i += 8) {
  3232. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  3233. if (hexByte.length === 1) {
  3234. hexByte = '0' + hexByte;
  3235. }
  3236. hexByteString = hexByteString + hexByte;
  3237. }
  3238. return hexByteString.toLowerCase();
  3239. };
  3240. /**
  3241. * Used to detect if we're in a Chrome content script (which executes in an
  3242. * isolated environment where long-polling doesn't work).
  3243. */
  3244. const isChromeExtensionContentScript = function () {
  3245. return !!(typeof window === 'object' &&
  3246. window['chrome'] &&
  3247. window['chrome']['extension'] &&
  3248. !/^chrome/.test(window.location.href));
  3249. };
  3250. /**
  3251. * Used to detect if we're in a Windows 8 Store app.
  3252. */
  3253. const isWindowsStoreApp = function () {
  3254. // Check for the presence of a couple WinRT globals
  3255. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  3256. };
  3257. /**
  3258. * Converts a server error code to a JavaScript Error
  3259. */
  3260. function errorForServerCode(code, query) {
  3261. let reason = 'Unknown Error';
  3262. if (code === 'too_big') {
  3263. reason =
  3264. 'The data requested exceeds the maximum size ' +
  3265. 'that can be accessed with a single request.';
  3266. }
  3267. else if (code === 'permission_denied') {
  3268. reason = "Client doesn't have permission to access the desired data.";
  3269. }
  3270. else if (code === 'unavailable') {
  3271. reason = 'The service is unavailable';
  3272. }
  3273. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  3274. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3275. error.code = code.toUpperCase();
  3276. return error;
  3277. }
  3278. /**
  3279. * Used to test for integer-looking strings
  3280. */
  3281. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  3282. /**
  3283. * For use in keys, the minimum possible 32-bit integer.
  3284. */
  3285. const INTEGER_32_MIN = -2147483648;
  3286. /**
  3287. * For use in keys, the maximum possible 32-bit integer.
  3288. */
  3289. const INTEGER_32_MAX = 2147483647;
  3290. /**
  3291. * If the string contains a 32-bit integer, return it. Else return null.
  3292. */
  3293. const tryParseInt = function (str) {
  3294. if (INTEGER_REGEXP_.test(str)) {
  3295. const intVal = Number(str);
  3296. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  3297. return intVal;
  3298. }
  3299. }
  3300. return null;
  3301. };
  3302. /**
  3303. * Helper to run some code but catch any exceptions and re-throw them later.
  3304. * Useful for preventing user callbacks from breaking internal code.
  3305. *
  3306. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  3307. * convenient (we don't have to try to figure out when is a safe point to
  3308. * re-throw it), and the behavior seems reasonable:
  3309. *
  3310. * * If you aren't pausing on exceptions, you get an error in the console with
  3311. * the correct stack trace.
  3312. * * If you're pausing on all exceptions, the debugger will pause on your
  3313. * exception and then again when we rethrow it.
  3314. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  3315. * on us re-throwing it.
  3316. *
  3317. * @param fn - The code to guard.
  3318. */
  3319. const exceptionGuard = function (fn) {
  3320. try {
  3321. fn();
  3322. }
  3323. catch (e) {
  3324. // Re-throw exception when it's safe.
  3325. setTimeout(() => {
  3326. // It used to be that "throw e" would result in a good console error with
  3327. // relevant context, but as of Chrome 39, you just get the firebase.js
  3328. // file/line number where we re-throw it, which is useless. So we log
  3329. // e.stack explicitly.
  3330. const stack = e.stack || '';
  3331. warn$1('Exception was thrown by user callback.', stack);
  3332. throw e;
  3333. }, Math.floor(0));
  3334. }
  3335. };
  3336. /**
  3337. * @returns {boolean} true if we think we're currently being crawled.
  3338. */
  3339. const beingCrawled = function () {
  3340. const userAgent = (typeof window === 'object' &&
  3341. window['navigator'] &&
  3342. window['navigator']['userAgent']) ||
  3343. '';
  3344. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  3345. // believe to support JavaScript/AJAX rendering.
  3346. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  3347. // would have seen the page" is flaky if we don't treat it as a crawler.
  3348. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  3349. };
  3350. /**
  3351. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  3352. *
  3353. * It is removed with clearTimeout() as normal.
  3354. *
  3355. * @param fn - Function to run.
  3356. * @param time - Milliseconds to wait before running.
  3357. * @returns The setTimeout() return value.
  3358. */
  3359. const setTimeoutNonBlocking = function (fn, time) {
  3360. const timeout = setTimeout(fn, time);
  3361. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  3362. if (typeof timeout === 'number' &&
  3363. // @ts-ignore Is only defined in Deno environments.
  3364. typeof Deno !== 'undefined' &&
  3365. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  3366. Deno['unrefTimer']) {
  3367. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  3368. Deno.unrefTimer(timeout);
  3369. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3370. }
  3371. else if (typeof timeout === 'object' && timeout['unref']) {
  3372. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3373. timeout['unref']();
  3374. }
  3375. return timeout;
  3376. };
  3377. /**
  3378. * @license
  3379. * Copyright 2017 Google LLC
  3380. *
  3381. * Licensed under the Apache License, Version 2.0 (the "License");
  3382. * you may not use this file except in compliance with the License.
  3383. * You may obtain a copy of the License at
  3384. *
  3385. * http://www.apache.org/licenses/LICENSE-2.0
  3386. *
  3387. * Unless required by applicable law or agreed to in writing, software
  3388. * distributed under the License is distributed on an "AS IS" BASIS,
  3389. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3390. * See the License for the specific language governing permissions and
  3391. * limitations under the License.
  3392. */
  3393. /**
  3394. * A class that holds metadata about a Repo object
  3395. */
  3396. class RepoInfo {
  3397. /**
  3398. * @param host - Hostname portion of the url for the repo
  3399. * @param secure - Whether or not this repo is accessed over ssl
  3400. * @param namespace - The namespace represented by the repo
  3401. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  3402. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  3403. * @param persistenceKey - Override the default session persistence storage key
  3404. */
  3405. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {
  3406. this.secure = secure;
  3407. this.namespace = namespace;
  3408. this.webSocketOnly = webSocketOnly;
  3409. this.nodeAdmin = nodeAdmin;
  3410. this.persistenceKey = persistenceKey;
  3411. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  3412. this.isUsingEmulator = isUsingEmulator;
  3413. this._host = host.toLowerCase();
  3414. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  3415. this.internalHost =
  3416. PersistentStorage.get('host:' + host) || this._host;
  3417. }
  3418. isCacheableHost() {
  3419. return this.internalHost.substr(0, 2) === 's-';
  3420. }
  3421. isCustomHost() {
  3422. return (this._domain !== 'firebaseio.com' &&
  3423. this._domain !== 'firebaseio-demo.com');
  3424. }
  3425. get host() {
  3426. return this._host;
  3427. }
  3428. set host(newHost) {
  3429. if (newHost !== this.internalHost) {
  3430. this.internalHost = newHost;
  3431. if (this.isCacheableHost()) {
  3432. PersistentStorage.set('host:' + this._host, this.internalHost);
  3433. }
  3434. }
  3435. }
  3436. toString() {
  3437. let str = this.toURLString();
  3438. if (this.persistenceKey) {
  3439. str += '<' + this.persistenceKey + '>';
  3440. }
  3441. return str;
  3442. }
  3443. toURLString() {
  3444. const protocol = this.secure ? 'https://' : 'http://';
  3445. const query = this.includeNamespaceInQueryParams
  3446. ? `?ns=${this.namespace}`
  3447. : '';
  3448. return `${protocol}${this.host}/${query}`;
  3449. }
  3450. }
  3451. function repoInfoNeedsQueryParam(repoInfo) {
  3452. return (repoInfo.host !== repoInfo.internalHost ||
  3453. repoInfo.isCustomHost() ||
  3454. repoInfo.includeNamespaceInQueryParams);
  3455. }
  3456. /**
  3457. * Returns the websocket URL for this repo
  3458. * @param repoInfo - RepoInfo object
  3459. * @param type - of connection
  3460. * @param params - list
  3461. * @returns The URL for this repo
  3462. */
  3463. function repoInfoConnectionURL(repoInfo, type, params) {
  3464. util.assert(typeof type === 'string', 'typeof type must == string');
  3465. util.assert(typeof params === 'object', 'typeof params must == object');
  3466. let connURL;
  3467. if (type === WEBSOCKET) {
  3468. connURL =
  3469. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  3470. }
  3471. else if (type === LONG_POLLING) {
  3472. connURL =
  3473. (repoInfo.secure ? 'https://' : 'http://') +
  3474. repoInfo.internalHost +
  3475. '/.lp?';
  3476. }
  3477. else {
  3478. throw new Error('Unknown connection type: ' + type);
  3479. }
  3480. if (repoInfoNeedsQueryParam(repoInfo)) {
  3481. params['ns'] = repoInfo.namespace;
  3482. }
  3483. const pairs = [];
  3484. each(params, (key, value) => {
  3485. pairs.push(key + '=' + value);
  3486. });
  3487. return connURL + pairs.join('&');
  3488. }
  3489. /**
  3490. * @license
  3491. * Copyright 2017 Google LLC
  3492. *
  3493. * Licensed under the Apache License, Version 2.0 (the "License");
  3494. * you may not use this file except in compliance with the License.
  3495. * You may obtain a copy of the License at
  3496. *
  3497. * http://www.apache.org/licenses/LICENSE-2.0
  3498. *
  3499. * Unless required by applicable law or agreed to in writing, software
  3500. * distributed under the License is distributed on an "AS IS" BASIS,
  3501. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3502. * See the License for the specific language governing permissions and
  3503. * limitations under the License.
  3504. */
  3505. /**
  3506. * Tracks a collection of stats.
  3507. */
  3508. class StatsCollection {
  3509. constructor() {
  3510. this.counters_ = {};
  3511. }
  3512. incrementCounter(name, amount = 1) {
  3513. if (!util.contains(this.counters_, name)) {
  3514. this.counters_[name] = 0;
  3515. }
  3516. this.counters_[name] += amount;
  3517. }
  3518. get() {
  3519. return util.deepCopy(this.counters_);
  3520. }
  3521. }
  3522. /**
  3523. * @license
  3524. * Copyright 2017 Google LLC
  3525. *
  3526. * Licensed under the Apache License, Version 2.0 (the "License");
  3527. * you may not use this file except in compliance with the License.
  3528. * You may obtain a copy of the License at
  3529. *
  3530. * http://www.apache.org/licenses/LICENSE-2.0
  3531. *
  3532. * Unless required by applicable law or agreed to in writing, software
  3533. * distributed under the License is distributed on an "AS IS" BASIS,
  3534. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3535. * See the License for the specific language governing permissions and
  3536. * limitations under the License.
  3537. */
  3538. const collections = {};
  3539. const reporters = {};
  3540. function statsManagerGetCollection(repoInfo) {
  3541. const hashString = repoInfo.toString();
  3542. if (!collections[hashString]) {
  3543. collections[hashString] = new StatsCollection();
  3544. }
  3545. return collections[hashString];
  3546. }
  3547. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  3548. const hashString = repoInfo.toString();
  3549. if (!reporters[hashString]) {
  3550. reporters[hashString] = creatorFunction();
  3551. }
  3552. return reporters[hashString];
  3553. }
  3554. /**
  3555. * @license
  3556. * Copyright 2019 Google LLC
  3557. *
  3558. * Licensed under the Apache License, Version 2.0 (the "License");
  3559. * you may not use this file except in compliance with the License.
  3560. * You may obtain a copy of the License at
  3561. *
  3562. * http://www.apache.org/licenses/LICENSE-2.0
  3563. *
  3564. * Unless required by applicable law or agreed to in writing, software
  3565. * distributed under the License is distributed on an "AS IS" BASIS,
  3566. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3567. * See the License for the specific language governing permissions and
  3568. * limitations under the License.
  3569. */
  3570. /** The semver (www.semver.org) version of the SDK. */
  3571. let SDK_VERSION = '';
  3572. /**
  3573. * SDK_VERSION should be set before any database instance is created
  3574. * @internal
  3575. */
  3576. function setSDKVersion(version) {
  3577. SDK_VERSION = version;
  3578. }
  3579. /**
  3580. * @license
  3581. * Copyright 2017 Google LLC
  3582. *
  3583. * Licensed under the Apache License, Version 2.0 (the "License");
  3584. * you may not use this file except in compliance with the License.
  3585. * You may obtain a copy of the License at
  3586. *
  3587. * http://www.apache.org/licenses/LICENSE-2.0
  3588. *
  3589. * Unless required by applicable law or agreed to in writing, software
  3590. * distributed under the License is distributed on an "AS IS" BASIS,
  3591. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3592. * See the License for the specific language governing permissions and
  3593. * limitations under the License.
  3594. */
  3595. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  3596. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  3597. let WebSocketImpl = null;
  3598. if (typeof MozWebSocket !== 'undefined') {
  3599. WebSocketImpl = MozWebSocket;
  3600. }
  3601. else if (typeof WebSocket !== 'undefined') {
  3602. WebSocketImpl = WebSocket;
  3603. }
  3604. function setWebSocketImpl(impl) {
  3605. WebSocketImpl = impl;
  3606. }
  3607. /**
  3608. * Create a new websocket connection with the given callbacks.
  3609. */
  3610. class WebSocketConnection {
  3611. /**
  3612. * @param connId identifier for this transport
  3613. * @param repoInfo The info for the websocket endpoint.
  3614. * @param applicationId The Firebase App ID for this project.
  3615. * @param appCheckToken The App Check Token for this client.
  3616. * @param authToken The Auth Token for this client.
  3617. * @param transportSessionId Optional transportSessionId if this is connecting
  3618. * to an existing transport session
  3619. * @param lastSessionId Optional lastSessionId if there was a previous
  3620. * connection
  3621. */
  3622. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  3623. this.connId = connId;
  3624. this.applicationId = applicationId;
  3625. this.appCheckToken = appCheckToken;
  3626. this.authToken = authToken;
  3627. this.keepaliveTimer = null;
  3628. this.frames = null;
  3629. this.totalFrames = 0;
  3630. this.bytesSent = 0;
  3631. this.bytesReceived = 0;
  3632. this.log_ = logWrapper(this.connId);
  3633. this.stats_ = statsManagerGetCollection(repoInfo);
  3634. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  3635. this.nodeAdmin = repoInfo.nodeAdmin;
  3636. }
  3637. /**
  3638. * @param repoInfo - The info for the websocket endpoint.
  3639. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  3640. * session
  3641. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  3642. * @returns connection url
  3643. */
  3644. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  3645. const urlParams = {};
  3646. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  3647. if (!util.isNodeSdk() &&
  3648. typeof location !== 'undefined' &&
  3649. location.hostname &&
  3650. FORGE_DOMAIN_RE.test(location.hostname)) {
  3651. urlParams[REFERER_PARAM] = FORGE_REF;
  3652. }
  3653. if (transportSessionId) {
  3654. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  3655. }
  3656. if (lastSessionId) {
  3657. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  3658. }
  3659. if (appCheckToken) {
  3660. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  3661. }
  3662. if (applicationId) {
  3663. urlParams[APPLICATION_ID_PARAM] = applicationId;
  3664. }
  3665. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  3666. }
  3667. /**
  3668. * @param onMessage - Callback when messages arrive
  3669. * @param onDisconnect - Callback with connection lost.
  3670. */
  3671. open(onMessage, onDisconnect) {
  3672. this.onDisconnect = onDisconnect;
  3673. this.onMessage = onMessage;
  3674. this.log_('Websocket connecting to ' + this.connURL);
  3675. this.everConnected_ = false;
  3676. // Assume failure until proven otherwise.
  3677. PersistentStorage.set('previous_websocket_failure', true);
  3678. try {
  3679. let options;
  3680. if (util.isNodeSdk()) {
  3681. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  3682. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  3683. options = {
  3684. headers: {
  3685. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  3686. 'X-Firebase-GMPID': this.applicationId || ''
  3687. }
  3688. };
  3689. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  3690. // Note that we send the credentials here even if they aren't admin credentials, which is
  3691. // not a problem.
  3692. // Note that this header is just used to bypass appcheck, and the token should still be sent
  3693. // through the websocket connection once it is established.
  3694. if (this.authToken) {
  3695. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  3696. }
  3697. if (this.appCheckToken) {
  3698. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  3699. }
  3700. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  3701. const env = process['env'];
  3702. const proxy = this.connURL.indexOf('wss://') === 0
  3703. ? env['HTTPS_PROXY'] || env['https_proxy']
  3704. : env['HTTP_PROXY'] || env['http_proxy'];
  3705. if (proxy) {
  3706. options['proxy'] = { origin: proxy };
  3707. }
  3708. }
  3709. this.mySock = new WebSocketImpl(this.connURL, [], options);
  3710. }
  3711. catch (e) {
  3712. this.log_('Error instantiating WebSocket.');
  3713. const error = e.message || e.data;
  3714. if (error) {
  3715. this.log_(error);
  3716. }
  3717. this.onClosed_();
  3718. return;
  3719. }
  3720. this.mySock.onopen = () => {
  3721. this.log_('Websocket connected.');
  3722. this.everConnected_ = true;
  3723. };
  3724. this.mySock.onclose = () => {
  3725. this.log_('Websocket connection was disconnected.');
  3726. this.mySock = null;
  3727. this.onClosed_();
  3728. };
  3729. this.mySock.onmessage = m => {
  3730. this.handleIncomingFrame(m);
  3731. };
  3732. this.mySock.onerror = e => {
  3733. this.log_('WebSocket error. Closing connection.');
  3734. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3735. const error = e.message || e.data;
  3736. if (error) {
  3737. this.log_(error);
  3738. }
  3739. this.onClosed_();
  3740. };
  3741. }
  3742. /**
  3743. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  3744. */
  3745. start() { }
  3746. static forceDisallow() {
  3747. WebSocketConnection.forceDisallow_ = true;
  3748. }
  3749. static isAvailable() {
  3750. let isOldAndroid = false;
  3751. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  3752. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  3753. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  3754. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  3755. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  3756. isOldAndroid = true;
  3757. }
  3758. }
  3759. }
  3760. return (!isOldAndroid &&
  3761. WebSocketImpl !== null &&
  3762. !WebSocketConnection.forceDisallow_);
  3763. }
  3764. /**
  3765. * Returns true if we previously failed to connect with this transport.
  3766. */
  3767. static previouslyFailed() {
  3768. // If our persistent storage is actually only in-memory storage,
  3769. // we default to assuming that it previously failed to be safe.
  3770. return (PersistentStorage.isInMemoryStorage ||
  3771. PersistentStorage.get('previous_websocket_failure') === true);
  3772. }
  3773. markConnectionHealthy() {
  3774. PersistentStorage.remove('previous_websocket_failure');
  3775. }
  3776. appendFrame_(data) {
  3777. this.frames.push(data);
  3778. if (this.frames.length === this.totalFrames) {
  3779. const fullMess = this.frames.join('');
  3780. this.frames = null;
  3781. const jsonMess = util.jsonEval(fullMess);
  3782. //handle the message
  3783. this.onMessage(jsonMess);
  3784. }
  3785. }
  3786. /**
  3787. * @param frameCount - The number of frames we are expecting from the server
  3788. */
  3789. handleNewFrameCount_(frameCount) {
  3790. this.totalFrames = frameCount;
  3791. this.frames = [];
  3792. }
  3793. /**
  3794. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  3795. * @returns Any remaining data to be process, or null if there is none
  3796. */
  3797. extractFrameCount_(data) {
  3798. util.assert(this.frames === null, 'We already have a frame buffer');
  3799. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  3800. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  3801. if (data.length <= 6) {
  3802. const frameCount = Number(data);
  3803. if (!isNaN(frameCount)) {
  3804. this.handleNewFrameCount_(frameCount);
  3805. return null;
  3806. }
  3807. }
  3808. this.handleNewFrameCount_(1);
  3809. return data;
  3810. }
  3811. /**
  3812. * Process a websocket frame that has arrived from the server.
  3813. * @param mess - The frame data
  3814. */
  3815. handleIncomingFrame(mess) {
  3816. if (this.mySock === null) {
  3817. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  3818. }
  3819. const data = mess['data'];
  3820. this.bytesReceived += data.length;
  3821. this.stats_.incrementCounter('bytes_received', data.length);
  3822. this.resetKeepAlive();
  3823. if (this.frames !== null) {
  3824. // we're buffering
  3825. this.appendFrame_(data);
  3826. }
  3827. else {
  3828. // try to parse out a frame count, otherwise, assume 1 and process it
  3829. const remainingData = this.extractFrameCount_(data);
  3830. if (remainingData !== null) {
  3831. this.appendFrame_(remainingData);
  3832. }
  3833. }
  3834. }
  3835. /**
  3836. * Send a message to the server
  3837. * @param data - The JSON object to transmit
  3838. */
  3839. send(data) {
  3840. this.resetKeepAlive();
  3841. const dataStr = util.stringify(data);
  3842. this.bytesSent += dataStr.length;
  3843. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  3844. //We can only fit a certain amount in each websocket frame, so we need to split this request
  3845. //up into multiple pieces if it doesn't fit in one request.
  3846. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  3847. //Send the length header
  3848. if (dataSegs.length > 1) {
  3849. this.sendString_(String(dataSegs.length));
  3850. }
  3851. //Send the actual data in segments.
  3852. for (let i = 0; i < dataSegs.length; i++) {
  3853. this.sendString_(dataSegs[i]);
  3854. }
  3855. }
  3856. shutdown_() {
  3857. this.isClosed_ = true;
  3858. if (this.keepaliveTimer) {
  3859. clearInterval(this.keepaliveTimer);
  3860. this.keepaliveTimer = null;
  3861. }
  3862. if (this.mySock) {
  3863. this.mySock.close();
  3864. this.mySock = null;
  3865. }
  3866. }
  3867. onClosed_() {
  3868. if (!this.isClosed_) {
  3869. this.log_('WebSocket is closing itself');
  3870. this.shutdown_();
  3871. // since this is an internal close, trigger the close listener
  3872. if (this.onDisconnect) {
  3873. this.onDisconnect(this.everConnected_);
  3874. this.onDisconnect = null;
  3875. }
  3876. }
  3877. }
  3878. /**
  3879. * External-facing close handler.
  3880. * Close the websocket and kill the connection.
  3881. */
  3882. close() {
  3883. if (!this.isClosed_) {
  3884. this.log_('WebSocket is being closed');
  3885. this.shutdown_();
  3886. }
  3887. }
  3888. /**
  3889. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  3890. * the last activity.
  3891. */
  3892. resetKeepAlive() {
  3893. clearInterval(this.keepaliveTimer);
  3894. this.keepaliveTimer = setInterval(() => {
  3895. //If there has been no websocket activity for a while, send a no-op
  3896. if (this.mySock) {
  3897. this.sendString_('0');
  3898. }
  3899. this.resetKeepAlive();
  3900. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3901. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  3902. }
  3903. /**
  3904. * Send a string over the websocket.
  3905. *
  3906. * @param str - String to send.
  3907. */
  3908. sendString_(str) {
  3909. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  3910. // calls for some unknown reason. We treat these as an error and disconnect.
  3911. // See https://app.asana.com/0/58926111402292/68021340250410
  3912. try {
  3913. this.mySock.send(str);
  3914. }
  3915. catch (e) {
  3916. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  3917. setTimeout(this.onClosed_.bind(this), 0);
  3918. }
  3919. }
  3920. }
  3921. /**
  3922. * Number of response before we consider the connection "healthy."
  3923. */
  3924. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  3925. /**
  3926. * Time to wait for the connection te become healthy before giving up.
  3927. */
  3928. WebSocketConnection.healthyTimeout = 30000;
  3929. /**
  3930. * @license
  3931. * Copyright 2021 Google LLC
  3932. *
  3933. * Licensed under the Apache License, Version 2.0 (the "License");
  3934. * you may not use this file except in compliance with the License.
  3935. * You may obtain a copy of the License at
  3936. *
  3937. * http://www.apache.org/licenses/LICENSE-2.0
  3938. *
  3939. * Unless required by applicable law or agreed to in writing, software
  3940. * distributed under the License is distributed on an "AS IS" BASIS,
  3941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3942. * See the License for the specific language governing permissions and
  3943. * limitations under the License.
  3944. */
  3945. /**
  3946. * Abstraction around AppCheck's token fetching capabilities.
  3947. */
  3948. class AppCheckTokenProvider {
  3949. constructor(appName_, appCheckProvider) {
  3950. this.appName_ = appName_;
  3951. this.appCheckProvider = appCheckProvider;
  3952. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  3953. if (!this.appCheck) {
  3954. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  3955. }
  3956. }
  3957. getToken(forceRefresh) {
  3958. if (!this.appCheck) {
  3959. return new Promise((resolve, reject) => {
  3960. // Support delayed initialization of FirebaseAppCheck. This allows our
  3961. // customers to initialize the RTDB SDK before initializing Firebase
  3962. // AppCheck and ensures that all requests are authenticated if a token
  3963. // becomes available before the timeout below expires.
  3964. setTimeout(() => {
  3965. if (this.appCheck) {
  3966. this.getToken(forceRefresh).then(resolve, reject);
  3967. }
  3968. else {
  3969. resolve(null);
  3970. }
  3971. }, 0);
  3972. });
  3973. }
  3974. return this.appCheck.getToken(forceRefresh);
  3975. }
  3976. addTokenChangeListener(listener) {
  3977. var _a;
  3978. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  3979. }
  3980. notifyForInvalidToken() {
  3981. warn$1(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  3982. 'are invalid. This usually indicates your app was not initialized correctly.');
  3983. }
  3984. }
  3985. /**
  3986. * @license
  3987. * Copyright 2017 Google LLC
  3988. *
  3989. * Licensed under the Apache License, Version 2.0 (the "License");
  3990. * you may not use this file except in compliance with the License.
  3991. * You may obtain a copy of the License at
  3992. *
  3993. * http://www.apache.org/licenses/LICENSE-2.0
  3994. *
  3995. * Unless required by applicable law or agreed to in writing, software
  3996. * distributed under the License is distributed on an "AS IS" BASIS,
  3997. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3998. * See the License for the specific language governing permissions and
  3999. * limitations under the License.
  4000. */
  4001. /**
  4002. * Abstraction around FirebaseApp's token fetching capabilities.
  4003. */
  4004. class FirebaseAuthTokenProvider {
  4005. constructor(appName_, firebaseOptions_, authProvider_) {
  4006. this.appName_ = appName_;
  4007. this.firebaseOptions_ = firebaseOptions_;
  4008. this.authProvider_ = authProvider_;
  4009. this.auth_ = null;
  4010. this.auth_ = authProvider_.getImmediate({ optional: true });
  4011. if (!this.auth_) {
  4012. authProvider_.onInit(auth => (this.auth_ = auth));
  4013. }
  4014. }
  4015. getToken(forceRefresh) {
  4016. if (!this.auth_) {
  4017. return new Promise((resolve, reject) => {
  4018. // Support delayed initialization of FirebaseAuth. This allows our
  4019. // customers to initialize the RTDB SDK before initializing Firebase
  4020. // Auth and ensures that all requests are authenticated if a token
  4021. // becomes available before the timeout below expires.
  4022. setTimeout(() => {
  4023. if (this.auth_) {
  4024. this.getToken(forceRefresh).then(resolve, reject);
  4025. }
  4026. else {
  4027. resolve(null);
  4028. }
  4029. }, 0);
  4030. });
  4031. }
  4032. return this.auth_.getToken(forceRefresh).catch(error => {
  4033. // TODO: Need to figure out all the cases this is raised and whether
  4034. // this makes sense.
  4035. if (error && error.code === 'auth/token-not-initialized') {
  4036. log('Got auth/token-not-initialized error. Treating as null token.');
  4037. return null;
  4038. }
  4039. else {
  4040. return Promise.reject(error);
  4041. }
  4042. });
  4043. }
  4044. addTokenChangeListener(listener) {
  4045. // TODO: We might want to wrap the listener and call it with no args to
  4046. // avoid a leaky abstraction, but that makes removing the listener harder.
  4047. if (this.auth_) {
  4048. this.auth_.addAuthTokenListener(listener);
  4049. }
  4050. else {
  4051. this.authProvider_
  4052. .get()
  4053. .then(auth => auth.addAuthTokenListener(listener));
  4054. }
  4055. }
  4056. removeTokenChangeListener(listener) {
  4057. this.authProvider_
  4058. .get()
  4059. .then(auth => auth.removeAuthTokenListener(listener));
  4060. }
  4061. notifyForInvalidToken() {
  4062. let errorMessage = 'Provided authentication credentials for the app named "' +
  4063. this.appName_ +
  4064. '" are invalid. This usually indicates your app was not ' +
  4065. 'initialized correctly. ';
  4066. if ('credential' in this.firebaseOptions_) {
  4067. errorMessage +=
  4068. 'Make sure the "credential" property provided to initializeApp() ' +
  4069. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  4070. 'project.';
  4071. }
  4072. else if ('serviceAccount' in this.firebaseOptions_) {
  4073. errorMessage +=
  4074. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  4075. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  4076. 'project.';
  4077. }
  4078. else {
  4079. errorMessage +=
  4080. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  4081. 'initializeApp() match the values provided for your app at ' +
  4082. 'https://console.firebase.google.com/.';
  4083. }
  4084. warn$1(errorMessage);
  4085. }
  4086. }
  4087. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  4088. class EmulatorTokenProvider {
  4089. constructor(accessToken) {
  4090. this.accessToken = accessToken;
  4091. }
  4092. getToken(forceRefresh) {
  4093. return Promise.resolve({
  4094. accessToken: this.accessToken
  4095. });
  4096. }
  4097. addTokenChangeListener(listener) {
  4098. // Invoke the listener immediately to match the behavior in Firebase Auth
  4099. // (see packages/auth/src/auth.js#L1807)
  4100. listener(this.accessToken);
  4101. }
  4102. removeTokenChangeListener(listener) { }
  4103. notifyForInvalidToken() { }
  4104. }
  4105. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  4106. EmulatorTokenProvider.OWNER = 'owner';
  4107. /**
  4108. * @license
  4109. * Copyright 2017 Google LLC
  4110. *
  4111. * Licensed under the Apache License, Version 2.0 (the "License");
  4112. * you may not use this file except in compliance with the License.
  4113. * You may obtain a copy of the License at
  4114. *
  4115. * http://www.apache.org/licenses/LICENSE-2.0
  4116. *
  4117. * Unless required by applicable law or agreed to in writing, software
  4118. * distributed under the License is distributed on an "AS IS" BASIS,
  4119. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4120. * See the License for the specific language governing permissions and
  4121. * limitations under the License.
  4122. */
  4123. /**
  4124. * This class ensures the packets from the server arrive in order
  4125. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  4126. */
  4127. class PacketReceiver {
  4128. /**
  4129. * @param onMessage_
  4130. */
  4131. constructor(onMessage_) {
  4132. this.onMessage_ = onMessage_;
  4133. this.pendingResponses = [];
  4134. this.currentResponseNum = 0;
  4135. this.closeAfterResponse = -1;
  4136. this.onClose = null;
  4137. }
  4138. closeAfter(responseNum, callback) {
  4139. this.closeAfterResponse = responseNum;
  4140. this.onClose = callback;
  4141. if (this.closeAfterResponse < this.currentResponseNum) {
  4142. this.onClose();
  4143. this.onClose = null;
  4144. }
  4145. }
  4146. /**
  4147. * Each message from the server comes with a response number, and an array of data. The responseNumber
  4148. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  4149. * browsers will respond in the same order as the requests we sent
  4150. */
  4151. handleResponse(requestNum, data) {
  4152. this.pendingResponses[requestNum] = data;
  4153. while (this.pendingResponses[this.currentResponseNum]) {
  4154. const toProcess = this.pendingResponses[this.currentResponseNum];
  4155. delete this.pendingResponses[this.currentResponseNum];
  4156. for (let i = 0; i < toProcess.length; ++i) {
  4157. if (toProcess[i]) {
  4158. exceptionGuard(() => {
  4159. this.onMessage_(toProcess[i]);
  4160. });
  4161. }
  4162. }
  4163. if (this.currentResponseNum === this.closeAfterResponse) {
  4164. if (this.onClose) {
  4165. this.onClose();
  4166. this.onClose = null;
  4167. }
  4168. break;
  4169. }
  4170. this.currentResponseNum++;
  4171. }
  4172. }
  4173. }
  4174. /**
  4175. * @license
  4176. * Copyright 2017 Google LLC
  4177. *
  4178. * Licensed under the Apache License, Version 2.0 (the "License");
  4179. * you may not use this file except in compliance with the License.
  4180. * You may obtain a copy of the License at
  4181. *
  4182. * http://www.apache.org/licenses/LICENSE-2.0
  4183. *
  4184. * Unless required by applicable law or agreed to in writing, software
  4185. * distributed under the License is distributed on an "AS IS" BASIS,
  4186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4187. * See the License for the specific language governing permissions and
  4188. * limitations under the License.
  4189. */
  4190. // URL query parameters associated with longpolling
  4191. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  4192. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  4193. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  4194. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  4195. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  4196. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  4197. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  4198. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  4199. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  4200. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  4201. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  4202. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  4203. //Data size constants.
  4204. //TODO: Perf: the maximum length actually differs from browser to browser.
  4205. // We should check what browser we're on and set accordingly.
  4206. const MAX_URL_DATA_SIZE = 1870;
  4207. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  4208. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  4209. /**
  4210. * Keepalive period
  4211. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  4212. * length of 30 seconds that we can't exceed.
  4213. */
  4214. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  4215. /**
  4216. * How long to wait before aborting a long-polling connection attempt.
  4217. */
  4218. const LP_CONNECT_TIMEOUT = 30000;
  4219. /**
  4220. * This class manages a single long-polling connection.
  4221. */
  4222. class BrowserPollConnection {
  4223. /**
  4224. * @param connId An identifier for this connection, used for logging
  4225. * @param repoInfo The info for the endpoint to send data to.
  4226. * @param applicationId The Firebase App ID for this project.
  4227. * @param appCheckToken The AppCheck token for this client.
  4228. * @param authToken The AuthToken to use for this connection.
  4229. * @param transportSessionId Optional transportSessionid if we are
  4230. * reconnecting for an existing transport session
  4231. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  4232. * already created a connection previously
  4233. */
  4234. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  4235. this.connId = connId;
  4236. this.repoInfo = repoInfo;
  4237. this.applicationId = applicationId;
  4238. this.appCheckToken = appCheckToken;
  4239. this.authToken = authToken;
  4240. this.transportSessionId = transportSessionId;
  4241. this.lastSessionId = lastSessionId;
  4242. this.bytesSent = 0;
  4243. this.bytesReceived = 0;
  4244. this.everConnected_ = false;
  4245. this.log_ = logWrapper(connId);
  4246. this.stats_ = statsManagerGetCollection(repoInfo);
  4247. this.urlFn = (params) => {
  4248. // Always add the token if we have one.
  4249. if (this.appCheckToken) {
  4250. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  4251. }
  4252. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  4253. };
  4254. }
  4255. /**
  4256. * @param onMessage - Callback when messages arrive
  4257. * @param onDisconnect - Callback with connection lost.
  4258. */
  4259. open(onMessage, onDisconnect) {
  4260. this.curSegmentNum = 0;
  4261. this.onDisconnect_ = onDisconnect;
  4262. this.myPacketOrderer = new PacketReceiver(onMessage);
  4263. this.isClosed_ = false;
  4264. this.connectTimeoutTimer_ = setTimeout(() => {
  4265. this.log_('Timed out trying to connect.');
  4266. // Make sure we clear the host cache
  4267. this.onClosed_();
  4268. this.connectTimeoutTimer_ = null;
  4269. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4270. }, Math.floor(LP_CONNECT_TIMEOUT));
  4271. // Ensure we delay the creation of the iframe until the DOM is loaded.
  4272. executeWhenDOMReady(() => {
  4273. if (this.isClosed_) {
  4274. return;
  4275. }
  4276. //Set up a callback that gets triggered once a connection is set up.
  4277. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  4278. const [command, arg1, arg2, arg3, arg4] = args;
  4279. this.incrementIncomingBytes_(args);
  4280. if (!this.scriptTagHolder) {
  4281. return; // we closed the connection.
  4282. }
  4283. if (this.connectTimeoutTimer_) {
  4284. clearTimeout(this.connectTimeoutTimer_);
  4285. this.connectTimeoutTimer_ = null;
  4286. }
  4287. this.everConnected_ = true;
  4288. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  4289. this.id = arg1;
  4290. this.password = arg2;
  4291. }
  4292. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  4293. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  4294. if (arg1) {
  4295. // We aren't expecting any more data (other than what the server's already in the process of sending us
  4296. // through our already open polls), so don't send any more.
  4297. this.scriptTagHolder.sendNewPolls = false;
  4298. // arg1 in this case is the last response number sent by the server. We should try to receive
  4299. // all of the responses up to this one before closing
  4300. this.myPacketOrderer.closeAfter(arg1, () => {
  4301. this.onClosed_();
  4302. });
  4303. }
  4304. else {
  4305. this.onClosed_();
  4306. }
  4307. }
  4308. else {
  4309. throw new Error('Unrecognized command received: ' + command);
  4310. }
  4311. }, (...args) => {
  4312. const [pN, data] = args;
  4313. this.incrementIncomingBytes_(args);
  4314. this.myPacketOrderer.handleResponse(pN, data);
  4315. }, () => {
  4316. this.onClosed_();
  4317. }, this.urlFn);
  4318. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  4319. //from cache.
  4320. const urlParams = {};
  4321. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  4322. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  4323. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  4324. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  4325. this.scriptTagHolder.uniqueCallbackIdentifier;
  4326. }
  4327. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  4328. if (this.transportSessionId) {
  4329. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  4330. }
  4331. if (this.lastSessionId) {
  4332. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  4333. }
  4334. if (this.applicationId) {
  4335. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  4336. }
  4337. if (this.appCheckToken) {
  4338. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  4339. }
  4340. if (typeof location !== 'undefined' &&
  4341. location.hostname &&
  4342. FORGE_DOMAIN_RE.test(location.hostname)) {
  4343. urlParams[REFERER_PARAM] = FORGE_REF;
  4344. }
  4345. const connectURL = this.urlFn(urlParams);
  4346. this.log_('Connecting via long-poll to ' + connectURL);
  4347. this.scriptTagHolder.addTag(connectURL, () => {
  4348. /* do nothing */
  4349. });
  4350. });
  4351. }
  4352. /**
  4353. * Call this when a handshake has completed successfully and we want to consider the connection established
  4354. */
  4355. start() {
  4356. this.scriptTagHolder.startLongPoll(this.id, this.password);
  4357. this.addDisconnectPingFrame(this.id, this.password);
  4358. }
  4359. /**
  4360. * Forces long polling to be considered as a potential transport
  4361. */
  4362. static forceAllow() {
  4363. BrowserPollConnection.forceAllow_ = true;
  4364. }
  4365. /**
  4366. * Forces longpolling to not be considered as a potential transport
  4367. */
  4368. static forceDisallow() {
  4369. BrowserPollConnection.forceDisallow_ = true;
  4370. }
  4371. // Static method, use string literal so it can be accessed in a generic way
  4372. static isAvailable() {
  4373. if (util.isNodeSdk()) {
  4374. return false;
  4375. }
  4376. else if (BrowserPollConnection.forceAllow_) {
  4377. return true;
  4378. }
  4379. else {
  4380. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  4381. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  4382. return (!BrowserPollConnection.forceDisallow_ &&
  4383. typeof document !== 'undefined' &&
  4384. document.createElement != null &&
  4385. !isChromeExtensionContentScript() &&
  4386. !isWindowsStoreApp());
  4387. }
  4388. }
  4389. /**
  4390. * No-op for polling
  4391. */
  4392. markConnectionHealthy() { }
  4393. /**
  4394. * Stops polling and cleans up the iframe
  4395. */
  4396. shutdown_() {
  4397. this.isClosed_ = true;
  4398. if (this.scriptTagHolder) {
  4399. this.scriptTagHolder.close();
  4400. this.scriptTagHolder = null;
  4401. }
  4402. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  4403. if (this.myDisconnFrame) {
  4404. document.body.removeChild(this.myDisconnFrame);
  4405. this.myDisconnFrame = null;
  4406. }
  4407. if (this.connectTimeoutTimer_) {
  4408. clearTimeout(this.connectTimeoutTimer_);
  4409. this.connectTimeoutTimer_ = null;
  4410. }
  4411. }
  4412. /**
  4413. * Triggered when this transport is closed
  4414. */
  4415. onClosed_() {
  4416. if (!this.isClosed_) {
  4417. this.log_('Longpoll is closing itself');
  4418. this.shutdown_();
  4419. if (this.onDisconnect_) {
  4420. this.onDisconnect_(this.everConnected_);
  4421. this.onDisconnect_ = null;
  4422. }
  4423. }
  4424. }
  4425. /**
  4426. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  4427. * that we've left.
  4428. */
  4429. close() {
  4430. if (!this.isClosed_) {
  4431. this.log_('Longpoll is being closed.');
  4432. this.shutdown_();
  4433. }
  4434. }
  4435. /**
  4436. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  4437. * broken into chunks (since URLs have a small maximum length).
  4438. * @param data - The JSON data to transmit.
  4439. */
  4440. send(data) {
  4441. const dataStr = util.stringify(data);
  4442. this.bytesSent += dataStr.length;
  4443. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  4444. //first, lets get the base64-encoded data
  4445. const base64data = util.base64Encode(dataStr);
  4446. //We can only fit a certain amount in each URL, so we need to split this request
  4447. //up into multiple pieces if it doesn't fit in one request.
  4448. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  4449. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  4450. //of segments so that we can reassemble the packet on the server.
  4451. for (let i = 0; i < dataSegs.length; i++) {
  4452. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  4453. this.curSegmentNum++;
  4454. }
  4455. }
  4456. /**
  4457. * This is how we notify the server that we're leaving.
  4458. * We aren't able to send requests with DHTML on a window close event, but we can
  4459. * trigger XHR requests in some browsers (everything but Opera basically).
  4460. */
  4461. addDisconnectPingFrame(id, pw) {
  4462. if (util.isNodeSdk()) {
  4463. return;
  4464. }
  4465. this.myDisconnFrame = document.createElement('iframe');
  4466. const urlParams = {};
  4467. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  4468. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  4469. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  4470. this.myDisconnFrame.src = this.urlFn(urlParams);
  4471. this.myDisconnFrame.style.display = 'none';
  4472. document.body.appendChild(this.myDisconnFrame);
  4473. }
  4474. /**
  4475. * Used to track the bytes received by this client
  4476. */
  4477. incrementIncomingBytes_(args) {
  4478. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  4479. const bytesReceived = util.stringify(args).length;
  4480. this.bytesReceived += bytesReceived;
  4481. this.stats_.incrementCounter('bytes_received', bytesReceived);
  4482. }
  4483. }
  4484. /*********************************************************************************************
  4485. * A wrapper around an iframe that is used as a long-polling script holder.
  4486. *********************************************************************************************/
  4487. class FirebaseIFrameScriptHolder {
  4488. /**
  4489. * @param commandCB - The callback to be called when control commands are received from the server.
  4490. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  4491. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  4492. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  4493. */
  4494. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  4495. this.onDisconnect = onDisconnect;
  4496. this.urlFn = urlFn;
  4497. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  4498. //problems in some browsers.
  4499. this.outstandingRequests = new Set();
  4500. //A queue of the pending segments waiting for transmission to the server.
  4501. this.pendingSegs = [];
  4502. //A serial number. We use this for two things:
  4503. // 1) A way to ensure the browser doesn't cache responses to polls
  4504. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  4505. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  4506. // JSONP code in the order it was added to the iframe.
  4507. this.currentSerial = Math.floor(Math.random() * 100000000);
  4508. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  4509. // incoming data from the server that we're waiting for).
  4510. this.sendNewPolls = true;
  4511. if (!util.isNodeSdk()) {
  4512. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  4513. //iframes where we put the long-polling script tags. We have two callbacks:
  4514. // 1) Command Callback - Triggered for control issues, like starting a connection.
  4515. // 2) Message Callback - Triggered when new data arrives.
  4516. this.uniqueCallbackIdentifier = LUIDGenerator();
  4517. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  4518. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  4519. onMessageCB;
  4520. //Create an iframe for us to add script tags to.
  4521. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  4522. // Set the iframe's contents.
  4523. let script = '';
  4524. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  4525. // for ie9, but ie8 needs to do it again in the document itself.
  4526. if (this.myIFrame.src &&
  4527. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  4528. const currentDomain = document.domain;
  4529. script = '<script>document.domain="' + currentDomain + '";</script>';
  4530. }
  4531. const iframeContents = '<html><body>' + script + '</body></html>';
  4532. try {
  4533. this.myIFrame.doc.open();
  4534. this.myIFrame.doc.write(iframeContents);
  4535. this.myIFrame.doc.close();
  4536. }
  4537. catch (e) {
  4538. log('frame writing exception');
  4539. if (e.stack) {
  4540. log(e.stack);
  4541. }
  4542. log(e);
  4543. }
  4544. }
  4545. else {
  4546. this.commandCB = commandCB;
  4547. this.onMessageCB = onMessageCB;
  4548. }
  4549. }
  4550. /**
  4551. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  4552. * actually use.
  4553. */
  4554. static createIFrame_() {
  4555. const iframe = document.createElement('iframe');
  4556. iframe.style.display = 'none';
  4557. // This is necessary in order to initialize the document inside the iframe
  4558. if (document.body) {
  4559. document.body.appendChild(iframe);
  4560. try {
  4561. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  4562. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  4563. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  4564. const a = iframe.contentWindow.document;
  4565. if (!a) {
  4566. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  4567. log('No IE domain setting required');
  4568. }
  4569. }
  4570. catch (e) {
  4571. const domain = document.domain;
  4572. iframe.src =
  4573. "javascript:void((function(){document.open();document.domain='" +
  4574. domain +
  4575. "';document.close();})())";
  4576. }
  4577. }
  4578. else {
  4579. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  4580. // never gets hit.
  4581. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  4582. }
  4583. // Get the document of the iframe in a browser-specific way.
  4584. if (iframe.contentDocument) {
  4585. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  4586. }
  4587. else if (iframe.contentWindow) {
  4588. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  4589. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4590. }
  4591. else if (iframe.document) {
  4592. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4593. iframe.doc = iframe.document; //others?
  4594. }
  4595. return iframe;
  4596. }
  4597. /**
  4598. * Cancel all outstanding queries and remove the frame.
  4599. */
  4600. close() {
  4601. //Mark this iframe as dead, so no new requests are sent.
  4602. this.alive = false;
  4603. if (this.myIFrame) {
  4604. //We have to actually remove all of the html inside this iframe before removing it from the
  4605. //window, or IE will continue loading and executing the script tags we've already added, which
  4606. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  4607. this.myIFrame.doc.body.textContent = '';
  4608. setTimeout(() => {
  4609. if (this.myIFrame !== null) {
  4610. document.body.removeChild(this.myIFrame);
  4611. this.myIFrame = null;
  4612. }
  4613. }, Math.floor(0));
  4614. }
  4615. // Protect from being called recursively.
  4616. const onDisconnect = this.onDisconnect;
  4617. if (onDisconnect) {
  4618. this.onDisconnect = null;
  4619. onDisconnect();
  4620. }
  4621. }
  4622. /**
  4623. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  4624. * @param id - The ID of this connection
  4625. * @param pw - The password for this connection
  4626. */
  4627. startLongPoll(id, pw) {
  4628. this.myID = id;
  4629. this.myPW = pw;
  4630. this.alive = true;
  4631. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  4632. while (this.newRequest_()) { }
  4633. }
  4634. /**
  4635. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  4636. * too many outstanding requests and we are still alive.
  4637. *
  4638. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  4639. * needed.
  4640. */
  4641. newRequest_() {
  4642. // We keep one outstanding request open all the time to receive data, but if we need to send data
  4643. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  4644. // close the old request.
  4645. if (this.alive &&
  4646. this.sendNewPolls &&
  4647. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  4648. //construct our url
  4649. this.currentSerial++;
  4650. const urlParams = {};
  4651. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  4652. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  4653. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  4654. let theURL = this.urlFn(urlParams);
  4655. //Now add as much data as we can.
  4656. let curDataString = '';
  4657. let i = 0;
  4658. while (this.pendingSegs.length > 0) {
  4659. //first, lets see if the next segment will fit.
  4660. const nextSeg = this.pendingSegs[0];
  4661. if (nextSeg.d.length +
  4662. SEG_HEADER_SIZE +
  4663. curDataString.length <=
  4664. MAX_URL_DATA_SIZE) {
  4665. //great, the segment will fit. Lets append it.
  4666. const theSeg = this.pendingSegs.shift();
  4667. curDataString =
  4668. curDataString +
  4669. '&' +
  4670. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  4671. i +
  4672. '=' +
  4673. theSeg.seg +
  4674. '&' +
  4675. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  4676. i +
  4677. '=' +
  4678. theSeg.ts +
  4679. '&' +
  4680. FIREBASE_LONGPOLL_DATA_PARAM +
  4681. i +
  4682. '=' +
  4683. theSeg.d;
  4684. i++;
  4685. }
  4686. else {
  4687. break;
  4688. }
  4689. }
  4690. theURL = theURL + curDataString;
  4691. this.addLongPollTag_(theURL, this.currentSerial);
  4692. return true;
  4693. }
  4694. else {
  4695. return false;
  4696. }
  4697. }
  4698. /**
  4699. * Queue a packet for transmission to the server.
  4700. * @param segnum - A sequential id for this packet segment used for reassembly
  4701. * @param totalsegs - The total number of segments in this packet
  4702. * @param data - The data for this segment.
  4703. */
  4704. enqueueSegment(segnum, totalsegs, data) {
  4705. //add this to the queue of segments to send.
  4706. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  4707. //send the data immediately if there isn't already data being transmitted, unless
  4708. //startLongPoll hasn't been called yet.
  4709. if (this.alive) {
  4710. this.newRequest_();
  4711. }
  4712. }
  4713. /**
  4714. * Add a script tag for a regular long-poll request.
  4715. * @param url - The URL of the script tag.
  4716. * @param serial - The serial number of the request.
  4717. */
  4718. addLongPollTag_(url, serial) {
  4719. //remember that we sent this request.
  4720. this.outstandingRequests.add(serial);
  4721. const doNewRequest = () => {
  4722. this.outstandingRequests.delete(serial);
  4723. this.newRequest_();
  4724. };
  4725. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  4726. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  4727. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  4728. const readyStateCB = () => {
  4729. // Request completed. Cancel the keepalive.
  4730. clearTimeout(keepaliveTimeout);
  4731. // Trigger a new request so we can continue receiving data.
  4732. doNewRequest();
  4733. };
  4734. this.addTag(url, readyStateCB);
  4735. }
  4736. /**
  4737. * Add an arbitrary script tag to the iframe.
  4738. * @param url - The URL for the script tag source.
  4739. * @param loadCB - A callback to be triggered once the script has loaded.
  4740. */
  4741. addTag(url, loadCB) {
  4742. if (util.isNodeSdk()) {
  4743. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4744. this.doNodeLongPoll(url, loadCB);
  4745. }
  4746. else {
  4747. setTimeout(() => {
  4748. try {
  4749. // if we're already closed, don't add this poll
  4750. if (!this.sendNewPolls) {
  4751. return;
  4752. }
  4753. const newScript = this.myIFrame.doc.createElement('script');
  4754. newScript.type = 'text/javascript';
  4755. newScript.async = true;
  4756. newScript.src = url;
  4757. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4758. newScript.onload = newScript.onreadystatechange =
  4759. function () {
  4760. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4761. const rstate = newScript.readyState;
  4762. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  4763. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4764. newScript.onload = newScript.onreadystatechange = null;
  4765. if (newScript.parentNode) {
  4766. newScript.parentNode.removeChild(newScript);
  4767. }
  4768. loadCB();
  4769. }
  4770. };
  4771. newScript.onerror = () => {
  4772. log('Long-poll script failed to load: ' + url);
  4773. this.sendNewPolls = false;
  4774. this.close();
  4775. };
  4776. this.myIFrame.doc.body.appendChild(newScript);
  4777. }
  4778. catch (e) {
  4779. // TODO: we should make this error visible somehow
  4780. }
  4781. }, Math.floor(1));
  4782. }
  4783. }
  4784. }
  4785. /**
  4786. * @license
  4787. * Copyright 2017 Google LLC
  4788. *
  4789. * Licensed under the Apache License, Version 2.0 (the "License");
  4790. * you may not use this file except in compliance with the License.
  4791. * You may obtain a copy of the License at
  4792. *
  4793. * http://www.apache.org/licenses/LICENSE-2.0
  4794. *
  4795. * Unless required by applicable law or agreed to in writing, software
  4796. * distributed under the License is distributed on an "AS IS" BASIS,
  4797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4798. * See the License for the specific language governing permissions and
  4799. * limitations under the License.
  4800. */
  4801. /**
  4802. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  4803. * lifecycle.
  4804. *
  4805. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  4806. * they are available.
  4807. */
  4808. class TransportManager {
  4809. /**
  4810. * @param repoInfo - Metadata around the namespace we're connecting to
  4811. */
  4812. constructor(repoInfo) {
  4813. this.initTransports_(repoInfo);
  4814. }
  4815. static get ALL_TRANSPORTS() {
  4816. return [BrowserPollConnection, WebSocketConnection];
  4817. }
  4818. /**
  4819. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  4820. * TransportManager has already set up transports_
  4821. */
  4822. static get IS_TRANSPORT_INITIALIZED() {
  4823. return this.globalTransportInitialized_;
  4824. }
  4825. initTransports_(repoInfo) {
  4826. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  4827. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  4828. if (repoInfo.webSocketOnly) {
  4829. if (!isWebSocketsAvailable) {
  4830. warn$1("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  4831. }
  4832. isSkipPollConnection = true;
  4833. }
  4834. if (isSkipPollConnection) {
  4835. this.transports_ = [WebSocketConnection];
  4836. }
  4837. else {
  4838. const transports = (this.transports_ = []);
  4839. for (const transport of TransportManager.ALL_TRANSPORTS) {
  4840. if (transport && transport['isAvailable']()) {
  4841. transports.push(transport);
  4842. }
  4843. }
  4844. TransportManager.globalTransportInitialized_ = true;
  4845. }
  4846. }
  4847. /**
  4848. * @returns The constructor for the initial transport to use
  4849. */
  4850. initialTransport() {
  4851. if (this.transports_.length > 0) {
  4852. return this.transports_[0];
  4853. }
  4854. else {
  4855. throw new Error('No transports available');
  4856. }
  4857. }
  4858. /**
  4859. * @returns The constructor for the next transport, or null
  4860. */
  4861. upgradeTransport() {
  4862. if (this.transports_.length > 1) {
  4863. return this.transports_[1];
  4864. }
  4865. else {
  4866. return null;
  4867. }
  4868. }
  4869. }
  4870. // Keeps track of whether the TransportManager has already chosen a transport to use
  4871. TransportManager.globalTransportInitialized_ = false;
  4872. /**
  4873. * @license
  4874. * Copyright 2017 Google LLC
  4875. *
  4876. * Licensed under the Apache License, Version 2.0 (the "License");
  4877. * you may not use this file except in compliance with the License.
  4878. * You may obtain a copy of the License at
  4879. *
  4880. * http://www.apache.org/licenses/LICENSE-2.0
  4881. *
  4882. * Unless required by applicable law or agreed to in writing, software
  4883. * distributed under the License is distributed on an "AS IS" BASIS,
  4884. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4885. * See the License for the specific language governing permissions and
  4886. * limitations under the License.
  4887. */
  4888. // Abort upgrade attempt if it takes longer than 60s.
  4889. const UPGRADE_TIMEOUT = 60000;
  4890. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  4891. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  4892. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  4893. // 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)
  4894. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  4895. // but we've sent/received enough bytes, we don't cancel the connection.
  4896. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  4897. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  4898. const MESSAGE_TYPE = 't';
  4899. const MESSAGE_DATA = 'd';
  4900. const CONTROL_SHUTDOWN = 's';
  4901. const CONTROL_RESET = 'r';
  4902. const CONTROL_ERROR = 'e';
  4903. const CONTROL_PONG = 'o';
  4904. const SWITCH_ACK = 'a';
  4905. const END_TRANSMISSION = 'n';
  4906. const PING = 'p';
  4907. const SERVER_HELLO = 'h';
  4908. /**
  4909. * Creates a new real-time connection to the server using whichever method works
  4910. * best in the current browser.
  4911. */
  4912. class Connection {
  4913. /**
  4914. * @param id - an id for this connection
  4915. * @param repoInfo_ - the info for the endpoint to connect to
  4916. * @param applicationId_ - the Firebase App ID for this project
  4917. * @param appCheckToken_ - The App Check Token for this device.
  4918. * @param authToken_ - The auth token for this session.
  4919. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  4920. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  4921. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  4922. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  4923. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  4924. */
  4925. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  4926. this.id = id;
  4927. this.repoInfo_ = repoInfo_;
  4928. this.applicationId_ = applicationId_;
  4929. this.appCheckToken_ = appCheckToken_;
  4930. this.authToken_ = authToken_;
  4931. this.onMessage_ = onMessage_;
  4932. this.onReady_ = onReady_;
  4933. this.onDisconnect_ = onDisconnect_;
  4934. this.onKill_ = onKill_;
  4935. this.lastSessionId = lastSessionId;
  4936. this.connectionCount = 0;
  4937. this.pendingDataMessages = [];
  4938. this.state_ = 0 /* RealtimeState.CONNECTING */;
  4939. this.log_ = logWrapper('c:' + this.id + ':');
  4940. this.transportManager_ = new TransportManager(repoInfo_);
  4941. this.log_('Connection created');
  4942. this.start_();
  4943. }
  4944. /**
  4945. * Starts a connection attempt
  4946. */
  4947. start_() {
  4948. const conn = this.transportManager_.initialTransport();
  4949. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  4950. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  4951. // can consider the transport healthy.
  4952. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  4953. const onMessageReceived = this.connReceiver_(this.conn_);
  4954. const onConnectionLost = this.disconnReceiver_(this.conn_);
  4955. this.tx_ = this.conn_;
  4956. this.rx_ = this.conn_;
  4957. this.secondaryConn_ = null;
  4958. this.isHealthy_ = false;
  4959. /*
  4960. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  4961. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  4962. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  4963. * still have the context of your originating frame.
  4964. */
  4965. setTimeout(() => {
  4966. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  4967. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  4968. }, Math.floor(0));
  4969. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  4970. if (healthyTimeoutMS > 0) {
  4971. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  4972. this.healthyTimeout_ = null;
  4973. if (!this.isHealthy_) {
  4974. if (this.conn_ &&
  4975. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  4976. this.log_('Connection exceeded healthy timeout but has received ' +
  4977. this.conn_.bytesReceived +
  4978. ' bytes. Marking connection healthy.');
  4979. this.isHealthy_ = true;
  4980. this.conn_.markConnectionHealthy();
  4981. }
  4982. else if (this.conn_ &&
  4983. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  4984. this.log_('Connection exceeded healthy timeout but has sent ' +
  4985. this.conn_.bytesSent +
  4986. ' bytes. Leaving connection alive.');
  4987. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  4988. // the server.
  4989. }
  4990. else {
  4991. this.log_('Closing unhealthy connection after timeout.');
  4992. this.close();
  4993. }
  4994. }
  4995. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4996. }, Math.floor(healthyTimeoutMS));
  4997. }
  4998. }
  4999. nextTransportId_() {
  5000. return 'c:' + this.id + ':' + this.connectionCount++;
  5001. }
  5002. disconnReceiver_(conn) {
  5003. return everConnected => {
  5004. if (conn === this.conn_) {
  5005. this.onConnectionLost_(everConnected);
  5006. }
  5007. else if (conn === this.secondaryConn_) {
  5008. this.log_('Secondary connection lost.');
  5009. this.onSecondaryConnectionLost_();
  5010. }
  5011. else {
  5012. this.log_('closing an old connection');
  5013. }
  5014. };
  5015. }
  5016. connReceiver_(conn) {
  5017. return (message) => {
  5018. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  5019. if (conn === this.rx_) {
  5020. this.onPrimaryMessageReceived_(message);
  5021. }
  5022. else if (conn === this.secondaryConn_) {
  5023. this.onSecondaryMessageReceived_(message);
  5024. }
  5025. else {
  5026. this.log_('message on old connection');
  5027. }
  5028. }
  5029. };
  5030. }
  5031. /**
  5032. * @param dataMsg - An arbitrary data message to be sent to the server
  5033. */
  5034. sendRequest(dataMsg) {
  5035. // wrap in a data message envelope and send it on
  5036. const msg = { t: 'd', d: dataMsg };
  5037. this.sendData_(msg);
  5038. }
  5039. tryCleanupConnection() {
  5040. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  5041. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  5042. this.conn_ = this.secondaryConn_;
  5043. this.secondaryConn_ = null;
  5044. // the server will shutdown the old connection
  5045. }
  5046. }
  5047. onSecondaryControl_(controlData) {
  5048. if (MESSAGE_TYPE in controlData) {
  5049. const cmd = controlData[MESSAGE_TYPE];
  5050. if (cmd === SWITCH_ACK) {
  5051. this.upgradeIfSecondaryHealthy_();
  5052. }
  5053. else if (cmd === CONTROL_RESET) {
  5054. // Most likely the session wasn't valid. Abandon the switch attempt
  5055. this.log_('Got a reset on secondary, closing it');
  5056. this.secondaryConn_.close();
  5057. // If we were already using this connection for something, than we need to fully close
  5058. if (this.tx_ === this.secondaryConn_ ||
  5059. this.rx_ === this.secondaryConn_) {
  5060. this.close();
  5061. }
  5062. }
  5063. else if (cmd === CONTROL_PONG) {
  5064. this.log_('got pong on secondary.');
  5065. this.secondaryResponsesRequired_--;
  5066. this.upgradeIfSecondaryHealthy_();
  5067. }
  5068. }
  5069. }
  5070. onSecondaryMessageReceived_(parsedData) {
  5071. const layer = requireKey('t', parsedData);
  5072. const data = requireKey('d', parsedData);
  5073. if (layer === 'c') {
  5074. this.onSecondaryControl_(data);
  5075. }
  5076. else if (layer === 'd') {
  5077. // got a data message, but we're still second connection. Need to buffer it up
  5078. this.pendingDataMessages.push(data);
  5079. }
  5080. else {
  5081. throw new Error('Unknown protocol layer: ' + layer);
  5082. }
  5083. }
  5084. upgradeIfSecondaryHealthy_() {
  5085. if (this.secondaryResponsesRequired_ <= 0) {
  5086. this.log_('Secondary connection is healthy.');
  5087. this.isHealthy_ = true;
  5088. this.secondaryConn_.markConnectionHealthy();
  5089. this.proceedWithUpgrade_();
  5090. }
  5091. else {
  5092. // Send a ping to make sure the connection is healthy.
  5093. this.log_('sending ping on secondary.');
  5094. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  5095. }
  5096. }
  5097. proceedWithUpgrade_() {
  5098. // tell this connection to consider itself open
  5099. this.secondaryConn_.start();
  5100. // send ack
  5101. this.log_('sending client ack on secondary');
  5102. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  5103. // send end packet on primary transport, switch to sending on this one
  5104. // can receive on this one, buffer responses until end received on primary transport
  5105. this.log_('Ending transmission on primary');
  5106. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  5107. this.tx_ = this.secondaryConn_;
  5108. this.tryCleanupConnection();
  5109. }
  5110. onPrimaryMessageReceived_(parsedData) {
  5111. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  5112. const layer = requireKey('t', parsedData);
  5113. const data = requireKey('d', parsedData);
  5114. if (layer === 'c') {
  5115. this.onControl_(data);
  5116. }
  5117. else if (layer === 'd') {
  5118. this.onDataMessage_(data);
  5119. }
  5120. }
  5121. onDataMessage_(message) {
  5122. this.onPrimaryResponse_();
  5123. // We don't do anything with data messages, just kick them up a level
  5124. this.onMessage_(message);
  5125. }
  5126. onPrimaryResponse_() {
  5127. if (!this.isHealthy_) {
  5128. this.primaryResponsesRequired_--;
  5129. if (this.primaryResponsesRequired_ <= 0) {
  5130. this.log_('Primary connection is healthy.');
  5131. this.isHealthy_ = true;
  5132. this.conn_.markConnectionHealthy();
  5133. }
  5134. }
  5135. }
  5136. onControl_(controlData) {
  5137. const cmd = requireKey(MESSAGE_TYPE, controlData);
  5138. if (MESSAGE_DATA in controlData) {
  5139. const payload = controlData[MESSAGE_DATA];
  5140. if (cmd === SERVER_HELLO) {
  5141. const handshakePayload = Object.assign({}, payload);
  5142. if (this.repoInfo_.isUsingEmulator) {
  5143. // 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.
  5144. handshakePayload.h = this.repoInfo_.host;
  5145. }
  5146. this.onHandshake_(handshakePayload);
  5147. }
  5148. else if (cmd === END_TRANSMISSION) {
  5149. this.log_('recvd end transmission on primary');
  5150. this.rx_ = this.secondaryConn_;
  5151. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  5152. this.onDataMessage_(this.pendingDataMessages[i]);
  5153. }
  5154. this.pendingDataMessages = [];
  5155. this.tryCleanupConnection();
  5156. }
  5157. else if (cmd === CONTROL_SHUTDOWN) {
  5158. // This was previously the 'onKill' callback passed to the lower-level connection
  5159. // payload in this case is the reason for the shutdown. Generally a human-readable error
  5160. this.onConnectionShutdown_(payload);
  5161. }
  5162. else if (cmd === CONTROL_RESET) {
  5163. // payload in this case is the host we should contact
  5164. this.onReset_(payload);
  5165. }
  5166. else if (cmd === CONTROL_ERROR) {
  5167. error('Server Error: ' + payload);
  5168. }
  5169. else if (cmd === CONTROL_PONG) {
  5170. this.log_('got pong on primary.');
  5171. this.onPrimaryResponse_();
  5172. this.sendPingOnPrimaryIfNecessary_();
  5173. }
  5174. else {
  5175. error('Unknown control packet command: ' + cmd);
  5176. }
  5177. }
  5178. }
  5179. /**
  5180. * @param handshake - The handshake data returned from the server
  5181. */
  5182. onHandshake_(handshake) {
  5183. const timestamp = handshake.ts;
  5184. const version = handshake.v;
  5185. const host = handshake.h;
  5186. this.sessionId = handshake.s;
  5187. this.repoInfo_.host = host;
  5188. // if we've already closed the connection, then don't bother trying to progress further
  5189. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  5190. this.conn_.start();
  5191. this.onConnectionEstablished_(this.conn_, timestamp);
  5192. if (PROTOCOL_VERSION !== version) {
  5193. warn$1('Protocol version mismatch detected');
  5194. }
  5195. // TODO: do we want to upgrade? when? maybe a delay?
  5196. this.tryStartUpgrade_();
  5197. }
  5198. }
  5199. tryStartUpgrade_() {
  5200. const conn = this.transportManager_.upgradeTransport();
  5201. if (conn) {
  5202. this.startUpgrade_(conn);
  5203. }
  5204. }
  5205. startUpgrade_(conn) {
  5206. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  5207. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  5208. // can consider the transport healthy.
  5209. this.secondaryResponsesRequired_ =
  5210. conn['responsesRequiredToBeHealthy'] || 0;
  5211. const onMessage = this.connReceiver_(this.secondaryConn_);
  5212. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  5213. this.secondaryConn_.open(onMessage, onDisconnect);
  5214. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  5215. setTimeoutNonBlocking(() => {
  5216. if (this.secondaryConn_) {
  5217. this.log_('Timed out trying to upgrade.');
  5218. this.secondaryConn_.close();
  5219. }
  5220. }, Math.floor(UPGRADE_TIMEOUT));
  5221. }
  5222. onReset_(host) {
  5223. this.log_('Reset packet received. New host: ' + host);
  5224. this.repoInfo_.host = host;
  5225. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  5226. // We don't currently support resets after the connection has already been established
  5227. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  5228. this.close();
  5229. }
  5230. else {
  5231. // Close whatever connections we have open and start again.
  5232. this.closeConnections_();
  5233. this.start_();
  5234. }
  5235. }
  5236. onConnectionEstablished_(conn, timestamp) {
  5237. this.log_('Realtime connection established.');
  5238. this.conn_ = conn;
  5239. this.state_ = 1 /* RealtimeState.CONNECTED */;
  5240. if (this.onReady_) {
  5241. this.onReady_(timestamp, this.sessionId);
  5242. this.onReady_ = null;
  5243. }
  5244. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  5245. // send some pings.
  5246. if (this.primaryResponsesRequired_ === 0) {
  5247. this.log_('Primary connection is healthy.');
  5248. this.isHealthy_ = true;
  5249. }
  5250. else {
  5251. setTimeoutNonBlocking(() => {
  5252. this.sendPingOnPrimaryIfNecessary_();
  5253. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  5254. }
  5255. }
  5256. sendPingOnPrimaryIfNecessary_() {
  5257. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  5258. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  5259. this.log_('sending ping on primary.');
  5260. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  5261. }
  5262. }
  5263. onSecondaryConnectionLost_() {
  5264. const conn = this.secondaryConn_;
  5265. this.secondaryConn_ = null;
  5266. if (this.tx_ === conn || this.rx_ === conn) {
  5267. // we are relying on this connection already in some capacity. Therefore, a failure is real
  5268. this.close();
  5269. }
  5270. }
  5271. /**
  5272. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  5273. * we should flush the host cache
  5274. */
  5275. onConnectionLost_(everConnected) {
  5276. this.conn_ = null;
  5277. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  5278. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  5279. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  5280. this.log_('Realtime connection failed.');
  5281. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  5282. if (this.repoInfo_.isCacheableHost()) {
  5283. PersistentStorage.remove('host:' + this.repoInfo_.host);
  5284. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  5285. this.repoInfo_.internalHost = this.repoInfo_.host;
  5286. }
  5287. }
  5288. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  5289. this.log_('Realtime connection lost.');
  5290. }
  5291. this.close();
  5292. }
  5293. onConnectionShutdown_(reason) {
  5294. this.log_('Connection shutdown command received. Shutting down...');
  5295. if (this.onKill_) {
  5296. this.onKill_(reason);
  5297. this.onKill_ = null;
  5298. }
  5299. // We intentionally don't want to fire onDisconnect (kill is a different case),
  5300. // so clear the callback.
  5301. this.onDisconnect_ = null;
  5302. this.close();
  5303. }
  5304. sendData_(data) {
  5305. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  5306. throw 'Connection is not connected';
  5307. }
  5308. else {
  5309. this.tx_.send(data);
  5310. }
  5311. }
  5312. /**
  5313. * Cleans up this connection, calling the appropriate callbacks
  5314. */
  5315. close() {
  5316. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  5317. this.log_('Closing realtime connection.');
  5318. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  5319. this.closeConnections_();
  5320. if (this.onDisconnect_) {
  5321. this.onDisconnect_();
  5322. this.onDisconnect_ = null;
  5323. }
  5324. }
  5325. }
  5326. closeConnections_() {
  5327. this.log_('Shutting down all connections');
  5328. if (this.conn_) {
  5329. this.conn_.close();
  5330. this.conn_ = null;
  5331. }
  5332. if (this.secondaryConn_) {
  5333. this.secondaryConn_.close();
  5334. this.secondaryConn_ = null;
  5335. }
  5336. if (this.healthyTimeout_) {
  5337. clearTimeout(this.healthyTimeout_);
  5338. this.healthyTimeout_ = null;
  5339. }
  5340. }
  5341. }
  5342. /**
  5343. * @license
  5344. * Copyright 2017 Google LLC
  5345. *
  5346. * Licensed under the Apache License, Version 2.0 (the "License");
  5347. * you may not use this file except in compliance with the License.
  5348. * You may obtain a copy of the License at
  5349. *
  5350. * http://www.apache.org/licenses/LICENSE-2.0
  5351. *
  5352. * Unless required by applicable law or agreed to in writing, software
  5353. * distributed under the License is distributed on an "AS IS" BASIS,
  5354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5355. * See the License for the specific language governing permissions and
  5356. * limitations under the License.
  5357. */
  5358. /**
  5359. * Interface defining the set of actions that can be performed against the Firebase server
  5360. * (basically corresponds to our wire protocol).
  5361. *
  5362. * @interface
  5363. */
  5364. class ServerActions {
  5365. put(pathString, data, onComplete, hash) { }
  5366. merge(pathString, data, onComplete, hash) { }
  5367. /**
  5368. * Refreshes the auth token for the current connection.
  5369. * @param token - The authentication token
  5370. */
  5371. refreshAuthToken(token) { }
  5372. /**
  5373. * Refreshes the app check token for the current connection.
  5374. * @param token The app check token
  5375. */
  5376. refreshAppCheckToken(token) { }
  5377. onDisconnectPut(pathString, data, onComplete) { }
  5378. onDisconnectMerge(pathString, data, onComplete) { }
  5379. onDisconnectCancel(pathString, onComplete) { }
  5380. reportStats(stats) { }
  5381. }
  5382. /**
  5383. * @license
  5384. * Copyright 2017 Google LLC
  5385. *
  5386. * Licensed under the Apache License, Version 2.0 (the "License");
  5387. * you may not use this file except in compliance with the License.
  5388. * You may obtain a copy of the License at
  5389. *
  5390. * http://www.apache.org/licenses/LICENSE-2.0
  5391. *
  5392. * Unless required by applicable law or agreed to in writing, software
  5393. * distributed under the License is distributed on an "AS IS" BASIS,
  5394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5395. * See the License for the specific language governing permissions and
  5396. * limitations under the License.
  5397. */
  5398. /**
  5399. * Base class to be used if you want to emit events. Call the constructor with
  5400. * the set of allowed event names.
  5401. */
  5402. class EventEmitter {
  5403. constructor(allowedEvents_) {
  5404. this.allowedEvents_ = allowedEvents_;
  5405. this.listeners_ = {};
  5406. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  5407. }
  5408. /**
  5409. * To be called by derived classes to trigger events.
  5410. */
  5411. trigger(eventType, ...varArgs) {
  5412. if (Array.isArray(this.listeners_[eventType])) {
  5413. // Clone the list, since callbacks could add/remove listeners.
  5414. const listeners = [...this.listeners_[eventType]];
  5415. for (let i = 0; i < listeners.length; i++) {
  5416. listeners[i].callback.apply(listeners[i].context, varArgs);
  5417. }
  5418. }
  5419. }
  5420. on(eventType, callback, context) {
  5421. this.validateEventType_(eventType);
  5422. this.listeners_[eventType] = this.listeners_[eventType] || [];
  5423. this.listeners_[eventType].push({ callback, context });
  5424. const eventData = this.getInitialEvent(eventType);
  5425. if (eventData) {
  5426. callback.apply(context, eventData);
  5427. }
  5428. }
  5429. off(eventType, callback, context) {
  5430. this.validateEventType_(eventType);
  5431. const listeners = this.listeners_[eventType] || [];
  5432. for (let i = 0; i < listeners.length; i++) {
  5433. if (listeners[i].callback === callback &&
  5434. (!context || context === listeners[i].context)) {
  5435. listeners.splice(i, 1);
  5436. return;
  5437. }
  5438. }
  5439. }
  5440. validateEventType_(eventType) {
  5441. util.assert(this.allowedEvents_.find(et => {
  5442. return et === eventType;
  5443. }), 'Unknown event: ' + eventType);
  5444. }
  5445. }
  5446. /**
  5447. * @license
  5448. * Copyright 2017 Google LLC
  5449. *
  5450. * Licensed under the Apache License, Version 2.0 (the "License");
  5451. * you may not use this file except in compliance with the License.
  5452. * You may obtain a copy of the License at
  5453. *
  5454. * http://www.apache.org/licenses/LICENSE-2.0
  5455. *
  5456. * Unless required by applicable law or agreed to in writing, software
  5457. * distributed under the License is distributed on an "AS IS" BASIS,
  5458. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5459. * See the License for the specific language governing permissions and
  5460. * limitations under the License.
  5461. */
  5462. /**
  5463. * Monitors online state (as reported by window.online/offline events).
  5464. *
  5465. * The expectation is that this could have many false positives (thinks we are online
  5466. * when we're not), but no false negatives. So we can safely use it to determine when
  5467. * we definitely cannot reach the internet.
  5468. */
  5469. class OnlineMonitor extends EventEmitter {
  5470. constructor() {
  5471. super(['online']);
  5472. this.online_ = true;
  5473. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  5474. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  5475. // It would seem that the 'online' event does not always fire consistently. So we disable it
  5476. // for Cordova.
  5477. if (typeof window !== 'undefined' &&
  5478. typeof window.addEventListener !== 'undefined' &&
  5479. !util.isMobileCordova()) {
  5480. window.addEventListener('online', () => {
  5481. if (!this.online_) {
  5482. this.online_ = true;
  5483. this.trigger('online', true);
  5484. }
  5485. }, false);
  5486. window.addEventListener('offline', () => {
  5487. if (this.online_) {
  5488. this.online_ = false;
  5489. this.trigger('online', false);
  5490. }
  5491. }, false);
  5492. }
  5493. }
  5494. static getInstance() {
  5495. return new OnlineMonitor();
  5496. }
  5497. getInitialEvent(eventType) {
  5498. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  5499. return [this.online_];
  5500. }
  5501. currentlyOnline() {
  5502. return this.online_;
  5503. }
  5504. }
  5505. /**
  5506. * @license
  5507. * Copyright 2017 Google LLC
  5508. *
  5509. * Licensed under the Apache License, Version 2.0 (the "License");
  5510. * you may not use this file except in compliance with the License.
  5511. * You may obtain a copy of the License at
  5512. *
  5513. * http://www.apache.org/licenses/LICENSE-2.0
  5514. *
  5515. * Unless required by applicable law or agreed to in writing, software
  5516. * distributed under the License is distributed on an "AS IS" BASIS,
  5517. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5518. * See the License for the specific language governing permissions and
  5519. * limitations under the License.
  5520. */
  5521. /** Maximum key depth. */
  5522. const MAX_PATH_DEPTH = 32;
  5523. /** Maximum number of (UTF8) bytes in a Firebase path. */
  5524. const MAX_PATH_LENGTH_BYTES = 768;
  5525. /**
  5526. * An immutable object representing a parsed path. It's immutable so that you
  5527. * can pass them around to other functions without worrying about them changing
  5528. * it.
  5529. */
  5530. class Path {
  5531. /**
  5532. * @param pathOrString - Path string to parse, or another path, or the raw
  5533. * tokens array
  5534. */
  5535. constructor(pathOrString, pieceNum) {
  5536. if (pieceNum === void 0) {
  5537. this.pieces_ = pathOrString.split('/');
  5538. // Remove empty pieces.
  5539. let copyTo = 0;
  5540. for (let i = 0; i < this.pieces_.length; i++) {
  5541. if (this.pieces_[i].length > 0) {
  5542. this.pieces_[copyTo] = this.pieces_[i];
  5543. copyTo++;
  5544. }
  5545. }
  5546. this.pieces_.length = copyTo;
  5547. this.pieceNum_ = 0;
  5548. }
  5549. else {
  5550. this.pieces_ = pathOrString;
  5551. this.pieceNum_ = pieceNum;
  5552. }
  5553. }
  5554. toString() {
  5555. let pathString = '';
  5556. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  5557. if (this.pieces_[i] !== '') {
  5558. pathString += '/' + this.pieces_[i];
  5559. }
  5560. }
  5561. return pathString || '/';
  5562. }
  5563. }
  5564. function newEmptyPath() {
  5565. return new Path('');
  5566. }
  5567. function pathGetFront(path) {
  5568. if (path.pieceNum_ >= path.pieces_.length) {
  5569. return null;
  5570. }
  5571. return path.pieces_[path.pieceNum_];
  5572. }
  5573. /**
  5574. * @returns The number of segments in this path
  5575. */
  5576. function pathGetLength(path) {
  5577. return path.pieces_.length - path.pieceNum_;
  5578. }
  5579. function pathPopFront(path) {
  5580. let pieceNum = path.pieceNum_;
  5581. if (pieceNum < path.pieces_.length) {
  5582. pieceNum++;
  5583. }
  5584. return new Path(path.pieces_, pieceNum);
  5585. }
  5586. function pathGetBack(path) {
  5587. if (path.pieceNum_ < path.pieces_.length) {
  5588. return path.pieces_[path.pieces_.length - 1];
  5589. }
  5590. return null;
  5591. }
  5592. function pathToUrlEncodedString(path) {
  5593. let pathString = '';
  5594. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  5595. if (path.pieces_[i] !== '') {
  5596. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  5597. }
  5598. }
  5599. return pathString || '/';
  5600. }
  5601. /**
  5602. * Shallow copy of the parts of the path.
  5603. *
  5604. */
  5605. function pathSlice(path, begin = 0) {
  5606. return path.pieces_.slice(path.pieceNum_ + begin);
  5607. }
  5608. function pathParent(path) {
  5609. if (path.pieceNum_ >= path.pieces_.length) {
  5610. return null;
  5611. }
  5612. const pieces = [];
  5613. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  5614. pieces.push(path.pieces_[i]);
  5615. }
  5616. return new Path(pieces, 0);
  5617. }
  5618. function pathChild(path, childPathObj) {
  5619. const pieces = [];
  5620. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  5621. pieces.push(path.pieces_[i]);
  5622. }
  5623. if (childPathObj instanceof Path) {
  5624. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  5625. pieces.push(childPathObj.pieces_[i]);
  5626. }
  5627. }
  5628. else {
  5629. const childPieces = childPathObj.split('/');
  5630. for (let i = 0; i < childPieces.length; i++) {
  5631. if (childPieces[i].length > 0) {
  5632. pieces.push(childPieces[i]);
  5633. }
  5634. }
  5635. }
  5636. return new Path(pieces, 0);
  5637. }
  5638. /**
  5639. * @returns True if there are no segments in this path
  5640. */
  5641. function pathIsEmpty(path) {
  5642. return path.pieceNum_ >= path.pieces_.length;
  5643. }
  5644. /**
  5645. * @returns The path from outerPath to innerPath
  5646. */
  5647. function newRelativePath(outerPath, innerPath) {
  5648. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  5649. if (outer === null) {
  5650. return innerPath;
  5651. }
  5652. else if (outer === inner) {
  5653. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  5654. }
  5655. else {
  5656. throw new Error('INTERNAL ERROR: innerPath (' +
  5657. innerPath +
  5658. ') is not within ' +
  5659. 'outerPath (' +
  5660. outerPath +
  5661. ')');
  5662. }
  5663. }
  5664. /**
  5665. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  5666. */
  5667. function pathCompare(left, right) {
  5668. const leftKeys = pathSlice(left, 0);
  5669. const rightKeys = pathSlice(right, 0);
  5670. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  5671. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  5672. if (cmp !== 0) {
  5673. return cmp;
  5674. }
  5675. }
  5676. if (leftKeys.length === rightKeys.length) {
  5677. return 0;
  5678. }
  5679. return leftKeys.length < rightKeys.length ? -1 : 1;
  5680. }
  5681. /**
  5682. * @returns true if paths are the same.
  5683. */
  5684. function pathEquals(path, other) {
  5685. if (pathGetLength(path) !== pathGetLength(other)) {
  5686. return false;
  5687. }
  5688. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  5689. if (path.pieces_[i] !== other.pieces_[j]) {
  5690. return false;
  5691. }
  5692. }
  5693. return true;
  5694. }
  5695. /**
  5696. * @returns True if this path is a parent of (or the same as) other
  5697. */
  5698. function pathContains(path, other) {
  5699. let i = path.pieceNum_;
  5700. let j = other.pieceNum_;
  5701. if (pathGetLength(path) > pathGetLength(other)) {
  5702. return false;
  5703. }
  5704. while (i < path.pieces_.length) {
  5705. if (path.pieces_[i] !== other.pieces_[j]) {
  5706. return false;
  5707. }
  5708. ++i;
  5709. ++j;
  5710. }
  5711. return true;
  5712. }
  5713. /**
  5714. * Dynamic (mutable) path used to count path lengths.
  5715. *
  5716. * This class is used to efficiently check paths for valid
  5717. * length (in UTF8 bytes) and depth (used in path validation).
  5718. *
  5719. * Throws Error exception if path is ever invalid.
  5720. *
  5721. * The definition of a path always begins with '/'.
  5722. */
  5723. class ValidationPath {
  5724. /**
  5725. * @param path - Initial Path.
  5726. * @param errorPrefix_ - Prefix for any error messages.
  5727. */
  5728. constructor(path, errorPrefix_) {
  5729. this.errorPrefix_ = errorPrefix_;
  5730. this.parts_ = pathSlice(path, 0);
  5731. /** Initialize to number of '/' chars needed in path. */
  5732. this.byteLength_ = Math.max(1, this.parts_.length);
  5733. for (let i = 0; i < this.parts_.length; i++) {
  5734. this.byteLength_ += util.stringLength(this.parts_[i]);
  5735. }
  5736. validationPathCheckValid(this);
  5737. }
  5738. }
  5739. function validationPathPush(validationPath, child) {
  5740. // Count the needed '/'
  5741. if (validationPath.parts_.length > 0) {
  5742. validationPath.byteLength_ += 1;
  5743. }
  5744. validationPath.parts_.push(child);
  5745. validationPath.byteLength_ += util.stringLength(child);
  5746. validationPathCheckValid(validationPath);
  5747. }
  5748. function validationPathPop(validationPath) {
  5749. const last = validationPath.parts_.pop();
  5750. validationPath.byteLength_ -= util.stringLength(last);
  5751. // Un-count the previous '/'
  5752. if (validationPath.parts_.length > 0) {
  5753. validationPath.byteLength_ -= 1;
  5754. }
  5755. }
  5756. function validationPathCheckValid(validationPath) {
  5757. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  5758. throw new Error(validationPath.errorPrefix_ +
  5759. 'has a key path longer than ' +
  5760. MAX_PATH_LENGTH_BYTES +
  5761. ' bytes (' +
  5762. validationPath.byteLength_ +
  5763. ').');
  5764. }
  5765. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  5766. throw new Error(validationPath.errorPrefix_ +
  5767. 'path specified exceeds the maximum depth that can be written (' +
  5768. MAX_PATH_DEPTH +
  5769. ') or object contains a cycle ' +
  5770. validationPathToErrorString(validationPath));
  5771. }
  5772. }
  5773. /**
  5774. * String for use in error messages - uses '.' notation for path.
  5775. */
  5776. function validationPathToErrorString(validationPath) {
  5777. if (validationPath.parts_.length === 0) {
  5778. return '';
  5779. }
  5780. return "in property '" + validationPath.parts_.join('.') + "'";
  5781. }
  5782. /**
  5783. * @license
  5784. * Copyright 2017 Google LLC
  5785. *
  5786. * Licensed under the Apache License, Version 2.0 (the "License");
  5787. * you may not use this file except in compliance with the License.
  5788. * You may obtain a copy of the License at
  5789. *
  5790. * http://www.apache.org/licenses/LICENSE-2.0
  5791. *
  5792. * Unless required by applicable law or agreed to in writing, software
  5793. * distributed under the License is distributed on an "AS IS" BASIS,
  5794. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5795. * See the License for the specific language governing permissions and
  5796. * limitations under the License.
  5797. */
  5798. class VisibilityMonitor extends EventEmitter {
  5799. constructor() {
  5800. super(['visible']);
  5801. let hidden;
  5802. let visibilityChange;
  5803. if (typeof document !== 'undefined' &&
  5804. typeof document.addEventListener !== 'undefined') {
  5805. if (typeof document['hidden'] !== 'undefined') {
  5806. // Opera 12.10 and Firefox 18 and later support
  5807. visibilityChange = 'visibilitychange';
  5808. hidden = 'hidden';
  5809. }
  5810. else if (typeof document['mozHidden'] !== 'undefined') {
  5811. visibilityChange = 'mozvisibilitychange';
  5812. hidden = 'mozHidden';
  5813. }
  5814. else if (typeof document['msHidden'] !== 'undefined') {
  5815. visibilityChange = 'msvisibilitychange';
  5816. hidden = 'msHidden';
  5817. }
  5818. else if (typeof document['webkitHidden'] !== 'undefined') {
  5819. visibilityChange = 'webkitvisibilitychange';
  5820. hidden = 'webkitHidden';
  5821. }
  5822. }
  5823. // Initially, we always assume we are visible. This ensures that in browsers
  5824. // without page visibility support or in cases where we are never visible
  5825. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  5826. // reconnects
  5827. this.visible_ = true;
  5828. if (visibilityChange) {
  5829. document.addEventListener(visibilityChange, () => {
  5830. const visible = !document[hidden];
  5831. if (visible !== this.visible_) {
  5832. this.visible_ = visible;
  5833. this.trigger('visible', visible);
  5834. }
  5835. }, false);
  5836. }
  5837. }
  5838. static getInstance() {
  5839. return new VisibilityMonitor();
  5840. }
  5841. getInitialEvent(eventType) {
  5842. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  5843. return [this.visible_];
  5844. }
  5845. }
  5846. /**
  5847. * @license
  5848. * Copyright 2017 Google LLC
  5849. *
  5850. * Licensed under the Apache License, Version 2.0 (the "License");
  5851. * you may not use this file except in compliance with the License.
  5852. * You may obtain a copy of the License at
  5853. *
  5854. * http://www.apache.org/licenses/LICENSE-2.0
  5855. *
  5856. * Unless required by applicable law or agreed to in writing, software
  5857. * distributed under the License is distributed on an "AS IS" BASIS,
  5858. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5859. * See the License for the specific language governing permissions and
  5860. * limitations under the License.
  5861. */
  5862. const RECONNECT_MIN_DELAY = 1000;
  5863. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  5864. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  5865. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  5866. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  5867. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  5868. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  5869. const INVALID_TOKEN_THRESHOLD = 3;
  5870. /**
  5871. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  5872. *
  5873. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  5874. * in quotes to make sure the closure compiler does not minify them.
  5875. */
  5876. class PersistentConnection extends ServerActions {
  5877. /**
  5878. * @param repoInfo_ - Data about the namespace we are connecting to
  5879. * @param applicationId_ - The Firebase App ID for this project
  5880. * @param onDataUpdate_ - A callback for new data from the server
  5881. */
  5882. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  5883. super();
  5884. this.repoInfo_ = repoInfo_;
  5885. this.applicationId_ = applicationId_;
  5886. this.onDataUpdate_ = onDataUpdate_;
  5887. this.onConnectStatus_ = onConnectStatus_;
  5888. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  5889. this.authTokenProvider_ = authTokenProvider_;
  5890. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  5891. this.authOverride_ = authOverride_;
  5892. // Used for diagnostic logging.
  5893. this.id = PersistentConnection.nextPersistentConnectionId_++;
  5894. this.log_ = logWrapper('p:' + this.id + ':');
  5895. this.interruptReasons_ = {};
  5896. this.listens = new Map();
  5897. this.outstandingPuts_ = [];
  5898. this.outstandingGets_ = [];
  5899. this.outstandingPutCount_ = 0;
  5900. this.outstandingGetCount_ = 0;
  5901. this.onDisconnectRequestQueue_ = [];
  5902. this.connected_ = false;
  5903. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  5904. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  5905. this.securityDebugCallback_ = null;
  5906. this.lastSessionId = null;
  5907. this.establishConnectionTimer_ = null;
  5908. this.visible_ = false;
  5909. // Before we get connected, we keep a queue of pending messages to send.
  5910. this.requestCBHash_ = {};
  5911. this.requestNumber_ = 0;
  5912. this.realtime_ = null;
  5913. this.authToken_ = null;
  5914. this.appCheckToken_ = null;
  5915. this.forceTokenRefresh_ = false;
  5916. this.invalidAuthTokenCount_ = 0;
  5917. this.invalidAppCheckTokenCount_ = 0;
  5918. this.firstConnection_ = true;
  5919. this.lastConnectionAttemptTime_ = null;
  5920. this.lastConnectionEstablishedTime_ = null;
  5921. if (authOverride_ && !util.isNodeSdk()) {
  5922. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  5923. }
  5924. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  5925. if (repoInfo_.host.indexOf('fblocal') === -1) {
  5926. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  5927. }
  5928. }
  5929. sendRequest(action, body, onResponse) {
  5930. const curReqNum = ++this.requestNumber_;
  5931. const msg = { r: curReqNum, a: action, b: body };
  5932. this.log_(util.stringify(msg));
  5933. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  5934. this.realtime_.sendRequest(msg);
  5935. if (onResponse) {
  5936. this.requestCBHash_[curReqNum] = onResponse;
  5937. }
  5938. }
  5939. get(query) {
  5940. this.initConnection_();
  5941. const deferred = new util.Deferred();
  5942. const request = {
  5943. p: query._path.toString(),
  5944. q: query._queryObject
  5945. };
  5946. const outstandingGet = {
  5947. action: 'g',
  5948. request,
  5949. onComplete: (message) => {
  5950. const payload = message['d'];
  5951. if (message['s'] === 'ok') {
  5952. deferred.resolve(payload);
  5953. }
  5954. else {
  5955. deferred.reject(payload);
  5956. }
  5957. }
  5958. };
  5959. this.outstandingGets_.push(outstandingGet);
  5960. this.outstandingGetCount_++;
  5961. const index = this.outstandingGets_.length - 1;
  5962. if (this.connected_) {
  5963. this.sendGet_(index);
  5964. }
  5965. return deferred.promise;
  5966. }
  5967. listen(query, currentHashFn, tag, onComplete) {
  5968. this.initConnection_();
  5969. const queryId = query._queryIdentifier;
  5970. const pathString = query._path.toString();
  5971. this.log_('Listen called for ' + pathString + ' ' + queryId);
  5972. if (!this.listens.has(pathString)) {
  5973. this.listens.set(pathString, new Map());
  5974. }
  5975. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  5976. util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  5977. const listenSpec = {
  5978. onComplete,
  5979. hashFn: currentHashFn,
  5980. query,
  5981. tag
  5982. };
  5983. this.listens.get(pathString).set(queryId, listenSpec);
  5984. if (this.connected_) {
  5985. this.sendListen_(listenSpec);
  5986. }
  5987. }
  5988. sendGet_(index) {
  5989. const get = this.outstandingGets_[index];
  5990. this.sendRequest('g', get.request, (message) => {
  5991. delete this.outstandingGets_[index];
  5992. this.outstandingGetCount_--;
  5993. if (this.outstandingGetCount_ === 0) {
  5994. this.outstandingGets_ = [];
  5995. }
  5996. if (get.onComplete) {
  5997. get.onComplete(message);
  5998. }
  5999. });
  6000. }
  6001. sendListen_(listenSpec) {
  6002. const query = listenSpec.query;
  6003. const pathString = query._path.toString();
  6004. const queryId = query._queryIdentifier;
  6005. this.log_('Listen on ' + pathString + ' for ' + queryId);
  6006. const req = { /*path*/ p: pathString };
  6007. const action = 'q';
  6008. // Only bother to send query if it's non-default.
  6009. if (listenSpec.tag) {
  6010. req['q'] = query._queryObject;
  6011. req['t'] = listenSpec.tag;
  6012. }
  6013. req[ /*hash*/'h'] = listenSpec.hashFn();
  6014. this.sendRequest(action, req, (message) => {
  6015. const payload = message[ /*data*/'d'];
  6016. const status = message[ /*status*/'s'];
  6017. // print warnings in any case...
  6018. PersistentConnection.warnOnListenWarnings_(payload, query);
  6019. const currentListenSpec = this.listens.get(pathString) &&
  6020. this.listens.get(pathString).get(queryId);
  6021. // only trigger actions if the listen hasn't been removed and readded
  6022. if (currentListenSpec === listenSpec) {
  6023. this.log_('listen response', message);
  6024. if (status !== 'ok') {
  6025. this.removeListen_(pathString, queryId);
  6026. }
  6027. if (listenSpec.onComplete) {
  6028. listenSpec.onComplete(status, payload);
  6029. }
  6030. }
  6031. });
  6032. }
  6033. static warnOnListenWarnings_(payload, query) {
  6034. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  6035. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6036. const warnings = util.safeGet(payload, 'w');
  6037. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  6038. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  6039. const indexPath = query._path.toString();
  6040. warn$1(`Using an unspecified index. Your data will be downloaded and ` +
  6041. `filtered on the client. Consider adding ${indexSpec} at ` +
  6042. `${indexPath} to your security rules for better performance.`);
  6043. }
  6044. }
  6045. }
  6046. refreshAuthToken(token) {
  6047. this.authToken_ = token;
  6048. this.log_('Auth token refreshed');
  6049. if (this.authToken_) {
  6050. this.tryAuth();
  6051. }
  6052. else {
  6053. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  6054. //the credential so we dont become authenticated next time we connect.
  6055. if (this.connected_) {
  6056. this.sendRequest('unauth', {}, () => { });
  6057. }
  6058. }
  6059. this.reduceReconnectDelayIfAdminCredential_(token);
  6060. }
  6061. reduceReconnectDelayIfAdminCredential_(credential) {
  6062. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  6063. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  6064. const isFirebaseSecret = credential && credential.length === 40;
  6065. if (isFirebaseSecret || util.isAdmin(credential)) {
  6066. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  6067. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  6068. }
  6069. }
  6070. refreshAppCheckToken(token) {
  6071. this.appCheckToken_ = token;
  6072. this.log_('App check token refreshed');
  6073. if (this.appCheckToken_) {
  6074. this.tryAppCheck();
  6075. }
  6076. else {
  6077. //If we're connected we want to let the server know to unauthenticate us.
  6078. //If we're not connected, simply delete the credential so we dont become
  6079. // authenticated next time we connect.
  6080. if (this.connected_) {
  6081. this.sendRequest('unappeck', {}, () => { });
  6082. }
  6083. }
  6084. }
  6085. /**
  6086. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  6087. * a auth revoked (the connection is closed).
  6088. */
  6089. tryAuth() {
  6090. if (this.connected_ && this.authToken_) {
  6091. const token = this.authToken_;
  6092. const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth';
  6093. const requestData = { cred: token };
  6094. if (this.authOverride_ === null) {
  6095. requestData['noauth'] = true;
  6096. }
  6097. else if (typeof this.authOverride_ === 'object') {
  6098. requestData['authvar'] = this.authOverride_;
  6099. }
  6100. this.sendRequest(authMethod, requestData, (res) => {
  6101. const status = res[ /*status*/'s'];
  6102. const data = res[ /*data*/'d'] || 'error';
  6103. if (this.authToken_ === token) {
  6104. if (status === 'ok') {
  6105. this.invalidAuthTokenCount_ = 0;
  6106. }
  6107. else {
  6108. // Triggers reconnect and force refresh for auth token
  6109. this.onAuthRevoked_(status, data);
  6110. }
  6111. }
  6112. });
  6113. }
  6114. }
  6115. /**
  6116. * Attempts to authenticate with the given token. If the authentication
  6117. * attempt fails, it's triggered like the token was revoked (the connection is
  6118. * closed).
  6119. */
  6120. tryAppCheck() {
  6121. if (this.connected_ && this.appCheckToken_) {
  6122. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  6123. const status = res[ /*status*/'s'];
  6124. const data = res[ /*data*/'d'] || 'error';
  6125. if (status === 'ok') {
  6126. this.invalidAppCheckTokenCount_ = 0;
  6127. }
  6128. else {
  6129. this.onAppCheckRevoked_(status, data);
  6130. }
  6131. });
  6132. }
  6133. }
  6134. /**
  6135. * @inheritDoc
  6136. */
  6137. unlisten(query, tag) {
  6138. const pathString = query._path.toString();
  6139. const queryId = query._queryIdentifier;
  6140. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  6141. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  6142. const listen = this.removeListen_(pathString, queryId);
  6143. if (listen && this.connected_) {
  6144. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  6145. }
  6146. }
  6147. sendUnlisten_(pathString, queryId, queryObj, tag) {
  6148. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  6149. const req = { /*path*/ p: pathString };
  6150. const action = 'n';
  6151. // Only bother sending queryId if it's non-default.
  6152. if (tag) {
  6153. req['q'] = queryObj;
  6154. req['t'] = tag;
  6155. }
  6156. this.sendRequest(action, req);
  6157. }
  6158. onDisconnectPut(pathString, data, onComplete) {
  6159. this.initConnection_();
  6160. if (this.connected_) {
  6161. this.sendOnDisconnect_('o', pathString, data, onComplete);
  6162. }
  6163. else {
  6164. this.onDisconnectRequestQueue_.push({
  6165. pathString,
  6166. action: 'o',
  6167. data,
  6168. onComplete
  6169. });
  6170. }
  6171. }
  6172. onDisconnectMerge(pathString, data, onComplete) {
  6173. this.initConnection_();
  6174. if (this.connected_) {
  6175. this.sendOnDisconnect_('om', pathString, data, onComplete);
  6176. }
  6177. else {
  6178. this.onDisconnectRequestQueue_.push({
  6179. pathString,
  6180. action: 'om',
  6181. data,
  6182. onComplete
  6183. });
  6184. }
  6185. }
  6186. onDisconnectCancel(pathString, onComplete) {
  6187. this.initConnection_();
  6188. if (this.connected_) {
  6189. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  6190. }
  6191. else {
  6192. this.onDisconnectRequestQueue_.push({
  6193. pathString,
  6194. action: 'oc',
  6195. data: null,
  6196. onComplete
  6197. });
  6198. }
  6199. }
  6200. sendOnDisconnect_(action, pathString, data, onComplete) {
  6201. const request = { /*path*/ p: pathString, /*data*/ d: data };
  6202. this.log_('onDisconnect ' + action, request);
  6203. this.sendRequest(action, request, (response) => {
  6204. if (onComplete) {
  6205. setTimeout(() => {
  6206. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  6207. }, Math.floor(0));
  6208. }
  6209. });
  6210. }
  6211. put(pathString, data, onComplete, hash) {
  6212. this.putInternal('p', pathString, data, onComplete, hash);
  6213. }
  6214. merge(pathString, data, onComplete, hash) {
  6215. this.putInternal('m', pathString, data, onComplete, hash);
  6216. }
  6217. putInternal(action, pathString, data, onComplete, hash) {
  6218. this.initConnection_();
  6219. const request = {
  6220. /*path*/ p: pathString,
  6221. /*data*/ d: data
  6222. };
  6223. if (hash !== undefined) {
  6224. request[ /*hash*/'h'] = hash;
  6225. }
  6226. // TODO: Only keep track of the most recent put for a given path?
  6227. this.outstandingPuts_.push({
  6228. action,
  6229. request,
  6230. onComplete
  6231. });
  6232. this.outstandingPutCount_++;
  6233. const index = this.outstandingPuts_.length - 1;
  6234. if (this.connected_) {
  6235. this.sendPut_(index);
  6236. }
  6237. else {
  6238. this.log_('Buffering put: ' + pathString);
  6239. }
  6240. }
  6241. sendPut_(index) {
  6242. const action = this.outstandingPuts_[index].action;
  6243. const request = this.outstandingPuts_[index].request;
  6244. const onComplete = this.outstandingPuts_[index].onComplete;
  6245. this.outstandingPuts_[index].queued = this.connected_;
  6246. this.sendRequest(action, request, (message) => {
  6247. this.log_(action + ' response', message);
  6248. delete this.outstandingPuts_[index];
  6249. this.outstandingPutCount_--;
  6250. // Clean up array occasionally.
  6251. if (this.outstandingPutCount_ === 0) {
  6252. this.outstandingPuts_ = [];
  6253. }
  6254. if (onComplete) {
  6255. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  6256. }
  6257. });
  6258. }
  6259. reportStats(stats) {
  6260. // If we're not connected, we just drop the stats.
  6261. if (this.connected_) {
  6262. const request = { /*counters*/ c: stats };
  6263. this.log_('reportStats', request);
  6264. this.sendRequest(/*stats*/ 's', request, result => {
  6265. const status = result[ /*status*/'s'];
  6266. if (status !== 'ok') {
  6267. const errorReason = result[ /* data */'d'];
  6268. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  6269. }
  6270. });
  6271. }
  6272. }
  6273. onDataMessage_(message) {
  6274. if ('r' in message) {
  6275. // this is a response
  6276. this.log_('from server: ' + util.stringify(message));
  6277. const reqNum = message['r'];
  6278. const onResponse = this.requestCBHash_[reqNum];
  6279. if (onResponse) {
  6280. delete this.requestCBHash_[reqNum];
  6281. onResponse(message[ /*body*/'b']);
  6282. }
  6283. }
  6284. else if ('error' in message) {
  6285. throw 'A server-side error has occurred: ' + message['error'];
  6286. }
  6287. else if ('a' in message) {
  6288. // a and b are action and body, respectively
  6289. this.onDataPush_(message['a'], message['b']);
  6290. }
  6291. }
  6292. onDataPush_(action, body) {
  6293. this.log_('handleServerMessage', action, body);
  6294. if (action === 'd') {
  6295. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  6296. /*isMerge*/ false, body['t']);
  6297. }
  6298. else if (action === 'm') {
  6299. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  6300. /*isMerge=*/ true, body['t']);
  6301. }
  6302. else if (action === 'c') {
  6303. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  6304. }
  6305. else if (action === 'ac') {
  6306. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  6307. }
  6308. else if (action === 'apc') {
  6309. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  6310. }
  6311. else if (action === 'sd') {
  6312. this.onSecurityDebugPacket_(body);
  6313. }
  6314. else {
  6315. error('Unrecognized action received from server: ' +
  6316. util.stringify(action) +
  6317. '\nAre you using the latest client?');
  6318. }
  6319. }
  6320. onReady_(timestamp, sessionId) {
  6321. this.log_('connection ready');
  6322. this.connected_ = true;
  6323. this.lastConnectionEstablishedTime_ = new Date().getTime();
  6324. this.handleTimestamp_(timestamp);
  6325. this.lastSessionId = sessionId;
  6326. if (this.firstConnection_) {
  6327. this.sendConnectStats_();
  6328. }
  6329. this.restoreState_();
  6330. this.firstConnection_ = false;
  6331. this.onConnectStatus_(true);
  6332. }
  6333. scheduleConnect_(timeout) {
  6334. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  6335. if (this.establishConnectionTimer_) {
  6336. clearTimeout(this.establishConnectionTimer_);
  6337. }
  6338. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  6339. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  6340. this.establishConnectionTimer_ = setTimeout(() => {
  6341. this.establishConnectionTimer_ = null;
  6342. this.establishConnection_();
  6343. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6344. }, Math.floor(timeout));
  6345. }
  6346. initConnection_() {
  6347. if (!this.realtime_ && this.firstConnection_) {
  6348. this.scheduleConnect_(0);
  6349. }
  6350. }
  6351. onVisible_(visible) {
  6352. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  6353. if (visible &&
  6354. !this.visible_ &&
  6355. this.reconnectDelay_ === this.maxReconnectDelay_) {
  6356. this.log_('Window became visible. Reducing delay.');
  6357. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6358. if (!this.realtime_) {
  6359. this.scheduleConnect_(0);
  6360. }
  6361. }
  6362. this.visible_ = visible;
  6363. }
  6364. onOnline_(online) {
  6365. if (online) {
  6366. this.log_('Browser went online.');
  6367. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6368. if (!this.realtime_) {
  6369. this.scheduleConnect_(0);
  6370. }
  6371. }
  6372. else {
  6373. this.log_('Browser went offline. Killing connection.');
  6374. if (this.realtime_) {
  6375. this.realtime_.close();
  6376. }
  6377. }
  6378. }
  6379. onRealtimeDisconnect_() {
  6380. this.log_('data client disconnected');
  6381. this.connected_ = false;
  6382. this.realtime_ = null;
  6383. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  6384. this.cancelSentTransactions_();
  6385. // Clear out the pending requests.
  6386. this.requestCBHash_ = {};
  6387. if (this.shouldReconnect_()) {
  6388. if (!this.visible_) {
  6389. this.log_("Window isn't visible. Delaying reconnect.");
  6390. this.reconnectDelay_ = this.maxReconnectDelay_;
  6391. this.lastConnectionAttemptTime_ = new Date().getTime();
  6392. }
  6393. else if (this.lastConnectionEstablishedTime_) {
  6394. // If we've been connected long enough, reset reconnect delay to minimum.
  6395. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  6396. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  6397. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6398. }
  6399. this.lastConnectionEstablishedTime_ = null;
  6400. }
  6401. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  6402. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  6403. reconnectDelay = Math.random() * reconnectDelay;
  6404. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  6405. this.scheduleConnect_(reconnectDelay);
  6406. // Adjust reconnect delay for next time.
  6407. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  6408. }
  6409. this.onConnectStatus_(false);
  6410. }
  6411. async establishConnection_() {
  6412. if (this.shouldReconnect_()) {
  6413. this.log_('Making a connection attempt');
  6414. this.lastConnectionAttemptTime_ = new Date().getTime();
  6415. this.lastConnectionEstablishedTime_ = null;
  6416. const onDataMessage = this.onDataMessage_.bind(this);
  6417. const onReady = this.onReady_.bind(this);
  6418. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  6419. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  6420. const lastSessionId = this.lastSessionId;
  6421. let canceled = false;
  6422. let connection = null;
  6423. const closeFn = function () {
  6424. if (connection) {
  6425. connection.close();
  6426. }
  6427. else {
  6428. canceled = true;
  6429. onDisconnect();
  6430. }
  6431. };
  6432. const sendRequestFn = function (msg) {
  6433. util.assert(connection, "sendRequest call when we're not connected not allowed.");
  6434. connection.sendRequest(msg);
  6435. };
  6436. this.realtime_ = {
  6437. close: closeFn,
  6438. sendRequest: sendRequestFn
  6439. };
  6440. const forceRefresh = this.forceTokenRefresh_;
  6441. this.forceTokenRefresh_ = false;
  6442. try {
  6443. // First fetch auth and app check token, and establish connection after
  6444. // fetching the token was successful
  6445. const [authToken, appCheckToken] = await Promise.all([
  6446. this.authTokenProvider_.getToken(forceRefresh),
  6447. this.appCheckTokenProvider_.getToken(forceRefresh)
  6448. ]);
  6449. if (!canceled) {
  6450. log('getToken() completed. Creating connection.');
  6451. this.authToken_ = authToken && authToken.accessToken;
  6452. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  6453. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  6454. /* onKill= */ reason => {
  6455. warn$1(reason + ' (' + this.repoInfo_.toString() + ')');
  6456. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  6457. }, lastSessionId);
  6458. }
  6459. else {
  6460. log('getToken() completed but was canceled');
  6461. }
  6462. }
  6463. catch (error) {
  6464. this.log_('Failed to get token: ' + error);
  6465. if (!canceled) {
  6466. if (this.repoInfo_.nodeAdmin) {
  6467. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  6468. // But getToken() may also just have temporarily failed, so we still want to
  6469. // continue retrying.
  6470. warn$1(error);
  6471. }
  6472. closeFn();
  6473. }
  6474. }
  6475. }
  6476. }
  6477. interrupt(reason) {
  6478. log('Interrupting connection for reason: ' + reason);
  6479. this.interruptReasons_[reason] = true;
  6480. if (this.realtime_) {
  6481. this.realtime_.close();
  6482. }
  6483. else {
  6484. if (this.establishConnectionTimer_) {
  6485. clearTimeout(this.establishConnectionTimer_);
  6486. this.establishConnectionTimer_ = null;
  6487. }
  6488. if (this.connected_) {
  6489. this.onRealtimeDisconnect_();
  6490. }
  6491. }
  6492. }
  6493. resume(reason) {
  6494. log('Resuming connection for reason: ' + reason);
  6495. delete this.interruptReasons_[reason];
  6496. if (util.isEmpty(this.interruptReasons_)) {
  6497. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6498. if (!this.realtime_) {
  6499. this.scheduleConnect_(0);
  6500. }
  6501. }
  6502. }
  6503. handleTimestamp_(timestamp) {
  6504. const delta = timestamp - new Date().getTime();
  6505. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  6506. }
  6507. cancelSentTransactions_() {
  6508. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  6509. const put = this.outstandingPuts_[i];
  6510. if (put && /*hash*/ 'h' in put.request && put.queued) {
  6511. if (put.onComplete) {
  6512. put.onComplete('disconnect');
  6513. }
  6514. delete this.outstandingPuts_[i];
  6515. this.outstandingPutCount_--;
  6516. }
  6517. }
  6518. // Clean up array occasionally.
  6519. if (this.outstandingPutCount_ === 0) {
  6520. this.outstandingPuts_ = [];
  6521. }
  6522. }
  6523. onListenRevoked_(pathString, query) {
  6524. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  6525. let queryId;
  6526. if (!query) {
  6527. queryId = 'default';
  6528. }
  6529. else {
  6530. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  6531. }
  6532. const listen = this.removeListen_(pathString, queryId);
  6533. if (listen && listen.onComplete) {
  6534. listen.onComplete('permission_denied');
  6535. }
  6536. }
  6537. removeListen_(pathString, queryId) {
  6538. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  6539. let listen;
  6540. if (this.listens.has(normalizedPathString)) {
  6541. const map = this.listens.get(normalizedPathString);
  6542. listen = map.get(queryId);
  6543. map.delete(queryId);
  6544. if (map.size === 0) {
  6545. this.listens.delete(normalizedPathString);
  6546. }
  6547. }
  6548. else {
  6549. // all listens for this path has already been removed
  6550. listen = undefined;
  6551. }
  6552. return listen;
  6553. }
  6554. onAuthRevoked_(statusCode, explanation) {
  6555. log('Auth token revoked: ' + statusCode + '/' + explanation);
  6556. this.authToken_ = null;
  6557. this.forceTokenRefresh_ = true;
  6558. this.realtime_.close();
  6559. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  6560. // We'll wait a couple times before logging the warning / increasing the
  6561. // retry period since oauth tokens will report as "invalid" if they're
  6562. // just expired. Plus there may be transient issues that resolve themselves.
  6563. this.invalidAuthTokenCount_++;
  6564. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  6565. // Set a long reconnect delay because recovery is unlikely
  6566. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  6567. // Notify the auth token provider that the token is invalid, which will log
  6568. // a warning
  6569. this.authTokenProvider_.notifyForInvalidToken();
  6570. }
  6571. }
  6572. }
  6573. onAppCheckRevoked_(statusCode, explanation) {
  6574. log('App check token revoked: ' + statusCode + '/' + explanation);
  6575. this.appCheckToken_ = null;
  6576. this.forceTokenRefresh_ = true;
  6577. // Note: We don't close the connection as the developer may not have
  6578. // enforcement enabled. The backend closes connections with enforcements.
  6579. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  6580. // We'll wait a couple times before logging the warning / increasing the
  6581. // retry period since oauth tokens will report as "invalid" if they're
  6582. // just expired. Plus there may be transient issues that resolve themselves.
  6583. this.invalidAppCheckTokenCount_++;
  6584. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  6585. this.appCheckTokenProvider_.notifyForInvalidToken();
  6586. }
  6587. }
  6588. }
  6589. onSecurityDebugPacket_(body) {
  6590. if (this.securityDebugCallback_) {
  6591. this.securityDebugCallback_(body);
  6592. }
  6593. else {
  6594. if ('msg' in body) {
  6595. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  6596. }
  6597. }
  6598. }
  6599. restoreState_() {
  6600. //Re-authenticate ourselves if we have a credential stored.
  6601. this.tryAuth();
  6602. this.tryAppCheck();
  6603. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  6604. // make sure to send listens before puts.
  6605. for (const queries of this.listens.values()) {
  6606. for (const listenSpec of queries.values()) {
  6607. this.sendListen_(listenSpec);
  6608. }
  6609. }
  6610. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  6611. if (this.outstandingPuts_[i]) {
  6612. this.sendPut_(i);
  6613. }
  6614. }
  6615. while (this.onDisconnectRequestQueue_.length) {
  6616. const request = this.onDisconnectRequestQueue_.shift();
  6617. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  6618. }
  6619. for (let i = 0; i < this.outstandingGets_.length; i++) {
  6620. if (this.outstandingGets_[i]) {
  6621. this.sendGet_(i);
  6622. }
  6623. }
  6624. }
  6625. /**
  6626. * Sends client stats for first connection
  6627. */
  6628. sendConnectStats_() {
  6629. const stats = {};
  6630. let clientName = 'js';
  6631. if (util.isNodeSdk()) {
  6632. if (this.repoInfo_.nodeAdmin) {
  6633. clientName = 'admin_node';
  6634. }
  6635. else {
  6636. clientName = 'node';
  6637. }
  6638. }
  6639. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  6640. if (util.isMobileCordova()) {
  6641. stats['framework.cordova'] = 1;
  6642. }
  6643. else if (util.isReactNative()) {
  6644. stats['framework.reactnative'] = 1;
  6645. }
  6646. this.reportStats(stats);
  6647. }
  6648. shouldReconnect_() {
  6649. const online = OnlineMonitor.getInstance().currentlyOnline();
  6650. return util.isEmpty(this.interruptReasons_) && online;
  6651. }
  6652. }
  6653. PersistentConnection.nextPersistentConnectionId_ = 0;
  6654. /**
  6655. * Counter for number of connections created. Mainly used for tagging in the logs
  6656. */
  6657. PersistentConnection.nextConnectionId_ = 0;
  6658. /**
  6659. * @license
  6660. * Copyright 2017 Google LLC
  6661. *
  6662. * Licensed under the Apache License, Version 2.0 (the "License");
  6663. * you may not use this file except in compliance with the License.
  6664. * You may obtain a copy of the License at
  6665. *
  6666. * http://www.apache.org/licenses/LICENSE-2.0
  6667. *
  6668. * Unless required by applicable law or agreed to in writing, software
  6669. * distributed under the License is distributed on an "AS IS" BASIS,
  6670. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6671. * See the License for the specific language governing permissions and
  6672. * limitations under the License.
  6673. */
  6674. class NamedNode {
  6675. constructor(name, node) {
  6676. this.name = name;
  6677. this.node = node;
  6678. }
  6679. static Wrap(name, node) {
  6680. return new NamedNode(name, node);
  6681. }
  6682. }
  6683. /**
  6684. * @license
  6685. * Copyright 2017 Google LLC
  6686. *
  6687. * Licensed under the Apache License, Version 2.0 (the "License");
  6688. * you may not use this file except in compliance with the License.
  6689. * You may obtain a copy of the License at
  6690. *
  6691. * http://www.apache.org/licenses/LICENSE-2.0
  6692. *
  6693. * Unless required by applicable law or agreed to in writing, software
  6694. * distributed under the License is distributed on an "AS IS" BASIS,
  6695. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6696. * See the License for the specific language governing permissions and
  6697. * limitations under the License.
  6698. */
  6699. class Index {
  6700. /**
  6701. * @returns A standalone comparison function for
  6702. * this index
  6703. */
  6704. getCompare() {
  6705. return this.compare.bind(this);
  6706. }
  6707. /**
  6708. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  6709. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  6710. *
  6711. *
  6712. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  6713. */
  6714. indexedValueChanged(oldNode, newNode) {
  6715. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  6716. const newWrapped = new NamedNode(MIN_NAME, newNode);
  6717. return this.compare(oldWrapped, newWrapped) !== 0;
  6718. }
  6719. /**
  6720. * @returns a node wrapper that will sort equal to or less than
  6721. * any other node wrapper, using this index
  6722. */
  6723. minPost() {
  6724. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6725. return NamedNode.MIN;
  6726. }
  6727. }
  6728. /**
  6729. * @license
  6730. * Copyright 2017 Google LLC
  6731. *
  6732. * Licensed under the Apache License, Version 2.0 (the "License");
  6733. * you may not use this file except in compliance with the License.
  6734. * You may obtain a copy of the License at
  6735. *
  6736. * http://www.apache.org/licenses/LICENSE-2.0
  6737. *
  6738. * Unless required by applicable law or agreed to in writing, software
  6739. * distributed under the License is distributed on an "AS IS" BASIS,
  6740. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6741. * See the License for the specific language governing permissions and
  6742. * limitations under the License.
  6743. */
  6744. let __EMPTY_NODE;
  6745. class KeyIndex extends Index {
  6746. static get __EMPTY_NODE() {
  6747. return __EMPTY_NODE;
  6748. }
  6749. static set __EMPTY_NODE(val) {
  6750. __EMPTY_NODE = val;
  6751. }
  6752. compare(a, b) {
  6753. return nameCompare(a.name, b.name);
  6754. }
  6755. isDefinedOn(node) {
  6756. // We could probably return true here (since every node has a key), but it's never called
  6757. // so just leaving unimplemented for now.
  6758. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  6759. }
  6760. indexedValueChanged(oldNode, newNode) {
  6761. return false; // The key for a node never changes.
  6762. }
  6763. minPost() {
  6764. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6765. return NamedNode.MIN;
  6766. }
  6767. maxPost() {
  6768. // TODO: This should really be created once and cached in a static property, but
  6769. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  6770. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  6771. }
  6772. makePost(indexValue, name) {
  6773. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  6774. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  6775. return new NamedNode(indexValue, __EMPTY_NODE);
  6776. }
  6777. /**
  6778. * @returns String representation for inclusion in a query spec
  6779. */
  6780. toString() {
  6781. return '.key';
  6782. }
  6783. }
  6784. const KEY_INDEX = new KeyIndex();
  6785. /**
  6786. * @license
  6787. * Copyright 2017 Google LLC
  6788. *
  6789. * Licensed under the Apache License, Version 2.0 (the "License");
  6790. * you may not use this file except in compliance with the License.
  6791. * You may obtain a copy of the License at
  6792. *
  6793. * http://www.apache.org/licenses/LICENSE-2.0
  6794. *
  6795. * Unless required by applicable law or agreed to in writing, software
  6796. * distributed under the License is distributed on an "AS IS" BASIS,
  6797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6798. * See the License for the specific language governing permissions and
  6799. * limitations under the License.
  6800. */
  6801. /**
  6802. * An iterator over an LLRBNode.
  6803. */
  6804. class SortedMapIterator {
  6805. /**
  6806. * @param node - Node to iterate.
  6807. * @param isReverse_ - Whether or not to iterate in reverse
  6808. */
  6809. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  6810. this.isReverse_ = isReverse_;
  6811. this.resultGenerator_ = resultGenerator_;
  6812. this.nodeStack_ = [];
  6813. let cmp = 1;
  6814. while (!node.isEmpty()) {
  6815. node = node;
  6816. cmp = startKey ? comparator(node.key, startKey) : 1;
  6817. // flip the comparison if we're going in reverse
  6818. if (isReverse_) {
  6819. cmp *= -1;
  6820. }
  6821. if (cmp < 0) {
  6822. // This node is less than our start key. ignore it
  6823. if (this.isReverse_) {
  6824. node = node.left;
  6825. }
  6826. else {
  6827. node = node.right;
  6828. }
  6829. }
  6830. else if (cmp === 0) {
  6831. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  6832. this.nodeStack_.push(node);
  6833. break;
  6834. }
  6835. else {
  6836. // This node is greater than our start key, add it to the stack and move to the next one
  6837. this.nodeStack_.push(node);
  6838. if (this.isReverse_) {
  6839. node = node.right;
  6840. }
  6841. else {
  6842. node = node.left;
  6843. }
  6844. }
  6845. }
  6846. }
  6847. getNext() {
  6848. if (this.nodeStack_.length === 0) {
  6849. return null;
  6850. }
  6851. let node = this.nodeStack_.pop();
  6852. let result;
  6853. if (this.resultGenerator_) {
  6854. result = this.resultGenerator_(node.key, node.value);
  6855. }
  6856. else {
  6857. result = { key: node.key, value: node.value };
  6858. }
  6859. if (this.isReverse_) {
  6860. node = node.left;
  6861. while (!node.isEmpty()) {
  6862. this.nodeStack_.push(node);
  6863. node = node.right;
  6864. }
  6865. }
  6866. else {
  6867. node = node.right;
  6868. while (!node.isEmpty()) {
  6869. this.nodeStack_.push(node);
  6870. node = node.left;
  6871. }
  6872. }
  6873. return result;
  6874. }
  6875. hasNext() {
  6876. return this.nodeStack_.length > 0;
  6877. }
  6878. peek() {
  6879. if (this.nodeStack_.length === 0) {
  6880. return null;
  6881. }
  6882. const node = this.nodeStack_[this.nodeStack_.length - 1];
  6883. if (this.resultGenerator_) {
  6884. return this.resultGenerator_(node.key, node.value);
  6885. }
  6886. else {
  6887. return { key: node.key, value: node.value };
  6888. }
  6889. }
  6890. }
  6891. /**
  6892. * Represents a node in a Left-leaning Red-Black tree.
  6893. */
  6894. class LLRBNode {
  6895. /**
  6896. * @param key - Key associated with this node.
  6897. * @param value - Value associated with this node.
  6898. * @param color - Whether this node is red.
  6899. * @param left - Left child.
  6900. * @param right - Right child.
  6901. */
  6902. constructor(key, value, color, left, right) {
  6903. this.key = key;
  6904. this.value = value;
  6905. this.color = color != null ? color : LLRBNode.RED;
  6906. this.left =
  6907. left != null ? left : SortedMap.EMPTY_NODE;
  6908. this.right =
  6909. right != null ? right : SortedMap.EMPTY_NODE;
  6910. }
  6911. /**
  6912. * Returns a copy of the current node, optionally replacing pieces of it.
  6913. *
  6914. * @param key - New key for the node, or null.
  6915. * @param value - New value for the node, or null.
  6916. * @param color - New color for the node, or null.
  6917. * @param left - New left child for the node, or null.
  6918. * @param right - New right child for the node, or null.
  6919. * @returns The node copy.
  6920. */
  6921. copy(key, value, color, left, right) {
  6922. 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);
  6923. }
  6924. /**
  6925. * @returns The total number of nodes in the tree.
  6926. */
  6927. count() {
  6928. return this.left.count() + 1 + this.right.count();
  6929. }
  6930. /**
  6931. * @returns True if the tree is empty.
  6932. */
  6933. isEmpty() {
  6934. return false;
  6935. }
  6936. /**
  6937. * Traverses the tree in key order and calls the specified action function
  6938. * for each node.
  6939. *
  6940. * @param action - Callback function to be called for each
  6941. * node. If it returns true, traversal is aborted.
  6942. * @returns The first truthy value returned by action, or the last falsey
  6943. * value returned by action
  6944. */
  6945. inorderTraversal(action) {
  6946. return (this.left.inorderTraversal(action) ||
  6947. !!action(this.key, this.value) ||
  6948. this.right.inorderTraversal(action));
  6949. }
  6950. /**
  6951. * Traverses the tree in reverse key order and calls the specified action function
  6952. * for each node.
  6953. *
  6954. * @param action - Callback function to be called for each
  6955. * node. If it returns true, traversal is aborted.
  6956. * @returns True if traversal was aborted.
  6957. */
  6958. reverseTraversal(action) {
  6959. return (this.right.reverseTraversal(action) ||
  6960. action(this.key, this.value) ||
  6961. this.left.reverseTraversal(action));
  6962. }
  6963. /**
  6964. * @returns The minimum node in the tree.
  6965. */
  6966. min_() {
  6967. if (this.left.isEmpty()) {
  6968. return this;
  6969. }
  6970. else {
  6971. return this.left.min_();
  6972. }
  6973. }
  6974. /**
  6975. * @returns The maximum key in the tree.
  6976. */
  6977. minKey() {
  6978. return this.min_().key;
  6979. }
  6980. /**
  6981. * @returns The maximum key in the tree.
  6982. */
  6983. maxKey() {
  6984. if (this.right.isEmpty()) {
  6985. return this.key;
  6986. }
  6987. else {
  6988. return this.right.maxKey();
  6989. }
  6990. }
  6991. /**
  6992. * @param key - Key to insert.
  6993. * @param value - Value to insert.
  6994. * @param comparator - Comparator.
  6995. * @returns New tree, with the key/value added.
  6996. */
  6997. insert(key, value, comparator) {
  6998. let n = this;
  6999. const cmp = comparator(key, n.key);
  7000. if (cmp < 0) {
  7001. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  7002. }
  7003. else if (cmp === 0) {
  7004. n = n.copy(null, value, null, null, null);
  7005. }
  7006. else {
  7007. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  7008. }
  7009. return n.fixUp_();
  7010. }
  7011. /**
  7012. * @returns New tree, with the minimum key removed.
  7013. */
  7014. removeMin_() {
  7015. if (this.left.isEmpty()) {
  7016. return SortedMap.EMPTY_NODE;
  7017. }
  7018. let n = this;
  7019. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  7020. n = n.moveRedLeft_();
  7021. }
  7022. n = n.copy(null, null, null, n.left.removeMin_(), null);
  7023. return n.fixUp_();
  7024. }
  7025. /**
  7026. * @param key - The key of the item to remove.
  7027. * @param comparator - Comparator.
  7028. * @returns New tree, with the specified item removed.
  7029. */
  7030. remove(key, comparator) {
  7031. let n, smallest;
  7032. n = this;
  7033. if (comparator(key, n.key) < 0) {
  7034. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  7035. n = n.moveRedLeft_();
  7036. }
  7037. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  7038. }
  7039. else {
  7040. if (n.left.isRed_()) {
  7041. n = n.rotateRight_();
  7042. }
  7043. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  7044. n = n.moveRedRight_();
  7045. }
  7046. if (comparator(key, n.key) === 0) {
  7047. if (n.right.isEmpty()) {
  7048. return SortedMap.EMPTY_NODE;
  7049. }
  7050. else {
  7051. smallest = n.right.min_();
  7052. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  7053. }
  7054. }
  7055. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  7056. }
  7057. return n.fixUp_();
  7058. }
  7059. /**
  7060. * @returns Whether this is a RED node.
  7061. */
  7062. isRed_() {
  7063. return this.color;
  7064. }
  7065. /**
  7066. * @returns New tree after performing any needed rotations.
  7067. */
  7068. fixUp_() {
  7069. let n = this;
  7070. if (n.right.isRed_() && !n.left.isRed_()) {
  7071. n = n.rotateLeft_();
  7072. }
  7073. if (n.left.isRed_() && n.left.left.isRed_()) {
  7074. n = n.rotateRight_();
  7075. }
  7076. if (n.left.isRed_() && n.right.isRed_()) {
  7077. n = n.colorFlip_();
  7078. }
  7079. return n;
  7080. }
  7081. /**
  7082. * @returns New tree, after moveRedLeft.
  7083. */
  7084. moveRedLeft_() {
  7085. let n = this.colorFlip_();
  7086. if (n.right.left.isRed_()) {
  7087. n = n.copy(null, null, null, null, n.right.rotateRight_());
  7088. n = n.rotateLeft_();
  7089. n = n.colorFlip_();
  7090. }
  7091. return n;
  7092. }
  7093. /**
  7094. * @returns New tree, after moveRedRight.
  7095. */
  7096. moveRedRight_() {
  7097. let n = this.colorFlip_();
  7098. if (n.left.left.isRed_()) {
  7099. n = n.rotateRight_();
  7100. n = n.colorFlip_();
  7101. }
  7102. return n;
  7103. }
  7104. /**
  7105. * @returns New tree, after rotateLeft.
  7106. */
  7107. rotateLeft_() {
  7108. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  7109. return this.right.copy(null, null, this.color, nl, null);
  7110. }
  7111. /**
  7112. * @returns New tree, after rotateRight.
  7113. */
  7114. rotateRight_() {
  7115. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  7116. return this.left.copy(null, null, this.color, null, nr);
  7117. }
  7118. /**
  7119. * @returns Newt ree, after colorFlip.
  7120. */
  7121. colorFlip_() {
  7122. const left = this.left.copy(null, null, !this.left.color, null, null);
  7123. const right = this.right.copy(null, null, !this.right.color, null, null);
  7124. return this.copy(null, null, !this.color, left, right);
  7125. }
  7126. /**
  7127. * For testing.
  7128. *
  7129. * @returns True if all is well.
  7130. */
  7131. checkMaxDepth_() {
  7132. const blackDepth = this.check_();
  7133. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  7134. }
  7135. check_() {
  7136. if (this.isRed_() && this.left.isRed_()) {
  7137. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  7138. }
  7139. if (this.right.isRed_()) {
  7140. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  7141. }
  7142. const blackDepth = this.left.check_();
  7143. if (blackDepth !== this.right.check_()) {
  7144. throw new Error('Black depths differ');
  7145. }
  7146. else {
  7147. return blackDepth + (this.isRed_() ? 0 : 1);
  7148. }
  7149. }
  7150. }
  7151. LLRBNode.RED = true;
  7152. LLRBNode.BLACK = false;
  7153. /**
  7154. * Represents an empty node (a leaf node in the Red-Black Tree).
  7155. */
  7156. class LLRBEmptyNode {
  7157. /**
  7158. * Returns a copy of the current node.
  7159. *
  7160. * @returns The node copy.
  7161. */
  7162. copy(key, value, color, left, right) {
  7163. return this;
  7164. }
  7165. /**
  7166. * Returns a copy of the tree, with the specified key/value added.
  7167. *
  7168. * @param key - Key to be added.
  7169. * @param value - Value to be added.
  7170. * @param comparator - Comparator.
  7171. * @returns New tree, with item added.
  7172. */
  7173. insert(key, value, comparator) {
  7174. return new LLRBNode(key, value, null);
  7175. }
  7176. /**
  7177. * Returns a copy of the tree, with the specified key removed.
  7178. *
  7179. * @param key - The key to remove.
  7180. * @param comparator - Comparator.
  7181. * @returns New tree, with item removed.
  7182. */
  7183. remove(key, comparator) {
  7184. return this;
  7185. }
  7186. /**
  7187. * @returns The total number of nodes in the tree.
  7188. */
  7189. count() {
  7190. return 0;
  7191. }
  7192. /**
  7193. * @returns True if the tree is empty.
  7194. */
  7195. isEmpty() {
  7196. return true;
  7197. }
  7198. /**
  7199. * Traverses the tree in key order and calls the specified action function
  7200. * for each node.
  7201. *
  7202. * @param action - Callback function to be called for each
  7203. * node. If it returns true, traversal is aborted.
  7204. * @returns True if traversal was aborted.
  7205. */
  7206. inorderTraversal(action) {
  7207. return false;
  7208. }
  7209. /**
  7210. * Traverses the tree in reverse key order and calls the specified action function
  7211. * for each node.
  7212. *
  7213. * @param action - Callback function to be called for each
  7214. * node. If it returns true, traversal is aborted.
  7215. * @returns True if traversal was aborted.
  7216. */
  7217. reverseTraversal(action) {
  7218. return false;
  7219. }
  7220. minKey() {
  7221. return null;
  7222. }
  7223. maxKey() {
  7224. return null;
  7225. }
  7226. check_() {
  7227. return 0;
  7228. }
  7229. /**
  7230. * @returns Whether this node is red.
  7231. */
  7232. isRed_() {
  7233. return false;
  7234. }
  7235. }
  7236. /**
  7237. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  7238. * tree.
  7239. */
  7240. class SortedMap {
  7241. /**
  7242. * @param comparator_ - Key comparator.
  7243. * @param root_ - Optional root node for the map.
  7244. */
  7245. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  7246. this.comparator_ = comparator_;
  7247. this.root_ = root_;
  7248. }
  7249. /**
  7250. * Returns a copy of the map, with the specified key/value added or replaced.
  7251. * (TODO: We should perhaps rename this method to 'put')
  7252. *
  7253. * @param key - Key to be added.
  7254. * @param value - Value to be added.
  7255. * @returns New map, with item added.
  7256. */
  7257. insert(key, value) {
  7258. return new SortedMap(this.comparator_, this.root_
  7259. .insert(key, value, this.comparator_)
  7260. .copy(null, null, LLRBNode.BLACK, null, null));
  7261. }
  7262. /**
  7263. * Returns a copy of the map, with the specified key removed.
  7264. *
  7265. * @param key - The key to remove.
  7266. * @returns New map, with item removed.
  7267. */
  7268. remove(key) {
  7269. return new SortedMap(this.comparator_, this.root_
  7270. .remove(key, this.comparator_)
  7271. .copy(null, null, LLRBNode.BLACK, null, null));
  7272. }
  7273. /**
  7274. * Returns the value of the node with the given key, or null.
  7275. *
  7276. * @param key - The key to look up.
  7277. * @returns The value of the node with the given key, or null if the
  7278. * key doesn't exist.
  7279. */
  7280. get(key) {
  7281. let cmp;
  7282. let node = this.root_;
  7283. while (!node.isEmpty()) {
  7284. cmp = this.comparator_(key, node.key);
  7285. if (cmp === 0) {
  7286. return node.value;
  7287. }
  7288. else if (cmp < 0) {
  7289. node = node.left;
  7290. }
  7291. else if (cmp > 0) {
  7292. node = node.right;
  7293. }
  7294. }
  7295. return null;
  7296. }
  7297. /**
  7298. * Returns the key of the item *before* the specified key, or null if key is the first item.
  7299. * @param key - The key to find the predecessor of
  7300. * @returns The predecessor key.
  7301. */
  7302. getPredecessorKey(key) {
  7303. let cmp, node = this.root_, rightParent = null;
  7304. while (!node.isEmpty()) {
  7305. cmp = this.comparator_(key, node.key);
  7306. if (cmp === 0) {
  7307. if (!node.left.isEmpty()) {
  7308. node = node.left;
  7309. while (!node.right.isEmpty()) {
  7310. node = node.right;
  7311. }
  7312. return node.key;
  7313. }
  7314. else if (rightParent) {
  7315. return rightParent.key;
  7316. }
  7317. else {
  7318. return null; // first item.
  7319. }
  7320. }
  7321. else if (cmp < 0) {
  7322. node = node.left;
  7323. }
  7324. else if (cmp > 0) {
  7325. rightParent = node;
  7326. node = node.right;
  7327. }
  7328. }
  7329. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  7330. }
  7331. /**
  7332. * @returns True if the map is empty.
  7333. */
  7334. isEmpty() {
  7335. return this.root_.isEmpty();
  7336. }
  7337. /**
  7338. * @returns The total number of nodes in the map.
  7339. */
  7340. count() {
  7341. return this.root_.count();
  7342. }
  7343. /**
  7344. * @returns The minimum key in the map.
  7345. */
  7346. minKey() {
  7347. return this.root_.minKey();
  7348. }
  7349. /**
  7350. * @returns The maximum key in the map.
  7351. */
  7352. maxKey() {
  7353. return this.root_.maxKey();
  7354. }
  7355. /**
  7356. * Traverses the map in key order and calls the specified action function
  7357. * for each key/value pair.
  7358. *
  7359. * @param action - Callback function to be called
  7360. * for each key/value pair. If action returns true, traversal is aborted.
  7361. * @returns The first truthy value returned by action, or the last falsey
  7362. * value returned by action
  7363. */
  7364. inorderTraversal(action) {
  7365. return this.root_.inorderTraversal(action);
  7366. }
  7367. /**
  7368. * Traverses the map in reverse key order and calls the specified action function
  7369. * for each key/value pair.
  7370. *
  7371. * @param action - Callback function to be called
  7372. * for each key/value pair. If action returns true, traversal is aborted.
  7373. * @returns True if the traversal was aborted.
  7374. */
  7375. reverseTraversal(action) {
  7376. return this.root_.reverseTraversal(action);
  7377. }
  7378. /**
  7379. * Returns an iterator over the SortedMap.
  7380. * @returns The iterator.
  7381. */
  7382. getIterator(resultGenerator) {
  7383. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  7384. }
  7385. getIteratorFrom(key, resultGenerator) {
  7386. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  7387. }
  7388. getReverseIteratorFrom(key, resultGenerator) {
  7389. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  7390. }
  7391. getReverseIterator(resultGenerator) {
  7392. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  7393. }
  7394. }
  7395. /**
  7396. * Always use the same empty node, to reduce memory.
  7397. */
  7398. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  7399. /**
  7400. * @license
  7401. * Copyright 2017 Google LLC
  7402. *
  7403. * Licensed under the Apache License, Version 2.0 (the "License");
  7404. * you may not use this file except in compliance with the License.
  7405. * You may obtain a copy of the License at
  7406. *
  7407. * http://www.apache.org/licenses/LICENSE-2.0
  7408. *
  7409. * Unless required by applicable law or agreed to in writing, software
  7410. * distributed under the License is distributed on an "AS IS" BASIS,
  7411. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7412. * See the License for the specific language governing permissions and
  7413. * limitations under the License.
  7414. */
  7415. function NAME_ONLY_COMPARATOR(left, right) {
  7416. return nameCompare(left.name, right.name);
  7417. }
  7418. function NAME_COMPARATOR(left, right) {
  7419. return nameCompare(left, right);
  7420. }
  7421. /**
  7422. * @license
  7423. * Copyright 2017 Google LLC
  7424. *
  7425. * Licensed under the Apache License, Version 2.0 (the "License");
  7426. * you may not use this file except in compliance with the License.
  7427. * You may obtain a copy of the License at
  7428. *
  7429. * http://www.apache.org/licenses/LICENSE-2.0
  7430. *
  7431. * Unless required by applicable law or agreed to in writing, software
  7432. * distributed under the License is distributed on an "AS IS" BASIS,
  7433. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7434. * See the License for the specific language governing permissions and
  7435. * limitations under the License.
  7436. */
  7437. let MAX_NODE$2;
  7438. function setMaxNode$1(val) {
  7439. MAX_NODE$2 = val;
  7440. }
  7441. const priorityHashText = function (priority) {
  7442. if (typeof priority === 'number') {
  7443. return 'number:' + doubleToIEEE754String(priority);
  7444. }
  7445. else {
  7446. return 'string:' + priority;
  7447. }
  7448. };
  7449. /**
  7450. * Validates that a priority snapshot Node is valid.
  7451. */
  7452. const validatePriorityNode = function (priorityNode) {
  7453. if (priorityNode.isLeafNode()) {
  7454. const val = priorityNode.val();
  7455. util.assert(typeof val === 'string' ||
  7456. typeof val === 'number' ||
  7457. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  7458. }
  7459. else {
  7460. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  7461. }
  7462. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  7463. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  7464. };
  7465. /**
  7466. * @license
  7467. * Copyright 2017 Google LLC
  7468. *
  7469. * Licensed under the Apache License, Version 2.0 (the "License");
  7470. * you may not use this file except in compliance with the License.
  7471. * You may obtain a copy of the License at
  7472. *
  7473. * http://www.apache.org/licenses/LICENSE-2.0
  7474. *
  7475. * Unless required by applicable law or agreed to in writing, software
  7476. * distributed under the License is distributed on an "AS IS" BASIS,
  7477. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7478. * See the License for the specific language governing permissions and
  7479. * limitations under the License.
  7480. */
  7481. let __childrenNodeConstructor;
  7482. /**
  7483. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  7484. * implements Node and stores the value of the node (a string,
  7485. * number, or boolean) accessible via getValue().
  7486. */
  7487. class LeafNode {
  7488. /**
  7489. * @param value_ - The value to store in this leaf node. The object type is
  7490. * possible in the event of a deferred value
  7491. * @param priorityNode_ - The priority of this node.
  7492. */
  7493. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  7494. this.value_ = value_;
  7495. this.priorityNode_ = priorityNode_;
  7496. this.lazyHash_ = null;
  7497. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  7498. validatePriorityNode(this.priorityNode_);
  7499. }
  7500. static set __childrenNodeConstructor(val) {
  7501. __childrenNodeConstructor = val;
  7502. }
  7503. static get __childrenNodeConstructor() {
  7504. return __childrenNodeConstructor;
  7505. }
  7506. /** @inheritDoc */
  7507. isLeafNode() {
  7508. return true;
  7509. }
  7510. /** @inheritDoc */
  7511. getPriority() {
  7512. return this.priorityNode_;
  7513. }
  7514. /** @inheritDoc */
  7515. updatePriority(newPriorityNode) {
  7516. return new LeafNode(this.value_, newPriorityNode);
  7517. }
  7518. /** @inheritDoc */
  7519. getImmediateChild(childName) {
  7520. // Hack to treat priority as a regular child
  7521. if (childName === '.priority') {
  7522. return this.priorityNode_;
  7523. }
  7524. else {
  7525. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  7526. }
  7527. }
  7528. /** @inheritDoc */
  7529. getChild(path) {
  7530. if (pathIsEmpty(path)) {
  7531. return this;
  7532. }
  7533. else if (pathGetFront(path) === '.priority') {
  7534. return this.priorityNode_;
  7535. }
  7536. else {
  7537. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  7538. }
  7539. }
  7540. hasChild() {
  7541. return false;
  7542. }
  7543. /** @inheritDoc */
  7544. getPredecessorChildName(childName, childNode) {
  7545. return null;
  7546. }
  7547. /** @inheritDoc */
  7548. updateImmediateChild(childName, newChildNode) {
  7549. if (childName === '.priority') {
  7550. return this.updatePriority(newChildNode);
  7551. }
  7552. else if (newChildNode.isEmpty() && childName !== '.priority') {
  7553. return this;
  7554. }
  7555. else {
  7556. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  7557. }
  7558. }
  7559. /** @inheritDoc */
  7560. updateChild(path, newChildNode) {
  7561. const front = pathGetFront(path);
  7562. if (front === null) {
  7563. return newChildNode;
  7564. }
  7565. else if (newChildNode.isEmpty() && front !== '.priority') {
  7566. return this;
  7567. }
  7568. else {
  7569. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  7570. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  7571. }
  7572. }
  7573. /** @inheritDoc */
  7574. isEmpty() {
  7575. return false;
  7576. }
  7577. /** @inheritDoc */
  7578. numChildren() {
  7579. return 0;
  7580. }
  7581. /** @inheritDoc */
  7582. forEachChild(index, action) {
  7583. return false;
  7584. }
  7585. val(exportFormat) {
  7586. if (exportFormat && !this.getPriority().isEmpty()) {
  7587. return {
  7588. '.value': this.getValue(),
  7589. '.priority': this.getPriority().val()
  7590. };
  7591. }
  7592. else {
  7593. return this.getValue();
  7594. }
  7595. }
  7596. /** @inheritDoc */
  7597. hash() {
  7598. if (this.lazyHash_ === null) {
  7599. let toHash = '';
  7600. if (!this.priorityNode_.isEmpty()) {
  7601. toHash +=
  7602. 'priority:' +
  7603. priorityHashText(this.priorityNode_.val()) +
  7604. ':';
  7605. }
  7606. const type = typeof this.value_;
  7607. toHash += type + ':';
  7608. if (type === 'number') {
  7609. toHash += doubleToIEEE754String(this.value_);
  7610. }
  7611. else {
  7612. toHash += this.value_;
  7613. }
  7614. this.lazyHash_ = sha1(toHash);
  7615. }
  7616. return this.lazyHash_;
  7617. }
  7618. /**
  7619. * Returns the value of the leaf node.
  7620. * @returns The value of the node.
  7621. */
  7622. getValue() {
  7623. return this.value_;
  7624. }
  7625. compareTo(other) {
  7626. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  7627. return 1;
  7628. }
  7629. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  7630. return -1;
  7631. }
  7632. else {
  7633. util.assert(other.isLeafNode(), 'Unknown node type');
  7634. return this.compareToLeafNode_(other);
  7635. }
  7636. }
  7637. /**
  7638. * Comparison specifically for two leaf nodes
  7639. */
  7640. compareToLeafNode_(otherLeaf) {
  7641. const otherLeafType = typeof otherLeaf.value_;
  7642. const thisLeafType = typeof this.value_;
  7643. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  7644. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  7645. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  7646. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  7647. if (otherIndex === thisIndex) {
  7648. // Same type, compare values
  7649. if (thisLeafType === 'object') {
  7650. // Deferred value nodes are all equal, but we should also never get to this point...
  7651. return 0;
  7652. }
  7653. else {
  7654. // Note that this works because true > false, all others are number or string comparisons
  7655. if (this.value_ < otherLeaf.value_) {
  7656. return -1;
  7657. }
  7658. else if (this.value_ === otherLeaf.value_) {
  7659. return 0;
  7660. }
  7661. else {
  7662. return 1;
  7663. }
  7664. }
  7665. }
  7666. else {
  7667. return thisIndex - otherIndex;
  7668. }
  7669. }
  7670. withIndex() {
  7671. return this;
  7672. }
  7673. isIndexed() {
  7674. return true;
  7675. }
  7676. equals(other) {
  7677. if (other === this) {
  7678. return true;
  7679. }
  7680. else if (other.isLeafNode()) {
  7681. const otherLeaf = other;
  7682. return (this.value_ === otherLeaf.value_ &&
  7683. this.priorityNode_.equals(otherLeaf.priorityNode_));
  7684. }
  7685. else {
  7686. return false;
  7687. }
  7688. }
  7689. }
  7690. /**
  7691. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  7692. * the same type, the comparison falls back to their value
  7693. */
  7694. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  7695. /**
  7696. * @license
  7697. * Copyright 2017 Google LLC
  7698. *
  7699. * Licensed under the Apache License, Version 2.0 (the "License");
  7700. * you may not use this file except in compliance with the License.
  7701. * You may obtain a copy of the License at
  7702. *
  7703. * http://www.apache.org/licenses/LICENSE-2.0
  7704. *
  7705. * Unless required by applicable law or agreed to in writing, software
  7706. * distributed under the License is distributed on an "AS IS" BASIS,
  7707. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7708. * See the License for the specific language governing permissions and
  7709. * limitations under the License.
  7710. */
  7711. let nodeFromJSON$1;
  7712. let MAX_NODE$1;
  7713. function setNodeFromJSON(val) {
  7714. nodeFromJSON$1 = val;
  7715. }
  7716. function setMaxNode(val) {
  7717. MAX_NODE$1 = val;
  7718. }
  7719. class PriorityIndex extends Index {
  7720. compare(a, b) {
  7721. const aPriority = a.node.getPriority();
  7722. const bPriority = b.node.getPriority();
  7723. const indexCmp = aPriority.compareTo(bPriority);
  7724. if (indexCmp === 0) {
  7725. return nameCompare(a.name, b.name);
  7726. }
  7727. else {
  7728. return indexCmp;
  7729. }
  7730. }
  7731. isDefinedOn(node) {
  7732. return !node.getPriority().isEmpty();
  7733. }
  7734. indexedValueChanged(oldNode, newNode) {
  7735. return !oldNode.getPriority().equals(newNode.getPriority());
  7736. }
  7737. minPost() {
  7738. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7739. return NamedNode.MIN;
  7740. }
  7741. maxPost() {
  7742. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  7743. }
  7744. makePost(indexValue, name) {
  7745. const priorityNode = nodeFromJSON$1(indexValue);
  7746. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  7747. }
  7748. /**
  7749. * @returns String representation for inclusion in a query spec
  7750. */
  7751. toString() {
  7752. return '.priority';
  7753. }
  7754. }
  7755. const PRIORITY_INDEX = new PriorityIndex();
  7756. /**
  7757. * @license
  7758. * Copyright 2017 Google LLC
  7759. *
  7760. * Licensed under the Apache License, Version 2.0 (the "License");
  7761. * you may not use this file except in compliance with the License.
  7762. * You may obtain a copy of the License at
  7763. *
  7764. * http://www.apache.org/licenses/LICENSE-2.0
  7765. *
  7766. * Unless required by applicable law or agreed to in writing, software
  7767. * distributed under the License is distributed on an "AS IS" BASIS,
  7768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7769. * See the License for the specific language governing permissions and
  7770. * limitations under the License.
  7771. */
  7772. const LOG_2 = Math.log(2);
  7773. class Base12Num {
  7774. constructor(length) {
  7775. const logBase2 = (num) =>
  7776. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7777. parseInt((Math.log(num) / LOG_2), 10);
  7778. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  7779. this.count = logBase2(length + 1);
  7780. this.current_ = this.count - 1;
  7781. const mask = bitMask(this.count);
  7782. this.bits_ = (length + 1) & mask;
  7783. }
  7784. nextBitIsOne() {
  7785. //noinspection JSBitwiseOperatorUsage
  7786. const result = !(this.bits_ & (0x1 << this.current_));
  7787. this.current_--;
  7788. return result;
  7789. }
  7790. }
  7791. /**
  7792. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  7793. * function
  7794. *
  7795. * Uses the algorithm described in the paper linked here:
  7796. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  7797. *
  7798. * @param childList - Unsorted list of children
  7799. * @param cmp - The comparison method to be used
  7800. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  7801. * type is not NamedNode
  7802. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  7803. */
  7804. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  7805. childList.sort(cmp);
  7806. const buildBalancedTree = function (low, high) {
  7807. const length = high - low;
  7808. let namedNode;
  7809. let key;
  7810. if (length === 0) {
  7811. return null;
  7812. }
  7813. else if (length === 1) {
  7814. namedNode = childList[low];
  7815. key = keyFn ? keyFn(namedNode) : namedNode;
  7816. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  7817. }
  7818. else {
  7819. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7820. const middle = parseInt((length / 2), 10) + low;
  7821. const left = buildBalancedTree(low, middle);
  7822. const right = buildBalancedTree(middle + 1, high);
  7823. namedNode = childList[middle];
  7824. key = keyFn ? keyFn(namedNode) : namedNode;
  7825. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  7826. }
  7827. };
  7828. const buildFrom12Array = function (base12) {
  7829. let node = null;
  7830. let root = null;
  7831. let index = childList.length;
  7832. const buildPennant = function (chunkSize, color) {
  7833. const low = index - chunkSize;
  7834. const high = index;
  7835. index -= chunkSize;
  7836. const childTree = buildBalancedTree(low + 1, high);
  7837. const namedNode = childList[low];
  7838. const key = keyFn ? keyFn(namedNode) : namedNode;
  7839. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  7840. };
  7841. const attachPennant = function (pennant) {
  7842. if (node) {
  7843. node.left = pennant;
  7844. node = pennant;
  7845. }
  7846. else {
  7847. root = pennant;
  7848. node = pennant;
  7849. }
  7850. };
  7851. for (let i = 0; i < base12.count; ++i) {
  7852. const isOne = base12.nextBitIsOne();
  7853. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  7854. const chunkSize = Math.pow(2, base12.count - (i + 1));
  7855. if (isOne) {
  7856. buildPennant(chunkSize, LLRBNode.BLACK);
  7857. }
  7858. else {
  7859. // current == 2
  7860. buildPennant(chunkSize, LLRBNode.BLACK);
  7861. buildPennant(chunkSize, LLRBNode.RED);
  7862. }
  7863. }
  7864. return root;
  7865. };
  7866. const base12 = new Base12Num(childList.length);
  7867. const root = buildFrom12Array(base12);
  7868. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7869. return new SortedMap(mapSortFn || cmp, root);
  7870. };
  7871. /**
  7872. * @license
  7873. * Copyright 2017 Google LLC
  7874. *
  7875. * Licensed under the Apache License, Version 2.0 (the "License");
  7876. * you may not use this file except in compliance with the License.
  7877. * You may obtain a copy of the License at
  7878. *
  7879. * http://www.apache.org/licenses/LICENSE-2.0
  7880. *
  7881. * Unless required by applicable law or agreed to in writing, software
  7882. * distributed under the License is distributed on an "AS IS" BASIS,
  7883. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7884. * See the License for the specific language governing permissions and
  7885. * limitations under the License.
  7886. */
  7887. let _defaultIndexMap;
  7888. const fallbackObject = {};
  7889. class IndexMap {
  7890. constructor(indexes_, indexSet_) {
  7891. this.indexes_ = indexes_;
  7892. this.indexSet_ = indexSet_;
  7893. }
  7894. /**
  7895. * The default IndexMap for nodes without a priority
  7896. */
  7897. static get Default() {
  7898. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  7899. _defaultIndexMap =
  7900. _defaultIndexMap ||
  7901. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  7902. return _defaultIndexMap;
  7903. }
  7904. get(indexKey) {
  7905. const sortedMap = util.safeGet(this.indexes_, indexKey);
  7906. if (!sortedMap) {
  7907. throw new Error('No index defined for ' + indexKey);
  7908. }
  7909. if (sortedMap instanceof SortedMap) {
  7910. return sortedMap;
  7911. }
  7912. else {
  7913. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  7914. // regular child map
  7915. return null;
  7916. }
  7917. }
  7918. hasIndex(indexDefinition) {
  7919. return util.contains(this.indexSet_, indexDefinition.toString());
  7920. }
  7921. addIndex(indexDefinition, existingChildren) {
  7922. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  7923. const childList = [];
  7924. let sawIndexedValue = false;
  7925. const iter = existingChildren.getIterator(NamedNode.Wrap);
  7926. let next = iter.getNext();
  7927. while (next) {
  7928. sawIndexedValue =
  7929. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  7930. childList.push(next);
  7931. next = iter.getNext();
  7932. }
  7933. let newIndex;
  7934. if (sawIndexedValue) {
  7935. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  7936. }
  7937. else {
  7938. newIndex = fallbackObject;
  7939. }
  7940. const indexName = indexDefinition.toString();
  7941. const newIndexSet = Object.assign({}, this.indexSet_);
  7942. newIndexSet[indexName] = indexDefinition;
  7943. const newIndexes = Object.assign({}, this.indexes_);
  7944. newIndexes[indexName] = newIndex;
  7945. return new IndexMap(newIndexes, newIndexSet);
  7946. }
  7947. /**
  7948. * Ensure that this node is properly tracked in any indexes that we're maintaining
  7949. */
  7950. addToIndexes(namedNode, existingChildren) {
  7951. const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => {
  7952. const index = util.safeGet(this.indexSet_, indexName);
  7953. util.assert(index, 'Missing index implementation for ' + indexName);
  7954. if (indexedChildren === fallbackObject) {
  7955. // Check to see if we need to index everything
  7956. if (index.isDefinedOn(namedNode.node)) {
  7957. // We need to build this index
  7958. const childList = [];
  7959. const iter = existingChildren.getIterator(NamedNode.Wrap);
  7960. let next = iter.getNext();
  7961. while (next) {
  7962. if (next.name !== namedNode.name) {
  7963. childList.push(next);
  7964. }
  7965. next = iter.getNext();
  7966. }
  7967. childList.push(namedNode);
  7968. return buildChildSet(childList, index.getCompare());
  7969. }
  7970. else {
  7971. // No change, this remains a fallback
  7972. return fallbackObject;
  7973. }
  7974. }
  7975. else {
  7976. const existingSnap = existingChildren.get(namedNode.name);
  7977. let newChildren = indexedChildren;
  7978. if (existingSnap) {
  7979. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  7980. }
  7981. return newChildren.insert(namedNode, namedNode.node);
  7982. }
  7983. });
  7984. return new IndexMap(newIndexes, this.indexSet_);
  7985. }
  7986. /**
  7987. * Create a new IndexMap instance with the given value removed
  7988. */
  7989. removeFromIndexes(namedNode, existingChildren) {
  7990. const newIndexes = util.map(this.indexes_, (indexedChildren) => {
  7991. if (indexedChildren === fallbackObject) {
  7992. // This is the fallback. Just return it, nothing to do in this case
  7993. return indexedChildren;
  7994. }
  7995. else {
  7996. const existingSnap = existingChildren.get(namedNode.name);
  7997. if (existingSnap) {
  7998. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  7999. }
  8000. else {
  8001. // No record of this child
  8002. return indexedChildren;
  8003. }
  8004. }
  8005. });
  8006. return new IndexMap(newIndexes, this.indexSet_);
  8007. }
  8008. }
  8009. /**
  8010. * @license
  8011. * Copyright 2017 Google LLC
  8012. *
  8013. * Licensed under the Apache License, Version 2.0 (the "License");
  8014. * you may not use this file except in compliance with the License.
  8015. * You may obtain a copy of the License at
  8016. *
  8017. * http://www.apache.org/licenses/LICENSE-2.0
  8018. *
  8019. * Unless required by applicable law or agreed to in writing, software
  8020. * distributed under the License is distributed on an "AS IS" BASIS,
  8021. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8022. * See the License for the specific language governing permissions and
  8023. * limitations under the License.
  8024. */
  8025. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  8026. let EMPTY_NODE;
  8027. /**
  8028. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  8029. * (i.e. nodes with children). It implements Node and stores the
  8030. * list of children in the children property, sorted by child name.
  8031. */
  8032. class ChildrenNode {
  8033. /**
  8034. * @param children_ - List of children of this node..
  8035. * @param priorityNode_ - The priority of this node (as a snapshot node).
  8036. */
  8037. constructor(children_, priorityNode_, indexMap_) {
  8038. this.children_ = children_;
  8039. this.priorityNode_ = priorityNode_;
  8040. this.indexMap_ = indexMap_;
  8041. this.lazyHash_ = null;
  8042. /**
  8043. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  8044. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  8045. * class instead of an empty ChildrenNode.
  8046. */
  8047. if (this.priorityNode_) {
  8048. validatePriorityNode(this.priorityNode_);
  8049. }
  8050. if (this.children_.isEmpty()) {
  8051. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  8052. }
  8053. }
  8054. static get EMPTY_NODE() {
  8055. return (EMPTY_NODE ||
  8056. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  8057. }
  8058. /** @inheritDoc */
  8059. isLeafNode() {
  8060. return false;
  8061. }
  8062. /** @inheritDoc */
  8063. getPriority() {
  8064. return this.priorityNode_ || EMPTY_NODE;
  8065. }
  8066. /** @inheritDoc */
  8067. updatePriority(newPriorityNode) {
  8068. if (this.children_.isEmpty()) {
  8069. // Don't allow priorities on empty nodes
  8070. return this;
  8071. }
  8072. else {
  8073. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  8074. }
  8075. }
  8076. /** @inheritDoc */
  8077. getImmediateChild(childName) {
  8078. // Hack to treat priority as a regular child
  8079. if (childName === '.priority') {
  8080. return this.getPriority();
  8081. }
  8082. else {
  8083. const child = this.children_.get(childName);
  8084. return child === null ? EMPTY_NODE : child;
  8085. }
  8086. }
  8087. /** @inheritDoc */
  8088. getChild(path) {
  8089. const front = pathGetFront(path);
  8090. if (front === null) {
  8091. return this;
  8092. }
  8093. return this.getImmediateChild(front).getChild(pathPopFront(path));
  8094. }
  8095. /** @inheritDoc */
  8096. hasChild(childName) {
  8097. return this.children_.get(childName) !== null;
  8098. }
  8099. /** @inheritDoc */
  8100. updateImmediateChild(childName, newChildNode) {
  8101. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  8102. if (childName === '.priority') {
  8103. return this.updatePriority(newChildNode);
  8104. }
  8105. else {
  8106. const namedNode = new NamedNode(childName, newChildNode);
  8107. let newChildren, newIndexMap;
  8108. if (newChildNode.isEmpty()) {
  8109. newChildren = this.children_.remove(childName);
  8110. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  8111. }
  8112. else {
  8113. newChildren = this.children_.insert(childName, newChildNode);
  8114. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  8115. }
  8116. const newPriority = newChildren.isEmpty()
  8117. ? EMPTY_NODE
  8118. : this.priorityNode_;
  8119. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  8120. }
  8121. }
  8122. /** @inheritDoc */
  8123. updateChild(path, newChildNode) {
  8124. const front = pathGetFront(path);
  8125. if (front === null) {
  8126. return newChildNode;
  8127. }
  8128. else {
  8129. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  8130. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  8131. return this.updateImmediateChild(front, newImmediateChild);
  8132. }
  8133. }
  8134. /** @inheritDoc */
  8135. isEmpty() {
  8136. return this.children_.isEmpty();
  8137. }
  8138. /** @inheritDoc */
  8139. numChildren() {
  8140. return this.children_.count();
  8141. }
  8142. /** @inheritDoc */
  8143. val(exportFormat) {
  8144. if (this.isEmpty()) {
  8145. return null;
  8146. }
  8147. const obj = {};
  8148. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  8149. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  8150. obj[key] = childNode.val(exportFormat);
  8151. numKeys++;
  8152. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  8153. maxKey = Math.max(maxKey, Number(key));
  8154. }
  8155. else {
  8156. allIntegerKeys = false;
  8157. }
  8158. });
  8159. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  8160. // convert to array.
  8161. const array = [];
  8162. // eslint-disable-next-line guard-for-in
  8163. for (const key in obj) {
  8164. array[key] = obj[key];
  8165. }
  8166. return array;
  8167. }
  8168. else {
  8169. if (exportFormat && !this.getPriority().isEmpty()) {
  8170. obj['.priority'] = this.getPriority().val();
  8171. }
  8172. return obj;
  8173. }
  8174. }
  8175. /** @inheritDoc */
  8176. hash() {
  8177. if (this.lazyHash_ === null) {
  8178. let toHash = '';
  8179. if (!this.getPriority().isEmpty()) {
  8180. toHash +=
  8181. 'priority:' +
  8182. priorityHashText(this.getPriority().val()) +
  8183. ':';
  8184. }
  8185. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  8186. const childHash = childNode.hash();
  8187. if (childHash !== '') {
  8188. toHash += ':' + key + ':' + childHash;
  8189. }
  8190. });
  8191. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  8192. }
  8193. return this.lazyHash_;
  8194. }
  8195. /** @inheritDoc */
  8196. getPredecessorChildName(childName, childNode, index) {
  8197. const idx = this.resolveIndex_(index);
  8198. if (idx) {
  8199. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  8200. return predecessor ? predecessor.name : null;
  8201. }
  8202. else {
  8203. return this.children_.getPredecessorKey(childName);
  8204. }
  8205. }
  8206. getFirstChildName(indexDefinition) {
  8207. const idx = this.resolveIndex_(indexDefinition);
  8208. if (idx) {
  8209. const minKey = idx.minKey();
  8210. return minKey && minKey.name;
  8211. }
  8212. else {
  8213. return this.children_.minKey();
  8214. }
  8215. }
  8216. getFirstChild(indexDefinition) {
  8217. const minKey = this.getFirstChildName(indexDefinition);
  8218. if (minKey) {
  8219. return new NamedNode(minKey, this.children_.get(minKey));
  8220. }
  8221. else {
  8222. return null;
  8223. }
  8224. }
  8225. /**
  8226. * Given an index, return the key name of the largest value we have, according to that index
  8227. */
  8228. getLastChildName(indexDefinition) {
  8229. const idx = this.resolveIndex_(indexDefinition);
  8230. if (idx) {
  8231. const maxKey = idx.maxKey();
  8232. return maxKey && maxKey.name;
  8233. }
  8234. else {
  8235. return this.children_.maxKey();
  8236. }
  8237. }
  8238. getLastChild(indexDefinition) {
  8239. const maxKey = this.getLastChildName(indexDefinition);
  8240. if (maxKey) {
  8241. return new NamedNode(maxKey, this.children_.get(maxKey));
  8242. }
  8243. else {
  8244. return null;
  8245. }
  8246. }
  8247. forEachChild(index, action) {
  8248. const idx = this.resolveIndex_(index);
  8249. if (idx) {
  8250. return idx.inorderTraversal(wrappedNode => {
  8251. return action(wrappedNode.name, wrappedNode.node);
  8252. });
  8253. }
  8254. else {
  8255. return this.children_.inorderTraversal(action);
  8256. }
  8257. }
  8258. getIterator(indexDefinition) {
  8259. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  8260. }
  8261. getIteratorFrom(startPost, indexDefinition) {
  8262. const idx = this.resolveIndex_(indexDefinition);
  8263. if (idx) {
  8264. return idx.getIteratorFrom(startPost, key => key);
  8265. }
  8266. else {
  8267. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  8268. let next = iterator.peek();
  8269. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  8270. iterator.getNext();
  8271. next = iterator.peek();
  8272. }
  8273. return iterator;
  8274. }
  8275. }
  8276. getReverseIterator(indexDefinition) {
  8277. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  8278. }
  8279. getReverseIteratorFrom(endPost, indexDefinition) {
  8280. const idx = this.resolveIndex_(indexDefinition);
  8281. if (idx) {
  8282. return idx.getReverseIteratorFrom(endPost, key => {
  8283. return key;
  8284. });
  8285. }
  8286. else {
  8287. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  8288. let next = iterator.peek();
  8289. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  8290. iterator.getNext();
  8291. next = iterator.peek();
  8292. }
  8293. return iterator;
  8294. }
  8295. }
  8296. compareTo(other) {
  8297. if (this.isEmpty()) {
  8298. if (other.isEmpty()) {
  8299. return 0;
  8300. }
  8301. else {
  8302. return -1;
  8303. }
  8304. }
  8305. else if (other.isLeafNode() || other.isEmpty()) {
  8306. return 1;
  8307. }
  8308. else if (other === MAX_NODE) {
  8309. return -1;
  8310. }
  8311. else {
  8312. // Must be another node with children.
  8313. return 0;
  8314. }
  8315. }
  8316. withIndex(indexDefinition) {
  8317. if (indexDefinition === KEY_INDEX ||
  8318. this.indexMap_.hasIndex(indexDefinition)) {
  8319. return this;
  8320. }
  8321. else {
  8322. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  8323. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  8324. }
  8325. }
  8326. isIndexed(index) {
  8327. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  8328. }
  8329. equals(other) {
  8330. if (other === this) {
  8331. return true;
  8332. }
  8333. else if (other.isLeafNode()) {
  8334. return false;
  8335. }
  8336. else {
  8337. const otherChildrenNode = other;
  8338. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  8339. return false;
  8340. }
  8341. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  8342. const thisIter = this.getIterator(PRIORITY_INDEX);
  8343. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  8344. let thisCurrent = thisIter.getNext();
  8345. let otherCurrent = otherIter.getNext();
  8346. while (thisCurrent && otherCurrent) {
  8347. if (thisCurrent.name !== otherCurrent.name ||
  8348. !thisCurrent.node.equals(otherCurrent.node)) {
  8349. return false;
  8350. }
  8351. thisCurrent = thisIter.getNext();
  8352. otherCurrent = otherIter.getNext();
  8353. }
  8354. return thisCurrent === null && otherCurrent === null;
  8355. }
  8356. else {
  8357. return false;
  8358. }
  8359. }
  8360. }
  8361. /**
  8362. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  8363. * instead.
  8364. *
  8365. */
  8366. resolveIndex_(indexDefinition) {
  8367. if (indexDefinition === KEY_INDEX) {
  8368. return null;
  8369. }
  8370. else {
  8371. return this.indexMap_.get(indexDefinition.toString());
  8372. }
  8373. }
  8374. }
  8375. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  8376. class MaxNode extends ChildrenNode {
  8377. constructor() {
  8378. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  8379. }
  8380. compareTo(other) {
  8381. if (other === this) {
  8382. return 0;
  8383. }
  8384. else {
  8385. return 1;
  8386. }
  8387. }
  8388. equals(other) {
  8389. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  8390. return other === this;
  8391. }
  8392. getPriority() {
  8393. return this;
  8394. }
  8395. getImmediateChild(childName) {
  8396. return ChildrenNode.EMPTY_NODE;
  8397. }
  8398. isEmpty() {
  8399. return false;
  8400. }
  8401. }
  8402. /**
  8403. * Marker that will sort higher than any other snapshot.
  8404. */
  8405. const MAX_NODE = new MaxNode();
  8406. Object.defineProperties(NamedNode, {
  8407. MIN: {
  8408. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  8409. },
  8410. MAX: {
  8411. value: new NamedNode(MAX_NAME, MAX_NODE)
  8412. }
  8413. });
  8414. /**
  8415. * Reference Extensions
  8416. */
  8417. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  8418. LeafNode.__childrenNodeConstructor = ChildrenNode;
  8419. setMaxNode$1(MAX_NODE);
  8420. setMaxNode(MAX_NODE);
  8421. /**
  8422. * @license
  8423. * Copyright 2017 Google LLC
  8424. *
  8425. * Licensed under the Apache License, Version 2.0 (the "License");
  8426. * you may not use this file except in compliance with the License.
  8427. * You may obtain a copy of the License at
  8428. *
  8429. * http://www.apache.org/licenses/LICENSE-2.0
  8430. *
  8431. * Unless required by applicable law or agreed to in writing, software
  8432. * distributed under the License is distributed on an "AS IS" BASIS,
  8433. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8434. * See the License for the specific language governing permissions and
  8435. * limitations under the License.
  8436. */
  8437. const USE_HINZE = true;
  8438. /**
  8439. * Constructs a snapshot node representing the passed JSON and returns it.
  8440. * @param json - JSON to create a node for.
  8441. * @param priority - Optional priority to use. This will be ignored if the
  8442. * passed JSON contains a .priority property.
  8443. */
  8444. function nodeFromJSON(json, priority = null) {
  8445. if (json === null) {
  8446. return ChildrenNode.EMPTY_NODE;
  8447. }
  8448. if (typeof json === 'object' && '.priority' in json) {
  8449. priority = json['.priority'];
  8450. }
  8451. util.assert(priority === null ||
  8452. typeof priority === 'string' ||
  8453. typeof priority === 'number' ||
  8454. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  8455. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  8456. json = json['.value'];
  8457. }
  8458. // Valid leaf nodes include non-objects or server-value wrapper objects
  8459. if (typeof json !== 'object' || '.sv' in json) {
  8460. const jsonLeaf = json;
  8461. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  8462. }
  8463. if (!(json instanceof Array) && USE_HINZE) {
  8464. const children = [];
  8465. let childrenHavePriority = false;
  8466. const hinzeJsonObj = json;
  8467. each(hinzeJsonObj, (key, child) => {
  8468. if (key.substring(0, 1) !== '.') {
  8469. // Ignore metadata nodes
  8470. const childNode = nodeFromJSON(child);
  8471. if (!childNode.isEmpty()) {
  8472. childrenHavePriority =
  8473. childrenHavePriority || !childNode.getPriority().isEmpty();
  8474. children.push(new NamedNode(key, childNode));
  8475. }
  8476. }
  8477. });
  8478. if (children.length === 0) {
  8479. return ChildrenNode.EMPTY_NODE;
  8480. }
  8481. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  8482. if (childrenHavePriority) {
  8483. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  8484. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  8485. }
  8486. else {
  8487. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  8488. }
  8489. }
  8490. else {
  8491. let node = ChildrenNode.EMPTY_NODE;
  8492. each(json, (key, childData) => {
  8493. if (util.contains(json, key)) {
  8494. if (key.substring(0, 1) !== '.') {
  8495. // ignore metadata nodes.
  8496. const childNode = nodeFromJSON(childData);
  8497. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  8498. node = node.updateImmediateChild(key, childNode);
  8499. }
  8500. }
  8501. }
  8502. });
  8503. return node.updatePriority(nodeFromJSON(priority));
  8504. }
  8505. }
  8506. setNodeFromJSON(nodeFromJSON);
  8507. /**
  8508. * @license
  8509. * Copyright 2017 Google LLC
  8510. *
  8511. * Licensed under the Apache License, Version 2.0 (the "License");
  8512. * you may not use this file except in compliance with the License.
  8513. * You may obtain a copy of the License at
  8514. *
  8515. * http://www.apache.org/licenses/LICENSE-2.0
  8516. *
  8517. * Unless required by applicable law or agreed to in writing, software
  8518. * distributed under the License is distributed on an "AS IS" BASIS,
  8519. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8520. * See the License for the specific language governing permissions and
  8521. * limitations under the License.
  8522. */
  8523. class PathIndex extends Index {
  8524. constructor(indexPath_) {
  8525. super();
  8526. this.indexPath_ = indexPath_;
  8527. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  8528. }
  8529. extractChild(snap) {
  8530. return snap.getChild(this.indexPath_);
  8531. }
  8532. isDefinedOn(node) {
  8533. return !node.getChild(this.indexPath_).isEmpty();
  8534. }
  8535. compare(a, b) {
  8536. const aChild = this.extractChild(a.node);
  8537. const bChild = this.extractChild(b.node);
  8538. const indexCmp = aChild.compareTo(bChild);
  8539. if (indexCmp === 0) {
  8540. return nameCompare(a.name, b.name);
  8541. }
  8542. else {
  8543. return indexCmp;
  8544. }
  8545. }
  8546. makePost(indexValue, name) {
  8547. const valueNode = nodeFromJSON(indexValue);
  8548. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  8549. return new NamedNode(name, node);
  8550. }
  8551. maxPost() {
  8552. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  8553. return new NamedNode(MAX_NAME, node);
  8554. }
  8555. toString() {
  8556. return pathSlice(this.indexPath_, 0).join('/');
  8557. }
  8558. }
  8559. /**
  8560. * @license
  8561. * Copyright 2017 Google LLC
  8562. *
  8563. * Licensed under the Apache License, Version 2.0 (the "License");
  8564. * you may not use this file except in compliance with the License.
  8565. * You may obtain a copy of the License at
  8566. *
  8567. * http://www.apache.org/licenses/LICENSE-2.0
  8568. *
  8569. * Unless required by applicable law or agreed to in writing, software
  8570. * distributed under the License is distributed on an "AS IS" BASIS,
  8571. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8572. * See the License for the specific language governing permissions and
  8573. * limitations under the License.
  8574. */
  8575. class ValueIndex extends Index {
  8576. compare(a, b) {
  8577. const indexCmp = a.node.compareTo(b.node);
  8578. if (indexCmp === 0) {
  8579. return nameCompare(a.name, b.name);
  8580. }
  8581. else {
  8582. return indexCmp;
  8583. }
  8584. }
  8585. isDefinedOn(node) {
  8586. return true;
  8587. }
  8588. indexedValueChanged(oldNode, newNode) {
  8589. return !oldNode.equals(newNode);
  8590. }
  8591. minPost() {
  8592. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8593. return NamedNode.MIN;
  8594. }
  8595. maxPost() {
  8596. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8597. return NamedNode.MAX;
  8598. }
  8599. makePost(indexValue, name) {
  8600. const valueNode = nodeFromJSON(indexValue);
  8601. return new NamedNode(name, valueNode);
  8602. }
  8603. /**
  8604. * @returns String representation for inclusion in a query spec
  8605. */
  8606. toString() {
  8607. return '.value';
  8608. }
  8609. }
  8610. const VALUE_INDEX = new ValueIndex();
  8611. /**
  8612. * @license
  8613. * Copyright 2017 Google LLC
  8614. *
  8615. * Licensed under the Apache License, Version 2.0 (the "License");
  8616. * you may not use this file except in compliance with the License.
  8617. * You may obtain a copy of the License at
  8618. *
  8619. * http://www.apache.org/licenses/LICENSE-2.0
  8620. *
  8621. * Unless required by applicable law or agreed to in writing, software
  8622. * distributed under the License is distributed on an "AS IS" BASIS,
  8623. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8624. * See the License for the specific language governing permissions and
  8625. * limitations under the License.
  8626. */
  8627. function changeValue(snapshotNode) {
  8628. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  8629. }
  8630. function changeChildAdded(childName, snapshotNode) {
  8631. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  8632. }
  8633. function changeChildRemoved(childName, snapshotNode) {
  8634. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  8635. }
  8636. function changeChildChanged(childName, snapshotNode, oldSnap) {
  8637. return {
  8638. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  8639. snapshotNode,
  8640. childName,
  8641. oldSnap
  8642. };
  8643. }
  8644. function changeChildMoved(childName, snapshotNode) {
  8645. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  8646. }
  8647. /**
  8648. * @license
  8649. * Copyright 2017 Google LLC
  8650. *
  8651. * Licensed under the Apache License, Version 2.0 (the "License");
  8652. * you may not use this file except in compliance with the License.
  8653. * You may obtain a copy of the License at
  8654. *
  8655. * http://www.apache.org/licenses/LICENSE-2.0
  8656. *
  8657. * Unless required by applicable law or agreed to in writing, software
  8658. * distributed under the License is distributed on an "AS IS" BASIS,
  8659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8660. * See the License for the specific language governing permissions and
  8661. * limitations under the License.
  8662. */
  8663. /**
  8664. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  8665. */
  8666. class IndexedFilter {
  8667. constructor(index_) {
  8668. this.index_ = index_;
  8669. }
  8670. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  8671. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  8672. const oldChild = snap.getImmediateChild(key);
  8673. // Check if anything actually changed.
  8674. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  8675. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  8676. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  8677. // to avoid treating these cases as "nothing changed."
  8678. if (oldChild.isEmpty() === newChild.isEmpty()) {
  8679. // Nothing changed.
  8680. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  8681. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  8682. return snap;
  8683. }
  8684. }
  8685. if (optChangeAccumulator != null) {
  8686. if (newChild.isEmpty()) {
  8687. if (snap.hasChild(key)) {
  8688. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  8689. }
  8690. else {
  8691. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  8692. }
  8693. }
  8694. else if (oldChild.isEmpty()) {
  8695. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  8696. }
  8697. else {
  8698. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  8699. }
  8700. }
  8701. if (snap.isLeafNode() && newChild.isEmpty()) {
  8702. return snap;
  8703. }
  8704. else {
  8705. // Make sure the node is indexed
  8706. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  8707. }
  8708. }
  8709. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  8710. if (optChangeAccumulator != null) {
  8711. if (!oldSnap.isLeafNode()) {
  8712. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  8713. if (!newSnap.hasChild(key)) {
  8714. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  8715. }
  8716. });
  8717. }
  8718. if (!newSnap.isLeafNode()) {
  8719. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  8720. if (oldSnap.hasChild(key)) {
  8721. const oldChild = oldSnap.getImmediateChild(key);
  8722. if (!oldChild.equals(childNode)) {
  8723. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  8724. }
  8725. }
  8726. else {
  8727. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  8728. }
  8729. });
  8730. }
  8731. }
  8732. return newSnap.withIndex(this.index_);
  8733. }
  8734. updatePriority(oldSnap, newPriority) {
  8735. if (oldSnap.isEmpty()) {
  8736. return ChildrenNode.EMPTY_NODE;
  8737. }
  8738. else {
  8739. return oldSnap.updatePriority(newPriority);
  8740. }
  8741. }
  8742. filtersNodes() {
  8743. return false;
  8744. }
  8745. getIndexedFilter() {
  8746. return this;
  8747. }
  8748. getIndex() {
  8749. return this.index_;
  8750. }
  8751. }
  8752. /**
  8753. * @license
  8754. * Copyright 2017 Google LLC
  8755. *
  8756. * Licensed under the Apache License, Version 2.0 (the "License");
  8757. * you may not use this file except in compliance with the License.
  8758. * You may obtain a copy of the License at
  8759. *
  8760. * http://www.apache.org/licenses/LICENSE-2.0
  8761. *
  8762. * Unless required by applicable law or agreed to in writing, software
  8763. * distributed under the License is distributed on an "AS IS" BASIS,
  8764. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8765. * See the License for the specific language governing permissions and
  8766. * limitations under the License.
  8767. */
  8768. /**
  8769. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  8770. */
  8771. class RangedFilter {
  8772. constructor(params) {
  8773. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  8774. this.index_ = params.getIndex();
  8775. this.startPost_ = RangedFilter.getStartPost_(params);
  8776. this.endPost_ = RangedFilter.getEndPost_(params);
  8777. this.startIsInclusive_ = !params.startAfterSet_;
  8778. this.endIsInclusive_ = !params.endBeforeSet_;
  8779. }
  8780. getStartPost() {
  8781. return this.startPost_;
  8782. }
  8783. getEndPost() {
  8784. return this.endPost_;
  8785. }
  8786. matches(node) {
  8787. const isWithinStart = this.startIsInclusive_
  8788. ? this.index_.compare(this.getStartPost(), node) <= 0
  8789. : this.index_.compare(this.getStartPost(), node) < 0;
  8790. const isWithinEnd = this.endIsInclusive_
  8791. ? this.index_.compare(node, this.getEndPost()) <= 0
  8792. : this.index_.compare(node, this.getEndPost()) < 0;
  8793. return isWithinStart && isWithinEnd;
  8794. }
  8795. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  8796. if (!this.matches(new NamedNode(key, newChild))) {
  8797. newChild = ChildrenNode.EMPTY_NODE;
  8798. }
  8799. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  8800. }
  8801. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  8802. if (newSnap.isLeafNode()) {
  8803. // Make sure we have a children node with the correct index, not a leaf node;
  8804. newSnap = ChildrenNode.EMPTY_NODE;
  8805. }
  8806. let filtered = newSnap.withIndex(this.index_);
  8807. // Don't support priorities on queries
  8808. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  8809. const self = this;
  8810. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  8811. if (!self.matches(new NamedNode(key, childNode))) {
  8812. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  8813. }
  8814. });
  8815. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  8816. }
  8817. updatePriority(oldSnap, newPriority) {
  8818. // Don't support priorities on queries
  8819. return oldSnap;
  8820. }
  8821. filtersNodes() {
  8822. return true;
  8823. }
  8824. getIndexedFilter() {
  8825. return this.indexedFilter_;
  8826. }
  8827. getIndex() {
  8828. return this.index_;
  8829. }
  8830. static getStartPost_(params) {
  8831. if (params.hasStart()) {
  8832. const startName = params.getIndexStartName();
  8833. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  8834. }
  8835. else {
  8836. return params.getIndex().minPost();
  8837. }
  8838. }
  8839. static getEndPost_(params) {
  8840. if (params.hasEnd()) {
  8841. const endName = params.getIndexEndName();
  8842. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  8843. }
  8844. else {
  8845. return params.getIndex().maxPost();
  8846. }
  8847. }
  8848. }
  8849. /**
  8850. * @license
  8851. * Copyright 2017 Google LLC
  8852. *
  8853. * Licensed under the Apache License, Version 2.0 (the "License");
  8854. * you may not use this file except in compliance with the License.
  8855. * You may obtain a copy of the License at
  8856. *
  8857. * http://www.apache.org/licenses/LICENSE-2.0
  8858. *
  8859. * Unless required by applicable law or agreed to in writing, software
  8860. * distributed under the License is distributed on an "AS IS" BASIS,
  8861. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8862. * See the License for the specific language governing permissions and
  8863. * limitations under the License.
  8864. */
  8865. /**
  8866. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  8867. */
  8868. class LimitedFilter {
  8869. constructor(params) {
  8870. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  8871. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  8872. this.withinStartPost = (node) => {
  8873. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  8874. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  8875. };
  8876. this.withinEndPost = (node) => {
  8877. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  8878. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  8879. };
  8880. this.rangedFilter_ = new RangedFilter(params);
  8881. this.index_ = params.getIndex();
  8882. this.limit_ = params.getLimit();
  8883. this.reverse_ = !params.isViewFromLeft();
  8884. this.startIsInclusive_ = !params.startAfterSet_;
  8885. this.endIsInclusive_ = !params.endBeforeSet_;
  8886. }
  8887. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  8888. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  8889. newChild = ChildrenNode.EMPTY_NODE;
  8890. }
  8891. if (snap.getImmediateChild(key).equals(newChild)) {
  8892. // No change
  8893. return snap;
  8894. }
  8895. else if (snap.numChildren() < this.limit_) {
  8896. return this.rangedFilter_
  8897. .getIndexedFilter()
  8898. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  8899. }
  8900. else {
  8901. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  8902. }
  8903. }
  8904. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  8905. let filtered;
  8906. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  8907. // Make sure we have a children node with the correct index, not a leaf node;
  8908. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  8909. }
  8910. else {
  8911. if (this.limit_ * 2 < newSnap.numChildren() &&
  8912. newSnap.isIndexed(this.index_)) {
  8913. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  8914. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  8915. // anchor to the startPost, endPost, or last element as appropriate
  8916. let iterator;
  8917. if (this.reverse_) {
  8918. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  8919. }
  8920. else {
  8921. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  8922. }
  8923. let count = 0;
  8924. while (iterator.hasNext() && count < this.limit_) {
  8925. const next = iterator.getNext();
  8926. if (!this.withinDirectionalStart(next)) {
  8927. // if we have not reached the start, skip to the next element
  8928. continue;
  8929. }
  8930. else if (!this.withinDirectionalEnd(next)) {
  8931. // if we have reached the end, stop adding elements
  8932. break;
  8933. }
  8934. else {
  8935. filtered = filtered.updateImmediateChild(next.name, next.node);
  8936. count++;
  8937. }
  8938. }
  8939. }
  8940. else {
  8941. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  8942. filtered = newSnap.withIndex(this.index_);
  8943. // Don't support priorities on queries
  8944. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  8945. let iterator;
  8946. if (this.reverse_) {
  8947. iterator = filtered.getReverseIterator(this.index_);
  8948. }
  8949. else {
  8950. iterator = filtered.getIterator(this.index_);
  8951. }
  8952. let count = 0;
  8953. while (iterator.hasNext()) {
  8954. const next = iterator.getNext();
  8955. const inRange = count < this.limit_ &&
  8956. this.withinDirectionalStart(next) &&
  8957. this.withinDirectionalEnd(next);
  8958. if (inRange) {
  8959. count++;
  8960. }
  8961. else {
  8962. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  8963. }
  8964. }
  8965. }
  8966. }
  8967. return this.rangedFilter_
  8968. .getIndexedFilter()
  8969. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  8970. }
  8971. updatePriority(oldSnap, newPriority) {
  8972. // Don't support priorities on queries
  8973. return oldSnap;
  8974. }
  8975. filtersNodes() {
  8976. return true;
  8977. }
  8978. getIndexedFilter() {
  8979. return this.rangedFilter_.getIndexedFilter();
  8980. }
  8981. getIndex() {
  8982. return this.index_;
  8983. }
  8984. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  8985. // TODO: rename all cache stuff etc to general snap terminology
  8986. let cmp;
  8987. if (this.reverse_) {
  8988. const indexCmp = this.index_.getCompare();
  8989. cmp = (a, b) => indexCmp(b, a);
  8990. }
  8991. else {
  8992. cmp = this.index_.getCompare();
  8993. }
  8994. const oldEventCache = snap;
  8995. util.assert(oldEventCache.numChildren() === this.limit_, '');
  8996. const newChildNamedNode = new NamedNode(childKey, childSnap);
  8997. const windowBoundary = this.reverse_
  8998. ? oldEventCache.getFirstChild(this.index_)
  8999. : oldEventCache.getLastChild(this.index_);
  9000. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  9001. if (oldEventCache.hasChild(childKey)) {
  9002. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  9003. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  9004. while (nextChild != null &&
  9005. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  9006. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  9007. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  9008. // the limited filter...
  9009. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  9010. }
  9011. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  9012. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  9013. if (remainsInWindow) {
  9014. if (changeAccumulator != null) {
  9015. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  9016. }
  9017. return oldEventCache.updateImmediateChild(childKey, childSnap);
  9018. }
  9019. else {
  9020. if (changeAccumulator != null) {
  9021. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  9022. }
  9023. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  9024. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  9025. if (nextChildInRange) {
  9026. if (changeAccumulator != null) {
  9027. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  9028. }
  9029. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  9030. }
  9031. else {
  9032. return newEventCache;
  9033. }
  9034. }
  9035. }
  9036. else if (childSnap.isEmpty()) {
  9037. // we're deleting a node, but it was not in the window, so ignore it
  9038. return snap;
  9039. }
  9040. else if (inRange) {
  9041. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  9042. if (changeAccumulator != null) {
  9043. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  9044. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  9045. }
  9046. return oldEventCache
  9047. .updateImmediateChild(childKey, childSnap)
  9048. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  9049. }
  9050. else {
  9051. return snap;
  9052. }
  9053. }
  9054. else {
  9055. return snap;
  9056. }
  9057. }
  9058. }
  9059. /**
  9060. * @license
  9061. * Copyright 2017 Google LLC
  9062. *
  9063. * Licensed under the Apache License, Version 2.0 (the "License");
  9064. * you may not use this file except in compliance with the License.
  9065. * You may obtain a copy of the License at
  9066. *
  9067. * http://www.apache.org/licenses/LICENSE-2.0
  9068. *
  9069. * Unless required by applicable law or agreed to in writing, software
  9070. * distributed under the License is distributed on an "AS IS" BASIS,
  9071. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9072. * See the License for the specific language governing permissions and
  9073. * limitations under the License.
  9074. */
  9075. /**
  9076. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  9077. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  9078. * user-facing API level, so it is not done here.
  9079. *
  9080. * @internal
  9081. */
  9082. class QueryParams {
  9083. constructor() {
  9084. this.limitSet_ = false;
  9085. this.startSet_ = false;
  9086. this.startNameSet_ = false;
  9087. this.startAfterSet_ = false; // can only be true if startSet_ is true
  9088. this.endSet_ = false;
  9089. this.endNameSet_ = false;
  9090. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  9091. this.limit_ = 0;
  9092. this.viewFrom_ = '';
  9093. this.indexStartValue_ = null;
  9094. this.indexStartName_ = '';
  9095. this.indexEndValue_ = null;
  9096. this.indexEndName_ = '';
  9097. this.index_ = PRIORITY_INDEX;
  9098. }
  9099. hasStart() {
  9100. return this.startSet_;
  9101. }
  9102. /**
  9103. * @returns True if it would return from left.
  9104. */
  9105. isViewFromLeft() {
  9106. if (this.viewFrom_ === '') {
  9107. // limit(), rather than limitToFirst or limitToLast was called.
  9108. // This means that only one of startSet_ and endSet_ is true. Use them
  9109. // to calculate which side of the view to anchor to. If neither is set,
  9110. // anchor to the end.
  9111. return this.startSet_;
  9112. }
  9113. else {
  9114. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  9115. }
  9116. }
  9117. /**
  9118. * Only valid to call if hasStart() returns true
  9119. */
  9120. getIndexStartValue() {
  9121. util.assert(this.startSet_, 'Only valid if start has been set');
  9122. return this.indexStartValue_;
  9123. }
  9124. /**
  9125. * Only valid to call if hasStart() returns true.
  9126. * Returns the starting key name for the range defined by these query parameters
  9127. */
  9128. getIndexStartName() {
  9129. util.assert(this.startSet_, 'Only valid if start has been set');
  9130. if (this.startNameSet_) {
  9131. return this.indexStartName_;
  9132. }
  9133. else {
  9134. return MIN_NAME;
  9135. }
  9136. }
  9137. hasEnd() {
  9138. return this.endSet_;
  9139. }
  9140. /**
  9141. * Only valid to call if hasEnd() returns true.
  9142. */
  9143. getIndexEndValue() {
  9144. util.assert(this.endSet_, 'Only valid if end has been set');
  9145. return this.indexEndValue_;
  9146. }
  9147. /**
  9148. * Only valid to call if hasEnd() returns true.
  9149. * Returns the end key name for the range defined by these query parameters
  9150. */
  9151. getIndexEndName() {
  9152. util.assert(this.endSet_, 'Only valid if end has been set');
  9153. if (this.endNameSet_) {
  9154. return this.indexEndName_;
  9155. }
  9156. else {
  9157. return MAX_NAME;
  9158. }
  9159. }
  9160. hasLimit() {
  9161. return this.limitSet_;
  9162. }
  9163. /**
  9164. * @returns True if a limit has been set and it has been explicitly anchored
  9165. */
  9166. hasAnchoredLimit() {
  9167. return this.limitSet_ && this.viewFrom_ !== '';
  9168. }
  9169. /**
  9170. * Only valid to call if hasLimit() returns true
  9171. */
  9172. getLimit() {
  9173. util.assert(this.limitSet_, 'Only valid if limit has been set');
  9174. return this.limit_;
  9175. }
  9176. getIndex() {
  9177. return this.index_;
  9178. }
  9179. loadsAllData() {
  9180. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  9181. }
  9182. isDefault() {
  9183. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  9184. }
  9185. copy() {
  9186. const copy = new QueryParams();
  9187. copy.limitSet_ = this.limitSet_;
  9188. copy.limit_ = this.limit_;
  9189. copy.startSet_ = this.startSet_;
  9190. copy.startAfterSet_ = this.startAfterSet_;
  9191. copy.indexStartValue_ = this.indexStartValue_;
  9192. copy.startNameSet_ = this.startNameSet_;
  9193. copy.indexStartName_ = this.indexStartName_;
  9194. copy.endSet_ = this.endSet_;
  9195. copy.endBeforeSet_ = this.endBeforeSet_;
  9196. copy.indexEndValue_ = this.indexEndValue_;
  9197. copy.endNameSet_ = this.endNameSet_;
  9198. copy.indexEndName_ = this.indexEndName_;
  9199. copy.index_ = this.index_;
  9200. copy.viewFrom_ = this.viewFrom_;
  9201. return copy;
  9202. }
  9203. }
  9204. function queryParamsGetNodeFilter(queryParams) {
  9205. if (queryParams.loadsAllData()) {
  9206. return new IndexedFilter(queryParams.getIndex());
  9207. }
  9208. else if (queryParams.hasLimit()) {
  9209. return new LimitedFilter(queryParams);
  9210. }
  9211. else {
  9212. return new RangedFilter(queryParams);
  9213. }
  9214. }
  9215. function queryParamsLimitToFirst(queryParams, newLimit) {
  9216. const newParams = queryParams.copy();
  9217. newParams.limitSet_ = true;
  9218. newParams.limit_ = newLimit;
  9219. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  9220. return newParams;
  9221. }
  9222. function queryParamsLimitToLast(queryParams, newLimit) {
  9223. const newParams = queryParams.copy();
  9224. newParams.limitSet_ = true;
  9225. newParams.limit_ = newLimit;
  9226. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  9227. return newParams;
  9228. }
  9229. function queryParamsStartAt(queryParams, indexValue, key) {
  9230. const newParams = queryParams.copy();
  9231. newParams.startSet_ = true;
  9232. if (indexValue === undefined) {
  9233. indexValue = null;
  9234. }
  9235. newParams.indexStartValue_ = indexValue;
  9236. if (key != null) {
  9237. newParams.startNameSet_ = true;
  9238. newParams.indexStartName_ = key;
  9239. }
  9240. else {
  9241. newParams.startNameSet_ = false;
  9242. newParams.indexStartName_ = '';
  9243. }
  9244. return newParams;
  9245. }
  9246. function queryParamsStartAfter(queryParams, indexValue, key) {
  9247. let params;
  9248. if (queryParams.index_ === KEY_INDEX || !!key) {
  9249. params = queryParamsStartAt(queryParams, indexValue, key);
  9250. }
  9251. else {
  9252. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  9253. }
  9254. params.startAfterSet_ = true;
  9255. return params;
  9256. }
  9257. function queryParamsEndAt(queryParams, indexValue, key) {
  9258. const newParams = queryParams.copy();
  9259. newParams.endSet_ = true;
  9260. if (indexValue === undefined) {
  9261. indexValue = null;
  9262. }
  9263. newParams.indexEndValue_ = indexValue;
  9264. if (key !== undefined) {
  9265. newParams.endNameSet_ = true;
  9266. newParams.indexEndName_ = key;
  9267. }
  9268. else {
  9269. newParams.endNameSet_ = false;
  9270. newParams.indexEndName_ = '';
  9271. }
  9272. return newParams;
  9273. }
  9274. function queryParamsEndBefore(queryParams, indexValue, key) {
  9275. let params;
  9276. if (queryParams.index_ === KEY_INDEX || !!key) {
  9277. params = queryParamsEndAt(queryParams, indexValue, key);
  9278. }
  9279. else {
  9280. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  9281. }
  9282. params.endBeforeSet_ = true;
  9283. return params;
  9284. }
  9285. function queryParamsOrderBy(queryParams, index) {
  9286. const newParams = queryParams.copy();
  9287. newParams.index_ = index;
  9288. return newParams;
  9289. }
  9290. /**
  9291. * Returns a set of REST query string parameters representing this query.
  9292. *
  9293. * @returns query string parameters
  9294. */
  9295. function queryParamsToRestQueryStringParameters(queryParams) {
  9296. const qs = {};
  9297. if (queryParams.isDefault()) {
  9298. return qs;
  9299. }
  9300. let orderBy;
  9301. if (queryParams.index_ === PRIORITY_INDEX) {
  9302. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  9303. }
  9304. else if (queryParams.index_ === VALUE_INDEX) {
  9305. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  9306. }
  9307. else if (queryParams.index_ === KEY_INDEX) {
  9308. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  9309. }
  9310. else {
  9311. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  9312. orderBy = queryParams.index_.toString();
  9313. }
  9314. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  9315. if (queryParams.startSet_) {
  9316. const startParam = queryParams.startAfterSet_
  9317. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  9318. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  9319. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  9320. if (queryParams.startNameSet_) {
  9321. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  9322. }
  9323. }
  9324. if (queryParams.endSet_) {
  9325. const endParam = queryParams.endBeforeSet_
  9326. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  9327. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  9328. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  9329. if (queryParams.endNameSet_) {
  9330. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  9331. }
  9332. }
  9333. if (queryParams.limitSet_) {
  9334. if (queryParams.isViewFromLeft()) {
  9335. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  9336. }
  9337. else {
  9338. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  9339. }
  9340. }
  9341. return qs;
  9342. }
  9343. function queryParamsGetQueryObject(queryParams) {
  9344. const obj = {};
  9345. if (queryParams.startSet_) {
  9346. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  9347. queryParams.indexStartValue_;
  9348. if (queryParams.startNameSet_) {
  9349. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  9350. queryParams.indexStartName_;
  9351. }
  9352. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  9353. !queryParams.startAfterSet_;
  9354. }
  9355. if (queryParams.endSet_) {
  9356. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  9357. if (queryParams.endNameSet_) {
  9358. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  9359. }
  9360. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  9361. !queryParams.endBeforeSet_;
  9362. }
  9363. if (queryParams.limitSet_) {
  9364. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  9365. let viewFrom = queryParams.viewFrom_;
  9366. if (viewFrom === '') {
  9367. if (queryParams.isViewFromLeft()) {
  9368. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  9369. }
  9370. else {
  9371. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  9372. }
  9373. }
  9374. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  9375. }
  9376. // For now, priority index is the default, so we only specify if it's some other index
  9377. if (queryParams.index_ !== PRIORITY_INDEX) {
  9378. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  9379. }
  9380. return obj;
  9381. }
  9382. /**
  9383. * @license
  9384. * Copyright 2017 Google LLC
  9385. *
  9386. * Licensed under the Apache License, Version 2.0 (the "License");
  9387. * you may not use this file except in compliance with the License.
  9388. * You may obtain a copy of the License at
  9389. *
  9390. * http://www.apache.org/licenses/LICENSE-2.0
  9391. *
  9392. * Unless required by applicable law or agreed to in writing, software
  9393. * distributed under the License is distributed on an "AS IS" BASIS,
  9394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9395. * See the License for the specific language governing permissions and
  9396. * limitations under the License.
  9397. */
  9398. /**
  9399. * An implementation of ServerActions that communicates with the server via REST requests.
  9400. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  9401. * persistent connection (using WebSockets or long-polling)
  9402. */
  9403. class ReadonlyRestClient extends ServerActions {
  9404. /**
  9405. * @param repoInfo_ - Data about the namespace we are connecting to
  9406. * @param onDataUpdate_ - A callback for new data from the server
  9407. */
  9408. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  9409. super();
  9410. this.repoInfo_ = repoInfo_;
  9411. this.onDataUpdate_ = onDataUpdate_;
  9412. this.authTokenProvider_ = authTokenProvider_;
  9413. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  9414. /** @private {function(...[*])} */
  9415. this.log_ = logWrapper('p:rest:');
  9416. /**
  9417. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  9418. * that's been removed. :-/
  9419. */
  9420. this.listens_ = {};
  9421. }
  9422. reportStats(stats) {
  9423. throw new Error('Method not implemented.');
  9424. }
  9425. static getListenId_(query, tag) {
  9426. if (tag !== undefined) {
  9427. return 'tag$' + tag;
  9428. }
  9429. else {
  9430. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  9431. return query._path.toString();
  9432. }
  9433. }
  9434. /** @inheritDoc */
  9435. listen(query, currentHashFn, tag, onComplete) {
  9436. const pathString = query._path.toString();
  9437. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  9438. // Mark this listener so we can tell if it's removed.
  9439. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  9440. const thisListen = {};
  9441. this.listens_[listenId] = thisListen;
  9442. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  9443. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  9444. let data = result;
  9445. if (error === 404) {
  9446. data = null;
  9447. error = null;
  9448. }
  9449. if (error === null) {
  9450. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  9451. }
  9452. if (util.safeGet(this.listens_, listenId) === thisListen) {
  9453. let status;
  9454. if (!error) {
  9455. status = 'ok';
  9456. }
  9457. else if (error === 401) {
  9458. status = 'permission_denied';
  9459. }
  9460. else {
  9461. status = 'rest_error:' + error;
  9462. }
  9463. onComplete(status, null);
  9464. }
  9465. });
  9466. }
  9467. /** @inheritDoc */
  9468. unlisten(query, tag) {
  9469. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  9470. delete this.listens_[listenId];
  9471. }
  9472. get(query) {
  9473. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  9474. const pathString = query._path.toString();
  9475. const deferred = new util.Deferred();
  9476. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  9477. let data = result;
  9478. if (error === 404) {
  9479. data = null;
  9480. error = null;
  9481. }
  9482. if (error === null) {
  9483. this.onDataUpdate_(pathString, data,
  9484. /*isMerge=*/ false,
  9485. /*tag=*/ null);
  9486. deferred.resolve(data);
  9487. }
  9488. else {
  9489. deferred.reject(new Error(data));
  9490. }
  9491. });
  9492. return deferred.promise;
  9493. }
  9494. /** @inheritDoc */
  9495. refreshAuthToken(token) {
  9496. // no-op since we just always call getToken.
  9497. }
  9498. /**
  9499. * Performs a REST request to the given path, with the provided query string parameters,
  9500. * and any auth credentials we have.
  9501. */
  9502. restRequest_(pathString, queryStringParameters = {}, callback) {
  9503. queryStringParameters['format'] = 'export';
  9504. return Promise.all([
  9505. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  9506. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  9507. ]).then(([authToken, appCheckToken]) => {
  9508. if (authToken && authToken.accessToken) {
  9509. queryStringParameters['auth'] = authToken.accessToken;
  9510. }
  9511. if (appCheckToken && appCheckToken.token) {
  9512. queryStringParameters['ac'] = appCheckToken.token;
  9513. }
  9514. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  9515. this.repoInfo_.host +
  9516. pathString +
  9517. '?' +
  9518. 'ns=' +
  9519. this.repoInfo_.namespace +
  9520. util.querystring(queryStringParameters);
  9521. this.log_('Sending REST request for ' + url);
  9522. const xhr = new XMLHttpRequest();
  9523. xhr.onreadystatechange = () => {
  9524. if (callback && xhr.readyState === 4) {
  9525. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  9526. let res = null;
  9527. if (xhr.status >= 200 && xhr.status < 300) {
  9528. try {
  9529. res = util.jsonEval(xhr.responseText);
  9530. }
  9531. catch (e) {
  9532. warn$1('Failed to parse JSON response for ' +
  9533. url +
  9534. ': ' +
  9535. xhr.responseText);
  9536. }
  9537. callback(null, res);
  9538. }
  9539. else {
  9540. // 401 and 404 are expected.
  9541. if (xhr.status !== 401 && xhr.status !== 404) {
  9542. warn$1('Got unsuccessful REST response for ' +
  9543. url +
  9544. ' Status: ' +
  9545. xhr.status);
  9546. }
  9547. callback(xhr.status);
  9548. }
  9549. callback = null;
  9550. }
  9551. };
  9552. xhr.open('GET', url, /*asynchronous=*/ true);
  9553. xhr.send();
  9554. });
  9555. }
  9556. }
  9557. /**
  9558. * @license
  9559. * Copyright 2017 Google LLC
  9560. *
  9561. * Licensed under the Apache License, Version 2.0 (the "License");
  9562. * you may not use this file except in compliance with the License.
  9563. * You may obtain a copy of the License at
  9564. *
  9565. * http://www.apache.org/licenses/LICENSE-2.0
  9566. *
  9567. * Unless required by applicable law or agreed to in writing, software
  9568. * distributed under the License is distributed on an "AS IS" BASIS,
  9569. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9570. * See the License for the specific language governing permissions and
  9571. * limitations under the License.
  9572. */
  9573. /**
  9574. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  9575. */
  9576. class SnapshotHolder {
  9577. constructor() {
  9578. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  9579. }
  9580. getNode(path) {
  9581. return this.rootNode_.getChild(path);
  9582. }
  9583. updateSnapshot(path, newSnapshotNode) {
  9584. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  9585. }
  9586. }
  9587. /**
  9588. * @license
  9589. * Copyright 2017 Google LLC
  9590. *
  9591. * Licensed under the Apache License, Version 2.0 (the "License");
  9592. * you may not use this file except in compliance with the License.
  9593. * You may obtain a copy of the License at
  9594. *
  9595. * http://www.apache.org/licenses/LICENSE-2.0
  9596. *
  9597. * Unless required by applicable law or agreed to in writing, software
  9598. * distributed under the License is distributed on an "AS IS" BASIS,
  9599. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9600. * See the License for the specific language governing permissions and
  9601. * limitations under the License.
  9602. */
  9603. function newSparseSnapshotTree() {
  9604. return {
  9605. value: null,
  9606. children: new Map()
  9607. };
  9608. }
  9609. /**
  9610. * Stores the given node at the specified path. If there is already a node
  9611. * at a shallower path, it merges the new data into that snapshot node.
  9612. *
  9613. * @param path - Path to look up snapshot for.
  9614. * @param data - The new data, or null.
  9615. */
  9616. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  9617. if (pathIsEmpty(path)) {
  9618. sparseSnapshotTree.value = data;
  9619. sparseSnapshotTree.children.clear();
  9620. }
  9621. else if (sparseSnapshotTree.value !== null) {
  9622. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  9623. }
  9624. else {
  9625. const childKey = pathGetFront(path);
  9626. if (!sparseSnapshotTree.children.has(childKey)) {
  9627. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  9628. }
  9629. const child = sparseSnapshotTree.children.get(childKey);
  9630. path = pathPopFront(path);
  9631. sparseSnapshotTreeRemember(child, path, data);
  9632. }
  9633. }
  9634. /**
  9635. * Purge the data at path from the cache.
  9636. *
  9637. * @param path - Path to look up snapshot for.
  9638. * @returns True if this node should now be removed.
  9639. */
  9640. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  9641. if (pathIsEmpty(path)) {
  9642. sparseSnapshotTree.value = null;
  9643. sparseSnapshotTree.children.clear();
  9644. return true;
  9645. }
  9646. else {
  9647. if (sparseSnapshotTree.value !== null) {
  9648. if (sparseSnapshotTree.value.isLeafNode()) {
  9649. // We're trying to forget a node that doesn't exist
  9650. return false;
  9651. }
  9652. else {
  9653. const value = sparseSnapshotTree.value;
  9654. sparseSnapshotTree.value = null;
  9655. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  9656. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  9657. });
  9658. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  9659. }
  9660. }
  9661. else if (sparseSnapshotTree.children.size > 0) {
  9662. const childKey = pathGetFront(path);
  9663. path = pathPopFront(path);
  9664. if (sparseSnapshotTree.children.has(childKey)) {
  9665. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  9666. if (safeToRemove) {
  9667. sparseSnapshotTree.children.delete(childKey);
  9668. }
  9669. }
  9670. return sparseSnapshotTree.children.size === 0;
  9671. }
  9672. else {
  9673. return true;
  9674. }
  9675. }
  9676. }
  9677. /**
  9678. * Recursively iterates through all of the stored tree and calls the
  9679. * callback on each one.
  9680. *
  9681. * @param prefixPath - Path to look up node for.
  9682. * @param func - The function to invoke for each tree.
  9683. */
  9684. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  9685. if (sparseSnapshotTree.value !== null) {
  9686. func(prefixPath, sparseSnapshotTree.value);
  9687. }
  9688. else {
  9689. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  9690. const path = new Path(prefixPath.toString() + '/' + key);
  9691. sparseSnapshotTreeForEachTree(tree, path, func);
  9692. });
  9693. }
  9694. }
  9695. /**
  9696. * Iterates through each immediate child and triggers the callback.
  9697. * Only seems to be used in tests.
  9698. *
  9699. * @param func - The function to invoke for each child.
  9700. */
  9701. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  9702. sparseSnapshotTree.children.forEach((tree, key) => {
  9703. func(key, tree);
  9704. });
  9705. }
  9706. /**
  9707. * @license
  9708. * Copyright 2017 Google LLC
  9709. *
  9710. * Licensed under the Apache License, Version 2.0 (the "License");
  9711. * you may not use this file except in compliance with the License.
  9712. * You may obtain a copy of the License at
  9713. *
  9714. * http://www.apache.org/licenses/LICENSE-2.0
  9715. *
  9716. * Unless required by applicable law or agreed to in writing, software
  9717. * distributed under the License is distributed on an "AS IS" BASIS,
  9718. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9719. * See the License for the specific language governing permissions and
  9720. * limitations under the License.
  9721. */
  9722. /**
  9723. * Returns the delta from the previous call to get stats.
  9724. *
  9725. * @param collection_ - The collection to "listen" to.
  9726. */
  9727. class StatsListener {
  9728. constructor(collection_) {
  9729. this.collection_ = collection_;
  9730. this.last_ = null;
  9731. }
  9732. get() {
  9733. const newStats = this.collection_.get();
  9734. const delta = Object.assign({}, newStats);
  9735. if (this.last_) {
  9736. each(this.last_, (stat, value) => {
  9737. delta[stat] = delta[stat] - value;
  9738. });
  9739. }
  9740. this.last_ = newStats;
  9741. return delta;
  9742. }
  9743. }
  9744. /**
  9745. * @license
  9746. * Copyright 2017 Google LLC
  9747. *
  9748. * Licensed under the Apache License, Version 2.0 (the "License");
  9749. * you may not use this file except in compliance with the License.
  9750. * You may obtain a copy of the License at
  9751. *
  9752. * http://www.apache.org/licenses/LICENSE-2.0
  9753. *
  9754. * Unless required by applicable law or agreed to in writing, software
  9755. * distributed under the License is distributed on an "AS IS" BASIS,
  9756. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9757. * See the License for the specific language governing permissions and
  9758. * limitations under the License.
  9759. */
  9760. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  9761. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  9762. // seconds to try to ensure the Firebase connection is established / settled.
  9763. const FIRST_STATS_MIN_TIME = 10 * 1000;
  9764. const FIRST_STATS_MAX_TIME = 30 * 1000;
  9765. // We'll continue to report stats on average every 5 minutes.
  9766. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  9767. class StatsReporter {
  9768. constructor(collection, server_) {
  9769. this.server_ = server_;
  9770. this.statsToReport_ = {};
  9771. this.statsListener_ = new StatsListener(collection);
  9772. const timeout = FIRST_STATS_MIN_TIME +
  9773. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  9774. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  9775. }
  9776. reportStats_() {
  9777. const stats = this.statsListener_.get();
  9778. const reportedStats = {};
  9779. let haveStatsToReport = false;
  9780. each(stats, (stat, value) => {
  9781. if (value > 0 && util.contains(this.statsToReport_, stat)) {
  9782. reportedStats[stat] = value;
  9783. haveStatsToReport = true;
  9784. }
  9785. });
  9786. if (haveStatsToReport) {
  9787. this.server_.reportStats(reportedStats);
  9788. }
  9789. // queue our next run.
  9790. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  9791. }
  9792. }
  9793. /**
  9794. * @license
  9795. * Copyright 2017 Google LLC
  9796. *
  9797. * Licensed under the Apache License, Version 2.0 (the "License");
  9798. * you may not use this file except in compliance with the License.
  9799. * You may obtain a copy of the License at
  9800. *
  9801. * http://www.apache.org/licenses/LICENSE-2.0
  9802. *
  9803. * Unless required by applicable law or agreed to in writing, software
  9804. * distributed under the License is distributed on an "AS IS" BASIS,
  9805. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9806. * See the License for the specific language governing permissions and
  9807. * limitations under the License.
  9808. */
  9809. /**
  9810. *
  9811. * @enum
  9812. */
  9813. var OperationType;
  9814. (function (OperationType) {
  9815. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  9816. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  9817. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  9818. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  9819. })(OperationType || (OperationType = {}));
  9820. function newOperationSourceUser() {
  9821. return {
  9822. fromUser: true,
  9823. fromServer: false,
  9824. queryId: null,
  9825. tagged: false
  9826. };
  9827. }
  9828. function newOperationSourceServer() {
  9829. return {
  9830. fromUser: false,
  9831. fromServer: true,
  9832. queryId: null,
  9833. tagged: false
  9834. };
  9835. }
  9836. function newOperationSourceServerTaggedQuery(queryId) {
  9837. return {
  9838. fromUser: false,
  9839. fromServer: true,
  9840. queryId,
  9841. tagged: true
  9842. };
  9843. }
  9844. /**
  9845. * @license
  9846. * Copyright 2017 Google LLC
  9847. *
  9848. * Licensed under the Apache License, Version 2.0 (the "License");
  9849. * you may not use this file except in compliance with the License.
  9850. * You may obtain a copy of the License at
  9851. *
  9852. * http://www.apache.org/licenses/LICENSE-2.0
  9853. *
  9854. * Unless required by applicable law or agreed to in writing, software
  9855. * distributed under the License is distributed on an "AS IS" BASIS,
  9856. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9857. * See the License for the specific language governing permissions and
  9858. * limitations under the License.
  9859. */
  9860. class AckUserWrite {
  9861. /**
  9862. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  9863. */
  9864. constructor(
  9865. /** @inheritDoc */ path,
  9866. /** @inheritDoc */ affectedTree,
  9867. /** @inheritDoc */ revert) {
  9868. this.path = path;
  9869. this.affectedTree = affectedTree;
  9870. this.revert = revert;
  9871. /** @inheritDoc */
  9872. this.type = OperationType.ACK_USER_WRITE;
  9873. /** @inheritDoc */
  9874. this.source = newOperationSourceUser();
  9875. }
  9876. operationForChild(childName) {
  9877. if (!pathIsEmpty(this.path)) {
  9878. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  9879. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  9880. }
  9881. else if (this.affectedTree.value != null) {
  9882. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  9883. // All child locations are affected as well; just return same operation.
  9884. return this;
  9885. }
  9886. else {
  9887. const childTree = this.affectedTree.subtree(new Path(childName));
  9888. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  9889. }
  9890. }
  9891. }
  9892. /**
  9893. * @license
  9894. * Copyright 2017 Google LLC
  9895. *
  9896. * Licensed under the Apache License, Version 2.0 (the "License");
  9897. * you may not use this file except in compliance with the License.
  9898. * You may obtain a copy of the License at
  9899. *
  9900. * http://www.apache.org/licenses/LICENSE-2.0
  9901. *
  9902. * Unless required by applicable law or agreed to in writing, software
  9903. * distributed under the License is distributed on an "AS IS" BASIS,
  9904. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9905. * See the License for the specific language governing permissions and
  9906. * limitations under the License.
  9907. */
  9908. class ListenComplete {
  9909. constructor(source, path) {
  9910. this.source = source;
  9911. this.path = path;
  9912. /** @inheritDoc */
  9913. this.type = OperationType.LISTEN_COMPLETE;
  9914. }
  9915. operationForChild(childName) {
  9916. if (pathIsEmpty(this.path)) {
  9917. return new ListenComplete(this.source, newEmptyPath());
  9918. }
  9919. else {
  9920. return new ListenComplete(this.source, pathPopFront(this.path));
  9921. }
  9922. }
  9923. }
  9924. /**
  9925. * @license
  9926. * Copyright 2017 Google LLC
  9927. *
  9928. * Licensed under the Apache License, Version 2.0 (the "License");
  9929. * you may not use this file except in compliance with the License.
  9930. * You may obtain a copy of the License at
  9931. *
  9932. * http://www.apache.org/licenses/LICENSE-2.0
  9933. *
  9934. * Unless required by applicable law or agreed to in writing, software
  9935. * distributed under the License is distributed on an "AS IS" BASIS,
  9936. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9937. * See the License for the specific language governing permissions and
  9938. * limitations under the License.
  9939. */
  9940. class Overwrite {
  9941. constructor(source, path, snap) {
  9942. this.source = source;
  9943. this.path = path;
  9944. this.snap = snap;
  9945. /** @inheritDoc */
  9946. this.type = OperationType.OVERWRITE;
  9947. }
  9948. operationForChild(childName) {
  9949. if (pathIsEmpty(this.path)) {
  9950. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  9951. }
  9952. else {
  9953. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  9954. }
  9955. }
  9956. }
  9957. /**
  9958. * @license
  9959. * Copyright 2017 Google LLC
  9960. *
  9961. * Licensed under the Apache License, Version 2.0 (the "License");
  9962. * you may not use this file except in compliance with the License.
  9963. * You may obtain a copy of the License at
  9964. *
  9965. * http://www.apache.org/licenses/LICENSE-2.0
  9966. *
  9967. * Unless required by applicable law or agreed to in writing, software
  9968. * distributed under the License is distributed on an "AS IS" BASIS,
  9969. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9970. * See the License for the specific language governing permissions and
  9971. * limitations under the License.
  9972. */
  9973. class Merge {
  9974. constructor(
  9975. /** @inheritDoc */ source,
  9976. /** @inheritDoc */ path,
  9977. /** @inheritDoc */ children) {
  9978. this.source = source;
  9979. this.path = path;
  9980. this.children = children;
  9981. /** @inheritDoc */
  9982. this.type = OperationType.MERGE;
  9983. }
  9984. operationForChild(childName) {
  9985. if (pathIsEmpty(this.path)) {
  9986. const childTree = this.children.subtree(new Path(childName));
  9987. if (childTree.isEmpty()) {
  9988. // This child is unaffected
  9989. return null;
  9990. }
  9991. else if (childTree.value) {
  9992. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  9993. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  9994. }
  9995. else {
  9996. // This is a merge at a deeper level
  9997. return new Merge(this.source, newEmptyPath(), childTree);
  9998. }
  9999. }
  10000. else {
  10001. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  10002. return new Merge(this.source, pathPopFront(this.path), this.children);
  10003. }
  10004. }
  10005. toString() {
  10006. return ('Operation(' +
  10007. this.path +
  10008. ': ' +
  10009. this.source.toString() +
  10010. ' merge: ' +
  10011. this.children.toString() +
  10012. ')');
  10013. }
  10014. }
  10015. /**
  10016. * @license
  10017. * Copyright 2017 Google LLC
  10018. *
  10019. * Licensed under the Apache License, Version 2.0 (the "License");
  10020. * you may not use this file except in compliance with the License.
  10021. * You may obtain a copy of the License at
  10022. *
  10023. * http://www.apache.org/licenses/LICENSE-2.0
  10024. *
  10025. * Unless required by applicable law or agreed to in writing, software
  10026. * distributed under the License is distributed on an "AS IS" BASIS,
  10027. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10028. * See the License for the specific language governing permissions and
  10029. * limitations under the License.
  10030. */
  10031. /**
  10032. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  10033. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  10034. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  10035. * whether a node potentially had children removed due to a filter.
  10036. */
  10037. class CacheNode {
  10038. constructor(node_, fullyInitialized_, filtered_) {
  10039. this.node_ = node_;
  10040. this.fullyInitialized_ = fullyInitialized_;
  10041. this.filtered_ = filtered_;
  10042. }
  10043. /**
  10044. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  10045. */
  10046. isFullyInitialized() {
  10047. return this.fullyInitialized_;
  10048. }
  10049. /**
  10050. * Returns whether this node is potentially missing children due to a filter applied to the node
  10051. */
  10052. isFiltered() {
  10053. return this.filtered_;
  10054. }
  10055. isCompleteForPath(path) {
  10056. if (pathIsEmpty(path)) {
  10057. return this.isFullyInitialized() && !this.filtered_;
  10058. }
  10059. const childKey = pathGetFront(path);
  10060. return this.isCompleteForChild(childKey);
  10061. }
  10062. isCompleteForChild(key) {
  10063. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  10064. }
  10065. getNode() {
  10066. return this.node_;
  10067. }
  10068. }
  10069. /**
  10070. * @license
  10071. * Copyright 2017 Google LLC
  10072. *
  10073. * Licensed under the Apache License, Version 2.0 (the "License");
  10074. * you may not use this file except in compliance with the License.
  10075. * You may obtain a copy of the License at
  10076. *
  10077. * http://www.apache.org/licenses/LICENSE-2.0
  10078. *
  10079. * Unless required by applicable law or agreed to in writing, software
  10080. * distributed under the License is distributed on an "AS IS" BASIS,
  10081. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10082. * See the License for the specific language governing permissions and
  10083. * limitations under the License.
  10084. */
  10085. /**
  10086. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  10087. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  10088. * for details.
  10089. *
  10090. */
  10091. class EventGenerator {
  10092. constructor(query_) {
  10093. this.query_ = query_;
  10094. this.index_ = this.query_._queryParams.getIndex();
  10095. }
  10096. }
  10097. /**
  10098. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  10099. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  10100. *
  10101. * Notes:
  10102. * - child_moved events will be synthesized at this time for any child_changed events that affect
  10103. * our index.
  10104. * - prevName will be calculated based on the index ordering.
  10105. */
  10106. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  10107. const events = [];
  10108. const moves = [];
  10109. changes.forEach(change => {
  10110. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  10111. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  10112. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  10113. }
  10114. });
  10115. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  10116. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  10117. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  10118. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  10119. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  10120. return events;
  10121. }
  10122. /**
  10123. * Given changes of a single change type, generate the corresponding events.
  10124. */
  10125. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  10126. const filteredChanges = changes.filter(change => change.type === eventType);
  10127. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  10128. filteredChanges.forEach(change => {
  10129. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  10130. registrations.forEach(registration => {
  10131. if (registration.respondsTo(change.type)) {
  10132. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  10133. }
  10134. });
  10135. });
  10136. }
  10137. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  10138. if (change.type === 'value' || change.type === 'child_removed') {
  10139. return change;
  10140. }
  10141. else {
  10142. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  10143. return change;
  10144. }
  10145. }
  10146. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  10147. if (a.childName == null || b.childName == null) {
  10148. throw util.assertionError('Should only compare child_ events.');
  10149. }
  10150. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  10151. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  10152. return eventGenerator.index_.compare(aWrapped, bWrapped);
  10153. }
  10154. /**
  10155. * @license
  10156. * Copyright 2017 Google LLC
  10157. *
  10158. * Licensed under the Apache License, Version 2.0 (the "License");
  10159. * you may not use this file except in compliance with the License.
  10160. * You may obtain a copy of the License at
  10161. *
  10162. * http://www.apache.org/licenses/LICENSE-2.0
  10163. *
  10164. * Unless required by applicable law or agreed to in writing, software
  10165. * distributed under the License is distributed on an "AS IS" BASIS,
  10166. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10167. * See the License for the specific language governing permissions and
  10168. * limitations under the License.
  10169. */
  10170. function newViewCache(eventCache, serverCache) {
  10171. return { eventCache, serverCache };
  10172. }
  10173. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  10174. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  10175. }
  10176. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  10177. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  10178. }
  10179. function viewCacheGetCompleteEventSnap(viewCache) {
  10180. return viewCache.eventCache.isFullyInitialized()
  10181. ? viewCache.eventCache.getNode()
  10182. : null;
  10183. }
  10184. function viewCacheGetCompleteServerSnap(viewCache) {
  10185. return viewCache.serverCache.isFullyInitialized()
  10186. ? viewCache.serverCache.getNode()
  10187. : null;
  10188. }
  10189. /**
  10190. * @license
  10191. * Copyright 2017 Google LLC
  10192. *
  10193. * Licensed under the Apache License, Version 2.0 (the "License");
  10194. * you may not use this file except in compliance with the License.
  10195. * You may obtain a copy of the License at
  10196. *
  10197. * http://www.apache.org/licenses/LICENSE-2.0
  10198. *
  10199. * Unless required by applicable law or agreed to in writing, software
  10200. * distributed under the License is distributed on an "AS IS" BASIS,
  10201. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10202. * See the License for the specific language governing permissions and
  10203. * limitations under the License.
  10204. */
  10205. let emptyChildrenSingleton;
  10206. /**
  10207. * Singleton empty children collection.
  10208. *
  10209. */
  10210. const EmptyChildren = () => {
  10211. if (!emptyChildrenSingleton) {
  10212. emptyChildrenSingleton = new SortedMap(stringCompare);
  10213. }
  10214. return emptyChildrenSingleton;
  10215. };
  10216. /**
  10217. * A tree with immutable elements.
  10218. */
  10219. class ImmutableTree {
  10220. constructor(value, children = EmptyChildren()) {
  10221. this.value = value;
  10222. this.children = children;
  10223. }
  10224. static fromObject(obj) {
  10225. let tree = new ImmutableTree(null);
  10226. each(obj, (childPath, childSnap) => {
  10227. tree = tree.set(new Path(childPath), childSnap);
  10228. });
  10229. return tree;
  10230. }
  10231. /**
  10232. * True if the value is empty and there are no children
  10233. */
  10234. isEmpty() {
  10235. return this.value === null && this.children.isEmpty();
  10236. }
  10237. /**
  10238. * Given a path and predicate, return the first node and the path to that node
  10239. * where the predicate returns true.
  10240. *
  10241. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  10242. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  10243. *
  10244. * @param relativePath - The remainder of the path
  10245. * @param predicate - The predicate to satisfy to return a node
  10246. */
  10247. findRootMostMatchingPathAndValue(relativePath, predicate) {
  10248. if (this.value != null && predicate(this.value)) {
  10249. return { path: newEmptyPath(), value: this.value };
  10250. }
  10251. else {
  10252. if (pathIsEmpty(relativePath)) {
  10253. return null;
  10254. }
  10255. else {
  10256. const front = pathGetFront(relativePath);
  10257. const child = this.children.get(front);
  10258. if (child !== null) {
  10259. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  10260. if (childExistingPathAndValue != null) {
  10261. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  10262. return { path: fullPath, value: childExistingPathAndValue.value };
  10263. }
  10264. else {
  10265. return null;
  10266. }
  10267. }
  10268. else {
  10269. return null;
  10270. }
  10271. }
  10272. }
  10273. }
  10274. /**
  10275. * Find, if it exists, the shortest subpath of the given path that points a defined
  10276. * value in the tree
  10277. */
  10278. findRootMostValueAndPath(relativePath) {
  10279. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  10280. }
  10281. /**
  10282. * @returns The subtree at the given path
  10283. */
  10284. subtree(relativePath) {
  10285. if (pathIsEmpty(relativePath)) {
  10286. return this;
  10287. }
  10288. else {
  10289. const front = pathGetFront(relativePath);
  10290. const childTree = this.children.get(front);
  10291. if (childTree !== null) {
  10292. return childTree.subtree(pathPopFront(relativePath));
  10293. }
  10294. else {
  10295. return new ImmutableTree(null);
  10296. }
  10297. }
  10298. }
  10299. /**
  10300. * Sets a value at the specified path.
  10301. *
  10302. * @param relativePath - Path to set value at.
  10303. * @param toSet - Value to set.
  10304. * @returns Resulting tree.
  10305. */
  10306. set(relativePath, toSet) {
  10307. if (pathIsEmpty(relativePath)) {
  10308. return new ImmutableTree(toSet, this.children);
  10309. }
  10310. else {
  10311. const front = pathGetFront(relativePath);
  10312. const child = this.children.get(front) || new ImmutableTree(null);
  10313. const newChild = child.set(pathPopFront(relativePath), toSet);
  10314. const newChildren = this.children.insert(front, newChild);
  10315. return new ImmutableTree(this.value, newChildren);
  10316. }
  10317. }
  10318. /**
  10319. * Removes the value at the specified path.
  10320. *
  10321. * @param relativePath - Path to value to remove.
  10322. * @returns Resulting tree.
  10323. */
  10324. remove(relativePath) {
  10325. if (pathIsEmpty(relativePath)) {
  10326. if (this.children.isEmpty()) {
  10327. return new ImmutableTree(null);
  10328. }
  10329. else {
  10330. return new ImmutableTree(null, this.children);
  10331. }
  10332. }
  10333. else {
  10334. const front = pathGetFront(relativePath);
  10335. const child = this.children.get(front);
  10336. if (child) {
  10337. const newChild = child.remove(pathPopFront(relativePath));
  10338. let newChildren;
  10339. if (newChild.isEmpty()) {
  10340. newChildren = this.children.remove(front);
  10341. }
  10342. else {
  10343. newChildren = this.children.insert(front, newChild);
  10344. }
  10345. if (this.value === null && newChildren.isEmpty()) {
  10346. return new ImmutableTree(null);
  10347. }
  10348. else {
  10349. return new ImmutableTree(this.value, newChildren);
  10350. }
  10351. }
  10352. else {
  10353. return this;
  10354. }
  10355. }
  10356. }
  10357. /**
  10358. * Gets a value from the tree.
  10359. *
  10360. * @param relativePath - Path to get value for.
  10361. * @returns Value at path, or null.
  10362. */
  10363. get(relativePath) {
  10364. if (pathIsEmpty(relativePath)) {
  10365. return this.value;
  10366. }
  10367. else {
  10368. const front = pathGetFront(relativePath);
  10369. const child = this.children.get(front);
  10370. if (child) {
  10371. return child.get(pathPopFront(relativePath));
  10372. }
  10373. else {
  10374. return null;
  10375. }
  10376. }
  10377. }
  10378. /**
  10379. * Replace the subtree at the specified path with the given new tree.
  10380. *
  10381. * @param relativePath - Path to replace subtree for.
  10382. * @param newTree - New tree.
  10383. * @returns Resulting tree.
  10384. */
  10385. setTree(relativePath, newTree) {
  10386. if (pathIsEmpty(relativePath)) {
  10387. return newTree;
  10388. }
  10389. else {
  10390. const front = pathGetFront(relativePath);
  10391. const child = this.children.get(front) || new ImmutableTree(null);
  10392. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  10393. let newChildren;
  10394. if (newChild.isEmpty()) {
  10395. newChildren = this.children.remove(front);
  10396. }
  10397. else {
  10398. newChildren = this.children.insert(front, newChild);
  10399. }
  10400. return new ImmutableTree(this.value, newChildren);
  10401. }
  10402. }
  10403. /**
  10404. * Performs a depth first fold on this tree. Transforms a tree into a single
  10405. * value, given a function that operates on the path to a node, an optional
  10406. * current value, and a map of child names to folded subtrees
  10407. */
  10408. fold(fn) {
  10409. return this.fold_(newEmptyPath(), fn);
  10410. }
  10411. /**
  10412. * Recursive helper for public-facing fold() method
  10413. */
  10414. fold_(pathSoFar, fn) {
  10415. const accum = {};
  10416. this.children.inorderTraversal((childKey, childTree) => {
  10417. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  10418. });
  10419. return fn(pathSoFar, this.value, accum);
  10420. }
  10421. /**
  10422. * Find the first matching value on the given path. Return the result of applying f to it.
  10423. */
  10424. findOnPath(path, f) {
  10425. return this.findOnPath_(path, newEmptyPath(), f);
  10426. }
  10427. findOnPath_(pathToFollow, pathSoFar, f) {
  10428. const result = this.value ? f(pathSoFar, this.value) : false;
  10429. if (result) {
  10430. return result;
  10431. }
  10432. else {
  10433. if (pathIsEmpty(pathToFollow)) {
  10434. return null;
  10435. }
  10436. else {
  10437. const front = pathGetFront(pathToFollow);
  10438. const nextChild = this.children.get(front);
  10439. if (nextChild) {
  10440. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  10441. }
  10442. else {
  10443. return null;
  10444. }
  10445. }
  10446. }
  10447. }
  10448. foreachOnPath(path, f) {
  10449. return this.foreachOnPath_(path, newEmptyPath(), f);
  10450. }
  10451. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  10452. if (pathIsEmpty(pathToFollow)) {
  10453. return this;
  10454. }
  10455. else {
  10456. if (this.value) {
  10457. f(currentRelativePath, this.value);
  10458. }
  10459. const front = pathGetFront(pathToFollow);
  10460. const nextChild = this.children.get(front);
  10461. if (nextChild) {
  10462. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  10463. }
  10464. else {
  10465. return new ImmutableTree(null);
  10466. }
  10467. }
  10468. }
  10469. /**
  10470. * Calls the given function for each node in the tree that has a value.
  10471. *
  10472. * @param f - A function to be called with the path from the root of the tree to
  10473. * a node, and the value at that node. Called in depth-first order.
  10474. */
  10475. foreach(f) {
  10476. this.foreach_(newEmptyPath(), f);
  10477. }
  10478. foreach_(currentRelativePath, f) {
  10479. this.children.inorderTraversal((childName, childTree) => {
  10480. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  10481. });
  10482. if (this.value) {
  10483. f(currentRelativePath, this.value);
  10484. }
  10485. }
  10486. foreachChild(f) {
  10487. this.children.inorderTraversal((childName, childTree) => {
  10488. if (childTree.value) {
  10489. f(childName, childTree.value);
  10490. }
  10491. });
  10492. }
  10493. }
  10494. /**
  10495. * @license
  10496. * Copyright 2017 Google LLC
  10497. *
  10498. * Licensed under the Apache License, Version 2.0 (the "License");
  10499. * you may not use this file except in compliance with the License.
  10500. * You may obtain a copy of the License at
  10501. *
  10502. * http://www.apache.org/licenses/LICENSE-2.0
  10503. *
  10504. * Unless required by applicable law or agreed to in writing, software
  10505. * distributed under the License is distributed on an "AS IS" BASIS,
  10506. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10507. * See the License for the specific language governing permissions and
  10508. * limitations under the License.
  10509. */
  10510. /**
  10511. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  10512. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  10513. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  10514. * to reflect the write added.
  10515. */
  10516. class CompoundWrite {
  10517. constructor(writeTree_) {
  10518. this.writeTree_ = writeTree_;
  10519. }
  10520. static empty() {
  10521. return new CompoundWrite(new ImmutableTree(null));
  10522. }
  10523. }
  10524. function compoundWriteAddWrite(compoundWrite, path, node) {
  10525. if (pathIsEmpty(path)) {
  10526. return new CompoundWrite(new ImmutableTree(node));
  10527. }
  10528. else {
  10529. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  10530. if (rootmost != null) {
  10531. const rootMostPath = rootmost.path;
  10532. let value = rootmost.value;
  10533. const relativePath = newRelativePath(rootMostPath, path);
  10534. value = value.updateChild(relativePath, node);
  10535. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  10536. }
  10537. else {
  10538. const subtree = new ImmutableTree(node);
  10539. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  10540. return new CompoundWrite(newWriteTree);
  10541. }
  10542. }
  10543. }
  10544. function compoundWriteAddWrites(compoundWrite, path, updates) {
  10545. let newWrite = compoundWrite;
  10546. each(updates, (childKey, node) => {
  10547. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  10548. });
  10549. return newWrite;
  10550. }
  10551. /**
  10552. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  10553. * location, which must be removed by calling this method with that path.
  10554. *
  10555. * @param compoundWrite - The CompoundWrite to remove.
  10556. * @param path - The path at which a write and all deeper writes should be removed
  10557. * @returns The new CompoundWrite with the removed path
  10558. */
  10559. function compoundWriteRemoveWrite(compoundWrite, path) {
  10560. if (pathIsEmpty(path)) {
  10561. return CompoundWrite.empty();
  10562. }
  10563. else {
  10564. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  10565. return new CompoundWrite(newWriteTree);
  10566. }
  10567. }
  10568. /**
  10569. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  10570. * considered "complete".
  10571. *
  10572. * @param compoundWrite - The CompoundWrite to check.
  10573. * @param path - The path to check for
  10574. * @returns Whether there is a complete write at that path
  10575. */
  10576. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  10577. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  10578. }
  10579. /**
  10580. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  10581. * writes from deeper paths, but will return child nodes from a more shallow path.
  10582. *
  10583. * @param compoundWrite - The CompoundWrite to get the node from.
  10584. * @param path - The path to get a complete write
  10585. * @returns The node if complete at that path, or null otherwise.
  10586. */
  10587. function compoundWriteGetCompleteNode(compoundWrite, path) {
  10588. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  10589. if (rootmost != null) {
  10590. return compoundWrite.writeTree_
  10591. .get(rootmost.path)
  10592. .getChild(newRelativePath(rootmost.path, path));
  10593. }
  10594. else {
  10595. return null;
  10596. }
  10597. }
  10598. /**
  10599. * Returns all children that are guaranteed to be a complete overwrite.
  10600. *
  10601. * @param compoundWrite - The CompoundWrite to get children from.
  10602. * @returns A list of all complete children.
  10603. */
  10604. function compoundWriteGetCompleteChildren(compoundWrite) {
  10605. const children = [];
  10606. const node = compoundWrite.writeTree_.value;
  10607. if (node != null) {
  10608. // If it's a leaf node, it has no children; so nothing to do.
  10609. if (!node.isLeafNode()) {
  10610. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10611. children.push(new NamedNode(childName, childNode));
  10612. });
  10613. }
  10614. }
  10615. else {
  10616. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  10617. if (childTree.value != null) {
  10618. children.push(new NamedNode(childName, childTree.value));
  10619. }
  10620. });
  10621. }
  10622. return children;
  10623. }
  10624. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  10625. if (pathIsEmpty(path)) {
  10626. return compoundWrite;
  10627. }
  10628. else {
  10629. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  10630. if (shadowingNode != null) {
  10631. return new CompoundWrite(new ImmutableTree(shadowingNode));
  10632. }
  10633. else {
  10634. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  10635. }
  10636. }
  10637. }
  10638. /**
  10639. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  10640. * @returns Whether this CompoundWrite is empty
  10641. */
  10642. function compoundWriteIsEmpty(compoundWrite) {
  10643. return compoundWrite.writeTree_.isEmpty();
  10644. }
  10645. /**
  10646. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  10647. * node
  10648. * @param node - The node to apply this CompoundWrite to
  10649. * @returns The node with all writes applied
  10650. */
  10651. function compoundWriteApply(compoundWrite, node) {
  10652. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  10653. }
  10654. function applySubtreeWrite(relativePath, writeTree, node) {
  10655. if (writeTree.value != null) {
  10656. // Since there a write is always a leaf, we're done here
  10657. return node.updateChild(relativePath, writeTree.value);
  10658. }
  10659. else {
  10660. let priorityWrite = null;
  10661. writeTree.children.inorderTraversal((childKey, childTree) => {
  10662. if (childKey === '.priority') {
  10663. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  10664. // to apply priorities to empty nodes that are later filled
  10665. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  10666. priorityWrite = childTree.value;
  10667. }
  10668. else {
  10669. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  10670. }
  10671. });
  10672. // If there was a priority write, we only apply it if the node is not empty
  10673. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  10674. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  10675. }
  10676. return node;
  10677. }
  10678. }
  10679. /**
  10680. * @license
  10681. * Copyright 2017 Google LLC
  10682. *
  10683. * Licensed under the Apache License, Version 2.0 (the "License");
  10684. * you may not use this file except in compliance with the License.
  10685. * You may obtain a copy of the License at
  10686. *
  10687. * http://www.apache.org/licenses/LICENSE-2.0
  10688. *
  10689. * Unless required by applicable law or agreed to in writing, software
  10690. * distributed under the License is distributed on an "AS IS" BASIS,
  10691. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10692. * See the License for the specific language governing permissions and
  10693. * limitations under the License.
  10694. */
  10695. /**
  10696. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  10697. *
  10698. */
  10699. function writeTreeChildWrites(writeTree, path) {
  10700. return newWriteTreeRef(path, writeTree);
  10701. }
  10702. /**
  10703. * Record a new overwrite from user code.
  10704. *
  10705. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  10706. */
  10707. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  10708. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  10709. if (visible === undefined) {
  10710. visible = true;
  10711. }
  10712. writeTree.allWrites.push({
  10713. path,
  10714. snap,
  10715. writeId,
  10716. visible
  10717. });
  10718. if (visible) {
  10719. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  10720. }
  10721. writeTree.lastWriteId = writeId;
  10722. }
  10723. /**
  10724. * Record a new merge from user code.
  10725. */
  10726. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  10727. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  10728. writeTree.allWrites.push({
  10729. path,
  10730. children: changedChildren,
  10731. writeId,
  10732. visible: true
  10733. });
  10734. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  10735. writeTree.lastWriteId = writeId;
  10736. }
  10737. function writeTreeGetWrite(writeTree, writeId) {
  10738. for (let i = 0; i < writeTree.allWrites.length; i++) {
  10739. const record = writeTree.allWrites[i];
  10740. if (record.writeId === writeId) {
  10741. return record;
  10742. }
  10743. }
  10744. return null;
  10745. }
  10746. /**
  10747. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  10748. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  10749. *
  10750. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  10751. * events as a result).
  10752. */
  10753. function writeTreeRemoveWrite(writeTree, writeId) {
  10754. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  10755. // out of order.
  10756. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  10757. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  10758. const idx = writeTree.allWrites.findIndex(s => {
  10759. return s.writeId === writeId;
  10760. });
  10761. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  10762. const writeToRemove = writeTree.allWrites[idx];
  10763. writeTree.allWrites.splice(idx, 1);
  10764. let removedWriteWasVisible = writeToRemove.visible;
  10765. let removedWriteOverlapsWithOtherWrites = false;
  10766. let i = writeTree.allWrites.length - 1;
  10767. while (removedWriteWasVisible && i >= 0) {
  10768. const currentWrite = writeTree.allWrites[i];
  10769. if (currentWrite.visible) {
  10770. if (i >= idx &&
  10771. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  10772. // The removed write was completely shadowed by a subsequent write.
  10773. removedWriteWasVisible = false;
  10774. }
  10775. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  10776. // Either we're covering some writes or they're covering part of us (depending on which came first).
  10777. removedWriteOverlapsWithOtherWrites = true;
  10778. }
  10779. }
  10780. i--;
  10781. }
  10782. if (!removedWriteWasVisible) {
  10783. return false;
  10784. }
  10785. else if (removedWriteOverlapsWithOtherWrites) {
  10786. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  10787. writeTreeResetTree_(writeTree);
  10788. return true;
  10789. }
  10790. else {
  10791. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  10792. if (writeToRemove.snap) {
  10793. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  10794. }
  10795. else {
  10796. const children = writeToRemove.children;
  10797. each(children, (childName) => {
  10798. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  10799. });
  10800. }
  10801. return true;
  10802. }
  10803. }
  10804. function writeTreeRecordContainsPath_(writeRecord, path) {
  10805. if (writeRecord.snap) {
  10806. return pathContains(writeRecord.path, path);
  10807. }
  10808. else {
  10809. for (const childName in writeRecord.children) {
  10810. if (writeRecord.children.hasOwnProperty(childName) &&
  10811. pathContains(pathChild(writeRecord.path, childName), path)) {
  10812. return true;
  10813. }
  10814. }
  10815. return false;
  10816. }
  10817. }
  10818. /**
  10819. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  10820. */
  10821. function writeTreeResetTree_(writeTree) {
  10822. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  10823. if (writeTree.allWrites.length > 0) {
  10824. writeTree.lastWriteId =
  10825. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  10826. }
  10827. else {
  10828. writeTree.lastWriteId = -1;
  10829. }
  10830. }
  10831. /**
  10832. * The default filter used when constructing the tree. Keep everything that's visible.
  10833. */
  10834. function writeTreeDefaultFilter_(write) {
  10835. return write.visible;
  10836. }
  10837. /**
  10838. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  10839. * event data at that path.
  10840. */
  10841. function writeTreeLayerTree_(writes, filter, treeRoot) {
  10842. let compoundWrite = CompoundWrite.empty();
  10843. for (let i = 0; i < writes.length; ++i) {
  10844. const write = writes[i];
  10845. // Theory, a later set will either:
  10846. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  10847. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  10848. if (filter(write)) {
  10849. const writePath = write.path;
  10850. let relativePath;
  10851. if (write.snap) {
  10852. if (pathContains(treeRoot, writePath)) {
  10853. relativePath = newRelativePath(treeRoot, writePath);
  10854. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  10855. }
  10856. else if (pathContains(writePath, treeRoot)) {
  10857. relativePath = newRelativePath(writePath, treeRoot);
  10858. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  10859. }
  10860. else ;
  10861. }
  10862. else if (write.children) {
  10863. if (pathContains(treeRoot, writePath)) {
  10864. relativePath = newRelativePath(treeRoot, writePath);
  10865. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  10866. }
  10867. else if (pathContains(writePath, treeRoot)) {
  10868. relativePath = newRelativePath(writePath, treeRoot);
  10869. if (pathIsEmpty(relativePath)) {
  10870. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  10871. }
  10872. else {
  10873. const child = util.safeGet(write.children, pathGetFront(relativePath));
  10874. if (child) {
  10875. // There exists a child in this node that matches the root path
  10876. const deepNode = child.getChild(pathPopFront(relativePath));
  10877. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  10878. }
  10879. }
  10880. }
  10881. else ;
  10882. }
  10883. else {
  10884. throw util.assertionError('WriteRecord should have .snap or .children');
  10885. }
  10886. }
  10887. }
  10888. return compoundWrite;
  10889. }
  10890. /**
  10891. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  10892. * writes), attempt to calculate a complete snapshot for the given path
  10893. *
  10894. * @param writeIdsToExclude - An optional set to be excluded
  10895. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  10896. */
  10897. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  10898. if (!writeIdsToExclude && !includeHiddenWrites) {
  10899. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  10900. if (shadowingNode != null) {
  10901. return shadowingNode;
  10902. }
  10903. else {
  10904. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  10905. if (compoundWriteIsEmpty(subMerge)) {
  10906. return completeServerCache;
  10907. }
  10908. else if (completeServerCache == null &&
  10909. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  10910. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  10911. return null;
  10912. }
  10913. else {
  10914. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  10915. return compoundWriteApply(subMerge, layeredCache);
  10916. }
  10917. }
  10918. }
  10919. else {
  10920. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  10921. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  10922. return completeServerCache;
  10923. }
  10924. else {
  10925. // If the server cache is null, and we don't have a complete cache, we need to return null
  10926. if (!includeHiddenWrites &&
  10927. completeServerCache == null &&
  10928. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  10929. return null;
  10930. }
  10931. else {
  10932. const filter = function (write) {
  10933. return ((write.visible || includeHiddenWrites) &&
  10934. (!writeIdsToExclude ||
  10935. !~writeIdsToExclude.indexOf(write.writeId)) &&
  10936. (pathContains(write.path, treePath) ||
  10937. pathContains(treePath, write.path)));
  10938. };
  10939. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  10940. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  10941. return compoundWriteApply(mergeAtPath, layeredCache);
  10942. }
  10943. }
  10944. }
  10945. }
  10946. /**
  10947. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  10948. * Used when creating new views, to pre-fill their complete event children snapshot.
  10949. */
  10950. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  10951. let completeChildren = ChildrenNode.EMPTY_NODE;
  10952. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  10953. if (topLevelSet) {
  10954. if (!topLevelSet.isLeafNode()) {
  10955. // we're shadowing everything. Return the children.
  10956. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  10957. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  10958. });
  10959. }
  10960. return completeChildren;
  10961. }
  10962. else if (completeServerChildren) {
  10963. // Layer any children we have on top of this
  10964. // We know we don't have a top-level set, so just enumerate existing children
  10965. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  10966. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10967. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  10968. completeChildren = completeChildren.updateImmediateChild(childName, node);
  10969. });
  10970. // Add any complete children we have from the set
  10971. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  10972. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  10973. });
  10974. return completeChildren;
  10975. }
  10976. else {
  10977. // We don't have anything to layer on top of. Layer on any children we have
  10978. // Note that we can return an empty snap if we have a defined delete
  10979. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  10980. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  10981. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  10982. });
  10983. return completeChildren;
  10984. }
  10985. }
  10986. /**
  10987. * Given that the underlying server data has updated, determine what, if anything, needs to be
  10988. * applied to the event cache.
  10989. *
  10990. * Possibilities:
  10991. *
  10992. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  10993. *
  10994. * 2. Some write is completely shadowing. No events to be raised
  10995. *
  10996. * 3. Is partially shadowed. Events
  10997. *
  10998. * Either existingEventSnap or existingServerSnap must exist
  10999. */
  11000. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  11001. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  11002. const path = pathChild(treePath, childPath);
  11003. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  11004. // At this point we can probably guarantee that we're in case 2, meaning no events
  11005. // May need to check visibility while doing the findRootMostValueAndPath call
  11006. return null;
  11007. }
  11008. else {
  11009. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  11010. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  11011. if (compoundWriteIsEmpty(childMerge)) {
  11012. // We're not shadowing at all. Case 1
  11013. return existingServerSnap.getChild(childPath);
  11014. }
  11015. else {
  11016. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  11017. // However this is tricky to find out, since user updates don't necessary change the server
  11018. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  11019. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  11020. // only check if the updates change the serverNode.
  11021. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  11022. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  11023. }
  11024. }
  11025. }
  11026. /**
  11027. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  11028. * complete child for this ChildKey.
  11029. */
  11030. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  11031. const path = pathChild(treePath, childKey);
  11032. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  11033. if (shadowingNode != null) {
  11034. return shadowingNode;
  11035. }
  11036. else {
  11037. if (existingServerSnap.isCompleteForChild(childKey)) {
  11038. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  11039. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  11040. }
  11041. else {
  11042. return null;
  11043. }
  11044. }
  11045. }
  11046. /**
  11047. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  11048. * a higher path, this will return the child of that write relative to the write and this path.
  11049. * Returns null if there is no write at this path.
  11050. */
  11051. function writeTreeShadowingWrite(writeTree, path) {
  11052. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  11053. }
  11054. /**
  11055. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  11056. * the window, but may now be in the window.
  11057. */
  11058. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  11059. let toIterate;
  11060. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  11061. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  11062. if (shadowingNode != null) {
  11063. toIterate = shadowingNode;
  11064. }
  11065. else if (completeServerData != null) {
  11066. toIterate = compoundWriteApply(merge, completeServerData);
  11067. }
  11068. else {
  11069. // no children to iterate on
  11070. return [];
  11071. }
  11072. toIterate = toIterate.withIndex(index);
  11073. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  11074. const nodes = [];
  11075. const cmp = index.getCompare();
  11076. const iter = reverse
  11077. ? toIterate.getReverseIteratorFrom(startPost, index)
  11078. : toIterate.getIteratorFrom(startPost, index);
  11079. let next = iter.getNext();
  11080. while (next && nodes.length < count) {
  11081. if (cmp(next, startPost) !== 0) {
  11082. nodes.push(next);
  11083. }
  11084. next = iter.getNext();
  11085. }
  11086. return nodes;
  11087. }
  11088. else {
  11089. return [];
  11090. }
  11091. }
  11092. function newWriteTree() {
  11093. return {
  11094. visibleWrites: CompoundWrite.empty(),
  11095. allWrites: [],
  11096. lastWriteId: -1
  11097. };
  11098. }
  11099. /**
  11100. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  11101. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  11102. * can lead to a more expensive calculation.
  11103. *
  11104. * @param writeIdsToExclude - Optional writes to exclude.
  11105. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  11106. */
  11107. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  11108. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  11109. }
  11110. /**
  11111. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  11112. * mix of the given server data and write data.
  11113. *
  11114. */
  11115. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  11116. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  11117. }
  11118. /**
  11119. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  11120. * if anything, needs to be applied to the event cache.
  11121. *
  11122. * Possibilities:
  11123. *
  11124. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  11125. *
  11126. * 2. Some write is completely shadowing. No events to be raised
  11127. *
  11128. * 3. Is partially shadowed. Events should be raised
  11129. *
  11130. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  11131. *
  11132. *
  11133. */
  11134. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  11135. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  11136. }
  11137. /**
  11138. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  11139. * a higher path, this will return the child of that write relative to the write and this path.
  11140. * Returns null if there is no write at this path.
  11141. *
  11142. */
  11143. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  11144. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  11145. }
  11146. /**
  11147. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  11148. * the window, but may now be in the window
  11149. */
  11150. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  11151. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  11152. }
  11153. /**
  11154. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  11155. * complete child for this ChildKey.
  11156. */
  11157. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  11158. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  11159. }
  11160. /**
  11161. * Return a WriteTreeRef for a child.
  11162. */
  11163. function writeTreeRefChild(writeTreeRef, childName) {
  11164. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  11165. }
  11166. function newWriteTreeRef(path, writeTree) {
  11167. return {
  11168. treePath: path,
  11169. writeTree
  11170. };
  11171. }
  11172. /**
  11173. * @license
  11174. * Copyright 2017 Google LLC
  11175. *
  11176. * Licensed under the Apache License, Version 2.0 (the "License");
  11177. * you may not use this file except in compliance with the License.
  11178. * You may obtain a copy of the License at
  11179. *
  11180. * http://www.apache.org/licenses/LICENSE-2.0
  11181. *
  11182. * Unless required by applicable law or agreed to in writing, software
  11183. * distributed under the License is distributed on an "AS IS" BASIS,
  11184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11185. * See the License for the specific language governing permissions and
  11186. * limitations under the License.
  11187. */
  11188. class ChildChangeAccumulator {
  11189. constructor() {
  11190. this.changeMap = new Map();
  11191. }
  11192. trackChildChange(change) {
  11193. const type = change.type;
  11194. const childKey = change.childName;
  11195. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  11196. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  11197. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  11198. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  11199. const oldChange = this.changeMap.get(childKey);
  11200. if (oldChange) {
  11201. const oldType = oldChange.type;
  11202. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  11203. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  11204. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  11205. }
  11206. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  11207. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  11208. this.changeMap.delete(childKey);
  11209. }
  11210. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  11211. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  11212. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  11213. }
  11214. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  11215. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  11216. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  11217. }
  11218. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  11219. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  11220. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  11221. }
  11222. else {
  11223. throw util.assertionError('Illegal combination of changes: ' +
  11224. change +
  11225. ' occurred after ' +
  11226. oldChange);
  11227. }
  11228. }
  11229. else {
  11230. this.changeMap.set(childKey, change);
  11231. }
  11232. }
  11233. getChanges() {
  11234. return Array.from(this.changeMap.values());
  11235. }
  11236. }
  11237. /**
  11238. * @license
  11239. * Copyright 2017 Google LLC
  11240. *
  11241. * Licensed under the Apache License, Version 2.0 (the "License");
  11242. * you may not use this file except in compliance with the License.
  11243. * You may obtain a copy of the License at
  11244. *
  11245. * http://www.apache.org/licenses/LICENSE-2.0
  11246. *
  11247. * Unless required by applicable law or agreed to in writing, software
  11248. * distributed under the License is distributed on an "AS IS" BASIS,
  11249. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11250. * See the License for the specific language governing permissions and
  11251. * limitations under the License.
  11252. */
  11253. /**
  11254. * An implementation of CompleteChildSource that never returns any additional children
  11255. */
  11256. // eslint-disable-next-line @typescript-eslint/naming-convention
  11257. class NoCompleteChildSource_ {
  11258. getCompleteChild(childKey) {
  11259. return null;
  11260. }
  11261. getChildAfterChild(index, child, reverse) {
  11262. return null;
  11263. }
  11264. }
  11265. /**
  11266. * Singleton instance.
  11267. */
  11268. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  11269. /**
  11270. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  11271. * old event caches available to calculate complete children.
  11272. */
  11273. class WriteTreeCompleteChildSource {
  11274. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  11275. this.writes_ = writes_;
  11276. this.viewCache_ = viewCache_;
  11277. this.optCompleteServerCache_ = optCompleteServerCache_;
  11278. }
  11279. getCompleteChild(childKey) {
  11280. const node = this.viewCache_.eventCache;
  11281. if (node.isCompleteForChild(childKey)) {
  11282. return node.getNode().getImmediateChild(childKey);
  11283. }
  11284. else {
  11285. const serverNode = this.optCompleteServerCache_ != null
  11286. ? new CacheNode(this.optCompleteServerCache_, true, false)
  11287. : this.viewCache_.serverCache;
  11288. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  11289. }
  11290. }
  11291. getChildAfterChild(index, child, reverse) {
  11292. const completeServerData = this.optCompleteServerCache_ != null
  11293. ? this.optCompleteServerCache_
  11294. : viewCacheGetCompleteServerSnap(this.viewCache_);
  11295. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  11296. if (nodes.length === 0) {
  11297. return null;
  11298. }
  11299. else {
  11300. return nodes[0];
  11301. }
  11302. }
  11303. }
  11304. /**
  11305. * @license
  11306. * Copyright 2017 Google LLC
  11307. *
  11308. * Licensed under the Apache License, Version 2.0 (the "License");
  11309. * you may not use this file except in compliance with the License.
  11310. * You may obtain a copy of the License at
  11311. *
  11312. * http://www.apache.org/licenses/LICENSE-2.0
  11313. *
  11314. * Unless required by applicable law or agreed to in writing, software
  11315. * distributed under the License is distributed on an "AS IS" BASIS,
  11316. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11317. * See the License for the specific language governing permissions and
  11318. * limitations under the License.
  11319. */
  11320. function newViewProcessor(filter) {
  11321. return { filter };
  11322. }
  11323. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  11324. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  11325. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  11326. }
  11327. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  11328. const accumulator = new ChildChangeAccumulator();
  11329. let newViewCache, filterServerNode;
  11330. if (operation.type === OperationType.OVERWRITE) {
  11331. const overwrite = operation;
  11332. if (overwrite.source.fromUser) {
  11333. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  11334. }
  11335. else {
  11336. util.assert(overwrite.source.fromServer, 'Unknown source.');
  11337. // We filter the node if it's a tagged update or the node has been previously filtered and the
  11338. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  11339. // again
  11340. filterServerNode =
  11341. overwrite.source.tagged ||
  11342. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  11343. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  11344. }
  11345. }
  11346. else if (operation.type === OperationType.MERGE) {
  11347. const merge = operation;
  11348. if (merge.source.fromUser) {
  11349. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  11350. }
  11351. else {
  11352. util.assert(merge.source.fromServer, 'Unknown source.');
  11353. // We filter the node if it's a tagged update or the node has been previously filtered
  11354. filterServerNode =
  11355. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  11356. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  11357. }
  11358. }
  11359. else if (operation.type === OperationType.ACK_USER_WRITE) {
  11360. const ackUserWrite = operation;
  11361. if (!ackUserWrite.revert) {
  11362. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  11363. }
  11364. else {
  11365. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  11366. }
  11367. }
  11368. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  11369. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  11370. }
  11371. else {
  11372. throw util.assertionError('Unknown operation type: ' + operation.type);
  11373. }
  11374. const changes = accumulator.getChanges();
  11375. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  11376. return { viewCache: newViewCache, changes };
  11377. }
  11378. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  11379. const eventSnap = newViewCache.eventCache;
  11380. if (eventSnap.isFullyInitialized()) {
  11381. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  11382. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  11383. if (accumulator.length > 0 ||
  11384. !oldViewCache.eventCache.isFullyInitialized() ||
  11385. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  11386. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  11387. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  11388. }
  11389. }
  11390. }
  11391. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  11392. const oldEventSnap = viewCache.eventCache;
  11393. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  11394. // we have a shadowing write, ignore changes
  11395. return viewCache;
  11396. }
  11397. else {
  11398. let newEventCache, serverNode;
  11399. if (pathIsEmpty(changePath)) {
  11400. // TODO: figure out how this plays with "sliding ack windows"
  11401. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  11402. if (viewCache.serverCache.isFiltered()) {
  11403. // We need to special case this, because we need to only apply writes to complete children, or
  11404. // we might end up raising events for incomplete children. If the server data is filtered deep
  11405. // writes cannot be guaranteed to be complete
  11406. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  11407. const completeChildren = serverCache instanceof ChildrenNode
  11408. ? serverCache
  11409. : ChildrenNode.EMPTY_NODE;
  11410. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  11411. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  11412. }
  11413. else {
  11414. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  11415. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  11416. }
  11417. }
  11418. else {
  11419. const childKey = pathGetFront(changePath);
  11420. if (childKey === '.priority') {
  11421. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  11422. const oldEventNode = oldEventSnap.getNode();
  11423. serverNode = viewCache.serverCache.getNode();
  11424. // we might have overwrites for this priority
  11425. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  11426. if (updatedPriority != null) {
  11427. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  11428. }
  11429. else {
  11430. // priority didn't change, keep old node
  11431. newEventCache = oldEventSnap.getNode();
  11432. }
  11433. }
  11434. else {
  11435. const childChangePath = pathPopFront(changePath);
  11436. // update child
  11437. let newEventChild;
  11438. if (oldEventSnap.isCompleteForChild(childKey)) {
  11439. serverNode = viewCache.serverCache.getNode();
  11440. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  11441. if (eventChildUpdate != null) {
  11442. newEventChild = oldEventSnap
  11443. .getNode()
  11444. .getImmediateChild(childKey)
  11445. .updateChild(childChangePath, eventChildUpdate);
  11446. }
  11447. else {
  11448. // Nothing changed, just keep the old child
  11449. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  11450. }
  11451. }
  11452. else {
  11453. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  11454. }
  11455. if (newEventChild != null) {
  11456. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  11457. }
  11458. else {
  11459. // no complete child available or no change
  11460. newEventCache = oldEventSnap.getNode();
  11461. }
  11462. }
  11463. }
  11464. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  11465. }
  11466. }
  11467. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  11468. const oldServerSnap = oldViewCache.serverCache;
  11469. let newServerCache;
  11470. const serverFilter = filterServerNode
  11471. ? viewProcessor.filter
  11472. : viewProcessor.filter.getIndexedFilter();
  11473. if (pathIsEmpty(changePath)) {
  11474. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  11475. }
  11476. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  11477. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  11478. const newServerNode = oldServerSnap
  11479. .getNode()
  11480. .updateChild(changePath, changedSnap);
  11481. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  11482. }
  11483. else {
  11484. const childKey = pathGetFront(changePath);
  11485. if (!oldServerSnap.isCompleteForPath(changePath) &&
  11486. pathGetLength(changePath) > 1) {
  11487. // We don't update incomplete nodes with updates intended for other listeners
  11488. return oldViewCache;
  11489. }
  11490. const childChangePath = pathPopFront(changePath);
  11491. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  11492. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  11493. if (childKey === '.priority') {
  11494. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  11495. }
  11496. else {
  11497. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  11498. }
  11499. }
  11500. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  11501. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  11502. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  11503. }
  11504. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  11505. const oldEventSnap = oldViewCache.eventCache;
  11506. let newViewCache, newEventCache;
  11507. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  11508. if (pathIsEmpty(changePath)) {
  11509. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  11510. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  11511. }
  11512. else {
  11513. const childKey = pathGetFront(changePath);
  11514. if (childKey === '.priority') {
  11515. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  11516. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  11517. }
  11518. else {
  11519. const childChangePath = pathPopFront(changePath);
  11520. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  11521. let newChild;
  11522. if (pathIsEmpty(childChangePath)) {
  11523. // Child overwrite, we can replace the child
  11524. newChild = changedSnap;
  11525. }
  11526. else {
  11527. const childNode = source.getCompleteChild(childKey);
  11528. if (childNode != null) {
  11529. if (pathGetBack(childChangePath) === '.priority' &&
  11530. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  11531. // This is a priority update on an empty node. If this node exists on the server, the
  11532. // server will send down the priority in the update, so ignore for now
  11533. newChild = childNode;
  11534. }
  11535. else {
  11536. newChild = childNode.updateChild(childChangePath, changedSnap);
  11537. }
  11538. }
  11539. else {
  11540. // There is no complete child node available
  11541. newChild = ChildrenNode.EMPTY_NODE;
  11542. }
  11543. }
  11544. if (!oldChild.equals(newChild)) {
  11545. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  11546. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  11547. }
  11548. else {
  11549. newViewCache = oldViewCache;
  11550. }
  11551. }
  11552. }
  11553. return newViewCache;
  11554. }
  11555. function viewProcessorCacheHasChild(viewCache, childKey) {
  11556. return viewCache.eventCache.isCompleteForChild(childKey);
  11557. }
  11558. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  11559. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  11560. // window leaving room for new items. It's important we process these changes first, so we
  11561. // iterate the changes twice, first processing any that affect items currently in view.
  11562. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  11563. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  11564. // not the other.
  11565. let curViewCache = viewCache;
  11566. changedChildren.foreach((relativePath, childNode) => {
  11567. const writePath = pathChild(path, relativePath);
  11568. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  11569. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  11570. }
  11571. });
  11572. changedChildren.foreach((relativePath, childNode) => {
  11573. const writePath = pathChild(path, relativePath);
  11574. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  11575. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  11576. }
  11577. });
  11578. return curViewCache;
  11579. }
  11580. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  11581. merge.foreach((relativePath, childNode) => {
  11582. node = node.updateChild(relativePath, childNode);
  11583. });
  11584. return node;
  11585. }
  11586. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  11587. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  11588. // wait for the complete data update coming soon.
  11589. if (viewCache.serverCache.getNode().isEmpty() &&
  11590. !viewCache.serverCache.isFullyInitialized()) {
  11591. return viewCache;
  11592. }
  11593. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  11594. // window leaving room for new items. It's important we process these changes first, so we
  11595. // iterate the changes twice, first processing any that affect items currently in view.
  11596. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  11597. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  11598. // not the other.
  11599. let curViewCache = viewCache;
  11600. let viewMergeTree;
  11601. if (pathIsEmpty(path)) {
  11602. viewMergeTree = changedChildren;
  11603. }
  11604. else {
  11605. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  11606. }
  11607. const serverNode = viewCache.serverCache.getNode();
  11608. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  11609. if (serverNode.hasChild(childKey)) {
  11610. const serverChild = viewCache.serverCache
  11611. .getNode()
  11612. .getImmediateChild(childKey);
  11613. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  11614. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  11615. }
  11616. });
  11617. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  11618. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  11619. childMergeTree.value === null;
  11620. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  11621. const serverChild = viewCache.serverCache
  11622. .getNode()
  11623. .getImmediateChild(childKey);
  11624. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  11625. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  11626. }
  11627. });
  11628. return curViewCache;
  11629. }
  11630. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  11631. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  11632. return viewCache;
  11633. }
  11634. // Only filter server node if it is currently filtered
  11635. const filterServerNode = viewCache.serverCache.isFiltered();
  11636. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  11637. // now that it won't be shadowed.
  11638. const serverCache = viewCache.serverCache;
  11639. if (affectedTree.value != null) {
  11640. // This is an overwrite.
  11641. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  11642. serverCache.isCompleteForPath(ackPath)) {
  11643. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  11644. }
  11645. else if (pathIsEmpty(ackPath)) {
  11646. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  11647. // should just re-apply whatever we have in our cache as a merge.
  11648. let changedChildren = new ImmutableTree(null);
  11649. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  11650. changedChildren = changedChildren.set(new Path(name), node);
  11651. });
  11652. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  11653. }
  11654. else {
  11655. return viewCache;
  11656. }
  11657. }
  11658. else {
  11659. // This is a merge.
  11660. let changedChildren = new ImmutableTree(null);
  11661. affectedTree.foreach((mergePath, value) => {
  11662. const serverCachePath = pathChild(ackPath, mergePath);
  11663. if (serverCache.isCompleteForPath(serverCachePath)) {
  11664. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  11665. }
  11666. });
  11667. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  11668. }
  11669. }
  11670. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  11671. const oldServerNode = viewCache.serverCache;
  11672. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  11673. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  11674. }
  11675. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  11676. let complete;
  11677. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  11678. return viewCache;
  11679. }
  11680. else {
  11681. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  11682. const oldEventCache = viewCache.eventCache.getNode();
  11683. let newEventCache;
  11684. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  11685. let newNode;
  11686. if (viewCache.serverCache.isFullyInitialized()) {
  11687. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  11688. }
  11689. else {
  11690. const serverChildren = viewCache.serverCache.getNode();
  11691. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  11692. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  11693. }
  11694. newNode = newNode;
  11695. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  11696. }
  11697. else {
  11698. const childKey = pathGetFront(path);
  11699. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  11700. if (newChild == null &&
  11701. viewCache.serverCache.isCompleteForChild(childKey)) {
  11702. newChild = oldEventCache.getImmediateChild(childKey);
  11703. }
  11704. if (newChild != null) {
  11705. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  11706. }
  11707. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  11708. // No complete child available, delete the existing one, if any
  11709. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  11710. }
  11711. else {
  11712. newEventCache = oldEventCache;
  11713. }
  11714. if (newEventCache.isEmpty() &&
  11715. viewCache.serverCache.isFullyInitialized()) {
  11716. // We might have reverted all child writes. Maybe the old event was a leaf node
  11717. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  11718. if (complete.isLeafNode()) {
  11719. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  11720. }
  11721. }
  11722. }
  11723. complete =
  11724. viewCache.serverCache.isFullyInitialized() ||
  11725. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  11726. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  11727. }
  11728. }
  11729. /**
  11730. * @license
  11731. * Copyright 2017 Google LLC
  11732. *
  11733. * Licensed under the Apache License, Version 2.0 (the "License");
  11734. * you may not use this file except in compliance with the License.
  11735. * You may obtain a copy of the License at
  11736. *
  11737. * http://www.apache.org/licenses/LICENSE-2.0
  11738. *
  11739. * Unless required by applicable law or agreed to in writing, software
  11740. * distributed under the License is distributed on an "AS IS" BASIS,
  11741. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11742. * See the License for the specific language governing permissions and
  11743. * limitations under the License.
  11744. */
  11745. /**
  11746. * A view represents a specific location and query that has 1 or more event registrations.
  11747. *
  11748. * It does several things:
  11749. * - Maintains the list of event registrations for this location/query.
  11750. * - Maintains a cache of the data visible for this location/query.
  11751. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  11752. * registrations returns the set of events to be raised.
  11753. */
  11754. class View {
  11755. constructor(query_, initialViewCache) {
  11756. this.query_ = query_;
  11757. this.eventRegistrations_ = [];
  11758. const params = this.query_._queryParams;
  11759. const indexFilter = new IndexedFilter(params.getIndex());
  11760. const filter = queryParamsGetNodeFilter(params);
  11761. this.processor_ = newViewProcessor(filter);
  11762. const initialServerCache = initialViewCache.serverCache;
  11763. const initialEventCache = initialViewCache.eventCache;
  11764. // Don't filter server node with other filter than index, wait for tagged listen
  11765. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  11766. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  11767. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  11768. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  11769. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  11770. this.eventGenerator_ = new EventGenerator(this.query_);
  11771. }
  11772. get query() {
  11773. return this.query_;
  11774. }
  11775. }
  11776. function viewGetServerCache(view) {
  11777. return view.viewCache_.serverCache.getNode();
  11778. }
  11779. function viewGetCompleteNode(view) {
  11780. return viewCacheGetCompleteEventSnap(view.viewCache_);
  11781. }
  11782. function viewGetCompleteServerCache(view, path) {
  11783. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  11784. if (cache) {
  11785. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  11786. // we need to see if it contains the child we're interested in.
  11787. if (view.query._queryParams.loadsAllData() ||
  11788. (!pathIsEmpty(path) &&
  11789. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  11790. return cache.getChild(path);
  11791. }
  11792. }
  11793. return null;
  11794. }
  11795. function viewIsEmpty(view) {
  11796. return view.eventRegistrations_.length === 0;
  11797. }
  11798. function viewAddEventRegistration(view, eventRegistration) {
  11799. view.eventRegistrations_.push(eventRegistration);
  11800. }
  11801. /**
  11802. * @param eventRegistration - If null, remove all callbacks.
  11803. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  11804. * @returns Cancel events, if cancelError was provided.
  11805. */
  11806. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  11807. const cancelEvents = [];
  11808. if (cancelError) {
  11809. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  11810. const path = view.query._path;
  11811. view.eventRegistrations_.forEach(registration => {
  11812. const maybeEvent = registration.createCancelEvent(cancelError, path);
  11813. if (maybeEvent) {
  11814. cancelEvents.push(maybeEvent);
  11815. }
  11816. });
  11817. }
  11818. if (eventRegistration) {
  11819. let remaining = [];
  11820. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  11821. const existing = view.eventRegistrations_[i];
  11822. if (!existing.matches(eventRegistration)) {
  11823. remaining.push(existing);
  11824. }
  11825. else if (eventRegistration.hasAnyCallback()) {
  11826. // We're removing just this one
  11827. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  11828. break;
  11829. }
  11830. }
  11831. view.eventRegistrations_ = remaining;
  11832. }
  11833. else {
  11834. view.eventRegistrations_ = [];
  11835. }
  11836. return cancelEvents;
  11837. }
  11838. /**
  11839. * Applies the given Operation, updates our cache, and returns the appropriate events.
  11840. */
  11841. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  11842. if (operation.type === OperationType.MERGE &&
  11843. operation.source.queryId !== null) {
  11844. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  11845. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  11846. }
  11847. const oldViewCache = view.viewCache_;
  11848. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  11849. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  11850. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  11851. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  11852. view.viewCache_ = result.viewCache;
  11853. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  11854. }
  11855. function viewGetInitialEvents(view, registration) {
  11856. const eventSnap = view.viewCache_.eventCache;
  11857. const initialChanges = [];
  11858. if (!eventSnap.getNode().isLeafNode()) {
  11859. const eventNode = eventSnap.getNode();
  11860. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  11861. initialChanges.push(changeChildAdded(key, childNode));
  11862. });
  11863. }
  11864. if (eventSnap.isFullyInitialized()) {
  11865. initialChanges.push(changeValue(eventSnap.getNode()));
  11866. }
  11867. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  11868. }
  11869. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  11870. const registrations = eventRegistration
  11871. ? [eventRegistration]
  11872. : view.eventRegistrations_;
  11873. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  11874. }
  11875. /**
  11876. * @license
  11877. * Copyright 2017 Google LLC
  11878. *
  11879. * Licensed under the Apache License, Version 2.0 (the "License");
  11880. * you may not use this file except in compliance with the License.
  11881. * You may obtain a copy of the License at
  11882. *
  11883. * http://www.apache.org/licenses/LICENSE-2.0
  11884. *
  11885. * Unless required by applicable law or agreed to in writing, software
  11886. * distributed under the License is distributed on an "AS IS" BASIS,
  11887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11888. * See the License for the specific language governing permissions and
  11889. * limitations under the License.
  11890. */
  11891. let referenceConstructor$1;
  11892. /**
  11893. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  11894. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  11895. * and user writes (set, transaction, update).
  11896. *
  11897. * It's responsible for:
  11898. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  11899. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  11900. * applyUserOverwrite, etc.)
  11901. */
  11902. class SyncPoint {
  11903. constructor() {
  11904. /**
  11905. * The Views being tracked at this location in the tree, stored as a map where the key is a
  11906. * queryId and the value is the View for that query.
  11907. *
  11908. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  11909. */
  11910. this.views = new Map();
  11911. }
  11912. }
  11913. function syncPointSetReferenceConstructor(val) {
  11914. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  11915. referenceConstructor$1 = val;
  11916. }
  11917. function syncPointGetReferenceConstructor() {
  11918. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  11919. return referenceConstructor$1;
  11920. }
  11921. function syncPointIsEmpty(syncPoint) {
  11922. return syncPoint.views.size === 0;
  11923. }
  11924. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  11925. const queryId = operation.source.queryId;
  11926. if (queryId !== null) {
  11927. const view = syncPoint.views.get(queryId);
  11928. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  11929. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  11930. }
  11931. else {
  11932. let events = [];
  11933. for (const view of syncPoint.views.values()) {
  11934. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  11935. }
  11936. return events;
  11937. }
  11938. }
  11939. /**
  11940. * Get a view for the specified query.
  11941. *
  11942. * @param query - The query to return a view for
  11943. * @param writesCache
  11944. * @param serverCache
  11945. * @param serverCacheComplete
  11946. * @returns Events to raise.
  11947. */
  11948. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  11949. const queryId = query._queryIdentifier;
  11950. const view = syncPoint.views.get(queryId);
  11951. if (!view) {
  11952. // TODO: make writesCache take flag for complete server node
  11953. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  11954. let eventCacheComplete = false;
  11955. if (eventCache) {
  11956. eventCacheComplete = true;
  11957. }
  11958. else if (serverCache instanceof ChildrenNode) {
  11959. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  11960. eventCacheComplete = false;
  11961. }
  11962. else {
  11963. eventCache = ChildrenNode.EMPTY_NODE;
  11964. eventCacheComplete = false;
  11965. }
  11966. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  11967. return new View(query, viewCache);
  11968. }
  11969. return view;
  11970. }
  11971. /**
  11972. * Add an event callback for the specified query.
  11973. *
  11974. * @param query
  11975. * @param eventRegistration
  11976. * @param writesCache
  11977. * @param serverCache - Complete server cache, if we have it.
  11978. * @param serverCacheComplete
  11979. * @returns Events to raise.
  11980. */
  11981. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  11982. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  11983. if (!syncPoint.views.has(query._queryIdentifier)) {
  11984. syncPoint.views.set(query._queryIdentifier, view);
  11985. }
  11986. // This is guaranteed to exist now, we just created anything that was missing
  11987. viewAddEventRegistration(view, eventRegistration);
  11988. return viewGetInitialEvents(view, eventRegistration);
  11989. }
  11990. /**
  11991. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  11992. *
  11993. * If query is the default query, we'll check all views for the specified eventRegistration.
  11994. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  11995. *
  11996. * @param eventRegistration - If null, remove all callbacks.
  11997. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  11998. * @returns removed queries and any cancel events
  11999. */
  12000. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  12001. const queryId = query._queryIdentifier;
  12002. const removed = [];
  12003. let cancelEvents = [];
  12004. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  12005. if (queryId === 'default') {
  12006. // When you do ref.off(...), we search all views for the registration to remove.
  12007. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  12008. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  12009. if (viewIsEmpty(view)) {
  12010. syncPoint.views.delete(viewQueryId);
  12011. // We'll deal with complete views later.
  12012. if (!view.query._queryParams.loadsAllData()) {
  12013. removed.push(view.query);
  12014. }
  12015. }
  12016. }
  12017. }
  12018. else {
  12019. // remove the callback from the specific view.
  12020. const view = syncPoint.views.get(queryId);
  12021. if (view) {
  12022. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  12023. if (viewIsEmpty(view)) {
  12024. syncPoint.views.delete(queryId);
  12025. // We'll deal with complete views later.
  12026. if (!view.query._queryParams.loadsAllData()) {
  12027. removed.push(view.query);
  12028. }
  12029. }
  12030. }
  12031. }
  12032. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  12033. // We removed our last complete view.
  12034. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  12035. }
  12036. return { removed, events: cancelEvents };
  12037. }
  12038. function syncPointGetQueryViews(syncPoint) {
  12039. const result = [];
  12040. for (const view of syncPoint.views.values()) {
  12041. if (!view.query._queryParams.loadsAllData()) {
  12042. result.push(view);
  12043. }
  12044. }
  12045. return result;
  12046. }
  12047. /**
  12048. * @param path - The path to the desired complete snapshot
  12049. * @returns A complete cache, if it exists
  12050. */
  12051. function syncPointGetCompleteServerCache(syncPoint, path) {
  12052. let serverCache = null;
  12053. for (const view of syncPoint.views.values()) {
  12054. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  12055. }
  12056. return serverCache;
  12057. }
  12058. function syncPointViewForQuery(syncPoint, query) {
  12059. const params = query._queryParams;
  12060. if (params.loadsAllData()) {
  12061. return syncPointGetCompleteView(syncPoint);
  12062. }
  12063. else {
  12064. const queryId = query._queryIdentifier;
  12065. return syncPoint.views.get(queryId);
  12066. }
  12067. }
  12068. function syncPointViewExistsForQuery(syncPoint, query) {
  12069. return syncPointViewForQuery(syncPoint, query) != null;
  12070. }
  12071. function syncPointHasCompleteView(syncPoint) {
  12072. return syncPointGetCompleteView(syncPoint) != null;
  12073. }
  12074. function syncPointGetCompleteView(syncPoint) {
  12075. for (const view of syncPoint.views.values()) {
  12076. if (view.query._queryParams.loadsAllData()) {
  12077. return view;
  12078. }
  12079. }
  12080. return null;
  12081. }
  12082. /**
  12083. * @license
  12084. * Copyright 2017 Google LLC
  12085. *
  12086. * Licensed under the Apache License, Version 2.0 (the "License");
  12087. * you may not use this file except in compliance with the License.
  12088. * You may obtain a copy of the License at
  12089. *
  12090. * http://www.apache.org/licenses/LICENSE-2.0
  12091. *
  12092. * Unless required by applicable law or agreed to in writing, software
  12093. * distributed under the License is distributed on an "AS IS" BASIS,
  12094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12095. * See the License for the specific language governing permissions and
  12096. * limitations under the License.
  12097. */
  12098. let referenceConstructor;
  12099. function syncTreeSetReferenceConstructor(val) {
  12100. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  12101. referenceConstructor = val;
  12102. }
  12103. function syncTreeGetReferenceConstructor() {
  12104. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  12105. return referenceConstructor;
  12106. }
  12107. /**
  12108. * Static tracker for next query tag.
  12109. */
  12110. let syncTreeNextQueryTag_ = 1;
  12111. /**
  12112. * SyncTree is the central class for managing event callback registration, data caching, views
  12113. * (query processing), and event generation. There are typically two SyncTree instances for
  12114. * each Repo, one for the normal Firebase data, and one for the .info data.
  12115. *
  12116. * It has a number of responsibilities, including:
  12117. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  12118. * - Applying and caching data changes for user set(), transaction(), and update() calls
  12119. * (applyUserOverwrite(), applyUserMerge()).
  12120. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  12121. * applyServerMerge()).
  12122. * - Generating user-facing events for server and user changes (all of the apply* methods
  12123. * return the set of events that need to be raised as a result).
  12124. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  12125. * to the correct set of paths and queries to satisfy the current set of user event
  12126. * callbacks (listens are started/stopped using the provided listenProvider).
  12127. *
  12128. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  12129. * events are returned to the caller rather than raised synchronously.
  12130. *
  12131. */
  12132. class SyncTree {
  12133. /**
  12134. * @param listenProvider_ - Used by SyncTree to start / stop listening
  12135. * to server data.
  12136. */
  12137. constructor(listenProvider_) {
  12138. this.listenProvider_ = listenProvider_;
  12139. /**
  12140. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  12141. */
  12142. this.syncPointTree_ = new ImmutableTree(null);
  12143. /**
  12144. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  12145. */
  12146. this.pendingWriteTree_ = newWriteTree();
  12147. this.tagToQueryMap = new Map();
  12148. this.queryToTagMap = new Map();
  12149. }
  12150. }
  12151. /**
  12152. * Apply the data changes for a user-generated set() or transaction() call.
  12153. *
  12154. * @returns Events to raise.
  12155. */
  12156. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  12157. // Record pending write.
  12158. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  12159. if (!visible) {
  12160. return [];
  12161. }
  12162. else {
  12163. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  12164. }
  12165. }
  12166. /**
  12167. * Apply the data from a user-generated update() call
  12168. *
  12169. * @returns Events to raise.
  12170. */
  12171. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  12172. // Record pending merge.
  12173. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  12174. const changeTree = ImmutableTree.fromObject(changedChildren);
  12175. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  12176. }
  12177. /**
  12178. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  12179. *
  12180. * @param revert - True if the given write failed and needs to be reverted
  12181. * @returns Events to raise.
  12182. */
  12183. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  12184. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  12185. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  12186. if (!needToReevaluate) {
  12187. return [];
  12188. }
  12189. else {
  12190. let affectedTree = new ImmutableTree(null);
  12191. if (write.snap != null) {
  12192. // overwrite
  12193. affectedTree = affectedTree.set(newEmptyPath(), true);
  12194. }
  12195. else {
  12196. each(write.children, (pathString) => {
  12197. affectedTree = affectedTree.set(new Path(pathString), true);
  12198. });
  12199. }
  12200. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  12201. }
  12202. }
  12203. /**
  12204. * Apply new server data for the specified path..
  12205. *
  12206. * @returns Events to raise.
  12207. */
  12208. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  12209. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  12210. }
  12211. /**
  12212. * Apply new server data to be merged in at the specified path.
  12213. *
  12214. * @returns Events to raise.
  12215. */
  12216. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  12217. const changeTree = ImmutableTree.fromObject(changedChildren);
  12218. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  12219. }
  12220. /**
  12221. * Apply a listen complete for a query
  12222. *
  12223. * @returns Events to raise.
  12224. */
  12225. function syncTreeApplyListenComplete(syncTree, path) {
  12226. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  12227. }
  12228. /**
  12229. * Apply a listen complete for a tagged query
  12230. *
  12231. * @returns Events to raise.
  12232. */
  12233. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  12234. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  12235. if (queryKey) {
  12236. const r = syncTreeParseQueryKey_(queryKey);
  12237. const queryPath = r.path, queryId = r.queryId;
  12238. const relativePath = newRelativePath(queryPath, path);
  12239. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  12240. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  12241. }
  12242. else {
  12243. // We've already removed the query. No big deal, ignore the update
  12244. return [];
  12245. }
  12246. }
  12247. /**
  12248. * Remove event callback(s).
  12249. *
  12250. * If query is the default query, we'll check all queries for the specified eventRegistration.
  12251. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  12252. *
  12253. * @param eventRegistration - If null, all callbacks are removed.
  12254. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  12255. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  12256. * deduping needs to take place. This flag allows toggling of that behavior
  12257. * @returns Cancel events, if cancelError was provided.
  12258. */
  12259. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  12260. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  12261. const path = query._path;
  12262. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  12263. let cancelEvents = [];
  12264. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  12265. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  12266. // not loadsAllData().
  12267. if (maybeSyncPoint &&
  12268. (query._queryIdentifier === 'default' ||
  12269. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  12270. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  12271. if (syncPointIsEmpty(maybeSyncPoint)) {
  12272. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  12273. }
  12274. const removed = removedAndEvents.removed;
  12275. cancelEvents = removedAndEvents.events;
  12276. if (!skipListenerDedup) {
  12277. /**
  12278. * We may have just removed one of many listeners and can short-circuit this whole process
  12279. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  12280. * properly set up.
  12281. */
  12282. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  12283. // queryId === 'default'
  12284. const removingDefault = -1 !==
  12285. removed.findIndex(query => {
  12286. return query._queryParams.loadsAllData();
  12287. });
  12288. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  12289. if (removingDefault && !covered) {
  12290. const subtree = syncTree.syncPointTree_.subtree(path);
  12291. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  12292. // removal
  12293. if (!subtree.isEmpty()) {
  12294. // We need to fold over our subtree and collect the listeners to send
  12295. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  12296. // Ok, we've collected all the listens we need. Set them up.
  12297. for (let i = 0; i < newViews.length; ++i) {
  12298. const view = newViews[i], newQuery = view.query;
  12299. const listener = syncTreeCreateListenerForView_(syncTree, view);
  12300. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  12301. }
  12302. }
  12303. // Otherwise there's nothing below us, so nothing we need to start listening on
  12304. }
  12305. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  12306. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  12307. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  12308. if (!covered && removed.length > 0 && !cancelError) {
  12309. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  12310. // default. Otherwise, we need to iterate through and cancel each individual query
  12311. if (removingDefault) {
  12312. // We don't tag default listeners
  12313. const defaultTag = null;
  12314. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  12315. }
  12316. else {
  12317. removed.forEach((queryToRemove) => {
  12318. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  12319. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  12320. });
  12321. }
  12322. }
  12323. }
  12324. // Now, clear all of the tags we're tracking for the removed listens
  12325. syncTreeRemoveTags_(syncTree, removed);
  12326. }
  12327. return cancelEvents;
  12328. }
  12329. /**
  12330. * Apply new server data for the specified tagged query.
  12331. *
  12332. * @returns Events to raise.
  12333. */
  12334. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  12335. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  12336. if (queryKey != null) {
  12337. const r = syncTreeParseQueryKey_(queryKey);
  12338. const queryPath = r.path, queryId = r.queryId;
  12339. const relativePath = newRelativePath(queryPath, path);
  12340. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  12341. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  12342. }
  12343. else {
  12344. // Query must have been removed already
  12345. return [];
  12346. }
  12347. }
  12348. /**
  12349. * Apply server data to be merged in for the specified tagged query.
  12350. *
  12351. * @returns Events to raise.
  12352. */
  12353. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  12354. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  12355. if (queryKey) {
  12356. const r = syncTreeParseQueryKey_(queryKey);
  12357. const queryPath = r.path, queryId = r.queryId;
  12358. const relativePath = newRelativePath(queryPath, path);
  12359. const changeTree = ImmutableTree.fromObject(changedChildren);
  12360. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  12361. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  12362. }
  12363. else {
  12364. // We've already removed the query. No big deal, ignore the update
  12365. return [];
  12366. }
  12367. }
  12368. /**
  12369. * Add an event callback for the specified query.
  12370. *
  12371. * @returns Events to raise.
  12372. */
  12373. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  12374. const path = query._path;
  12375. let serverCache = null;
  12376. let foundAncestorDefaultView = false;
  12377. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  12378. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  12379. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  12380. const relativePath = newRelativePath(pathToSyncPoint, path);
  12381. serverCache =
  12382. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  12383. foundAncestorDefaultView =
  12384. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  12385. });
  12386. let syncPoint = syncTree.syncPointTree_.get(path);
  12387. if (!syncPoint) {
  12388. syncPoint = new SyncPoint();
  12389. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  12390. }
  12391. else {
  12392. foundAncestorDefaultView =
  12393. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  12394. serverCache =
  12395. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12396. }
  12397. let serverCacheComplete;
  12398. if (serverCache != null) {
  12399. serverCacheComplete = true;
  12400. }
  12401. else {
  12402. serverCacheComplete = false;
  12403. serverCache = ChildrenNode.EMPTY_NODE;
  12404. const subtree = syncTree.syncPointTree_.subtree(path);
  12405. subtree.foreachChild((childName, childSyncPoint) => {
  12406. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  12407. if (completeCache) {
  12408. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  12409. }
  12410. });
  12411. }
  12412. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  12413. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  12414. // We need to track a tag for this query
  12415. const queryKey = syncTreeMakeQueryKey_(query);
  12416. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  12417. const tag = syncTreeGetNextQueryTag_();
  12418. syncTree.queryToTagMap.set(queryKey, tag);
  12419. syncTree.tagToQueryMap.set(tag, queryKey);
  12420. }
  12421. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  12422. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  12423. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  12424. const view = syncPointViewForQuery(syncPoint, query);
  12425. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  12426. }
  12427. return events;
  12428. }
  12429. /**
  12430. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  12431. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  12432. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  12433. * <incremented total> as the write is applied locally and then acknowledged at the server.
  12434. *
  12435. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  12436. *
  12437. * @param path - The path to the data we want
  12438. * @param writeIdsToExclude - A specific set to be excluded
  12439. */
  12440. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  12441. const includeHiddenSets = true;
  12442. const writeTree = syncTree.pendingWriteTree_;
  12443. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  12444. const relativePath = newRelativePath(pathSoFar, path);
  12445. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  12446. if (serverCache) {
  12447. return serverCache;
  12448. }
  12449. });
  12450. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  12451. }
  12452. function syncTreeGetServerValue(syncTree, query) {
  12453. const path = query._path;
  12454. let serverCache = null;
  12455. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  12456. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  12457. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  12458. const relativePath = newRelativePath(pathToSyncPoint, path);
  12459. serverCache =
  12460. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  12461. });
  12462. let syncPoint = syncTree.syncPointTree_.get(path);
  12463. if (!syncPoint) {
  12464. syncPoint = new SyncPoint();
  12465. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  12466. }
  12467. else {
  12468. serverCache =
  12469. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12470. }
  12471. const serverCacheComplete = serverCache != null;
  12472. const serverCacheNode = serverCacheComplete
  12473. ? new CacheNode(serverCache, true, false)
  12474. : null;
  12475. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  12476. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  12477. return viewGetCompleteNode(view);
  12478. }
  12479. /**
  12480. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  12481. *
  12482. * NOTES:
  12483. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  12484. *
  12485. * - We call applyOperation() on each SyncPoint passing three things:
  12486. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  12487. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  12488. * 3. A snapshot Node with cached server data, if we have it.
  12489. *
  12490. * - We concatenate all of the events returned by each SyncPoint and return the result.
  12491. */
  12492. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  12493. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  12494. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  12495. }
  12496. /**
  12497. * Recursive helper for applyOperationToSyncPoints_
  12498. */
  12499. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  12500. if (pathIsEmpty(operation.path)) {
  12501. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  12502. }
  12503. else {
  12504. const syncPoint = syncPointTree.get(newEmptyPath());
  12505. // If we don't have cached server data, see if we can get it from this SyncPoint.
  12506. if (serverCache == null && syncPoint != null) {
  12507. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12508. }
  12509. let events = [];
  12510. const childName = pathGetFront(operation.path);
  12511. const childOperation = operation.operationForChild(childName);
  12512. const childTree = syncPointTree.children.get(childName);
  12513. if (childTree && childOperation) {
  12514. const childServerCache = serverCache
  12515. ? serverCache.getImmediateChild(childName)
  12516. : null;
  12517. const childWritesCache = writeTreeRefChild(writesCache, childName);
  12518. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  12519. }
  12520. if (syncPoint) {
  12521. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  12522. }
  12523. return events;
  12524. }
  12525. }
  12526. /**
  12527. * Recursive helper for applyOperationToSyncPoints_
  12528. */
  12529. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  12530. const syncPoint = syncPointTree.get(newEmptyPath());
  12531. // If we don't have cached server data, see if we can get it from this SyncPoint.
  12532. if (serverCache == null && syncPoint != null) {
  12533. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12534. }
  12535. let events = [];
  12536. syncPointTree.children.inorderTraversal((childName, childTree) => {
  12537. const childServerCache = serverCache
  12538. ? serverCache.getImmediateChild(childName)
  12539. : null;
  12540. const childWritesCache = writeTreeRefChild(writesCache, childName);
  12541. const childOperation = operation.operationForChild(childName);
  12542. if (childOperation) {
  12543. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  12544. }
  12545. });
  12546. if (syncPoint) {
  12547. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  12548. }
  12549. return events;
  12550. }
  12551. function syncTreeCreateListenerForView_(syncTree, view) {
  12552. const query = view.query;
  12553. const tag = syncTreeTagForQuery(syncTree, query);
  12554. return {
  12555. hashFn: () => {
  12556. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  12557. return cache.hash();
  12558. },
  12559. onComplete: (status) => {
  12560. if (status === 'ok') {
  12561. if (tag) {
  12562. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  12563. }
  12564. else {
  12565. return syncTreeApplyListenComplete(syncTree, query._path);
  12566. }
  12567. }
  12568. else {
  12569. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  12570. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  12571. const error = errorForServerCode(status, query);
  12572. return syncTreeRemoveEventRegistration(syncTree, query,
  12573. /*eventRegistration*/ null, error);
  12574. }
  12575. }
  12576. };
  12577. }
  12578. /**
  12579. * Return the tag associated with the given query.
  12580. */
  12581. function syncTreeTagForQuery(syncTree, query) {
  12582. const queryKey = syncTreeMakeQueryKey_(query);
  12583. return syncTree.queryToTagMap.get(queryKey);
  12584. }
  12585. /**
  12586. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  12587. */
  12588. function syncTreeMakeQueryKey_(query) {
  12589. return query._path.toString() + '$' + query._queryIdentifier;
  12590. }
  12591. /**
  12592. * Return the query associated with the given tag, if we have one
  12593. */
  12594. function syncTreeQueryKeyForTag_(syncTree, tag) {
  12595. return syncTree.tagToQueryMap.get(tag);
  12596. }
  12597. /**
  12598. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  12599. */
  12600. function syncTreeParseQueryKey_(queryKey) {
  12601. const splitIndex = queryKey.indexOf('$');
  12602. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  12603. return {
  12604. queryId: queryKey.substr(splitIndex + 1),
  12605. path: new Path(queryKey.substr(0, splitIndex))
  12606. };
  12607. }
  12608. /**
  12609. * A helper method to apply tagged operations
  12610. */
  12611. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  12612. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  12613. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  12614. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  12615. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  12616. }
  12617. /**
  12618. * This collapses multiple unfiltered views into a single view, since we only need a single
  12619. * listener for them.
  12620. */
  12621. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  12622. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  12623. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  12624. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  12625. return [completeView];
  12626. }
  12627. else {
  12628. // No complete view here, flatten any deeper listens into an array
  12629. let views = [];
  12630. if (maybeChildSyncPoint) {
  12631. views = syncPointGetQueryViews(maybeChildSyncPoint);
  12632. }
  12633. each(childMap, (_key, childViews) => {
  12634. views = views.concat(childViews);
  12635. });
  12636. return views;
  12637. }
  12638. });
  12639. }
  12640. /**
  12641. * Normalizes a query to a query we send the server for listening
  12642. *
  12643. * @returns The normalized query
  12644. */
  12645. function syncTreeQueryForListening_(query) {
  12646. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  12647. // We treat queries that load all data as default queries
  12648. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  12649. // from Query
  12650. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  12651. }
  12652. else {
  12653. return query;
  12654. }
  12655. }
  12656. function syncTreeRemoveTags_(syncTree, queries) {
  12657. for (let j = 0; j < queries.length; ++j) {
  12658. const removedQuery = queries[j];
  12659. if (!removedQuery._queryParams.loadsAllData()) {
  12660. // We should have a tag for this
  12661. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  12662. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  12663. syncTree.queryToTagMap.delete(removedQueryKey);
  12664. syncTree.tagToQueryMap.delete(removedQueryTag);
  12665. }
  12666. }
  12667. }
  12668. /**
  12669. * Static accessor for query tags.
  12670. */
  12671. function syncTreeGetNextQueryTag_() {
  12672. return syncTreeNextQueryTag_++;
  12673. }
  12674. /**
  12675. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  12676. *
  12677. * @returns This method can return events to support synchronous data sources
  12678. */
  12679. function syncTreeSetupListener_(syncTree, query, view) {
  12680. const path = query._path;
  12681. const tag = syncTreeTagForQuery(syncTree, query);
  12682. const listener = syncTreeCreateListenerForView_(syncTree, view);
  12683. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  12684. const subtree = syncTree.syncPointTree_.subtree(path);
  12685. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  12686. // may need to shadow other listens as well.
  12687. if (tag) {
  12688. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  12689. }
  12690. else {
  12691. // Shadow everything at or below this location, this is a default listener.
  12692. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  12693. if (!pathIsEmpty(relativePath) &&
  12694. maybeChildSyncPoint &&
  12695. syncPointHasCompleteView(maybeChildSyncPoint)) {
  12696. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  12697. }
  12698. else {
  12699. // No default listener here, flatten any deeper queries into an array
  12700. let queries = [];
  12701. if (maybeChildSyncPoint) {
  12702. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  12703. }
  12704. each(childMap, (_key, childQueries) => {
  12705. queries = queries.concat(childQueries);
  12706. });
  12707. return queries;
  12708. }
  12709. });
  12710. for (let i = 0; i < queriesToStop.length; ++i) {
  12711. const queryToStop = queriesToStop[i];
  12712. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  12713. }
  12714. }
  12715. return events;
  12716. }
  12717. /**
  12718. * @license
  12719. * Copyright 2017 Google LLC
  12720. *
  12721. * Licensed under the Apache License, Version 2.0 (the "License");
  12722. * you may not use this file except in compliance with the License.
  12723. * You may obtain a copy of the License at
  12724. *
  12725. * http://www.apache.org/licenses/LICENSE-2.0
  12726. *
  12727. * Unless required by applicable law or agreed to in writing, software
  12728. * distributed under the License is distributed on an "AS IS" BASIS,
  12729. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12730. * See the License for the specific language governing permissions and
  12731. * limitations under the License.
  12732. */
  12733. class ExistingValueProvider {
  12734. constructor(node_) {
  12735. this.node_ = node_;
  12736. }
  12737. getImmediateChild(childName) {
  12738. const child = this.node_.getImmediateChild(childName);
  12739. return new ExistingValueProvider(child);
  12740. }
  12741. node() {
  12742. return this.node_;
  12743. }
  12744. }
  12745. class DeferredValueProvider {
  12746. constructor(syncTree, path) {
  12747. this.syncTree_ = syncTree;
  12748. this.path_ = path;
  12749. }
  12750. getImmediateChild(childName) {
  12751. const childPath = pathChild(this.path_, childName);
  12752. return new DeferredValueProvider(this.syncTree_, childPath);
  12753. }
  12754. node() {
  12755. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  12756. }
  12757. }
  12758. /**
  12759. * Generate placeholders for deferred values.
  12760. */
  12761. const generateWithValues = function (values) {
  12762. values = values || {};
  12763. values['timestamp'] = values['timestamp'] || new Date().getTime();
  12764. return values;
  12765. };
  12766. /**
  12767. * Value to use when firing local events. When writing server values, fire
  12768. * local events with an approximate value, otherwise return value as-is.
  12769. */
  12770. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  12771. if (!value || typeof value !== 'object') {
  12772. return value;
  12773. }
  12774. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  12775. if (typeof value['.sv'] === 'string') {
  12776. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  12777. }
  12778. else if (typeof value['.sv'] === 'object') {
  12779. return resolveComplexDeferredValue(value['.sv'], existingVal);
  12780. }
  12781. else {
  12782. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  12783. }
  12784. };
  12785. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  12786. switch (op) {
  12787. case 'timestamp':
  12788. return serverValues['timestamp'];
  12789. default:
  12790. util.assert(false, 'Unexpected server value: ' + op);
  12791. }
  12792. };
  12793. const resolveComplexDeferredValue = function (op, existing, unused) {
  12794. if (!op.hasOwnProperty('increment')) {
  12795. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  12796. }
  12797. const delta = op['increment'];
  12798. if (typeof delta !== 'number') {
  12799. util.assert(false, 'Unexpected increment value: ' + delta);
  12800. }
  12801. const existingNode = existing.node();
  12802. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  12803. // Incrementing a non-number sets the value to the incremented amount
  12804. if (!existingNode.isLeafNode()) {
  12805. return delta;
  12806. }
  12807. const leaf = existingNode;
  12808. const existingVal = leaf.getValue();
  12809. if (typeof existingVal !== 'number') {
  12810. return delta;
  12811. }
  12812. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  12813. return existingVal + delta;
  12814. };
  12815. /**
  12816. * Recursively replace all deferred values and priorities in the tree with the
  12817. * specified generated replacement values.
  12818. * @param path - path to which write is relative
  12819. * @param node - new data written at path
  12820. * @param syncTree - current data
  12821. */
  12822. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  12823. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  12824. };
  12825. /**
  12826. * Recursively replace all deferred values and priorities in the node with the
  12827. * specified generated replacement values. If there are no server values in the node,
  12828. * it'll be returned as-is.
  12829. */
  12830. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  12831. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  12832. };
  12833. function resolveDeferredValue(node, existingVal, serverValues) {
  12834. const rawPri = node.getPriority().val();
  12835. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  12836. let newNode;
  12837. if (node.isLeafNode()) {
  12838. const leafNode = node;
  12839. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  12840. if (value !== leafNode.getValue() ||
  12841. priority !== leafNode.getPriority().val()) {
  12842. return new LeafNode(value, nodeFromJSON(priority));
  12843. }
  12844. else {
  12845. return node;
  12846. }
  12847. }
  12848. else {
  12849. const childrenNode = node;
  12850. newNode = childrenNode;
  12851. if (priority !== childrenNode.getPriority().val()) {
  12852. newNode = newNode.updatePriority(new LeafNode(priority));
  12853. }
  12854. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  12855. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  12856. if (newChildNode !== childNode) {
  12857. newNode = newNode.updateImmediateChild(childName, newChildNode);
  12858. }
  12859. });
  12860. return newNode;
  12861. }
  12862. }
  12863. /**
  12864. * @license
  12865. * Copyright 2017 Google LLC
  12866. *
  12867. * Licensed under the Apache License, Version 2.0 (the "License");
  12868. * you may not use this file except in compliance with the License.
  12869. * You may obtain a copy of the License at
  12870. *
  12871. * http://www.apache.org/licenses/LICENSE-2.0
  12872. *
  12873. * Unless required by applicable law or agreed to in writing, software
  12874. * distributed under the License is distributed on an "AS IS" BASIS,
  12875. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12876. * See the License for the specific language governing permissions and
  12877. * limitations under the License.
  12878. */
  12879. /**
  12880. * A light-weight tree, traversable by path. Nodes can have both values and children.
  12881. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  12882. * children.
  12883. */
  12884. class Tree {
  12885. /**
  12886. * @param name - Optional name of the node.
  12887. * @param parent - Optional parent node.
  12888. * @param node - Optional node to wrap.
  12889. */
  12890. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  12891. this.name = name;
  12892. this.parent = parent;
  12893. this.node = node;
  12894. }
  12895. }
  12896. /**
  12897. * Returns a sub-Tree for the given path.
  12898. *
  12899. * @param pathObj - Path to look up.
  12900. * @returns Tree for path.
  12901. */
  12902. function treeSubTree(tree, pathObj) {
  12903. // TODO: Require pathObj to be Path?
  12904. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  12905. let child = tree, next = pathGetFront(path);
  12906. while (next !== null) {
  12907. const childNode = util.safeGet(child.node.children, next) || {
  12908. children: {},
  12909. childCount: 0
  12910. };
  12911. child = new Tree(next, child, childNode);
  12912. path = pathPopFront(path);
  12913. next = pathGetFront(path);
  12914. }
  12915. return child;
  12916. }
  12917. /**
  12918. * Returns the data associated with this tree node.
  12919. *
  12920. * @returns The data or null if no data exists.
  12921. */
  12922. function treeGetValue(tree) {
  12923. return tree.node.value;
  12924. }
  12925. /**
  12926. * Sets data to this tree node.
  12927. *
  12928. * @param value - Value to set.
  12929. */
  12930. function treeSetValue(tree, value) {
  12931. tree.node.value = value;
  12932. treeUpdateParents(tree);
  12933. }
  12934. /**
  12935. * @returns Whether the tree has any children.
  12936. */
  12937. function treeHasChildren(tree) {
  12938. return tree.node.childCount > 0;
  12939. }
  12940. /**
  12941. * @returns Whether the tree is empty (no value or children).
  12942. */
  12943. function treeIsEmpty(tree) {
  12944. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  12945. }
  12946. /**
  12947. * Calls action for each child of this tree node.
  12948. *
  12949. * @param action - Action to be called for each child.
  12950. */
  12951. function treeForEachChild(tree, action) {
  12952. each(tree.node.children, (child, childTree) => {
  12953. action(new Tree(child, tree, childTree));
  12954. });
  12955. }
  12956. /**
  12957. * Does a depth-first traversal of this node's descendants, calling action for each one.
  12958. *
  12959. * @param action - Action to be called for each child.
  12960. * @param includeSelf - Whether to call action on this node as well. Defaults to
  12961. * false.
  12962. * @param childrenFirst - Whether to call action on children before calling it on
  12963. * parent.
  12964. */
  12965. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  12966. if (includeSelf && !childrenFirst) {
  12967. action(tree);
  12968. }
  12969. treeForEachChild(tree, child => {
  12970. treeForEachDescendant(child, action, true, childrenFirst);
  12971. });
  12972. if (includeSelf && childrenFirst) {
  12973. action(tree);
  12974. }
  12975. }
  12976. /**
  12977. * Calls action on each ancestor node.
  12978. *
  12979. * @param action - Action to be called on each parent; return
  12980. * true to abort.
  12981. * @param includeSelf - Whether to call action on this node as well.
  12982. * @returns true if the action callback returned true.
  12983. */
  12984. function treeForEachAncestor(tree, action, includeSelf) {
  12985. let node = includeSelf ? tree : tree.parent;
  12986. while (node !== null) {
  12987. if (action(node)) {
  12988. return true;
  12989. }
  12990. node = node.parent;
  12991. }
  12992. return false;
  12993. }
  12994. /**
  12995. * @returns The path of this tree node, as a Path.
  12996. */
  12997. function treeGetPath(tree) {
  12998. return new Path(tree.parent === null
  12999. ? tree.name
  13000. : treeGetPath(tree.parent) + '/' + tree.name);
  13001. }
  13002. /**
  13003. * Adds or removes this child from its parent based on whether it's empty or not.
  13004. */
  13005. function treeUpdateParents(tree) {
  13006. if (tree.parent !== null) {
  13007. treeUpdateChild(tree.parent, tree.name, tree);
  13008. }
  13009. }
  13010. /**
  13011. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  13012. *
  13013. * @param childName - The name of the child to update.
  13014. * @param child - The child to update.
  13015. */
  13016. function treeUpdateChild(tree, childName, child) {
  13017. const childEmpty = treeIsEmpty(child);
  13018. const childExists = util.contains(tree.node.children, childName);
  13019. if (childEmpty && childExists) {
  13020. delete tree.node.children[childName];
  13021. tree.node.childCount--;
  13022. treeUpdateParents(tree);
  13023. }
  13024. else if (!childEmpty && !childExists) {
  13025. tree.node.children[childName] = child.node;
  13026. tree.node.childCount++;
  13027. treeUpdateParents(tree);
  13028. }
  13029. }
  13030. /**
  13031. * @license
  13032. * Copyright 2017 Google LLC
  13033. *
  13034. * Licensed under the Apache License, Version 2.0 (the "License");
  13035. * you may not use this file except in compliance with the License.
  13036. * You may obtain a copy of the License at
  13037. *
  13038. * http://www.apache.org/licenses/LICENSE-2.0
  13039. *
  13040. * Unless required by applicable law or agreed to in writing, software
  13041. * distributed under the License is distributed on an "AS IS" BASIS,
  13042. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13043. * See the License for the specific language governing permissions and
  13044. * limitations under the License.
  13045. */
  13046. /**
  13047. * True for invalid Firebase keys
  13048. */
  13049. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  13050. /**
  13051. * True for invalid Firebase paths.
  13052. * Allows '/' in paths.
  13053. */
  13054. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  13055. /**
  13056. * Maximum number of characters to allow in leaf value
  13057. */
  13058. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  13059. const isValidKey = function (key) {
  13060. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  13061. };
  13062. const isValidPathString = function (pathString) {
  13063. return (typeof pathString === 'string' &&
  13064. pathString.length !== 0 &&
  13065. !INVALID_PATH_REGEX_.test(pathString));
  13066. };
  13067. const isValidRootPathString = function (pathString) {
  13068. if (pathString) {
  13069. // Allow '/.info/' at the beginning.
  13070. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  13071. }
  13072. return isValidPathString(pathString);
  13073. };
  13074. const isValidPriority = function (priority) {
  13075. return (priority === null ||
  13076. typeof priority === 'string' ||
  13077. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  13078. (priority &&
  13079. typeof priority === 'object' &&
  13080. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13081. util.contains(priority, '.sv')));
  13082. };
  13083. /**
  13084. * Pre-validate a datum passed as an argument to Firebase function.
  13085. */
  13086. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  13087. if (optional && value === undefined) {
  13088. return;
  13089. }
  13090. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  13091. };
  13092. /**
  13093. * Validate a data object client-side before sending to server.
  13094. */
  13095. const validateFirebaseData = function (errorPrefix, data, path_) {
  13096. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  13097. if (data === undefined) {
  13098. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  13099. }
  13100. if (typeof data === 'function') {
  13101. throw new Error(errorPrefix +
  13102. 'contains a function ' +
  13103. validationPathToErrorString(path) +
  13104. ' with contents = ' +
  13105. data.toString());
  13106. }
  13107. if (isInvalidJSONNumber(data)) {
  13108. throw new Error(errorPrefix +
  13109. 'contains ' +
  13110. data.toString() +
  13111. ' ' +
  13112. validationPathToErrorString(path));
  13113. }
  13114. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  13115. if (typeof data === 'string' &&
  13116. data.length > MAX_LEAF_SIZE_ / 3 &&
  13117. util.stringLength(data) > MAX_LEAF_SIZE_) {
  13118. throw new Error(errorPrefix +
  13119. 'contains a string greater than ' +
  13120. MAX_LEAF_SIZE_ +
  13121. ' utf8 bytes ' +
  13122. validationPathToErrorString(path) +
  13123. " ('" +
  13124. data.substring(0, 50) +
  13125. "...')");
  13126. }
  13127. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  13128. // to save extra walking of large objects.
  13129. if (data && typeof data === 'object') {
  13130. let hasDotValue = false;
  13131. let hasActualChild = false;
  13132. each(data, (key, value) => {
  13133. if (key === '.value') {
  13134. hasDotValue = true;
  13135. }
  13136. else if (key !== '.priority' && key !== '.sv') {
  13137. hasActualChild = true;
  13138. if (!isValidKey(key)) {
  13139. throw new Error(errorPrefix +
  13140. ' contains an invalid key (' +
  13141. key +
  13142. ') ' +
  13143. validationPathToErrorString(path) +
  13144. '. Keys must be non-empty strings ' +
  13145. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  13146. }
  13147. }
  13148. validationPathPush(path, key);
  13149. validateFirebaseData(errorPrefix, value, path);
  13150. validationPathPop(path);
  13151. });
  13152. if (hasDotValue && hasActualChild) {
  13153. throw new Error(errorPrefix +
  13154. ' contains ".value" child ' +
  13155. validationPathToErrorString(path) +
  13156. ' in addition to actual children.');
  13157. }
  13158. }
  13159. };
  13160. /**
  13161. * Pre-validate paths passed in the firebase function.
  13162. */
  13163. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  13164. let i, curPath;
  13165. for (i = 0; i < mergePaths.length; i++) {
  13166. curPath = mergePaths[i];
  13167. const keys = pathSlice(curPath);
  13168. for (let j = 0; j < keys.length; j++) {
  13169. if (keys[j] === '.priority' && j === keys.length - 1) ;
  13170. else if (!isValidKey(keys[j])) {
  13171. throw new Error(errorPrefix +
  13172. 'contains an invalid key (' +
  13173. keys[j] +
  13174. ') in path ' +
  13175. curPath.toString() +
  13176. '. Keys must be non-empty strings ' +
  13177. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  13178. }
  13179. }
  13180. }
  13181. // Check that update keys are not descendants of each other.
  13182. // We rely on the property that sorting guarantees that ancestors come
  13183. // right before descendants.
  13184. mergePaths.sort(pathCompare);
  13185. let prevPath = null;
  13186. for (i = 0; i < mergePaths.length; i++) {
  13187. curPath = mergePaths[i];
  13188. if (prevPath !== null && pathContains(prevPath, curPath)) {
  13189. throw new Error(errorPrefix +
  13190. 'contains a path ' +
  13191. prevPath.toString() +
  13192. ' that is ancestor of another path ' +
  13193. curPath.toString());
  13194. }
  13195. prevPath = curPath;
  13196. }
  13197. };
  13198. /**
  13199. * pre-validate an object passed as an argument to firebase function (
  13200. * must be an object - e.g. for firebase.update()).
  13201. */
  13202. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  13203. if (optional && data === undefined) {
  13204. return;
  13205. }
  13206. const errorPrefix = util.errorPrefix(fnName, 'values');
  13207. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  13208. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  13209. }
  13210. const mergePaths = [];
  13211. each(data, (key, value) => {
  13212. const curPath = new Path(key);
  13213. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  13214. if (pathGetBack(curPath) === '.priority') {
  13215. if (!isValidPriority(value)) {
  13216. throw new Error(errorPrefix +
  13217. "contains an invalid value for '" +
  13218. curPath.toString() +
  13219. "', which must be a valid " +
  13220. 'Firebase priority (a string, finite number, server value, or null).');
  13221. }
  13222. }
  13223. mergePaths.push(curPath);
  13224. });
  13225. validateFirebaseMergePaths(errorPrefix, mergePaths);
  13226. };
  13227. const validatePriority = function (fnName, priority, optional) {
  13228. if (optional && priority === undefined) {
  13229. return;
  13230. }
  13231. if (isInvalidJSONNumber(priority)) {
  13232. throw new Error(util.errorPrefix(fnName, 'priority') +
  13233. 'is ' +
  13234. priority.toString() +
  13235. ', but must be a valid Firebase priority (a string, finite number, ' +
  13236. 'server value, or null).');
  13237. }
  13238. // Special case to allow importing data with a .sv.
  13239. if (!isValidPriority(priority)) {
  13240. throw new Error(util.errorPrefix(fnName, 'priority') +
  13241. 'must be a valid Firebase priority ' +
  13242. '(a string, finite number, server value, or null).');
  13243. }
  13244. };
  13245. const validateKey = function (fnName, argumentName, key, optional) {
  13246. if (optional && key === undefined) {
  13247. return;
  13248. }
  13249. if (!isValidKey(key)) {
  13250. throw new Error(util.errorPrefix(fnName, argumentName) +
  13251. 'was an invalid key = "' +
  13252. key +
  13253. '". Firebase keys must be non-empty strings and ' +
  13254. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  13255. }
  13256. };
  13257. /**
  13258. * @internal
  13259. */
  13260. const validatePathString = function (fnName, argumentName, pathString, optional) {
  13261. if (optional && pathString === undefined) {
  13262. return;
  13263. }
  13264. if (!isValidPathString(pathString)) {
  13265. throw new Error(util.errorPrefix(fnName, argumentName) +
  13266. 'was an invalid path = "' +
  13267. pathString +
  13268. '". Paths must be non-empty strings and ' +
  13269. 'can\'t contain ".", "#", "$", "[", or "]"');
  13270. }
  13271. };
  13272. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  13273. if (pathString) {
  13274. // Allow '/.info/' at the beginning.
  13275. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  13276. }
  13277. validatePathString(fnName, argumentName, pathString, optional);
  13278. };
  13279. /**
  13280. * @internal
  13281. */
  13282. const validateWritablePath = function (fnName, path) {
  13283. if (pathGetFront(path) === '.info') {
  13284. throw new Error(fnName + " failed = Can't modify data under /.info/");
  13285. }
  13286. };
  13287. const validateUrl = function (fnName, parsedUrl) {
  13288. // TODO = Validate server better.
  13289. const pathString = parsedUrl.path.toString();
  13290. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  13291. parsedUrl.repoInfo.host.length === 0 ||
  13292. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  13293. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  13294. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  13295. throw new Error(util.errorPrefix(fnName, 'url') +
  13296. 'must be a valid firebase URL and ' +
  13297. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  13298. }
  13299. };
  13300. /**
  13301. * @license
  13302. * Copyright 2017 Google LLC
  13303. *
  13304. * Licensed under the Apache License, Version 2.0 (the "License");
  13305. * you may not use this file except in compliance with the License.
  13306. * You may obtain a copy of the License at
  13307. *
  13308. * http://www.apache.org/licenses/LICENSE-2.0
  13309. *
  13310. * Unless required by applicable law or agreed to in writing, software
  13311. * distributed under the License is distributed on an "AS IS" BASIS,
  13312. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13313. * See the License for the specific language governing permissions and
  13314. * limitations under the License.
  13315. */
  13316. /**
  13317. * The event queue serves a few purposes:
  13318. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  13319. * events being queued.
  13320. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  13321. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  13322. * left off, ensuring that the events are still raised synchronously and in order.
  13323. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  13324. * events are raised synchronously.
  13325. *
  13326. * NOTE: This can all go away if/when we move to async events.
  13327. *
  13328. */
  13329. class EventQueue {
  13330. constructor() {
  13331. this.eventLists_ = [];
  13332. /**
  13333. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  13334. */
  13335. this.recursionDepth_ = 0;
  13336. }
  13337. }
  13338. /**
  13339. * @param eventDataList - The new events to queue.
  13340. */
  13341. function eventQueueQueueEvents(eventQueue, eventDataList) {
  13342. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  13343. let currList = null;
  13344. for (let i = 0; i < eventDataList.length; i++) {
  13345. const data = eventDataList[i];
  13346. const path = data.getPath();
  13347. if (currList !== null && !pathEquals(path, currList.path)) {
  13348. eventQueue.eventLists_.push(currList);
  13349. currList = null;
  13350. }
  13351. if (currList === null) {
  13352. currList = { events: [], path };
  13353. }
  13354. currList.events.push(data);
  13355. }
  13356. if (currList) {
  13357. eventQueue.eventLists_.push(currList);
  13358. }
  13359. }
  13360. /**
  13361. * Queues the specified events and synchronously raises all events (including previously queued ones)
  13362. * for the specified path.
  13363. *
  13364. * It is assumed that the new events are all for the specified path.
  13365. *
  13366. * @param path - The path to raise events for.
  13367. * @param eventDataList - The new events to raise.
  13368. */
  13369. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  13370. eventQueueQueueEvents(eventQueue, eventDataList);
  13371. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  13372. }
  13373. /**
  13374. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  13375. * locations related to the specified change path (i.e. all ancestors and descendants).
  13376. *
  13377. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  13378. *
  13379. * @param changedPath - The path to raise events for.
  13380. * @param eventDataList - The events to raise
  13381. */
  13382. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  13383. eventQueueQueueEvents(eventQueue, eventDataList);
  13384. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  13385. pathContains(changedPath, eventPath));
  13386. }
  13387. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  13388. eventQueue.recursionDepth_++;
  13389. let sentAll = true;
  13390. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  13391. const eventList = eventQueue.eventLists_[i];
  13392. if (eventList) {
  13393. const eventPath = eventList.path;
  13394. if (predicate(eventPath)) {
  13395. eventListRaise(eventQueue.eventLists_[i]);
  13396. eventQueue.eventLists_[i] = null;
  13397. }
  13398. else {
  13399. sentAll = false;
  13400. }
  13401. }
  13402. }
  13403. if (sentAll) {
  13404. eventQueue.eventLists_ = [];
  13405. }
  13406. eventQueue.recursionDepth_--;
  13407. }
  13408. /**
  13409. * Iterates through the list and raises each event
  13410. */
  13411. function eventListRaise(eventList) {
  13412. for (let i = 0; i < eventList.events.length; i++) {
  13413. const eventData = eventList.events[i];
  13414. if (eventData !== null) {
  13415. eventList.events[i] = null;
  13416. const eventFn = eventData.getEventRunner();
  13417. if (logger) {
  13418. log('event: ' + eventData.toString());
  13419. }
  13420. exceptionGuard(eventFn);
  13421. }
  13422. }
  13423. }
  13424. /**
  13425. * @license
  13426. * Copyright 2017 Google LLC
  13427. *
  13428. * Licensed under the Apache License, Version 2.0 (the "License");
  13429. * you may not use this file except in compliance with the License.
  13430. * You may obtain a copy of the License at
  13431. *
  13432. * http://www.apache.org/licenses/LICENSE-2.0
  13433. *
  13434. * Unless required by applicable law or agreed to in writing, software
  13435. * distributed under the License is distributed on an "AS IS" BASIS,
  13436. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13437. * See the License for the specific language governing permissions and
  13438. * limitations under the License.
  13439. */
  13440. const INTERRUPT_REASON = 'repo_interrupt';
  13441. /**
  13442. * If a transaction does not succeed after 25 retries, we abort it. Among other
  13443. * things this ensure that if there's ever a bug causing a mismatch between
  13444. * client / server hashes for some data, we won't retry indefinitely.
  13445. */
  13446. const MAX_TRANSACTION_RETRIES = 25;
  13447. /**
  13448. * A connection to a single data repository.
  13449. */
  13450. class Repo {
  13451. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  13452. this.repoInfo_ = repoInfo_;
  13453. this.forceRestClient_ = forceRestClient_;
  13454. this.authTokenProvider_ = authTokenProvider_;
  13455. this.appCheckProvider_ = appCheckProvider_;
  13456. this.dataUpdateCount = 0;
  13457. this.statsListener_ = null;
  13458. this.eventQueue_ = new EventQueue();
  13459. this.nextWriteId_ = 1;
  13460. this.interceptServerDataCallback_ = null;
  13461. /** A list of data pieces and paths to be set when this client disconnects. */
  13462. this.onDisconnect_ = newSparseSnapshotTree();
  13463. /** Stores queues of outstanding transactions for Firebase locations. */
  13464. this.transactionQueueTree_ = new Tree();
  13465. // TODO: This should be @private but it's used by test_access.js and internal.js
  13466. this.persistentConnection_ = null;
  13467. // This key is intentionally not updated if RepoInfo is later changed or replaced
  13468. this.key = this.repoInfo_.toURLString();
  13469. }
  13470. /**
  13471. * @returns The URL corresponding to the root of this Firebase.
  13472. */
  13473. toString() {
  13474. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  13475. }
  13476. }
  13477. function repoStart(repo, appId, authOverride) {
  13478. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  13479. if (repo.forceRestClient_ || beingCrawled()) {
  13480. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  13481. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  13482. }, repo.authTokenProvider_, repo.appCheckProvider_);
  13483. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  13484. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  13485. }
  13486. else {
  13487. // Validate authOverride
  13488. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  13489. if (typeof authOverride !== 'object') {
  13490. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  13491. }
  13492. try {
  13493. util.stringify(authOverride);
  13494. }
  13495. catch (e) {
  13496. throw new Error('Invalid authOverride provided: ' + e);
  13497. }
  13498. }
  13499. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  13500. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  13501. }, (connectStatus) => {
  13502. repoOnConnectStatus(repo, connectStatus);
  13503. }, (updates) => {
  13504. repoOnServerInfoUpdate(repo, updates);
  13505. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  13506. repo.server_ = repo.persistentConnection_;
  13507. }
  13508. repo.authTokenProvider_.addTokenChangeListener(token => {
  13509. repo.server_.refreshAuthToken(token);
  13510. });
  13511. repo.appCheckProvider_.addTokenChangeListener(result => {
  13512. repo.server_.refreshAppCheckToken(result.token);
  13513. });
  13514. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  13515. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  13516. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  13517. // Used for .info.
  13518. repo.infoData_ = new SnapshotHolder();
  13519. repo.infoSyncTree_ = new SyncTree({
  13520. startListening: (query, tag, currentHashFn, onComplete) => {
  13521. let infoEvents = [];
  13522. const node = repo.infoData_.getNode(query._path);
  13523. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  13524. // on initial data...
  13525. if (!node.isEmpty()) {
  13526. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  13527. setTimeout(() => {
  13528. onComplete('ok');
  13529. }, 0);
  13530. }
  13531. return infoEvents;
  13532. },
  13533. stopListening: () => { }
  13534. });
  13535. repoUpdateInfo(repo, 'connected', false);
  13536. repo.serverSyncTree_ = new SyncTree({
  13537. startListening: (query, tag, currentHashFn, onComplete) => {
  13538. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  13539. const events = onComplete(status, data);
  13540. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  13541. });
  13542. // No synchronous events for network-backed sync trees
  13543. return [];
  13544. },
  13545. stopListening: (query, tag) => {
  13546. repo.server_.unlisten(query, tag);
  13547. }
  13548. });
  13549. }
  13550. /**
  13551. * @returns The time in milliseconds, taking the server offset into account if we have one.
  13552. */
  13553. function repoServerTime(repo) {
  13554. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  13555. const offset = offsetNode.val() || 0;
  13556. return new Date().getTime() + offset;
  13557. }
  13558. /**
  13559. * Generate ServerValues using some variables from the repo object.
  13560. */
  13561. function repoGenerateServerValues(repo) {
  13562. return generateWithValues({
  13563. timestamp: repoServerTime(repo)
  13564. });
  13565. }
  13566. /**
  13567. * Called by realtime when we get new messages from the server.
  13568. */
  13569. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  13570. // For testing.
  13571. repo.dataUpdateCount++;
  13572. const path = new Path(pathString);
  13573. data = repo.interceptServerDataCallback_
  13574. ? repo.interceptServerDataCallback_(pathString, data)
  13575. : data;
  13576. let events = [];
  13577. if (tag) {
  13578. if (isMerge) {
  13579. const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  13580. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  13581. }
  13582. else {
  13583. const taggedSnap = nodeFromJSON(data);
  13584. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  13585. }
  13586. }
  13587. else if (isMerge) {
  13588. const changedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  13589. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  13590. }
  13591. else {
  13592. const snap = nodeFromJSON(data);
  13593. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  13594. }
  13595. let affectedPath = path;
  13596. if (events.length > 0) {
  13597. // Since we have a listener outstanding for each transaction, receiving any events
  13598. // is a proxy for some change having occurred.
  13599. affectedPath = repoRerunTransactions(repo, path);
  13600. }
  13601. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  13602. }
  13603. function repoOnConnectStatus(repo, connectStatus) {
  13604. repoUpdateInfo(repo, 'connected', connectStatus);
  13605. if (connectStatus === false) {
  13606. repoRunOnDisconnectEvents(repo);
  13607. }
  13608. }
  13609. function repoOnServerInfoUpdate(repo, updates) {
  13610. each(updates, (key, value) => {
  13611. repoUpdateInfo(repo, key, value);
  13612. });
  13613. }
  13614. function repoUpdateInfo(repo, pathString, value) {
  13615. const path = new Path('/.info/' + pathString);
  13616. const newNode = nodeFromJSON(value);
  13617. repo.infoData_.updateSnapshot(path, newNode);
  13618. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  13619. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  13620. }
  13621. function repoGetNextWriteId(repo) {
  13622. return repo.nextWriteId_++;
  13623. }
  13624. /**
  13625. * The purpose of `getValue` is to return the latest known value
  13626. * satisfying `query`.
  13627. *
  13628. * This method will first check for in-memory cached values
  13629. * belonging to active listeners. If they are found, such values
  13630. * are considered to be the most up-to-date.
  13631. *
  13632. * If the client is not connected, this method will wait until the
  13633. * repo has established a connection and then request the value for `query`.
  13634. * If the client is not able to retrieve the query result for another reason,
  13635. * it reports an error.
  13636. *
  13637. * @param query - The query to surface a value for.
  13638. */
  13639. function repoGetValue(repo, query, eventRegistration) {
  13640. // Only active queries are cached. There is no persisted cache.
  13641. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  13642. if (cached != null) {
  13643. return Promise.resolve(cached);
  13644. }
  13645. return repo.server_.get(query).then(payload => {
  13646. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  13647. /**
  13648. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  13649. * Add an event registration,
  13650. * Update data at the path,
  13651. * Raise any events,
  13652. * Cleanup the SyncTree
  13653. */
  13654. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  13655. let events;
  13656. if (query._queryParams.loadsAllData()) {
  13657. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  13658. }
  13659. else {
  13660. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  13661. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  13662. }
  13663. /*
  13664. * We need to raise events in the scenario where `get()` is called at a parent path, and
  13665. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  13666. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  13667. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  13668. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  13669. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  13670. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  13671. * ensure the corresponding child events will get fired.
  13672. */
  13673. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  13674. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  13675. return node;
  13676. }, err => {
  13677. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  13678. return Promise.reject(new Error(err));
  13679. });
  13680. }
  13681. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  13682. repoLog(repo, 'set', {
  13683. path: path.toString(),
  13684. value: newVal,
  13685. priority: newPriority
  13686. });
  13687. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  13688. // (b) store unresolved paths on JSON parse
  13689. const serverValues = repoGenerateServerValues(repo);
  13690. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  13691. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  13692. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  13693. const writeId = repoGetNextWriteId(repo);
  13694. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  13695. eventQueueQueueEvents(repo.eventQueue_, events);
  13696. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  13697. const success = status === 'ok';
  13698. if (!success) {
  13699. warn$1('set at ' + path + ' failed: ' + status);
  13700. }
  13701. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  13702. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  13703. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  13704. });
  13705. const affectedPath = repoAbortTransactions(repo, path);
  13706. repoRerunTransactions(repo, affectedPath);
  13707. // We queued the events above, so just flush the queue here
  13708. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  13709. }
  13710. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  13711. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  13712. // Start with our existing data and merge each child into it.
  13713. let empty = true;
  13714. const serverValues = repoGenerateServerValues(repo);
  13715. const changedChildren = {};
  13716. each(childrenToMerge, (changedKey, changedValue) => {
  13717. empty = false;
  13718. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  13719. });
  13720. if (!empty) {
  13721. const writeId = repoGetNextWriteId(repo);
  13722. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  13723. eventQueueQueueEvents(repo.eventQueue_, events);
  13724. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  13725. const success = status === 'ok';
  13726. if (!success) {
  13727. warn$1('update at ' + path + ' failed: ' + status);
  13728. }
  13729. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  13730. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  13731. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  13732. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  13733. });
  13734. each(childrenToMerge, (changedPath) => {
  13735. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  13736. repoRerunTransactions(repo, affectedPath);
  13737. });
  13738. // We queued the events above, so just flush the queue here
  13739. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  13740. }
  13741. else {
  13742. log("update() called with empty data. Don't do anything.");
  13743. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  13744. }
  13745. }
  13746. /**
  13747. * Applies all of the changes stored up in the onDisconnect_ tree.
  13748. */
  13749. function repoRunOnDisconnectEvents(repo) {
  13750. repoLog(repo, 'onDisconnectEvents');
  13751. const serverValues = repoGenerateServerValues(repo);
  13752. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  13753. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  13754. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  13755. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  13756. });
  13757. let events = [];
  13758. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  13759. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  13760. const affectedPath = repoAbortTransactions(repo, path);
  13761. repoRerunTransactions(repo, affectedPath);
  13762. });
  13763. repo.onDisconnect_ = newSparseSnapshotTree();
  13764. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  13765. }
  13766. function repoOnDisconnectCancel(repo, path, onComplete) {
  13767. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  13768. if (status === 'ok') {
  13769. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  13770. }
  13771. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  13772. });
  13773. }
  13774. function repoOnDisconnectSet(repo, path, value, onComplete) {
  13775. const newNode = nodeFromJSON(value);
  13776. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  13777. if (status === 'ok') {
  13778. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  13779. }
  13780. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  13781. });
  13782. }
  13783. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  13784. const newNode = nodeFromJSON(value, priority);
  13785. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  13786. if (status === 'ok') {
  13787. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  13788. }
  13789. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  13790. });
  13791. }
  13792. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  13793. if (util.isEmpty(childrenToMerge)) {
  13794. log("onDisconnect().update() called with empty data. Don't do anything.");
  13795. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  13796. return;
  13797. }
  13798. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  13799. if (status === 'ok') {
  13800. each(childrenToMerge, (childName, childNode) => {
  13801. const newChildNode = nodeFromJSON(childNode);
  13802. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  13803. });
  13804. }
  13805. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  13806. });
  13807. }
  13808. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  13809. let events;
  13810. if (pathGetFront(query._path) === '.info') {
  13811. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  13812. }
  13813. else {
  13814. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  13815. }
  13816. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  13817. }
  13818. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  13819. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  13820. // a little bit by handling the return values anyways.
  13821. let events;
  13822. if (pathGetFront(query._path) === '.info') {
  13823. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  13824. }
  13825. else {
  13826. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  13827. }
  13828. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  13829. }
  13830. function repoInterrupt(repo) {
  13831. if (repo.persistentConnection_) {
  13832. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  13833. }
  13834. }
  13835. function repoResume(repo) {
  13836. if (repo.persistentConnection_) {
  13837. repo.persistentConnection_.resume(INTERRUPT_REASON);
  13838. }
  13839. }
  13840. function repoLog(repo, ...varArgs) {
  13841. let prefix = '';
  13842. if (repo.persistentConnection_) {
  13843. prefix = repo.persistentConnection_.id + ':';
  13844. }
  13845. log(prefix, ...varArgs);
  13846. }
  13847. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  13848. if (callback) {
  13849. exceptionGuard(() => {
  13850. if (status === 'ok') {
  13851. callback(null);
  13852. }
  13853. else {
  13854. const code = (status || 'error').toUpperCase();
  13855. let message = code;
  13856. if (errorReason) {
  13857. message += ': ' + errorReason;
  13858. }
  13859. const error = new Error(message);
  13860. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13861. error.code = code;
  13862. callback(error);
  13863. }
  13864. });
  13865. }
  13866. }
  13867. /**
  13868. * Creates a new transaction, adds it to the transactions we're tracking, and
  13869. * sends it to the server if possible.
  13870. *
  13871. * @param path - Path at which to do transaction.
  13872. * @param transactionUpdate - Update callback.
  13873. * @param onComplete - Completion callback.
  13874. * @param unwatcher - Function that will be called when the transaction no longer
  13875. * need data updates for `path`.
  13876. * @param applyLocally - Whether or not to make intermediate results visible
  13877. */
  13878. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  13879. repoLog(repo, 'transaction on ' + path);
  13880. // Initialize transaction.
  13881. const transaction = {
  13882. path,
  13883. update: transactionUpdate,
  13884. onComplete,
  13885. // One of TransactionStatus enums.
  13886. status: null,
  13887. // Used when combining transactions at different locations to figure out
  13888. // which one goes first.
  13889. order: LUIDGenerator(),
  13890. // Whether to raise local events for this transaction.
  13891. applyLocally,
  13892. // Count of how many times we've retried the transaction.
  13893. retryCount: 0,
  13894. // Function to call to clean up our .on() listener.
  13895. unwatcher,
  13896. // Stores why a transaction was aborted.
  13897. abortReason: null,
  13898. currentWriteId: null,
  13899. currentInputSnapshot: null,
  13900. currentOutputSnapshotRaw: null,
  13901. currentOutputSnapshotResolved: null
  13902. };
  13903. // Run transaction initially.
  13904. const currentState = repoGetLatestState(repo, path, undefined);
  13905. transaction.currentInputSnapshot = currentState;
  13906. const newVal = transaction.update(currentState.val());
  13907. if (newVal === undefined) {
  13908. // Abort transaction.
  13909. transaction.unwatcher();
  13910. transaction.currentOutputSnapshotRaw = null;
  13911. transaction.currentOutputSnapshotResolved = null;
  13912. if (transaction.onComplete) {
  13913. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  13914. }
  13915. }
  13916. else {
  13917. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  13918. // Mark as run and add to our queue.
  13919. transaction.status = 0 /* TransactionStatus.RUN */;
  13920. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  13921. const nodeQueue = treeGetValue(queueNode) || [];
  13922. nodeQueue.push(transaction);
  13923. treeSetValue(queueNode, nodeQueue);
  13924. // Update visibleData and raise events
  13925. // Note: We intentionally raise events after updating all of our
  13926. // transaction state, since the user could start new transactions from the
  13927. // event callbacks.
  13928. let priorityForNode;
  13929. if (typeof newVal === 'object' &&
  13930. newVal !== null &&
  13931. util.contains(newVal, '.priority')) {
  13932. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13933. priorityForNode = util.safeGet(newVal, '.priority');
  13934. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  13935. 'Priority must be a valid string, finite number, server value, or null.');
  13936. }
  13937. else {
  13938. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  13939. ChildrenNode.EMPTY_NODE;
  13940. priorityForNode = currentNode.getPriority().val();
  13941. }
  13942. const serverValues = repoGenerateServerValues(repo);
  13943. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  13944. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  13945. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  13946. transaction.currentOutputSnapshotResolved = newNode;
  13947. transaction.currentWriteId = repoGetNextWriteId(repo);
  13948. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  13949. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  13950. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  13951. }
  13952. }
  13953. /**
  13954. * @param excludeSets - A specific set to exclude
  13955. */
  13956. function repoGetLatestState(repo, path, excludeSets) {
  13957. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  13958. ChildrenNode.EMPTY_NODE);
  13959. }
  13960. /**
  13961. * Sends any already-run transactions that aren't waiting for outstanding
  13962. * transactions to complete.
  13963. *
  13964. * Externally it's called with no arguments, but it calls itself recursively
  13965. * with a particular transactionQueueTree node to recurse through the tree.
  13966. *
  13967. * @param node - transactionQueueTree node to start at.
  13968. */
  13969. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  13970. // Before recursing, make sure any completed transactions are removed.
  13971. if (!node) {
  13972. repoPruneCompletedTransactionsBelowNode(repo, node);
  13973. }
  13974. if (treeGetValue(node)) {
  13975. const queue = repoBuildTransactionQueue(repo, node);
  13976. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  13977. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  13978. // If they're all run (and not sent), we can send them. Else, we must wait.
  13979. if (allRun) {
  13980. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  13981. }
  13982. }
  13983. else if (treeHasChildren(node)) {
  13984. treeForEachChild(node, childNode => {
  13985. repoSendReadyTransactions(repo, childNode);
  13986. });
  13987. }
  13988. }
  13989. /**
  13990. * Given a list of run transactions, send them to the server and then handle
  13991. * the result (success or failure).
  13992. *
  13993. * @param path - The location of the queue.
  13994. * @param queue - Queue of transactions under the specified location.
  13995. */
  13996. function repoSendTransactionQueue(repo, path, queue) {
  13997. // Mark transactions as sent and increment retry count!
  13998. const setsToIgnore = queue.map(txn => {
  13999. return txn.currentWriteId;
  14000. });
  14001. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  14002. let snapToSend = latestState;
  14003. const latestHash = latestState.hash();
  14004. for (let i = 0; i < queue.length; i++) {
  14005. const txn = queue[i];
  14006. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  14007. txn.status = 1 /* TransactionStatus.SENT */;
  14008. txn.retryCount++;
  14009. const relativePath = newRelativePath(path, txn.path);
  14010. // If we've gotten to this point, the output snapshot must be defined.
  14011. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  14012. }
  14013. const dataToSend = snapToSend.val(true);
  14014. const pathToSend = path;
  14015. // Send the put.
  14016. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  14017. repoLog(repo, 'transaction put response', {
  14018. path: pathToSend.toString(),
  14019. status
  14020. });
  14021. let events = [];
  14022. if (status === 'ok') {
  14023. // Queue up the callbacks and fire them after cleaning up all of our
  14024. // transaction state, since the callback could trigger more
  14025. // transactions or sets.
  14026. const callbacks = [];
  14027. for (let i = 0; i < queue.length; i++) {
  14028. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  14029. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  14030. if (queue[i].onComplete) {
  14031. // We never unset the output snapshot, and given that this
  14032. // transaction is complete, it should be set
  14033. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  14034. }
  14035. queue[i].unwatcher();
  14036. }
  14037. // Now remove the completed transactions.
  14038. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  14039. // There may be pending transactions that we can now send.
  14040. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  14041. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  14042. // Finally, trigger onComplete callbacks.
  14043. for (let i = 0; i < callbacks.length; i++) {
  14044. exceptionGuard(callbacks[i]);
  14045. }
  14046. }
  14047. else {
  14048. // transactions are no longer sent. Update their status appropriately.
  14049. if (status === 'datastale') {
  14050. for (let i = 0; i < queue.length; i++) {
  14051. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  14052. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  14053. }
  14054. else {
  14055. queue[i].status = 0 /* TransactionStatus.RUN */;
  14056. }
  14057. }
  14058. }
  14059. else {
  14060. warn$1('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  14061. for (let i = 0; i < queue.length; i++) {
  14062. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  14063. queue[i].abortReason = status;
  14064. }
  14065. }
  14066. repoRerunTransactions(repo, path);
  14067. }
  14068. }, latestHash);
  14069. }
  14070. /**
  14071. * Finds all transactions dependent on the data at changedPath and reruns them.
  14072. *
  14073. * Should be called any time cached data changes.
  14074. *
  14075. * Return the highest path that was affected by rerunning transactions. This
  14076. * is the path at which events need to be raised for.
  14077. *
  14078. * @param changedPath - The path in mergedData that changed.
  14079. * @returns The rootmost path that was affected by rerunning transactions.
  14080. */
  14081. function repoRerunTransactions(repo, changedPath) {
  14082. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  14083. const path = treeGetPath(rootMostTransactionNode);
  14084. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  14085. repoRerunTransactionQueue(repo, queue, path);
  14086. return path;
  14087. }
  14088. /**
  14089. * Does all the work of rerunning transactions (as well as cleans up aborted
  14090. * transactions and whatnot).
  14091. *
  14092. * @param queue - The queue of transactions to run.
  14093. * @param path - The path the queue is for.
  14094. */
  14095. function repoRerunTransactionQueue(repo, queue, path) {
  14096. if (queue.length === 0) {
  14097. return; // Nothing to do!
  14098. }
  14099. // Queue up the callbacks and fire them after cleaning up all of our
  14100. // transaction state, since the callback could trigger more transactions or
  14101. // sets.
  14102. const callbacks = [];
  14103. let events = [];
  14104. // Ignore all of the sets we're going to re-run.
  14105. const txnsToRerun = queue.filter(q => {
  14106. return q.status === 0 /* TransactionStatus.RUN */;
  14107. });
  14108. const setsToIgnore = txnsToRerun.map(q => {
  14109. return q.currentWriteId;
  14110. });
  14111. for (let i = 0; i < queue.length; i++) {
  14112. const transaction = queue[i];
  14113. const relativePath = newRelativePath(path, transaction.path);
  14114. let abortTransaction = false, abortReason;
  14115. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  14116. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  14117. abortTransaction = true;
  14118. abortReason = transaction.abortReason;
  14119. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  14120. }
  14121. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  14122. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  14123. abortTransaction = true;
  14124. abortReason = 'maxretry';
  14125. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  14126. }
  14127. else {
  14128. // This code reruns a transaction
  14129. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  14130. transaction.currentInputSnapshot = currentNode;
  14131. const newData = queue[i].update(currentNode.val());
  14132. if (newData !== undefined) {
  14133. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  14134. let newDataNode = nodeFromJSON(newData);
  14135. const hasExplicitPriority = typeof newData === 'object' &&
  14136. newData != null &&
  14137. util.contains(newData, '.priority');
  14138. if (!hasExplicitPriority) {
  14139. // Keep the old priority if there wasn't a priority explicitly specified.
  14140. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  14141. }
  14142. const oldWriteId = transaction.currentWriteId;
  14143. const serverValues = repoGenerateServerValues(repo);
  14144. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  14145. transaction.currentOutputSnapshotRaw = newDataNode;
  14146. transaction.currentOutputSnapshotResolved = newNodeResolved;
  14147. transaction.currentWriteId = repoGetNextWriteId(repo);
  14148. // Mutates setsToIgnore in place
  14149. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  14150. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  14151. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  14152. }
  14153. else {
  14154. abortTransaction = true;
  14155. abortReason = 'nodata';
  14156. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  14157. }
  14158. }
  14159. }
  14160. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  14161. events = [];
  14162. if (abortTransaction) {
  14163. // Abort.
  14164. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  14165. // Removing a listener can trigger pruning which can muck with
  14166. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  14167. // until we're done.
  14168. (function (unwatcher) {
  14169. setTimeout(unwatcher, Math.floor(0));
  14170. })(queue[i].unwatcher);
  14171. if (queue[i].onComplete) {
  14172. if (abortReason === 'nodata') {
  14173. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  14174. }
  14175. else {
  14176. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  14177. }
  14178. }
  14179. }
  14180. }
  14181. // Clean up completed transactions.
  14182. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  14183. // Now fire callbacks, now that we're in a good, known state.
  14184. for (let i = 0; i < callbacks.length; i++) {
  14185. exceptionGuard(callbacks[i]);
  14186. }
  14187. // Try to send the transaction result to the server.
  14188. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  14189. }
  14190. /**
  14191. * Returns the rootmost ancestor node of the specified path that has a pending
  14192. * transaction on it, or just returns the node for the given path if there are
  14193. * no pending transactions on any ancestor.
  14194. *
  14195. * @param path - The location to start at.
  14196. * @returns The rootmost node with a transaction.
  14197. */
  14198. function repoGetAncestorTransactionNode(repo, path) {
  14199. let front;
  14200. // Start at the root and walk deeper into the tree towards path until we
  14201. // find a node with pending transactions.
  14202. let transactionNode = repo.transactionQueueTree_;
  14203. front = pathGetFront(path);
  14204. while (front !== null && treeGetValue(transactionNode) === undefined) {
  14205. transactionNode = treeSubTree(transactionNode, front);
  14206. path = pathPopFront(path);
  14207. front = pathGetFront(path);
  14208. }
  14209. return transactionNode;
  14210. }
  14211. /**
  14212. * Builds the queue of all transactions at or below the specified
  14213. * transactionNode.
  14214. *
  14215. * @param transactionNode
  14216. * @returns The generated queue.
  14217. */
  14218. function repoBuildTransactionQueue(repo, transactionNode) {
  14219. // Walk any child transaction queues and aggregate them into a single queue.
  14220. const transactionQueue = [];
  14221. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  14222. // Sort them by the order the transactions were created.
  14223. transactionQueue.sort((a, b) => a.order - b.order);
  14224. return transactionQueue;
  14225. }
  14226. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  14227. const nodeQueue = treeGetValue(node);
  14228. if (nodeQueue) {
  14229. for (let i = 0; i < nodeQueue.length; i++) {
  14230. queue.push(nodeQueue[i]);
  14231. }
  14232. }
  14233. treeForEachChild(node, child => {
  14234. repoAggregateTransactionQueuesForNode(repo, child, queue);
  14235. });
  14236. }
  14237. /**
  14238. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  14239. */
  14240. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  14241. const queue = treeGetValue(node);
  14242. if (queue) {
  14243. let to = 0;
  14244. for (let from = 0; from < queue.length; from++) {
  14245. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  14246. queue[to] = queue[from];
  14247. to++;
  14248. }
  14249. }
  14250. queue.length = to;
  14251. treeSetValue(node, queue.length > 0 ? queue : undefined);
  14252. }
  14253. treeForEachChild(node, childNode => {
  14254. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  14255. });
  14256. }
  14257. /**
  14258. * Aborts all transactions on ancestors or descendants of the specified path.
  14259. * Called when doing a set() or update() since we consider them incompatible
  14260. * with transactions.
  14261. *
  14262. * @param path - Path for which we want to abort related transactions.
  14263. */
  14264. function repoAbortTransactions(repo, path) {
  14265. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  14266. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  14267. treeForEachAncestor(transactionNode, (node) => {
  14268. repoAbortTransactionsOnNode(repo, node);
  14269. });
  14270. repoAbortTransactionsOnNode(repo, transactionNode);
  14271. treeForEachDescendant(transactionNode, (node) => {
  14272. repoAbortTransactionsOnNode(repo, node);
  14273. });
  14274. return affectedPath;
  14275. }
  14276. /**
  14277. * Abort transactions stored in this transaction queue node.
  14278. *
  14279. * @param node - Node to abort transactions for.
  14280. */
  14281. function repoAbortTransactionsOnNode(repo, node) {
  14282. const queue = treeGetValue(node);
  14283. if (queue) {
  14284. // Queue up the callbacks and fire them after cleaning up all of our
  14285. // transaction state, since the callback could trigger more transactions
  14286. // or sets.
  14287. const callbacks = [];
  14288. // Go through queue. Any already-sent transactions must be marked for
  14289. // abort, while the unsent ones can be immediately aborted and removed.
  14290. let events = [];
  14291. let lastSent = -1;
  14292. for (let i = 0; i < queue.length; i++) {
  14293. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  14294. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  14295. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  14296. lastSent = i;
  14297. // Mark transaction for abort when it comes back.
  14298. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  14299. queue[i].abortReason = 'set';
  14300. }
  14301. else {
  14302. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  14303. // We can abort it immediately.
  14304. queue[i].unwatcher();
  14305. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  14306. if (queue[i].onComplete) {
  14307. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  14308. }
  14309. }
  14310. }
  14311. if (lastSent === -1) {
  14312. // We're not waiting for any sent transactions. We can clear the queue.
  14313. treeSetValue(node, undefined);
  14314. }
  14315. else {
  14316. // Remove the transactions we aborted.
  14317. queue.length = lastSent + 1;
  14318. }
  14319. // Now fire the callbacks.
  14320. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  14321. for (let i = 0; i < callbacks.length; i++) {
  14322. exceptionGuard(callbacks[i]);
  14323. }
  14324. }
  14325. }
  14326. /**
  14327. * @license
  14328. * Copyright 2017 Google LLC
  14329. *
  14330. * Licensed under the Apache License, Version 2.0 (the "License");
  14331. * you may not use this file except in compliance with the License.
  14332. * You may obtain a copy of the License at
  14333. *
  14334. * http://www.apache.org/licenses/LICENSE-2.0
  14335. *
  14336. * Unless required by applicable law or agreed to in writing, software
  14337. * distributed under the License is distributed on an "AS IS" BASIS,
  14338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14339. * See the License for the specific language governing permissions and
  14340. * limitations under the License.
  14341. */
  14342. function decodePath(pathString) {
  14343. let pathStringDecoded = '';
  14344. const pieces = pathString.split('/');
  14345. for (let i = 0; i < pieces.length; i++) {
  14346. if (pieces[i].length > 0) {
  14347. let piece = pieces[i];
  14348. try {
  14349. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  14350. }
  14351. catch (e) { }
  14352. pathStringDecoded += '/' + piece;
  14353. }
  14354. }
  14355. return pathStringDecoded;
  14356. }
  14357. /**
  14358. * @returns key value hash
  14359. */
  14360. function decodeQuery(queryString) {
  14361. const results = {};
  14362. if (queryString.charAt(0) === '?') {
  14363. queryString = queryString.substring(1);
  14364. }
  14365. for (const segment of queryString.split('&')) {
  14366. if (segment.length === 0) {
  14367. continue;
  14368. }
  14369. const kv = segment.split('=');
  14370. if (kv.length === 2) {
  14371. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  14372. }
  14373. else {
  14374. warn$1(`Invalid query segment '${segment}' in query '${queryString}'`);
  14375. }
  14376. }
  14377. return results;
  14378. }
  14379. const parseRepoInfo = function (dataURL, nodeAdmin) {
  14380. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  14381. if (parsedUrl.domain === 'firebase.com') {
  14382. fatal(parsedUrl.host +
  14383. ' is no longer supported. ' +
  14384. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  14385. }
  14386. // Catch common error of uninitialized namespace value.
  14387. if ((!namespace || namespace === 'undefined') &&
  14388. parsedUrl.domain !== 'localhost') {
  14389. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  14390. }
  14391. if (!parsedUrl.secure) {
  14392. warnIfPageIsSecure();
  14393. }
  14394. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  14395. return {
  14396. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  14397. /*persistenceKey=*/ '',
  14398. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  14399. path: new Path(parsedUrl.pathString)
  14400. };
  14401. };
  14402. const parseDatabaseURL = function (dataURL) {
  14403. // Default to empty strings in the event of a malformed string.
  14404. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  14405. // Always default to SSL, unless otherwise specified.
  14406. let secure = true, scheme = 'https', port = 443;
  14407. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  14408. if (typeof dataURL === 'string') {
  14409. // Parse scheme.
  14410. let colonInd = dataURL.indexOf('//');
  14411. if (colonInd >= 0) {
  14412. scheme = dataURL.substring(0, colonInd - 1);
  14413. dataURL = dataURL.substring(colonInd + 2);
  14414. }
  14415. // Parse host, path, and query string.
  14416. let slashInd = dataURL.indexOf('/');
  14417. if (slashInd === -1) {
  14418. slashInd = dataURL.length;
  14419. }
  14420. let questionMarkInd = dataURL.indexOf('?');
  14421. if (questionMarkInd === -1) {
  14422. questionMarkInd = dataURL.length;
  14423. }
  14424. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  14425. if (slashInd < questionMarkInd) {
  14426. // For pathString, questionMarkInd will always come after slashInd
  14427. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  14428. }
  14429. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  14430. // If we have a port, use scheme for determining if it's secure.
  14431. colonInd = host.indexOf(':');
  14432. if (colonInd >= 0) {
  14433. secure = scheme === 'https' || scheme === 'wss';
  14434. port = parseInt(host.substring(colonInd + 1), 10);
  14435. }
  14436. else {
  14437. colonInd = host.length;
  14438. }
  14439. const hostWithoutPort = host.slice(0, colonInd);
  14440. if (hostWithoutPort.toLowerCase() === 'localhost') {
  14441. domain = 'localhost';
  14442. }
  14443. else if (hostWithoutPort.split('.').length <= 2) {
  14444. domain = hostWithoutPort;
  14445. }
  14446. else {
  14447. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  14448. const dotInd = host.indexOf('.');
  14449. subdomain = host.substring(0, dotInd).toLowerCase();
  14450. domain = host.substring(dotInd + 1);
  14451. // Normalize namespaces to lowercase to share storage / connection.
  14452. namespace = subdomain;
  14453. }
  14454. // Always treat the value of the `ns` as the namespace name if it is present.
  14455. if ('ns' in queryParams) {
  14456. namespace = queryParams['ns'];
  14457. }
  14458. }
  14459. return {
  14460. host,
  14461. port,
  14462. domain,
  14463. subdomain,
  14464. secure,
  14465. scheme,
  14466. pathString,
  14467. namespace
  14468. };
  14469. };
  14470. /**
  14471. * @license
  14472. * Copyright 2017 Google LLC
  14473. *
  14474. * Licensed under the Apache License, Version 2.0 (the "License");
  14475. * you may not use this file except in compliance with the License.
  14476. * You may obtain a copy of the License at
  14477. *
  14478. * http://www.apache.org/licenses/LICENSE-2.0
  14479. *
  14480. * Unless required by applicable law or agreed to in writing, software
  14481. * distributed under the License is distributed on an "AS IS" BASIS,
  14482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14483. * See the License for the specific language governing permissions and
  14484. * limitations under the License.
  14485. */
  14486. // Modeled after base64 web-safe chars, but ordered by ASCII.
  14487. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  14488. /**
  14489. * Fancy ID generator that creates 20-character string identifiers with the
  14490. * following properties:
  14491. *
  14492. * 1. They're based on timestamp so that they sort *after* any existing ids.
  14493. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  14494. * collide with other clients' IDs.
  14495. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  14496. * that will sort properly).
  14497. * 4. They're monotonically increasing. Even if you generate more than one in
  14498. * the same timestamp, the latter ones will sort after the former ones. We do
  14499. * this by using the previous random bits but "incrementing" them by 1 (only
  14500. * in the case of a timestamp collision).
  14501. */
  14502. const nextPushId = (function () {
  14503. // Timestamp of last push, used to prevent local collisions if you push twice
  14504. // in one ms.
  14505. let lastPushTime = 0;
  14506. // We generate 72-bits of randomness which get turned into 12 characters and
  14507. // appended to the timestamp to prevent collisions with other clients. We
  14508. // store the last characters we generated because in the event of a collision,
  14509. // we'll use those same characters except "incremented" by one.
  14510. const lastRandChars = [];
  14511. return function (now) {
  14512. const duplicateTime = now === lastPushTime;
  14513. lastPushTime = now;
  14514. let i;
  14515. const timeStampChars = new Array(8);
  14516. for (i = 7; i >= 0; i--) {
  14517. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  14518. // NOTE: Can't use << here because javascript will convert to int and lose
  14519. // the upper bits.
  14520. now = Math.floor(now / 64);
  14521. }
  14522. util.assert(now === 0, 'Cannot push at time == 0');
  14523. let id = timeStampChars.join('');
  14524. if (!duplicateTime) {
  14525. for (i = 0; i < 12; i++) {
  14526. lastRandChars[i] = Math.floor(Math.random() * 64);
  14527. }
  14528. }
  14529. else {
  14530. // If the timestamp hasn't changed since last push, use the same random
  14531. // number, except incremented by 1.
  14532. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  14533. lastRandChars[i] = 0;
  14534. }
  14535. lastRandChars[i]++;
  14536. }
  14537. for (i = 0; i < 12; i++) {
  14538. id += PUSH_CHARS.charAt(lastRandChars[i]);
  14539. }
  14540. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  14541. return id;
  14542. };
  14543. })();
  14544. /**
  14545. * @license
  14546. * Copyright 2017 Google LLC
  14547. *
  14548. * Licensed under the Apache License, Version 2.0 (the "License");
  14549. * you may not use this file except in compliance with the License.
  14550. * You may obtain a copy of the License at
  14551. *
  14552. * http://www.apache.org/licenses/LICENSE-2.0
  14553. *
  14554. * Unless required by applicable law or agreed to in writing, software
  14555. * distributed under the License is distributed on an "AS IS" BASIS,
  14556. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14557. * See the License for the specific language governing permissions and
  14558. * limitations under the License.
  14559. */
  14560. /**
  14561. * Encapsulates the data needed to raise an event
  14562. */
  14563. class DataEvent {
  14564. /**
  14565. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  14566. * @param eventRegistration - The function to call to with the event data. User provided
  14567. * @param snapshot - The data backing the event
  14568. * @param prevName - Optional, the name of the previous child for child_* events.
  14569. */
  14570. constructor(eventType, eventRegistration, snapshot, prevName) {
  14571. this.eventType = eventType;
  14572. this.eventRegistration = eventRegistration;
  14573. this.snapshot = snapshot;
  14574. this.prevName = prevName;
  14575. }
  14576. getPath() {
  14577. const ref = this.snapshot.ref;
  14578. if (this.eventType === 'value') {
  14579. return ref._path;
  14580. }
  14581. else {
  14582. return ref.parent._path;
  14583. }
  14584. }
  14585. getEventType() {
  14586. return this.eventType;
  14587. }
  14588. getEventRunner() {
  14589. return this.eventRegistration.getEventRunner(this);
  14590. }
  14591. toString() {
  14592. return (this.getPath().toString() +
  14593. ':' +
  14594. this.eventType +
  14595. ':' +
  14596. util.stringify(this.snapshot.exportVal()));
  14597. }
  14598. }
  14599. class CancelEvent {
  14600. constructor(eventRegistration, error, path) {
  14601. this.eventRegistration = eventRegistration;
  14602. this.error = error;
  14603. this.path = path;
  14604. }
  14605. getPath() {
  14606. return this.path;
  14607. }
  14608. getEventType() {
  14609. return 'cancel';
  14610. }
  14611. getEventRunner() {
  14612. return this.eventRegistration.getEventRunner(this);
  14613. }
  14614. toString() {
  14615. return this.path.toString() + ':cancel';
  14616. }
  14617. }
  14618. /**
  14619. * @license
  14620. * Copyright 2017 Google LLC
  14621. *
  14622. * Licensed under the Apache License, Version 2.0 (the "License");
  14623. * you may not use this file except in compliance with the License.
  14624. * You may obtain a copy of the License at
  14625. *
  14626. * http://www.apache.org/licenses/LICENSE-2.0
  14627. *
  14628. * Unless required by applicable law or agreed to in writing, software
  14629. * distributed under the License is distributed on an "AS IS" BASIS,
  14630. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14631. * See the License for the specific language governing permissions and
  14632. * limitations under the License.
  14633. */
  14634. /**
  14635. * A wrapper class that converts events from the database@exp SDK to the legacy
  14636. * Database SDK. Events are not converted directly as event registration relies
  14637. * on reference comparison of the original user callback (see `matches()`) and
  14638. * relies on equality of the legacy SDK's `context` object.
  14639. */
  14640. class CallbackContext {
  14641. constructor(snapshotCallback, cancelCallback) {
  14642. this.snapshotCallback = snapshotCallback;
  14643. this.cancelCallback = cancelCallback;
  14644. }
  14645. onValue(expDataSnapshot, previousChildName) {
  14646. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  14647. }
  14648. onCancel(error) {
  14649. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  14650. return this.cancelCallback.call(null, error);
  14651. }
  14652. get hasCancelCallback() {
  14653. return !!this.cancelCallback;
  14654. }
  14655. matches(other) {
  14656. return (this.snapshotCallback === other.snapshotCallback ||
  14657. (this.snapshotCallback.userCallback !== undefined &&
  14658. this.snapshotCallback.userCallback ===
  14659. other.snapshotCallback.userCallback &&
  14660. this.snapshotCallback.context === other.snapshotCallback.context));
  14661. }
  14662. }
  14663. /**
  14664. * @license
  14665. * Copyright 2021 Google LLC
  14666. *
  14667. * Licensed under the Apache License, Version 2.0 (the "License");
  14668. * you may not use this file except in compliance with the License.
  14669. * You may obtain a copy of the License at
  14670. *
  14671. * http://www.apache.org/licenses/LICENSE-2.0
  14672. *
  14673. * Unless required by applicable law or agreed to in writing, software
  14674. * distributed under the License is distributed on an "AS IS" BASIS,
  14675. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14676. * See the License for the specific language governing permissions and
  14677. * limitations under the License.
  14678. */
  14679. /**
  14680. * The `onDisconnect` class allows you to write or clear data when your client
  14681. * disconnects from the Database server. These updates occur whether your
  14682. * client disconnects cleanly or not, so you can rely on them to clean up data
  14683. * even if a connection is dropped or a client crashes.
  14684. *
  14685. * The `onDisconnect` class is most commonly used to manage presence in
  14686. * applications where it is useful to detect how many clients are connected and
  14687. * when other clients disconnect. See
  14688. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  14689. * for more information.
  14690. *
  14691. * To avoid problems when a connection is dropped before the requests can be
  14692. * transferred to the Database server, these functions should be called before
  14693. * writing any data.
  14694. *
  14695. * Note that `onDisconnect` operations are only triggered once. If you want an
  14696. * operation to occur each time a disconnect occurs, you'll need to re-establish
  14697. * the `onDisconnect` operations each time you reconnect.
  14698. */
  14699. class OnDisconnect$1 {
  14700. /** @hideconstructor */
  14701. constructor(_repo, _path) {
  14702. this._repo = _repo;
  14703. this._path = _path;
  14704. }
  14705. /**
  14706. * Cancels all previously queued `onDisconnect()` set or update events for this
  14707. * location and all children.
  14708. *
  14709. * If a write has been queued for this location via a `set()` or `update()` at a
  14710. * parent location, the write at this location will be canceled, though writes
  14711. * to sibling locations will still occur.
  14712. *
  14713. * @returns Resolves when synchronization to the server is complete.
  14714. */
  14715. cancel() {
  14716. const deferred = new util.Deferred();
  14717. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  14718. return deferred.promise;
  14719. }
  14720. /**
  14721. * Ensures the data at this location is deleted when the client is disconnected
  14722. * (due to closing the browser, navigating to a new page, or network issues).
  14723. *
  14724. * @returns Resolves when synchronization to the server is complete.
  14725. */
  14726. remove() {
  14727. validateWritablePath('OnDisconnect.remove', this._path);
  14728. const deferred = new util.Deferred();
  14729. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  14730. return deferred.promise;
  14731. }
  14732. /**
  14733. * Ensures the data at this location is set to the specified value when the
  14734. * client is disconnected (due to closing the browser, navigating to a new page,
  14735. * or network issues).
  14736. *
  14737. * `set()` is especially useful for implementing "presence" systems, where a
  14738. * value should be changed or cleared when a user disconnects so that they
  14739. * appear "offline" to other users. See
  14740. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  14741. * for more information.
  14742. *
  14743. * Note that `onDisconnect` operations are only triggered once. If you want an
  14744. * operation to occur each time a disconnect occurs, you'll need to re-establish
  14745. * the `onDisconnect` operations each time.
  14746. *
  14747. * @param value - The value to be written to this location on disconnect (can
  14748. * be an object, array, string, number, boolean, or null).
  14749. * @returns Resolves when synchronization to the Database is complete.
  14750. */
  14751. set(value) {
  14752. validateWritablePath('OnDisconnect.set', this._path);
  14753. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  14754. const deferred = new util.Deferred();
  14755. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  14756. return deferred.promise;
  14757. }
  14758. /**
  14759. * Ensures the data at this location is set to the specified value and priority
  14760. * when the client is disconnected (due to closing the browser, navigating to a
  14761. * new page, or network issues).
  14762. *
  14763. * @param value - The value to be written to this location on disconnect (can
  14764. * be an object, array, string, number, boolean, or null).
  14765. * @param priority - The priority to be written (string, number, or null).
  14766. * @returns Resolves when synchronization to the Database is complete.
  14767. */
  14768. setWithPriority(value, priority) {
  14769. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  14770. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  14771. validatePriority('OnDisconnect.setWithPriority', priority, false);
  14772. const deferred = new util.Deferred();
  14773. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  14774. return deferred.promise;
  14775. }
  14776. /**
  14777. * Writes multiple values at this location when the client is disconnected (due
  14778. * to closing the browser, navigating to a new page, or network issues).
  14779. *
  14780. * The `values` argument contains multiple property-value pairs that will be
  14781. * written to the Database together. Each child property can either be a simple
  14782. * property (for example, "name") or a relative path (for example, "name/first")
  14783. * from the current location to the data to update.
  14784. *
  14785. * As opposed to the `set()` method, `update()` can be use to selectively update
  14786. * only the referenced properties at the current location (instead of replacing
  14787. * all the child properties at the current location).
  14788. *
  14789. * @param values - Object containing multiple values.
  14790. * @returns Resolves when synchronization to the Database is complete.
  14791. */
  14792. update(values) {
  14793. validateWritablePath('OnDisconnect.update', this._path);
  14794. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  14795. const deferred = new util.Deferred();
  14796. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  14797. return deferred.promise;
  14798. }
  14799. }
  14800. /**
  14801. * @license
  14802. * Copyright 2020 Google LLC
  14803. *
  14804. * Licensed under the Apache License, Version 2.0 (the "License");
  14805. * you may not use this file except in compliance with the License.
  14806. * You may obtain a copy of the License at
  14807. *
  14808. * http://www.apache.org/licenses/LICENSE-2.0
  14809. *
  14810. * Unless required by applicable law or agreed to in writing, software
  14811. * distributed under the License is distributed on an "AS IS" BASIS,
  14812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14813. * See the License for the specific language governing permissions and
  14814. * limitations under the License.
  14815. */
  14816. /**
  14817. * @internal
  14818. */
  14819. class QueryImpl {
  14820. /**
  14821. * @hideconstructor
  14822. */
  14823. constructor(_repo, _path, _queryParams, _orderByCalled) {
  14824. this._repo = _repo;
  14825. this._path = _path;
  14826. this._queryParams = _queryParams;
  14827. this._orderByCalled = _orderByCalled;
  14828. }
  14829. get key() {
  14830. if (pathIsEmpty(this._path)) {
  14831. return null;
  14832. }
  14833. else {
  14834. return pathGetBack(this._path);
  14835. }
  14836. }
  14837. get ref() {
  14838. return new ReferenceImpl(this._repo, this._path);
  14839. }
  14840. get _queryIdentifier() {
  14841. const obj = queryParamsGetQueryObject(this._queryParams);
  14842. const id = ObjectToUniqueKey(obj);
  14843. return id === '{}' ? 'default' : id;
  14844. }
  14845. /**
  14846. * An object representation of the query parameters used by this Query.
  14847. */
  14848. get _queryObject() {
  14849. return queryParamsGetQueryObject(this._queryParams);
  14850. }
  14851. isEqual(other) {
  14852. other = util.getModularInstance(other);
  14853. if (!(other instanceof QueryImpl)) {
  14854. return false;
  14855. }
  14856. const sameRepo = this._repo === other._repo;
  14857. const samePath = pathEquals(this._path, other._path);
  14858. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  14859. return sameRepo && samePath && sameQueryIdentifier;
  14860. }
  14861. toJSON() {
  14862. return this.toString();
  14863. }
  14864. toString() {
  14865. return this._repo.toString() + pathToUrlEncodedString(this._path);
  14866. }
  14867. }
  14868. /**
  14869. * Validates that no other order by call has been made
  14870. */
  14871. function validateNoPreviousOrderByCall(query, fnName) {
  14872. if (query._orderByCalled === true) {
  14873. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  14874. }
  14875. }
  14876. /**
  14877. * Validates start/end values for queries.
  14878. */
  14879. function validateQueryEndpoints(params) {
  14880. let startNode = null;
  14881. let endNode = null;
  14882. if (params.hasStart()) {
  14883. startNode = params.getIndexStartValue();
  14884. }
  14885. if (params.hasEnd()) {
  14886. endNode = params.getIndexEndValue();
  14887. }
  14888. if (params.getIndex() === KEY_INDEX) {
  14889. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  14890. 'startAt(), endAt(), or equalTo().';
  14891. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  14892. 'endAt(), endBefore(), or equalTo() must be a string.';
  14893. if (params.hasStart()) {
  14894. const startName = params.getIndexStartName();
  14895. if (startName !== MIN_NAME) {
  14896. throw new Error(tooManyArgsError);
  14897. }
  14898. else if (typeof startNode !== 'string') {
  14899. throw new Error(wrongArgTypeError);
  14900. }
  14901. }
  14902. if (params.hasEnd()) {
  14903. const endName = params.getIndexEndName();
  14904. if (endName !== MAX_NAME) {
  14905. throw new Error(tooManyArgsError);
  14906. }
  14907. else if (typeof endNode !== 'string') {
  14908. throw new Error(wrongArgTypeError);
  14909. }
  14910. }
  14911. }
  14912. else if (params.getIndex() === PRIORITY_INDEX) {
  14913. if ((startNode != null && !isValidPriority(startNode)) ||
  14914. (endNode != null && !isValidPriority(endNode))) {
  14915. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  14916. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  14917. '(null, a number, or a string).');
  14918. }
  14919. }
  14920. else {
  14921. util.assert(params.getIndex() instanceof PathIndex ||
  14922. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  14923. if ((startNode != null && typeof startNode === 'object') ||
  14924. (endNode != null && typeof endNode === 'object')) {
  14925. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  14926. 'equalTo() cannot be an object.');
  14927. }
  14928. }
  14929. }
  14930. /**
  14931. * Validates that limit* has been called with the correct combination of parameters
  14932. */
  14933. function validateLimit(params) {
  14934. if (params.hasStart() &&
  14935. params.hasEnd() &&
  14936. params.hasLimit() &&
  14937. !params.hasAnchoredLimit()) {
  14938. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  14939. 'limitToFirst() or limitToLast() instead.');
  14940. }
  14941. }
  14942. /**
  14943. * @internal
  14944. */
  14945. class ReferenceImpl extends QueryImpl {
  14946. /** @hideconstructor */
  14947. constructor(repo, path) {
  14948. super(repo, path, new QueryParams(), false);
  14949. }
  14950. get parent() {
  14951. const parentPath = pathParent(this._path);
  14952. return parentPath === null
  14953. ? null
  14954. : new ReferenceImpl(this._repo, parentPath);
  14955. }
  14956. get root() {
  14957. let ref = this;
  14958. while (ref.parent !== null) {
  14959. ref = ref.parent;
  14960. }
  14961. return ref;
  14962. }
  14963. }
  14964. /**
  14965. * A `DataSnapshot` contains data from a Database location.
  14966. *
  14967. * Any time you read data from the Database, you receive the data as a
  14968. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  14969. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  14970. * JavaScript object by calling the `val()` method. Alternatively, you can
  14971. * traverse into the snapshot by calling `child()` to return child snapshots
  14972. * (which you could then call `val()` on).
  14973. *
  14974. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  14975. * a Database location. It cannot be modified and will never change (to modify
  14976. * data, you always call the `set()` method on a `Reference` directly).
  14977. */
  14978. class DataSnapshot$1 {
  14979. /**
  14980. * @param _node - A SnapshotNode to wrap.
  14981. * @param ref - The location this snapshot came from.
  14982. * @param _index - The iteration order for this snapshot
  14983. * @hideconstructor
  14984. */
  14985. constructor(_node,
  14986. /**
  14987. * The location of this DataSnapshot.
  14988. */
  14989. ref, _index) {
  14990. this._node = _node;
  14991. this.ref = ref;
  14992. this._index = _index;
  14993. }
  14994. /**
  14995. * Gets the priority value of the data in this `DataSnapshot`.
  14996. *
  14997. * Applications need not use priority but can order collections by
  14998. * ordinary properties (see
  14999. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  15000. * ).
  15001. */
  15002. get priority() {
  15003. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  15004. return this._node.getPriority().val();
  15005. }
  15006. /**
  15007. * The key (last part of the path) of the location of this `DataSnapshot`.
  15008. *
  15009. * The last token in a Database location is considered its key. For example,
  15010. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  15011. * `DataSnapshot` will return the key for the location that generated it.
  15012. * However, accessing the key on the root URL of a Database will return
  15013. * `null`.
  15014. */
  15015. get key() {
  15016. return this.ref.key;
  15017. }
  15018. /** Returns the number of child properties of this `DataSnapshot`. */
  15019. get size() {
  15020. return this._node.numChildren();
  15021. }
  15022. /**
  15023. * Gets another `DataSnapshot` for the location at the specified relative path.
  15024. *
  15025. * Passing a relative path to the `child()` method of a DataSnapshot returns
  15026. * another `DataSnapshot` for the location at the specified relative path. The
  15027. * relative path can either be a simple child name (for example, "ada") or a
  15028. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  15029. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  15030. * whose value is `null`) is returned.
  15031. *
  15032. * @param path - A relative path to the location of child data.
  15033. */
  15034. child(path) {
  15035. const childPath = new Path(path);
  15036. const childRef = child(this.ref, path);
  15037. return new DataSnapshot$1(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  15038. }
  15039. /**
  15040. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  15041. * efficient than using `snapshot.val() !== null`.
  15042. */
  15043. exists() {
  15044. return !this._node.isEmpty();
  15045. }
  15046. /**
  15047. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  15048. *
  15049. * The `exportVal()` method is similar to `val()`, except priority information
  15050. * is included (if available), making it suitable for backing up your data.
  15051. *
  15052. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  15053. * Array, string, number, boolean, or `null`).
  15054. */
  15055. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15056. exportVal() {
  15057. return this._node.val(true);
  15058. }
  15059. /**
  15060. * Enumerates the top-level children in the `IteratedDataSnapshot`.
  15061. *
  15062. * Because of the way JavaScript objects work, the ordering of data in the
  15063. * JavaScript object returned by `val()` is not guaranteed to match the
  15064. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  15065. * where `forEach()` comes in handy. It guarantees the children of a
  15066. * `DataSnapshot` will be iterated in their query order.
  15067. *
  15068. * If no explicit `orderBy*()` method is used, results are returned
  15069. * ordered by key (unless priorities are used, in which case, results are
  15070. * returned by priority).
  15071. *
  15072. * @param action - A function that will be called for each child DataSnapshot.
  15073. * The callback can return true to cancel further enumeration.
  15074. * @returns true if enumeration was canceled due to your callback returning
  15075. * true.
  15076. */
  15077. forEach(action) {
  15078. if (this._node.isLeafNode()) {
  15079. return false;
  15080. }
  15081. const childrenNode = this._node;
  15082. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  15083. return !!childrenNode.forEachChild(this._index, (key, node) => {
  15084. return action(new DataSnapshot$1(node, child(this.ref, key), PRIORITY_INDEX));
  15085. });
  15086. }
  15087. /**
  15088. * Returns true if the specified child path has (non-null) data.
  15089. *
  15090. * @param path - A relative path to the location of a potential child.
  15091. * @returns `true` if data exists at the specified child path; else
  15092. * `false`.
  15093. */
  15094. hasChild(path) {
  15095. const childPath = new Path(path);
  15096. return !this._node.getChild(childPath).isEmpty();
  15097. }
  15098. /**
  15099. * Returns whether or not the `DataSnapshot` has any non-`null` child
  15100. * properties.
  15101. *
  15102. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  15103. * children. If it does, you can enumerate them using `forEach()`. If it
  15104. * doesn't, then either this snapshot contains a primitive value (which can be
  15105. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  15106. * `null`).
  15107. *
  15108. * @returns true if this snapshot has any children; else false.
  15109. */
  15110. hasChildren() {
  15111. if (this._node.isLeafNode()) {
  15112. return false;
  15113. }
  15114. else {
  15115. return !this._node.isEmpty();
  15116. }
  15117. }
  15118. /**
  15119. * Returns a JSON-serializable representation of this object.
  15120. */
  15121. toJSON() {
  15122. return this.exportVal();
  15123. }
  15124. /**
  15125. * Extracts a JavaScript value from a `DataSnapshot`.
  15126. *
  15127. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  15128. * scalar type (string, number, or boolean), an array, or an object. It may
  15129. * also return null, indicating that the `DataSnapshot` is empty (contains no
  15130. * data).
  15131. *
  15132. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  15133. * Array, string, number, boolean, or `null`).
  15134. */
  15135. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15136. val() {
  15137. return this._node.val();
  15138. }
  15139. }
  15140. /**
  15141. *
  15142. * Returns a `Reference` representing the location in the Database
  15143. * corresponding to the provided path. If no path is provided, the `Reference`
  15144. * will point to the root of the Database.
  15145. *
  15146. * @param db - The database instance to obtain a reference for.
  15147. * @param path - Optional path representing the location the returned
  15148. * `Reference` will point. If not provided, the returned `Reference` will
  15149. * point to the root of the Database.
  15150. * @returns If a path is provided, a `Reference`
  15151. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  15152. * root of the Database.
  15153. */
  15154. function ref(db, path) {
  15155. db = util.getModularInstance(db);
  15156. db._checkNotDeleted('ref');
  15157. return path !== undefined ? child(db._root, path) : db._root;
  15158. }
  15159. /**
  15160. * Returns a `Reference` representing the location in the Database
  15161. * corresponding to the provided Firebase URL.
  15162. *
  15163. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  15164. * has a different domain than the current `Database` instance.
  15165. *
  15166. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  15167. * and are not applied to the returned `Reference`.
  15168. *
  15169. * @param db - The database instance to obtain a reference for.
  15170. * @param url - The Firebase URL at which the returned `Reference` will
  15171. * point.
  15172. * @returns A `Reference` pointing to the provided
  15173. * Firebase URL.
  15174. */
  15175. function refFromURL(db, url) {
  15176. db = util.getModularInstance(db);
  15177. db._checkNotDeleted('refFromURL');
  15178. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  15179. validateUrl('refFromURL', parsedURL);
  15180. const repoInfo = parsedURL.repoInfo;
  15181. if (!db._repo.repoInfo_.isCustomHost() &&
  15182. repoInfo.host !== db._repo.repoInfo_.host) {
  15183. fatal('refFromURL' +
  15184. ': Host name does not match the current database: ' +
  15185. '(found ' +
  15186. repoInfo.host +
  15187. ' but expected ' +
  15188. db._repo.repoInfo_.host +
  15189. ')');
  15190. }
  15191. return ref(db, parsedURL.path.toString());
  15192. }
  15193. /**
  15194. * Gets a `Reference` for the location at the specified relative path.
  15195. *
  15196. * The relative path can either be a simple child name (for example, "ada") or
  15197. * a deeper slash-separated path (for example, "ada/name/first").
  15198. *
  15199. * @param parent - The parent location.
  15200. * @param path - A relative path from this location to the desired child
  15201. * location.
  15202. * @returns The specified child location.
  15203. */
  15204. function child(parent, path) {
  15205. parent = util.getModularInstance(parent);
  15206. if (pathGetFront(parent._path) === null) {
  15207. validateRootPathString('child', 'path', path, false);
  15208. }
  15209. else {
  15210. validatePathString('child', 'path', path, false);
  15211. }
  15212. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  15213. }
  15214. /**
  15215. * Returns an `OnDisconnect` object - see
  15216. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  15217. * for more information on how to use it.
  15218. *
  15219. * @param ref - The reference to add OnDisconnect triggers for.
  15220. */
  15221. function onDisconnect(ref) {
  15222. ref = util.getModularInstance(ref);
  15223. return new OnDisconnect$1(ref._repo, ref._path);
  15224. }
  15225. /**
  15226. * Generates a new child location using a unique key and returns its
  15227. * `Reference`.
  15228. *
  15229. * This is the most common pattern for adding data to a collection of items.
  15230. *
  15231. * If you provide a value to `push()`, the value is written to the
  15232. * generated location. If you don't pass a value, nothing is written to the
  15233. * database and the child remains empty (but you can use the `Reference`
  15234. * elsewhere).
  15235. *
  15236. * The unique keys generated by `push()` are ordered by the current time, so the
  15237. * resulting list of items is chronologically sorted. The keys are also
  15238. * designed to be unguessable (they contain 72 random bits of entropy).
  15239. *
  15240. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  15241. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  15242. *
  15243. * @param parent - The parent location.
  15244. * @param value - Optional value to be written at the generated location.
  15245. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  15246. * but can be used immediately as the `Reference` to the child location.
  15247. */
  15248. function push(parent, value) {
  15249. parent = util.getModularInstance(parent);
  15250. validateWritablePath('push', parent._path);
  15251. validateFirebaseDataArg('push', value, parent._path, true);
  15252. const now = repoServerTime(parent._repo);
  15253. const name = nextPushId(now);
  15254. // push() returns a ThennableReference whose promise is fulfilled with a
  15255. // regular Reference. We use child() to create handles to two different
  15256. // references. The first is turned into a ThennableReference below by adding
  15257. // then() and catch() methods and is used as the return value of push(). The
  15258. // second remains a regular Reference and is used as the fulfilled value of
  15259. // the first ThennableReference.
  15260. const thenablePushRef = child(parent, name);
  15261. const pushRef = child(parent, name);
  15262. let promise;
  15263. if (value != null) {
  15264. promise = set(pushRef, value).then(() => pushRef);
  15265. }
  15266. else {
  15267. promise = Promise.resolve(pushRef);
  15268. }
  15269. thenablePushRef.then = promise.then.bind(promise);
  15270. thenablePushRef.catch = promise.then.bind(promise, undefined);
  15271. return thenablePushRef;
  15272. }
  15273. /**
  15274. * Removes the data at this Database location.
  15275. *
  15276. * Any data at child locations will also be deleted.
  15277. *
  15278. * The effect of the remove will be visible immediately and the corresponding
  15279. * event 'value' will be triggered. Synchronization of the remove to the
  15280. * Firebase servers will also be started, and the returned Promise will resolve
  15281. * when complete. If provided, the onComplete callback will be called
  15282. * asynchronously after synchronization has finished.
  15283. *
  15284. * @param ref - The location to remove.
  15285. * @returns Resolves when remove on server is complete.
  15286. */
  15287. function remove(ref) {
  15288. validateWritablePath('remove', ref._path);
  15289. return set(ref, null);
  15290. }
  15291. /**
  15292. * Writes data to this Database location.
  15293. *
  15294. * This will overwrite any data at this location and all child locations.
  15295. *
  15296. * The effect of the write will be visible immediately, and the corresponding
  15297. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  15298. * the data to the Firebase servers will also be started, and the returned
  15299. * Promise will resolve when complete. If provided, the `onComplete` callback
  15300. * will be called asynchronously after synchronization has finished.
  15301. *
  15302. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  15303. * all data at this location and all child locations will be deleted.
  15304. *
  15305. * `set()` will remove any priority stored at this location, so if priority is
  15306. * meant to be preserved, you need to use `setWithPriority()` instead.
  15307. *
  15308. * Note that modifying data with `set()` will cancel any pending transactions
  15309. * at that location, so extreme care should be taken if mixing `set()` and
  15310. * `transaction()` to modify the same data.
  15311. *
  15312. * A single `set()` will generate a single "value" event at the location where
  15313. * the `set()` was performed.
  15314. *
  15315. * @param ref - The location to write to.
  15316. * @param value - The value to be written (string, number, boolean, object,
  15317. * array, or null).
  15318. * @returns Resolves when write to server is complete.
  15319. */
  15320. function set(ref, value) {
  15321. ref = util.getModularInstance(ref);
  15322. validateWritablePath('set', ref._path);
  15323. validateFirebaseDataArg('set', value, ref._path, false);
  15324. const deferred = new util.Deferred();
  15325. repoSetWithPriority(ref._repo, ref._path, value,
  15326. /*priority=*/ null, deferred.wrapCallback(() => { }));
  15327. return deferred.promise;
  15328. }
  15329. /**
  15330. * Sets a priority for the data at this Database location.
  15331. *
  15332. * Applications need not use priority but can order collections by
  15333. * ordinary properties (see
  15334. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  15335. * ).
  15336. *
  15337. * @param ref - The location to write to.
  15338. * @param priority - The priority to be written (string, number, or null).
  15339. * @returns Resolves when write to server is complete.
  15340. */
  15341. function setPriority(ref, priority) {
  15342. ref = util.getModularInstance(ref);
  15343. validateWritablePath('setPriority', ref._path);
  15344. validatePriority('setPriority', priority, false);
  15345. const deferred = new util.Deferred();
  15346. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  15347. return deferred.promise;
  15348. }
  15349. /**
  15350. * Writes data the Database location. Like `set()` but also specifies the
  15351. * priority for that data.
  15352. *
  15353. * Applications need not use priority but can order collections by
  15354. * ordinary properties (see
  15355. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  15356. * ).
  15357. *
  15358. * @param ref - The location to write to.
  15359. * @param value - The value to be written (string, number, boolean, object,
  15360. * array, or null).
  15361. * @param priority - The priority to be written (string, number, or null).
  15362. * @returns Resolves when write to server is complete.
  15363. */
  15364. function setWithPriority(ref, value, priority) {
  15365. validateWritablePath('setWithPriority', ref._path);
  15366. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  15367. validatePriority('setWithPriority', priority, false);
  15368. if (ref.key === '.length' || ref.key === '.keys') {
  15369. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  15370. }
  15371. const deferred = new util.Deferred();
  15372. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  15373. return deferred.promise;
  15374. }
  15375. /**
  15376. * Writes multiple values to the Database at once.
  15377. *
  15378. * The `values` argument contains multiple property-value pairs that will be
  15379. * written to the Database together. Each child property can either be a simple
  15380. * property (for example, "name") or a relative path (for example,
  15381. * "name/first") from the current location to the data to update.
  15382. *
  15383. * As opposed to the `set()` method, `update()` can be use to selectively update
  15384. * only the referenced properties at the current location (instead of replacing
  15385. * all the child properties at the current location).
  15386. *
  15387. * The effect of the write will be visible immediately, and the corresponding
  15388. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  15389. * the data to the Firebase servers will also be started, and the returned
  15390. * Promise will resolve when complete. If provided, the `onComplete` callback
  15391. * will be called asynchronously after synchronization has finished.
  15392. *
  15393. * A single `update()` will generate a single "value" event at the location
  15394. * where the `update()` was performed, regardless of how many children were
  15395. * modified.
  15396. *
  15397. * Note that modifying data with `update()` will cancel any pending
  15398. * transactions at that location, so extreme care should be taken if mixing
  15399. * `update()` and `transaction()` to modify the same data.
  15400. *
  15401. * Passing `null` to `update()` will remove the data at this location.
  15402. *
  15403. * See
  15404. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  15405. *
  15406. * @param ref - The location to write to.
  15407. * @param values - Object containing multiple values.
  15408. * @returns Resolves when update on server is complete.
  15409. */
  15410. function update(ref, values) {
  15411. validateFirebaseMergeDataArg('update', values, ref._path, false);
  15412. const deferred = new util.Deferred();
  15413. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  15414. return deferred.promise;
  15415. }
  15416. /**
  15417. * Gets the most up-to-date result for this query.
  15418. *
  15419. * @param query - The query to run.
  15420. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  15421. * available, or rejects if the client is unable to return a value (e.g., if the
  15422. * server is unreachable and there is nothing cached).
  15423. */
  15424. function get(query) {
  15425. query = util.getModularInstance(query);
  15426. const callbackContext = new CallbackContext(() => { });
  15427. const container = new ValueEventRegistration(callbackContext);
  15428. return repoGetValue(query._repo, query, container).then(node => {
  15429. return new DataSnapshot$1(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  15430. });
  15431. }
  15432. /**
  15433. * Represents registration for 'value' events.
  15434. */
  15435. class ValueEventRegistration {
  15436. constructor(callbackContext) {
  15437. this.callbackContext = callbackContext;
  15438. }
  15439. respondsTo(eventType) {
  15440. return eventType === 'value';
  15441. }
  15442. createEvent(change, query) {
  15443. const index = query._queryParams.getIndex();
  15444. return new DataEvent('value', this, new DataSnapshot$1(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  15445. }
  15446. getEventRunner(eventData) {
  15447. if (eventData.getEventType() === 'cancel') {
  15448. return () => this.callbackContext.onCancel(eventData.error);
  15449. }
  15450. else {
  15451. return () => this.callbackContext.onValue(eventData.snapshot, null);
  15452. }
  15453. }
  15454. createCancelEvent(error, path) {
  15455. if (this.callbackContext.hasCancelCallback) {
  15456. return new CancelEvent(this, error, path);
  15457. }
  15458. else {
  15459. return null;
  15460. }
  15461. }
  15462. matches(other) {
  15463. if (!(other instanceof ValueEventRegistration)) {
  15464. return false;
  15465. }
  15466. else if (!other.callbackContext || !this.callbackContext) {
  15467. // If no callback specified, we consider it to match any callback.
  15468. return true;
  15469. }
  15470. else {
  15471. return other.callbackContext.matches(this.callbackContext);
  15472. }
  15473. }
  15474. hasAnyCallback() {
  15475. return this.callbackContext !== null;
  15476. }
  15477. }
  15478. /**
  15479. * Represents the registration of a child_x event.
  15480. */
  15481. class ChildEventRegistration {
  15482. constructor(eventType, callbackContext) {
  15483. this.eventType = eventType;
  15484. this.callbackContext = callbackContext;
  15485. }
  15486. respondsTo(eventType) {
  15487. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  15488. eventToCheck =
  15489. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  15490. return this.eventType === eventToCheck;
  15491. }
  15492. createCancelEvent(error, path) {
  15493. if (this.callbackContext.hasCancelCallback) {
  15494. return new CancelEvent(this, error, path);
  15495. }
  15496. else {
  15497. return null;
  15498. }
  15499. }
  15500. createEvent(change, query) {
  15501. util.assert(change.childName != null, 'Child events should have a childName.');
  15502. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  15503. const index = query._queryParams.getIndex();
  15504. return new DataEvent(change.type, this, new DataSnapshot$1(change.snapshotNode, childRef, index), change.prevName);
  15505. }
  15506. getEventRunner(eventData) {
  15507. if (eventData.getEventType() === 'cancel') {
  15508. return () => this.callbackContext.onCancel(eventData.error);
  15509. }
  15510. else {
  15511. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  15512. }
  15513. }
  15514. matches(other) {
  15515. if (other instanceof ChildEventRegistration) {
  15516. return (this.eventType === other.eventType &&
  15517. (!this.callbackContext ||
  15518. !other.callbackContext ||
  15519. this.callbackContext.matches(other.callbackContext)));
  15520. }
  15521. return false;
  15522. }
  15523. hasAnyCallback() {
  15524. return !!this.callbackContext;
  15525. }
  15526. }
  15527. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  15528. let cancelCallback;
  15529. if (typeof cancelCallbackOrListenOptions === 'object') {
  15530. cancelCallback = undefined;
  15531. options = cancelCallbackOrListenOptions;
  15532. }
  15533. if (typeof cancelCallbackOrListenOptions === 'function') {
  15534. cancelCallback = cancelCallbackOrListenOptions;
  15535. }
  15536. if (options && options.onlyOnce) {
  15537. const userCallback = callback;
  15538. const onceCallback = (dataSnapshot, previousChildName) => {
  15539. repoRemoveEventCallbackForQuery(query._repo, query, container);
  15540. userCallback(dataSnapshot, previousChildName);
  15541. };
  15542. onceCallback.userCallback = callback.userCallback;
  15543. onceCallback.context = callback.context;
  15544. callback = onceCallback;
  15545. }
  15546. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  15547. const container = eventType === 'value'
  15548. ? new ValueEventRegistration(callbackContext)
  15549. : new ChildEventRegistration(eventType, callbackContext);
  15550. repoAddEventCallbackForQuery(query._repo, query, container);
  15551. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  15552. }
  15553. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  15554. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  15555. }
  15556. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  15557. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  15558. }
  15559. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  15560. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  15561. }
  15562. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  15563. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  15564. }
  15565. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  15566. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  15567. }
  15568. /**
  15569. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  15570. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  15571. * the respective `on*` callbacks.
  15572. *
  15573. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  15574. * will not automatically remove listeners registered on child nodes, `off()`
  15575. * must also be called on any child listeners to remove the callback.
  15576. *
  15577. * If a callback is not specified, all callbacks for the specified eventType
  15578. * will be removed. Similarly, if no eventType is specified, all callbacks
  15579. * for the `Reference` will be removed.
  15580. *
  15581. * Individual listeners can also be removed by invoking their unsubscribe
  15582. * callbacks.
  15583. *
  15584. * @param query - The query that the listener was registered with.
  15585. * @param eventType - One of the following strings: "value", "child_added",
  15586. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  15587. * for the `Reference` will be removed.
  15588. * @param callback - The callback function that was passed to `on()` or
  15589. * `undefined` to remove all callbacks.
  15590. */
  15591. function off(query, eventType, callback) {
  15592. let container = null;
  15593. const expCallback = callback ? new CallbackContext(callback) : null;
  15594. if (eventType === 'value') {
  15595. container = new ValueEventRegistration(expCallback);
  15596. }
  15597. else if (eventType) {
  15598. container = new ChildEventRegistration(eventType, expCallback);
  15599. }
  15600. repoRemoveEventCallbackForQuery(query._repo, query, container);
  15601. }
  15602. /**
  15603. * A `QueryConstraint` is used to narrow the set of documents returned by a
  15604. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  15605. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  15606. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  15607. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  15608. * {@link orderByValue} or {@link equalTo} and
  15609. * can then be passed to {@link query} to create a new query instance that
  15610. * also contains this `QueryConstraint`.
  15611. */
  15612. class QueryConstraint {
  15613. }
  15614. class QueryEndAtConstraint extends QueryConstraint {
  15615. constructor(_value, _key) {
  15616. super();
  15617. this._value = _value;
  15618. this._key = _key;
  15619. this.type = 'endAt';
  15620. }
  15621. _apply(query) {
  15622. validateFirebaseDataArg('endAt', this._value, query._path, true);
  15623. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  15624. validateLimit(newParams);
  15625. validateQueryEndpoints(newParams);
  15626. if (query._queryParams.hasEnd()) {
  15627. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  15628. 'endBefore or equalTo).');
  15629. }
  15630. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  15631. }
  15632. }
  15633. /**
  15634. * Creates a `QueryConstraint` with the specified ending point.
  15635. *
  15636. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  15637. * allows you to choose arbitrary starting and ending points for your queries.
  15638. *
  15639. * The ending point is inclusive, so children with exactly the specified value
  15640. * will be included in the query. The optional key argument can be used to
  15641. * further limit the range of the query. If it is specified, then children that
  15642. * have exactly the specified value must also have a key name less than or equal
  15643. * to the specified key.
  15644. *
  15645. * You can read more about `endAt()` in
  15646. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  15647. *
  15648. * @param value - The value to end at. The argument type depends on which
  15649. * `orderBy*()` function was used in this query. Specify a value that matches
  15650. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  15651. * value must be a string.
  15652. * @param key - The child key to end at, among the children with the previously
  15653. * specified priority. This argument is only allowed if ordering by child,
  15654. * value, or priority.
  15655. */
  15656. function endAt(value, key) {
  15657. validateKey('endAt', 'key', key, true);
  15658. return new QueryEndAtConstraint(value, key);
  15659. }
  15660. class QueryEndBeforeConstraint extends QueryConstraint {
  15661. constructor(_value, _key) {
  15662. super();
  15663. this._value = _value;
  15664. this._key = _key;
  15665. this.type = 'endBefore';
  15666. }
  15667. _apply(query) {
  15668. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  15669. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  15670. validateLimit(newParams);
  15671. validateQueryEndpoints(newParams);
  15672. if (query._queryParams.hasEnd()) {
  15673. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  15674. 'endBefore or equalTo).');
  15675. }
  15676. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  15677. }
  15678. }
  15679. /**
  15680. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  15681. *
  15682. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  15683. * allows you to choose arbitrary starting and ending points for your queries.
  15684. *
  15685. * The ending point is exclusive. If only a value is provided, children
  15686. * with a value less than the specified value will be included in the query.
  15687. * If a key is specified, then children must have a value less than or equal
  15688. * to the specified value and a key name less than the specified key.
  15689. *
  15690. * @param value - The value to end before. The argument type depends on which
  15691. * `orderBy*()` function was used in this query. Specify a value that matches
  15692. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  15693. * value must be a string.
  15694. * @param key - The child key to end before, among the children with the
  15695. * previously specified priority. This argument is only allowed if ordering by
  15696. * child, value, or priority.
  15697. */
  15698. function endBefore(value, key) {
  15699. validateKey('endBefore', 'key', key, true);
  15700. return new QueryEndBeforeConstraint(value, key);
  15701. }
  15702. class QueryStartAtConstraint extends QueryConstraint {
  15703. constructor(_value, _key) {
  15704. super();
  15705. this._value = _value;
  15706. this._key = _key;
  15707. this.type = 'startAt';
  15708. }
  15709. _apply(query) {
  15710. validateFirebaseDataArg('startAt', this._value, query._path, true);
  15711. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  15712. validateLimit(newParams);
  15713. validateQueryEndpoints(newParams);
  15714. if (query._queryParams.hasStart()) {
  15715. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  15716. 'startBefore or equalTo).');
  15717. }
  15718. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  15719. }
  15720. }
  15721. /**
  15722. * Creates a `QueryConstraint` with the specified starting point.
  15723. *
  15724. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  15725. * allows you to choose arbitrary starting and ending points for your queries.
  15726. *
  15727. * The starting point is inclusive, so children with exactly the specified value
  15728. * will be included in the query. The optional key argument can be used to
  15729. * further limit the range of the query. If it is specified, then children that
  15730. * have exactly the specified value must also have a key name greater than or
  15731. * equal to the specified key.
  15732. *
  15733. * You can read more about `startAt()` in
  15734. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  15735. *
  15736. * @param value - The value to start at. The argument type depends on which
  15737. * `orderBy*()` function was used in this query. Specify a value that matches
  15738. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  15739. * value must be a string.
  15740. * @param key - The child key to start at. This argument is only allowed if
  15741. * ordering by child, value, or priority.
  15742. */
  15743. function startAt(value = null, key) {
  15744. validateKey('startAt', 'key', key, true);
  15745. return new QueryStartAtConstraint(value, key);
  15746. }
  15747. class QueryStartAfterConstraint extends QueryConstraint {
  15748. constructor(_value, _key) {
  15749. super();
  15750. this._value = _value;
  15751. this._key = _key;
  15752. this.type = 'startAfter';
  15753. }
  15754. _apply(query) {
  15755. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  15756. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  15757. validateLimit(newParams);
  15758. validateQueryEndpoints(newParams);
  15759. if (query._queryParams.hasStart()) {
  15760. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  15761. 'startAfter, or equalTo).');
  15762. }
  15763. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  15764. }
  15765. }
  15766. /**
  15767. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  15768. *
  15769. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  15770. * allows you to choose arbitrary starting and ending points for your queries.
  15771. *
  15772. * The starting point is exclusive. If only a value is provided, children
  15773. * with a value greater than the specified value will be included in the query.
  15774. * If a key is specified, then children must have a value greater than or equal
  15775. * to the specified value and a a key name greater than the specified key.
  15776. *
  15777. * @param value - The value to start after. The argument type depends on which
  15778. * `orderBy*()` function was used in this query. Specify a value that matches
  15779. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  15780. * value must be a string.
  15781. * @param key - The child key to start after. This argument is only allowed if
  15782. * ordering by child, value, or priority.
  15783. */
  15784. function startAfter(value, key) {
  15785. validateKey('startAfter', 'key', key, true);
  15786. return new QueryStartAfterConstraint(value, key);
  15787. }
  15788. class QueryLimitToFirstConstraint extends QueryConstraint {
  15789. constructor(_limit) {
  15790. super();
  15791. this._limit = _limit;
  15792. this.type = 'limitToFirst';
  15793. }
  15794. _apply(query) {
  15795. if (query._queryParams.hasLimit()) {
  15796. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  15797. 'or limitToLast).');
  15798. }
  15799. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  15800. }
  15801. }
  15802. /**
  15803. * Creates a new `QueryConstraint` that if limited to the first specific number
  15804. * of children.
  15805. *
  15806. * The `limitToFirst()` method is used to set a maximum number of children to be
  15807. * synced for a given callback. If we set a limit of 100, we will initially only
  15808. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  15809. * stored in our Database, a `child_added` event will fire for each message.
  15810. * However, if we have over 100 messages, we will only receive a `child_added`
  15811. * event for the first 100 ordered messages. As items change, we will receive
  15812. * `child_removed` events for each item that drops out of the active list so
  15813. * that the total number stays at 100.
  15814. *
  15815. * You can read more about `limitToFirst()` in
  15816. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  15817. *
  15818. * @param limit - The maximum number of nodes to include in this query.
  15819. */
  15820. function limitToFirst(limit) {
  15821. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  15822. throw new Error('limitToFirst: First argument must be a positive integer.');
  15823. }
  15824. return new QueryLimitToFirstConstraint(limit);
  15825. }
  15826. class QueryLimitToLastConstraint extends QueryConstraint {
  15827. constructor(_limit) {
  15828. super();
  15829. this._limit = _limit;
  15830. this.type = 'limitToLast';
  15831. }
  15832. _apply(query) {
  15833. if (query._queryParams.hasLimit()) {
  15834. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  15835. 'or limitToLast).');
  15836. }
  15837. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  15838. }
  15839. }
  15840. /**
  15841. * Creates a new `QueryConstraint` that is limited to return only the last
  15842. * specified number of children.
  15843. *
  15844. * The `limitToLast()` method is used to set a maximum number of children to be
  15845. * synced for a given callback. If we set a limit of 100, we will initially only
  15846. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  15847. * stored in our Database, a `child_added` event will fire for each message.
  15848. * However, if we have over 100 messages, we will only receive a `child_added`
  15849. * event for the last 100 ordered messages. As items change, we will receive
  15850. * `child_removed` events for each item that drops out of the active list so
  15851. * that the total number stays at 100.
  15852. *
  15853. * You can read more about `limitToLast()` in
  15854. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  15855. *
  15856. * @param limit - The maximum number of nodes to include in this query.
  15857. */
  15858. function limitToLast(limit) {
  15859. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  15860. throw new Error('limitToLast: First argument must be a positive integer.');
  15861. }
  15862. return new QueryLimitToLastConstraint(limit);
  15863. }
  15864. class QueryOrderByChildConstraint extends QueryConstraint {
  15865. constructor(_path) {
  15866. super();
  15867. this._path = _path;
  15868. this.type = 'orderByChild';
  15869. }
  15870. _apply(query) {
  15871. validateNoPreviousOrderByCall(query, 'orderByChild');
  15872. const parsedPath = new Path(this._path);
  15873. if (pathIsEmpty(parsedPath)) {
  15874. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  15875. }
  15876. const index = new PathIndex(parsedPath);
  15877. const newParams = queryParamsOrderBy(query._queryParams, index);
  15878. validateQueryEndpoints(newParams);
  15879. return new QueryImpl(query._repo, query._path, newParams,
  15880. /*orderByCalled=*/ true);
  15881. }
  15882. }
  15883. /**
  15884. * Creates a new `QueryConstraint` that orders by the specified child key.
  15885. *
  15886. * Queries can only order by one key at a time. Calling `orderByChild()`
  15887. * multiple times on the same query is an error.
  15888. *
  15889. * Firebase queries allow you to order your data by any child key on the fly.
  15890. * However, if you know in advance what your indexes will be, you can define
  15891. * them via the .indexOn rule in your Security Rules for better performance. See
  15892. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  15893. * rule for more information.
  15894. *
  15895. * You can read more about `orderByChild()` in
  15896. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  15897. *
  15898. * @param path - The path to order by.
  15899. */
  15900. function orderByChild(path) {
  15901. if (path === '$key') {
  15902. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  15903. }
  15904. else if (path === '$priority') {
  15905. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  15906. }
  15907. else if (path === '$value') {
  15908. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  15909. }
  15910. validatePathString('orderByChild', 'path', path, false);
  15911. return new QueryOrderByChildConstraint(path);
  15912. }
  15913. class QueryOrderByKeyConstraint extends QueryConstraint {
  15914. constructor() {
  15915. super(...arguments);
  15916. this.type = 'orderByKey';
  15917. }
  15918. _apply(query) {
  15919. validateNoPreviousOrderByCall(query, 'orderByKey');
  15920. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  15921. validateQueryEndpoints(newParams);
  15922. return new QueryImpl(query._repo, query._path, newParams,
  15923. /*orderByCalled=*/ true);
  15924. }
  15925. }
  15926. /**
  15927. * Creates a new `QueryConstraint` that orders by the key.
  15928. *
  15929. * Sorts the results of a query by their (ascending) key values.
  15930. *
  15931. * You can read more about `orderByKey()` in
  15932. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  15933. */
  15934. function orderByKey() {
  15935. return new QueryOrderByKeyConstraint();
  15936. }
  15937. class QueryOrderByPriorityConstraint extends QueryConstraint {
  15938. constructor() {
  15939. super(...arguments);
  15940. this.type = 'orderByPriority';
  15941. }
  15942. _apply(query) {
  15943. validateNoPreviousOrderByCall(query, 'orderByPriority');
  15944. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  15945. validateQueryEndpoints(newParams);
  15946. return new QueryImpl(query._repo, query._path, newParams,
  15947. /*orderByCalled=*/ true);
  15948. }
  15949. }
  15950. /**
  15951. * Creates a new `QueryConstraint` that orders by priority.
  15952. *
  15953. * Applications need not use priority but can order collections by
  15954. * ordinary properties (see
  15955. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  15956. * for alternatives to priority.
  15957. */
  15958. function orderByPriority() {
  15959. return new QueryOrderByPriorityConstraint();
  15960. }
  15961. class QueryOrderByValueConstraint extends QueryConstraint {
  15962. constructor() {
  15963. super(...arguments);
  15964. this.type = 'orderByValue';
  15965. }
  15966. _apply(query) {
  15967. validateNoPreviousOrderByCall(query, 'orderByValue');
  15968. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  15969. validateQueryEndpoints(newParams);
  15970. return new QueryImpl(query._repo, query._path, newParams,
  15971. /*orderByCalled=*/ true);
  15972. }
  15973. }
  15974. /**
  15975. * Creates a new `QueryConstraint` that orders by value.
  15976. *
  15977. * If the children of a query are all scalar values (string, number, or
  15978. * boolean), you can order the results by their (ascending) values.
  15979. *
  15980. * You can read more about `orderByValue()` in
  15981. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  15982. */
  15983. function orderByValue() {
  15984. return new QueryOrderByValueConstraint();
  15985. }
  15986. class QueryEqualToValueConstraint extends QueryConstraint {
  15987. constructor(_value, _key) {
  15988. super();
  15989. this._value = _value;
  15990. this._key = _key;
  15991. this.type = 'equalTo';
  15992. }
  15993. _apply(query) {
  15994. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  15995. if (query._queryParams.hasStart()) {
  15996. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  15997. 'equalTo).');
  15998. }
  15999. if (query._queryParams.hasEnd()) {
  16000. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  16001. 'equalTo).');
  16002. }
  16003. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  16004. }
  16005. }
  16006. /**
  16007. * Creates a `QueryConstraint` that includes children that match the specified
  16008. * value.
  16009. *
  16010. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  16011. * allows you to choose arbitrary starting and ending points for your queries.
  16012. *
  16013. * The optional key argument can be used to further limit the range of the
  16014. * query. If it is specified, then children that have exactly the specified
  16015. * value must also have exactly the specified key as their key name. This can be
  16016. * used to filter result sets with many matches for the same value.
  16017. *
  16018. * You can read more about `equalTo()` in
  16019. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  16020. *
  16021. * @param value - The value to match for. The argument type depends on which
  16022. * `orderBy*()` function was used in this query. Specify a value that matches
  16023. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  16024. * value must be a string.
  16025. * @param key - The child key to start at, among the children with the
  16026. * previously specified priority. This argument is only allowed if ordering by
  16027. * child, value, or priority.
  16028. */
  16029. function equalTo(value, key) {
  16030. validateKey('equalTo', 'key', key, true);
  16031. return new QueryEqualToValueConstraint(value, key);
  16032. }
  16033. /**
  16034. * Creates a new immutable instance of `Query` that is extended to also include
  16035. * additional query constraints.
  16036. *
  16037. * @param query - The Query instance to use as a base for the new constraints.
  16038. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  16039. * @throws if any of the provided query constraints cannot be combined with the
  16040. * existing or new constraints.
  16041. */
  16042. function query(query, ...queryConstraints) {
  16043. let queryImpl = util.getModularInstance(query);
  16044. for (const constraint of queryConstraints) {
  16045. queryImpl = constraint._apply(queryImpl);
  16046. }
  16047. return queryImpl;
  16048. }
  16049. /**
  16050. * Define reference constructor in various modules
  16051. *
  16052. * We are doing this here to avoid several circular
  16053. * dependency issues
  16054. */
  16055. syncPointSetReferenceConstructor(ReferenceImpl);
  16056. syncTreeSetReferenceConstructor(ReferenceImpl);
  16057. /**
  16058. * @license
  16059. * Copyright 2020 Google LLC
  16060. *
  16061. * Licensed under the Apache License, Version 2.0 (the "License");
  16062. * you may not use this file except in compliance with the License.
  16063. * You may obtain a copy of the License at
  16064. *
  16065. * http://www.apache.org/licenses/LICENSE-2.0
  16066. *
  16067. * Unless required by applicable law or agreed to in writing, software
  16068. * distributed under the License is distributed on an "AS IS" BASIS,
  16069. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16070. * See the License for the specific language governing permissions and
  16071. * limitations under the License.
  16072. */
  16073. /**
  16074. * This variable is also defined in the firebase Node.js Admin SDK. Before
  16075. * modifying this definition, consult the definition in:
  16076. *
  16077. * https://github.com/firebase/firebase-admin-node
  16078. *
  16079. * and make sure the two are consistent.
  16080. */
  16081. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  16082. /**
  16083. * Creates and caches `Repo` instances.
  16084. */
  16085. const repos = {};
  16086. /**
  16087. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  16088. */
  16089. let useRestClient = false;
  16090. /**
  16091. * Update an existing `Repo` in place to point to a new host/port.
  16092. */
  16093. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  16094. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  16095. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  16096. /*isUsingEmulator=*/ true);
  16097. if (tokenProvider) {
  16098. repo.authTokenProvider_ = tokenProvider;
  16099. }
  16100. }
  16101. /**
  16102. * This function should only ever be called to CREATE a new database instance.
  16103. * @internal
  16104. */
  16105. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  16106. let dbUrl = url || app.options.databaseURL;
  16107. if (dbUrl === undefined) {
  16108. if (!app.options.projectId) {
  16109. fatal("Can't determine Firebase Database URL. Be sure to include " +
  16110. ' a Project ID when calling firebase.initializeApp().');
  16111. }
  16112. log('Using default host for project ', app.options.projectId);
  16113. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  16114. }
  16115. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  16116. let repoInfo = parsedUrl.repoInfo;
  16117. let isEmulator;
  16118. let dbEmulatorHost = undefined;
  16119. if (typeof process !== 'undefined' && process.env) {
  16120. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  16121. }
  16122. if (dbEmulatorHost) {
  16123. isEmulator = true;
  16124. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  16125. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  16126. repoInfo = parsedUrl.repoInfo;
  16127. }
  16128. else {
  16129. isEmulator = !parsedUrl.repoInfo.secure;
  16130. }
  16131. const authTokenProvider = nodeAdmin && isEmulator
  16132. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  16133. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  16134. validateUrl('Invalid Firebase Database URL', parsedUrl);
  16135. if (!pathIsEmpty(parsedUrl.path)) {
  16136. fatal('Database URL must point to the root of a Firebase Database ' +
  16137. '(not including a child path).');
  16138. }
  16139. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  16140. return new Database$1(repo, app);
  16141. }
  16142. /**
  16143. * Remove the repo and make sure it is disconnected.
  16144. *
  16145. */
  16146. function repoManagerDeleteRepo(repo, appName) {
  16147. const appRepos = repos[appName];
  16148. // This should never happen...
  16149. if (!appRepos || appRepos[repo.key] !== repo) {
  16150. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  16151. }
  16152. repoInterrupt(repo);
  16153. delete appRepos[repo.key];
  16154. }
  16155. /**
  16156. * Ensures a repo doesn't already exist and then creates one using the
  16157. * provided app.
  16158. *
  16159. * @param repoInfo - The metadata about the Repo
  16160. * @returns The Repo object for the specified server / repoName.
  16161. */
  16162. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  16163. let appRepos = repos[app.name];
  16164. if (!appRepos) {
  16165. appRepos = {};
  16166. repos[app.name] = appRepos;
  16167. }
  16168. let repo = appRepos[repoInfo.toURLString()];
  16169. if (repo) {
  16170. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  16171. }
  16172. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  16173. appRepos[repoInfo.toURLString()] = repo;
  16174. return repo;
  16175. }
  16176. /**
  16177. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  16178. */
  16179. function repoManagerForceRestClient(forceRestClient) {
  16180. useRestClient = forceRestClient;
  16181. }
  16182. /**
  16183. * Class representing a Firebase Realtime Database.
  16184. */
  16185. class Database$1 {
  16186. /** @hideconstructor */
  16187. constructor(_repoInternal,
  16188. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  16189. app) {
  16190. this._repoInternal = _repoInternal;
  16191. this.app = app;
  16192. /** Represents a `Database` instance. */
  16193. this['type'] = 'database';
  16194. /** Track if the instance has been used (root or repo accessed) */
  16195. this._instanceStarted = false;
  16196. }
  16197. get _repo() {
  16198. if (!this._instanceStarted) {
  16199. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  16200. this._instanceStarted = true;
  16201. }
  16202. return this._repoInternal;
  16203. }
  16204. get _root() {
  16205. if (!this._rootInternal) {
  16206. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  16207. }
  16208. return this._rootInternal;
  16209. }
  16210. _delete() {
  16211. if (this._rootInternal !== null) {
  16212. repoManagerDeleteRepo(this._repo, this.app.name);
  16213. this._repoInternal = null;
  16214. this._rootInternal = null;
  16215. }
  16216. return Promise.resolve();
  16217. }
  16218. _checkNotDeleted(apiName) {
  16219. if (this._rootInternal === null) {
  16220. fatal('Cannot call ' + apiName + ' on a deleted database.');
  16221. }
  16222. }
  16223. }
  16224. function checkTransportInit() {
  16225. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  16226. warn$1('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  16227. }
  16228. }
  16229. /**
  16230. * Force the use of websockets instead of longPolling.
  16231. */
  16232. function forceWebSockets() {
  16233. checkTransportInit();
  16234. BrowserPollConnection.forceDisallow();
  16235. }
  16236. /**
  16237. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  16238. */
  16239. function forceLongPolling() {
  16240. checkTransportInit();
  16241. WebSocketConnection.forceDisallow();
  16242. BrowserPollConnection.forceAllow();
  16243. }
  16244. /**
  16245. * Modify the provided instance to communicate with the Realtime Database
  16246. * emulator.
  16247. *
  16248. * <p>Note: This method must be called before performing any other operation.
  16249. *
  16250. * @param db - The instance to modify.
  16251. * @param host - The emulator host (ex: localhost)
  16252. * @param port - The emulator port (ex: 8080)
  16253. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  16254. */
  16255. function connectDatabaseEmulator(db, host, port, options = {}) {
  16256. db = util.getModularInstance(db);
  16257. db._checkNotDeleted('useEmulator');
  16258. if (db._instanceStarted) {
  16259. fatal('Cannot call useEmulator() after instance has already been initialized.');
  16260. }
  16261. const repo = db._repoInternal;
  16262. let tokenProvider = undefined;
  16263. if (repo.repoInfo_.nodeAdmin) {
  16264. if (options.mockUserToken) {
  16265. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  16266. }
  16267. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  16268. }
  16269. else if (options.mockUserToken) {
  16270. const token = typeof options.mockUserToken === 'string'
  16271. ? options.mockUserToken
  16272. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  16273. tokenProvider = new EmulatorTokenProvider(token);
  16274. }
  16275. // Modify the repo to apply emulator settings
  16276. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  16277. }
  16278. /**
  16279. * Disconnects from the server (all Database operations will be completed
  16280. * offline).
  16281. *
  16282. * The client automatically maintains a persistent connection to the Database
  16283. * server, which will remain active indefinitely and reconnect when
  16284. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  16285. * to control the client connection in cases where a persistent connection is
  16286. * undesirable.
  16287. *
  16288. * While offline, the client will no longer receive data updates from the
  16289. * Database. However, all Database operations performed locally will continue to
  16290. * immediately fire events, allowing your application to continue behaving
  16291. * normally. Additionally, each operation performed locally will automatically
  16292. * be queued and retried upon reconnection to the Database server.
  16293. *
  16294. * To reconnect to the Database and begin receiving remote events, see
  16295. * `goOnline()`.
  16296. *
  16297. * @param db - The instance to disconnect.
  16298. */
  16299. function goOffline(db) {
  16300. db = util.getModularInstance(db);
  16301. db._checkNotDeleted('goOffline');
  16302. repoInterrupt(db._repo);
  16303. }
  16304. /**
  16305. * Reconnects to the server and synchronizes the offline Database state
  16306. * with the server state.
  16307. *
  16308. * This method should be used after disabling the active connection with
  16309. * `goOffline()`. Once reconnected, the client will transmit the proper data
  16310. * and fire the appropriate events so that your client "catches up"
  16311. * automatically.
  16312. *
  16313. * @param db - The instance to reconnect.
  16314. */
  16315. function goOnline(db) {
  16316. db = util.getModularInstance(db);
  16317. db._checkNotDeleted('goOnline');
  16318. repoResume(db._repo);
  16319. }
  16320. function enableLogging(logger, persistent) {
  16321. enableLogging$1(logger, persistent);
  16322. }
  16323. /**
  16324. * @license
  16325. * Copyright 2020 Google LLC
  16326. *
  16327. * Licensed under the Apache License, Version 2.0 (the "License");
  16328. * you may not use this file except in compliance with the License.
  16329. * You may obtain a copy of the License at
  16330. *
  16331. * http://www.apache.org/licenses/LICENSE-2.0
  16332. *
  16333. * Unless required by applicable law or agreed to in writing, software
  16334. * distributed under the License is distributed on an "AS IS" BASIS,
  16335. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16336. * See the License for the specific language governing permissions and
  16337. * limitations under the License.
  16338. */
  16339. const SERVER_TIMESTAMP = {
  16340. '.sv': 'timestamp'
  16341. };
  16342. /**
  16343. * Returns a placeholder value for auto-populating the current timestamp (time
  16344. * since the Unix epoch, in milliseconds) as determined by the Firebase
  16345. * servers.
  16346. */
  16347. function serverTimestamp() {
  16348. return SERVER_TIMESTAMP;
  16349. }
  16350. /**
  16351. * Returns a placeholder value that can be used to atomically increment the
  16352. * current database value by the provided delta.
  16353. *
  16354. * @param delta - the amount to modify the current value atomically.
  16355. * @returns A placeholder value for modifying data atomically server-side.
  16356. */
  16357. function increment(delta) {
  16358. return {
  16359. '.sv': {
  16360. 'increment': delta
  16361. }
  16362. };
  16363. }
  16364. /**
  16365. * @license
  16366. * Copyright 2020 Google LLC
  16367. *
  16368. * Licensed under the Apache License, Version 2.0 (the "License");
  16369. * you may not use this file except in compliance with the License.
  16370. * You may obtain a copy of the License at
  16371. *
  16372. * http://www.apache.org/licenses/LICENSE-2.0
  16373. *
  16374. * Unless required by applicable law or agreed to in writing, software
  16375. * distributed under the License is distributed on an "AS IS" BASIS,
  16376. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16377. * See the License for the specific language governing permissions and
  16378. * limitations under the License.
  16379. */
  16380. /**
  16381. * A type for the resolve value of {@link runTransaction}.
  16382. */
  16383. class TransactionResult$1 {
  16384. /** @hideconstructor */
  16385. constructor(
  16386. /** Whether the transaction was successfully committed. */
  16387. committed,
  16388. /** The resulting data snapshot. */
  16389. snapshot) {
  16390. this.committed = committed;
  16391. this.snapshot = snapshot;
  16392. }
  16393. /** Returns a JSON-serializable representation of this object. */
  16394. toJSON() {
  16395. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  16396. }
  16397. }
  16398. /**
  16399. * Atomically modifies the data at this location.
  16400. *
  16401. * Atomically modify the data at this location. Unlike a normal `set()`, which
  16402. * just overwrites the data regardless of its previous value, `runTransaction()` is
  16403. * used to modify the existing value to a new value, ensuring there are no
  16404. * conflicts with other clients writing to the same location at the same time.
  16405. *
  16406. * To accomplish this, you pass `runTransaction()` an update function which is
  16407. * used to transform the current value into a new value. If another client
  16408. * writes to the location before your new value is successfully written, your
  16409. * update function will be called again with the new current value, and the
  16410. * write will be retried. This will happen repeatedly until your write succeeds
  16411. * without conflict or you abort the transaction by not returning a value from
  16412. * your update function.
  16413. *
  16414. * Note: Modifying data with `set()` will cancel any pending transactions at
  16415. * that location, so extreme care should be taken if mixing `set()` and
  16416. * `runTransaction()` to update the same data.
  16417. *
  16418. * Note: When using transactions with Security and Firebase Rules in place, be
  16419. * aware that a client needs `.read` access in addition to `.write` access in
  16420. * order to perform a transaction. This is because the client-side nature of
  16421. * transactions requires the client to read the data in order to transactionally
  16422. * update it.
  16423. *
  16424. * @param ref - The location to atomically modify.
  16425. * @param transactionUpdate - A developer-supplied function which will be passed
  16426. * the current data stored at this location (as a JavaScript object). The
  16427. * function should return the new value it would like written (as a JavaScript
  16428. * object). If `undefined` is returned (i.e. you return with no arguments) the
  16429. * transaction will be aborted and the data at this location will not be
  16430. * modified.
  16431. * @param options - An options object to configure transactions.
  16432. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  16433. * callback to handle success and failure.
  16434. */
  16435. function runTransaction(ref,
  16436. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16437. transactionUpdate, options) {
  16438. var _a;
  16439. ref = util.getModularInstance(ref);
  16440. validateWritablePath('Reference.transaction', ref._path);
  16441. if (ref.key === '.length' || ref.key === '.keys') {
  16442. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  16443. }
  16444. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  16445. const deferred = new util.Deferred();
  16446. const promiseComplete = (error, committed, node) => {
  16447. let dataSnapshot = null;
  16448. if (error) {
  16449. deferred.reject(error);
  16450. }
  16451. else {
  16452. dataSnapshot = new DataSnapshot$1(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  16453. deferred.resolve(new TransactionResult$1(committed, dataSnapshot));
  16454. }
  16455. };
  16456. // Add a watch to make sure we get server updates.
  16457. const unwatcher = onValue(ref, () => { });
  16458. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  16459. return deferred.promise;
  16460. }
  16461. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16462. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  16463. this.sendRequest('q', { p: pathString }, onComplete);
  16464. };
  16465. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16466. PersistentConnection.prototype.echo = function (data, onEcho) {
  16467. this.sendRequest('echo', { d: data }, onEcho);
  16468. };
  16469. /**
  16470. * @internal
  16471. */
  16472. const hijackHash = function (newHash) {
  16473. const oldPut = PersistentConnection.prototype.put;
  16474. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  16475. if (hash !== undefined) {
  16476. hash = newHash();
  16477. }
  16478. oldPut.call(this, pathString, data, onComplete, hash);
  16479. };
  16480. return function () {
  16481. PersistentConnection.prototype.put = oldPut;
  16482. };
  16483. };
  16484. /**
  16485. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  16486. * @internal
  16487. */
  16488. const forceRestClient = function (forceRestClient) {
  16489. repoManagerForceRestClient(forceRestClient);
  16490. };
  16491. /**
  16492. * @license
  16493. * Copyright 2023 Google LLC
  16494. *
  16495. * Licensed under the Apache License, Version 2.0 (the "License");
  16496. * you may not use this file except in compliance with the License.
  16497. * You may obtain a copy of the License at
  16498. *
  16499. * http://www.apache.org/licenses/LICENSE-2.0
  16500. *
  16501. * Unless required by applicable law or agreed to in writing, software
  16502. * distributed under the License is distributed on an "AS IS" BASIS,
  16503. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16504. * See the License for the specific language governing permissions and
  16505. * limitations under the License.
  16506. */
  16507. /**
  16508. * Used by console to create a database based on the app,
  16509. * passed database URL and a custom auth implementation.
  16510. * @internal
  16511. * @param app - A valid FirebaseApp-like object
  16512. * @param url - A valid Firebase databaseURL
  16513. * @param version - custom version e.g. firebase-admin version
  16514. * @param customAppCheckImpl - custom app check implementation
  16515. * @param customAuthImpl - custom auth implementation
  16516. */
  16517. function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {
  16518. setSDKVersion(version);
  16519. /**
  16520. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  16521. * any actual function.
  16522. */
  16523. const componentContainer = new component.ComponentContainer('database-standalone');
  16524. const authProvider = new component.Provider('auth-internal', componentContainer);
  16525. let appCheckProvider;
  16526. if (customAppCheckImpl) {
  16527. appCheckProvider = new component.Provider('app-check-internal', componentContainer);
  16528. appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  16529. }
  16530. authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  16531. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);
  16532. }
  16533. /**
  16534. * @license
  16535. * Copyright 2021 Google LLC
  16536. *
  16537. * Licensed under the Apache License, Version 2.0 (the "License");
  16538. * you may not use this file except in compliance with the License.
  16539. * You may obtain a copy of the License at
  16540. *
  16541. * http://www.apache.org/licenses/LICENSE-2.0
  16542. *
  16543. * Unless required by applicable law or agreed to in writing, software
  16544. * distributed under the License is distributed on an "AS IS" BASIS,
  16545. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16546. * See the License for the specific language governing permissions and
  16547. * limitations under the License.
  16548. */
  16549. setWebSocketImpl(Websocket__default["default"].Client);
  16550. index_standalone.DataSnapshot = DataSnapshot$1;
  16551. index_standalone.Database = Database$1;
  16552. var OnDisconnect_1 = index_standalone.OnDisconnect = OnDisconnect$1;
  16553. index_standalone.QueryConstraint = QueryConstraint;
  16554. index_standalone.TransactionResult = TransactionResult$1;
  16555. var _QueryImpl = index_standalone._QueryImpl = QueryImpl;
  16556. var _QueryParams = index_standalone._QueryParams = QueryParams;
  16557. var _ReferenceImpl = index_standalone._ReferenceImpl = ReferenceImpl;
  16558. index_standalone._TEST_ACCESS_forceRestClient = forceRestClient;
  16559. index_standalone._TEST_ACCESS_hijackHash = hijackHash;
  16560. index_standalone._initStandalone = _initStandalone;
  16561. var _repoManagerDatabaseFromApp = index_standalone._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  16562. var _setSDKVersion = index_standalone._setSDKVersion = setSDKVersion;
  16563. var _validatePathString = index_standalone._validatePathString = validatePathString;
  16564. var _validateWritablePath = index_standalone._validateWritablePath = validateWritablePath;
  16565. var child_1 = index_standalone.child = child;
  16566. var connectDatabaseEmulator_1 = index_standalone.connectDatabaseEmulator = connectDatabaseEmulator;
  16567. var enableLogging_1 = index_standalone.enableLogging = enableLogging;
  16568. var endAt_1 = index_standalone.endAt = endAt;
  16569. var endBefore_1 = index_standalone.endBefore = endBefore;
  16570. var equalTo_1 = index_standalone.equalTo = equalTo;
  16571. var forceLongPolling_1 = index_standalone.forceLongPolling = forceLongPolling;
  16572. var forceWebSockets_1 = index_standalone.forceWebSockets = forceWebSockets;
  16573. var get_1 = index_standalone.get = get;
  16574. var goOffline_1 = index_standalone.goOffline = goOffline;
  16575. var goOnline_1 = index_standalone.goOnline = goOnline;
  16576. var increment_1 = index_standalone.increment = increment;
  16577. var limitToFirst_1 = index_standalone.limitToFirst = limitToFirst;
  16578. var limitToLast_1 = index_standalone.limitToLast = limitToLast;
  16579. var off_1 = index_standalone.off = off;
  16580. var onChildAdded_1 = index_standalone.onChildAdded = onChildAdded;
  16581. var onChildChanged_1 = index_standalone.onChildChanged = onChildChanged;
  16582. var onChildMoved_1 = index_standalone.onChildMoved = onChildMoved;
  16583. var onChildRemoved_1 = index_standalone.onChildRemoved = onChildRemoved;
  16584. index_standalone.onDisconnect = onDisconnect;
  16585. var onValue_1 = index_standalone.onValue = onValue;
  16586. var orderByChild_1 = index_standalone.orderByChild = orderByChild;
  16587. var orderByKey_1 = index_standalone.orderByKey = orderByKey;
  16588. var orderByPriority_1 = index_standalone.orderByPriority = orderByPriority;
  16589. var orderByValue_1 = index_standalone.orderByValue = orderByValue;
  16590. var push_1 = index_standalone.push = push;
  16591. var query_1 = index_standalone.query = query;
  16592. var ref_1 = index_standalone.ref = ref;
  16593. var refFromURL_1 = index_standalone.refFromURL = refFromURL;
  16594. var remove_1 = index_standalone.remove = remove;
  16595. var runTransaction_1 = index_standalone.runTransaction = runTransaction;
  16596. var serverTimestamp_1 = index_standalone.serverTimestamp = serverTimestamp;
  16597. var set_1 = index_standalone.set = set;
  16598. var setPriority_1 = index_standalone.setPriority = setPriority;
  16599. var setWithPriority_1 = index_standalone.setWithPriority = setWithPriority;
  16600. var startAfter_1 = index_standalone.startAfter = startAfter;
  16601. var startAt_1 = index_standalone.startAt = startAt;
  16602. var update_1 = index_standalone.update = update;
  16603. /**
  16604. * @license
  16605. * Copyright 2021 Google LLC
  16606. *
  16607. * Licensed under the Apache License, Version 2.0 (the "License");
  16608. * you may not use this file except in compliance with the License.
  16609. * You may obtain a copy of the License at
  16610. *
  16611. * http://www.apache.org/licenses/LICENSE-2.0
  16612. *
  16613. * Unless required by applicable law or agreed to in writing, software
  16614. * distributed under the License is distributed on an "AS IS" BASIS,
  16615. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16616. * See the License for the specific language governing permissions and
  16617. * limitations under the License.
  16618. */
  16619. const logClient = new require$$2$3.Logger('@firebase/database-compat');
  16620. const warn = function (msg) {
  16621. const message = 'FIREBASE WARNING: ' + msg;
  16622. logClient.warn(message);
  16623. };
  16624. /**
  16625. * @license
  16626. * Copyright 2021 Google LLC
  16627. *
  16628. * Licensed under the Apache License, Version 2.0 (the "License");
  16629. * you may not use this file except in compliance with the License.
  16630. * You may obtain a copy of the License at
  16631. *
  16632. * http://www.apache.org/licenses/LICENSE-2.0
  16633. *
  16634. * Unless required by applicable law or agreed to in writing, software
  16635. * distributed under the License is distributed on an "AS IS" BASIS,
  16636. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16637. * See the License for the specific language governing permissions and
  16638. * limitations under the License.
  16639. */
  16640. const validateBoolean = function (fnName, argumentName, bool, optional) {
  16641. if (optional && bool === undefined) {
  16642. return;
  16643. }
  16644. if (typeof bool !== 'boolean') {
  16645. throw new Error(require$$1$3.errorPrefix(fnName, argumentName) + 'must be a boolean.');
  16646. }
  16647. };
  16648. const validateEventType = function (fnName, eventType, optional) {
  16649. if (optional && eventType === undefined) {
  16650. return;
  16651. }
  16652. switch (eventType) {
  16653. case 'value':
  16654. case 'child_added':
  16655. case 'child_removed':
  16656. case 'child_changed':
  16657. case 'child_moved':
  16658. break;
  16659. default:
  16660. throw new Error(require$$1$3.errorPrefix(fnName, 'eventType') +
  16661. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  16662. '"child_changed", or "child_moved".');
  16663. }
  16664. };
  16665. /**
  16666. * @license
  16667. * Copyright 2017 Google LLC
  16668. *
  16669. * Licensed under the Apache License, Version 2.0 (the "License");
  16670. * you may not use this file except in compliance with the License.
  16671. * You may obtain a copy of the License at
  16672. *
  16673. * http://www.apache.org/licenses/LICENSE-2.0
  16674. *
  16675. * Unless required by applicable law or agreed to in writing, software
  16676. * distributed under the License is distributed on an "AS IS" BASIS,
  16677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16678. * See the License for the specific language governing permissions and
  16679. * limitations under the License.
  16680. */
  16681. class OnDisconnect {
  16682. constructor(_delegate) {
  16683. this._delegate = _delegate;
  16684. }
  16685. cancel(onComplete) {
  16686. require$$1$3.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);
  16687. require$$1$3.validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);
  16688. const result = this._delegate.cancel();
  16689. if (onComplete) {
  16690. result.then(() => onComplete(null), error => onComplete(error));
  16691. }
  16692. return result;
  16693. }
  16694. remove(onComplete) {
  16695. require$$1$3.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);
  16696. require$$1$3.validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);
  16697. const result = this._delegate.remove();
  16698. if (onComplete) {
  16699. result.then(() => onComplete(null), error => onComplete(error));
  16700. }
  16701. return result;
  16702. }
  16703. set(value, onComplete) {
  16704. require$$1$3.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);
  16705. require$$1$3.validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);
  16706. const result = this._delegate.set(value);
  16707. if (onComplete) {
  16708. result.then(() => onComplete(null), error => onComplete(error));
  16709. }
  16710. return result;
  16711. }
  16712. setWithPriority(value, priority, onComplete) {
  16713. require$$1$3.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);
  16714. require$$1$3.validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true);
  16715. const result = this._delegate.setWithPriority(value, priority);
  16716. if (onComplete) {
  16717. result.then(() => onComplete(null), error => onComplete(error));
  16718. }
  16719. return result;
  16720. }
  16721. update(objectToMerge, onComplete) {
  16722. require$$1$3.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);
  16723. if (Array.isArray(objectToMerge)) {
  16724. const newObjectToMerge = {};
  16725. for (let i = 0; i < objectToMerge.length; ++i) {
  16726. newObjectToMerge['' + i] = objectToMerge[i];
  16727. }
  16728. objectToMerge = newObjectToMerge;
  16729. warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +
  16730. 'existing data, or an Object with integer keys if you really do want to only update some of the children.');
  16731. }
  16732. require$$1$3.validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);
  16733. const result = this._delegate.update(objectToMerge);
  16734. if (onComplete) {
  16735. result.then(() => onComplete(null), error => onComplete(error));
  16736. }
  16737. return result;
  16738. }
  16739. }
  16740. /**
  16741. * @license
  16742. * Copyright 2017 Google LLC
  16743. *
  16744. * Licensed under the Apache License, Version 2.0 (the "License");
  16745. * you may not use this file except in compliance with the License.
  16746. * You may obtain a copy of the License at
  16747. *
  16748. * http://www.apache.org/licenses/LICENSE-2.0
  16749. *
  16750. * Unless required by applicable law or agreed to in writing, software
  16751. * distributed under the License is distributed on an "AS IS" BASIS,
  16752. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16753. * See the License for the specific language governing permissions and
  16754. * limitations under the License.
  16755. */
  16756. class TransactionResult {
  16757. /**
  16758. * A type for the resolve value of Firebase.transaction.
  16759. */
  16760. constructor(committed, snapshot) {
  16761. this.committed = committed;
  16762. this.snapshot = snapshot;
  16763. }
  16764. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  16765. // for end-users
  16766. toJSON() {
  16767. require$$1$3.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);
  16768. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  16769. }
  16770. }
  16771. /**
  16772. * @license
  16773. * Copyright 2017 Google LLC
  16774. *
  16775. * Licensed under the Apache License, Version 2.0 (the "License");
  16776. * you may not use this file except in compliance with the License.
  16777. * You may obtain a copy of the License at
  16778. *
  16779. * http://www.apache.org/licenses/LICENSE-2.0
  16780. *
  16781. * Unless required by applicable law or agreed to in writing, software
  16782. * distributed under the License is distributed on an "AS IS" BASIS,
  16783. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16784. * See the License for the specific language governing permissions and
  16785. * limitations under the License.
  16786. */
  16787. /**
  16788. * Class representing a firebase data snapshot. It wraps a SnapshotNode and
  16789. * surfaces the public methods (val, forEach, etc.) we want to expose.
  16790. */
  16791. class DataSnapshot {
  16792. constructor(_database, _delegate) {
  16793. this._database = _database;
  16794. this._delegate = _delegate;
  16795. }
  16796. /**
  16797. * Retrieves the snapshot contents as JSON. Returns null if the snapshot is
  16798. * empty.
  16799. *
  16800. * @returns JSON representation of the DataSnapshot contents, or null if empty.
  16801. */
  16802. val() {
  16803. require$$1$3.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);
  16804. return this._delegate.val();
  16805. }
  16806. /**
  16807. * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting
  16808. * the entire node contents.
  16809. * @returns JSON representation of the DataSnapshot contents, or null if empty.
  16810. */
  16811. exportVal() {
  16812. require$$1$3.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);
  16813. return this._delegate.exportVal();
  16814. }
  16815. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  16816. // for end-users
  16817. toJSON() {
  16818. // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content
  16819. require$$1$3.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);
  16820. return this._delegate.toJSON();
  16821. }
  16822. /**
  16823. * Returns whether the snapshot contains a non-null value.
  16824. *
  16825. * @returns Whether the snapshot contains a non-null value, or is empty.
  16826. */
  16827. exists() {
  16828. require$$1$3.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);
  16829. return this._delegate.exists();
  16830. }
  16831. /**
  16832. * Returns a DataSnapshot of the specified child node's contents.
  16833. *
  16834. * @param path - Path to a child.
  16835. * @returns DataSnapshot for child node.
  16836. */
  16837. child(path) {
  16838. require$$1$3.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);
  16839. // Ensure the childPath is a string (can be a number)
  16840. path = String(path);
  16841. _validatePathString('DataSnapshot.child', 'path', path, false);
  16842. return new DataSnapshot(this._database, this._delegate.child(path));
  16843. }
  16844. /**
  16845. * Returns whether the snapshot contains a child at the specified path.
  16846. *
  16847. * @param path - Path to a child.
  16848. * @returns Whether the child exists.
  16849. */
  16850. hasChild(path) {
  16851. require$$1$3.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);
  16852. _validatePathString('DataSnapshot.hasChild', 'path', path, false);
  16853. return this._delegate.hasChild(path);
  16854. }
  16855. /**
  16856. * Returns the priority of the object, or null if no priority was set.
  16857. *
  16858. * @returns The priority.
  16859. */
  16860. getPriority() {
  16861. require$$1$3.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);
  16862. return this._delegate.priority;
  16863. }
  16864. /**
  16865. * Iterates through child nodes and calls the specified action for each one.
  16866. *
  16867. * @param action - Callback function to be called
  16868. * for each child.
  16869. * @returns True if forEach was canceled by action returning true for
  16870. * one of the child nodes.
  16871. */
  16872. forEach(action) {
  16873. require$$1$3.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);
  16874. require$$1$3.validateCallback('DataSnapshot.forEach', 'action', action, false);
  16875. return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot)));
  16876. }
  16877. /**
  16878. * Returns whether this DataSnapshot has children.
  16879. * @returns True if the DataSnapshot contains 1 or more child nodes.
  16880. */
  16881. hasChildren() {
  16882. require$$1$3.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);
  16883. return this._delegate.hasChildren();
  16884. }
  16885. get key() {
  16886. return this._delegate.key;
  16887. }
  16888. /**
  16889. * Returns the number of children for this DataSnapshot.
  16890. * @returns The number of children that this DataSnapshot contains.
  16891. */
  16892. numChildren() {
  16893. require$$1$3.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);
  16894. return this._delegate.size;
  16895. }
  16896. /**
  16897. * @returns The Firebase reference for the location this snapshot's data came
  16898. * from.
  16899. */
  16900. getRef() {
  16901. require$$1$3.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);
  16902. return new Reference(this._database, this._delegate.ref);
  16903. }
  16904. get ref() {
  16905. return this.getRef();
  16906. }
  16907. }
  16908. /**
  16909. * A Query represents a filter to be applied to a firebase location. This object purely represents the
  16910. * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.
  16911. *
  16912. * Since every Firebase reference is a query, Firebase inherits from this object.
  16913. */
  16914. class Query {
  16915. constructor(database, _delegate) {
  16916. this.database = database;
  16917. this._delegate = _delegate;
  16918. }
  16919. on(eventType, callback, cancelCallbackOrContext, context) {
  16920. var _a;
  16921. require$$1$3.validateArgCount('Query.on', 2, 4, arguments.length);
  16922. require$$1$3.validateCallback('Query.on', 'callback', callback, false);
  16923. const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);
  16924. const valueCallback = (expSnapshot, previousChildName) => {
  16925. callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName);
  16926. };
  16927. valueCallback.userCallback = callback;
  16928. valueCallback.context = ret.context;
  16929. const cancelCallback = (_a = ret.cancel) === null || _a === void 0 ? void 0 : _a.bind(ret.context);
  16930. switch (eventType) {
  16931. case 'value':
  16932. onValue_1(this._delegate, valueCallback, cancelCallback);
  16933. return callback;
  16934. case 'child_added':
  16935. onChildAdded_1(this._delegate, valueCallback, cancelCallback);
  16936. return callback;
  16937. case 'child_removed':
  16938. onChildRemoved_1(this._delegate, valueCallback, cancelCallback);
  16939. return callback;
  16940. case 'child_changed':
  16941. onChildChanged_1(this._delegate, valueCallback, cancelCallback);
  16942. return callback;
  16943. case 'child_moved':
  16944. onChildMoved_1(this._delegate, valueCallback, cancelCallback);
  16945. return callback;
  16946. default:
  16947. throw new Error(require$$1$3.errorPrefix('Query.on', 'eventType') +
  16948. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  16949. '"child_changed", or "child_moved".');
  16950. }
  16951. }
  16952. off(eventType, callback, context) {
  16953. require$$1$3.validateArgCount('Query.off', 0, 3, arguments.length);
  16954. validateEventType('Query.off', eventType, true);
  16955. require$$1$3.validateCallback('Query.off', 'callback', callback, true);
  16956. require$$1$3.validateContextObject('Query.off', 'context', context, true);
  16957. if (callback) {
  16958. const valueCallback = () => { };
  16959. valueCallback.userCallback = callback;
  16960. valueCallback.context = context;
  16961. off_1(this._delegate, eventType, valueCallback);
  16962. }
  16963. else {
  16964. off_1(this._delegate, eventType);
  16965. }
  16966. }
  16967. /**
  16968. * Get the server-value for this query, or return a cached value if not connected.
  16969. */
  16970. get() {
  16971. return get_1(this._delegate).then(expSnapshot => {
  16972. return new DataSnapshot(this.database, expSnapshot);
  16973. });
  16974. }
  16975. /**
  16976. * Attaches a listener, waits for the first event, and then removes the listener
  16977. */
  16978. once(eventType, callback, failureCallbackOrContext, context) {
  16979. require$$1$3.validateArgCount('Query.once', 1, 4, arguments.length);
  16980. require$$1$3.validateCallback('Query.once', 'callback', callback, true);
  16981. const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context);
  16982. const deferred = new require$$1$3.Deferred();
  16983. const valueCallback = (expSnapshot, previousChildName) => {
  16984. const result = new DataSnapshot(this.database, expSnapshot);
  16985. if (callback) {
  16986. callback.call(ret.context, result, previousChildName);
  16987. }
  16988. deferred.resolve(result);
  16989. };
  16990. valueCallback.userCallback = callback;
  16991. valueCallback.context = ret.context;
  16992. const cancelCallback = (error) => {
  16993. if (ret.cancel) {
  16994. ret.cancel.call(ret.context, error);
  16995. }
  16996. deferred.reject(error);
  16997. };
  16998. switch (eventType) {
  16999. case 'value':
  17000. onValue_1(this._delegate, valueCallback, cancelCallback, {
  17001. onlyOnce: true
  17002. });
  17003. break;
  17004. case 'child_added':
  17005. onChildAdded_1(this._delegate, valueCallback, cancelCallback, {
  17006. onlyOnce: true
  17007. });
  17008. break;
  17009. case 'child_removed':
  17010. onChildRemoved_1(this._delegate, valueCallback, cancelCallback, {
  17011. onlyOnce: true
  17012. });
  17013. break;
  17014. case 'child_changed':
  17015. onChildChanged_1(this._delegate, valueCallback, cancelCallback, {
  17016. onlyOnce: true
  17017. });
  17018. break;
  17019. case 'child_moved':
  17020. onChildMoved_1(this._delegate, valueCallback, cancelCallback, {
  17021. onlyOnce: true
  17022. });
  17023. break;
  17024. default:
  17025. throw new Error(require$$1$3.errorPrefix('Query.once', 'eventType') +
  17026. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  17027. '"child_changed", or "child_moved".');
  17028. }
  17029. return deferred.promise;
  17030. }
  17031. /**
  17032. * Set a limit and anchor it to the start of the window.
  17033. */
  17034. limitToFirst(limit) {
  17035. require$$1$3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);
  17036. return new Query(this.database, query_1(this._delegate, limitToFirst_1(limit)));
  17037. }
  17038. /**
  17039. * Set a limit and anchor it to the end of the window.
  17040. */
  17041. limitToLast(limit) {
  17042. require$$1$3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);
  17043. return new Query(this.database, query_1(this._delegate, limitToLast_1(limit)));
  17044. }
  17045. /**
  17046. * Given a child path, return a new query ordered by the specified grandchild path.
  17047. */
  17048. orderByChild(path) {
  17049. require$$1$3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);
  17050. return new Query(this.database, query_1(this._delegate, orderByChild_1(path)));
  17051. }
  17052. /**
  17053. * Return a new query ordered by the KeyIndex
  17054. */
  17055. orderByKey() {
  17056. require$$1$3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);
  17057. return new Query(this.database, query_1(this._delegate, orderByKey_1()));
  17058. }
  17059. /**
  17060. * Return a new query ordered by the PriorityIndex
  17061. */
  17062. orderByPriority() {
  17063. require$$1$3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);
  17064. return new Query(this.database, query_1(this._delegate, orderByPriority_1()));
  17065. }
  17066. /**
  17067. * Return a new query ordered by the ValueIndex
  17068. */
  17069. orderByValue() {
  17070. require$$1$3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);
  17071. return new Query(this.database, query_1(this._delegate, orderByValue_1()));
  17072. }
  17073. startAt(value = null, name) {
  17074. require$$1$3.validateArgCount('Query.startAt', 0, 2, arguments.length);
  17075. return new Query(this.database, query_1(this._delegate, startAt_1(value, name)));
  17076. }
  17077. startAfter(value = null, name) {
  17078. require$$1$3.validateArgCount('Query.startAfter', 0, 2, arguments.length);
  17079. return new Query(this.database, query_1(this._delegate, startAfter_1(value, name)));
  17080. }
  17081. endAt(value = null, name) {
  17082. require$$1$3.validateArgCount('Query.endAt', 0, 2, arguments.length);
  17083. return new Query(this.database, query_1(this._delegate, endAt_1(value, name)));
  17084. }
  17085. endBefore(value = null, name) {
  17086. require$$1$3.validateArgCount('Query.endBefore', 0, 2, arguments.length);
  17087. return new Query(this.database, query_1(this._delegate, endBefore_1(value, name)));
  17088. }
  17089. /**
  17090. * Load the selection of children with exactly the specified value, and, optionally,
  17091. * the specified name.
  17092. */
  17093. equalTo(value, name) {
  17094. require$$1$3.validateArgCount('Query.equalTo', 1, 2, arguments.length);
  17095. return new Query(this.database, query_1(this._delegate, equalTo_1(value, name)));
  17096. }
  17097. /**
  17098. * @returns URL for this location.
  17099. */
  17100. toString() {
  17101. require$$1$3.validateArgCount('Query.toString', 0, 0, arguments.length);
  17102. return this._delegate.toString();
  17103. }
  17104. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  17105. // for end-users.
  17106. toJSON() {
  17107. // An optional spacer argument is unnecessary for a string.
  17108. require$$1$3.validateArgCount('Query.toJSON', 0, 1, arguments.length);
  17109. return this._delegate.toJSON();
  17110. }
  17111. /**
  17112. * Return true if this query and the provided query are equivalent; otherwise, return false.
  17113. */
  17114. isEqual(other) {
  17115. require$$1$3.validateArgCount('Query.isEqual', 1, 1, arguments.length);
  17116. if (!(other instanceof Query)) {
  17117. const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';
  17118. throw new Error(error);
  17119. }
  17120. return this._delegate.isEqual(other._delegate);
  17121. }
  17122. /**
  17123. * Helper used by .on and .once to extract the context and or cancel arguments.
  17124. * @param fnName - The function name (on or once)
  17125. *
  17126. */
  17127. static getCancelAndContextArgs_(fnName, cancelOrContext, context) {
  17128. const ret = { cancel: undefined, context: undefined };
  17129. if (cancelOrContext && context) {
  17130. ret.cancel = cancelOrContext;
  17131. require$$1$3.validateCallback(fnName, 'cancel', ret.cancel, true);
  17132. ret.context = context;
  17133. require$$1$3.validateContextObject(fnName, 'context', ret.context, true);
  17134. }
  17135. else if (cancelOrContext) {
  17136. // we have either a cancel callback or a context.
  17137. if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {
  17138. // it's a context!
  17139. ret.context = cancelOrContext;
  17140. }
  17141. else if (typeof cancelOrContext === 'function') {
  17142. ret.cancel = cancelOrContext;
  17143. }
  17144. else {
  17145. throw new Error(require$$1$3.errorPrefix(fnName, 'cancelOrContext') +
  17146. ' must either be a cancel callback or a context object.');
  17147. }
  17148. }
  17149. return ret;
  17150. }
  17151. get ref() {
  17152. return new Reference(this.database, new _ReferenceImpl(this._delegate._repo, this._delegate._path));
  17153. }
  17154. }
  17155. class Reference extends Query {
  17156. /**
  17157. * Call options:
  17158. * new Reference(Repo, Path) or
  17159. * new Reference(url: string, string|RepoManager)
  17160. *
  17161. * Externally - this is the firebase.database.Reference type.
  17162. */
  17163. constructor(database, _delegate) {
  17164. super(database, new _QueryImpl(_delegate._repo, _delegate._path, new _QueryParams(), false));
  17165. this.database = database;
  17166. this._delegate = _delegate;
  17167. }
  17168. /** @returns {?string} */
  17169. getKey() {
  17170. require$$1$3.validateArgCount('Reference.key', 0, 0, arguments.length);
  17171. return this._delegate.key;
  17172. }
  17173. child(pathString) {
  17174. require$$1$3.validateArgCount('Reference.child', 1, 1, arguments.length);
  17175. if (typeof pathString === 'number') {
  17176. pathString = String(pathString);
  17177. }
  17178. return new Reference(this.database, child_1(this._delegate, pathString));
  17179. }
  17180. /** @returns {?Reference} */
  17181. getParent() {
  17182. require$$1$3.validateArgCount('Reference.parent', 0, 0, arguments.length);
  17183. const parent = this._delegate.parent;
  17184. return parent ? new Reference(this.database, parent) : null;
  17185. }
  17186. /** @returns {!Reference} */
  17187. getRoot() {
  17188. require$$1$3.validateArgCount('Reference.root', 0, 0, arguments.length);
  17189. return new Reference(this.database, this._delegate.root);
  17190. }
  17191. set(newVal, onComplete) {
  17192. require$$1$3.validateArgCount('Reference.set', 1, 2, arguments.length);
  17193. require$$1$3.validateCallback('Reference.set', 'onComplete', onComplete, true);
  17194. const result = set_1(this._delegate, newVal);
  17195. if (onComplete) {
  17196. result.then(() => onComplete(null), error => onComplete(error));
  17197. }
  17198. return result;
  17199. }
  17200. update(values, onComplete) {
  17201. require$$1$3.validateArgCount('Reference.update', 1, 2, arguments.length);
  17202. if (Array.isArray(values)) {
  17203. const newObjectToMerge = {};
  17204. for (let i = 0; i < values.length; ++i) {
  17205. newObjectToMerge['' + i] = values[i];
  17206. }
  17207. values = newObjectToMerge;
  17208. warn('Passing an Array to Firebase.update() is deprecated. ' +
  17209. 'Use set() if you want to overwrite the existing data, or ' +
  17210. 'an Object with integer keys if you really do want to ' +
  17211. 'only update some of the children.');
  17212. }
  17213. _validateWritablePath('Reference.update', this._delegate._path);
  17214. require$$1$3.validateCallback('Reference.update', 'onComplete', onComplete, true);
  17215. const result = update_1(this._delegate, values);
  17216. if (onComplete) {
  17217. result.then(() => onComplete(null), error => onComplete(error));
  17218. }
  17219. return result;
  17220. }
  17221. setWithPriority(newVal, newPriority, onComplete) {
  17222. require$$1$3.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);
  17223. require$$1$3.validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true);
  17224. const result = setWithPriority_1(this._delegate, newVal, newPriority);
  17225. if (onComplete) {
  17226. result.then(() => onComplete(null), error => onComplete(error));
  17227. }
  17228. return result;
  17229. }
  17230. remove(onComplete) {
  17231. require$$1$3.validateArgCount('Reference.remove', 0, 1, arguments.length);
  17232. require$$1$3.validateCallback('Reference.remove', 'onComplete', onComplete, true);
  17233. const result = remove_1(this._delegate);
  17234. if (onComplete) {
  17235. result.then(() => onComplete(null), error => onComplete(error));
  17236. }
  17237. return result;
  17238. }
  17239. transaction(transactionUpdate, onComplete, applyLocally) {
  17240. require$$1$3.validateArgCount('Reference.transaction', 1, 3, arguments.length);
  17241. require$$1$3.validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false);
  17242. require$$1$3.validateCallback('Reference.transaction', 'onComplete', onComplete, true);
  17243. validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true);
  17244. const result = runTransaction_1(this._delegate, transactionUpdate, {
  17245. applyLocally
  17246. }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot)));
  17247. if (onComplete) {
  17248. result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null));
  17249. }
  17250. return result;
  17251. }
  17252. setPriority(priority, onComplete) {
  17253. require$$1$3.validateArgCount('Reference.setPriority', 1, 2, arguments.length);
  17254. require$$1$3.validateCallback('Reference.setPriority', 'onComplete', onComplete, true);
  17255. const result = setPriority_1(this._delegate, priority);
  17256. if (onComplete) {
  17257. result.then(() => onComplete(null), error => onComplete(error));
  17258. }
  17259. return result;
  17260. }
  17261. push(value, onComplete) {
  17262. require$$1$3.validateArgCount('Reference.push', 0, 2, arguments.length);
  17263. require$$1$3.validateCallback('Reference.push', 'onComplete', onComplete, true);
  17264. const expPromise = push_1(this._delegate, value);
  17265. const promise = expPromise.then(expRef => new Reference(this.database, expRef));
  17266. if (onComplete) {
  17267. promise.then(() => onComplete(null), error => onComplete(error));
  17268. }
  17269. const result = new Reference(this.database, expPromise);
  17270. result.then = promise.then.bind(promise);
  17271. result.catch = promise.catch.bind(promise, undefined);
  17272. return result;
  17273. }
  17274. onDisconnect() {
  17275. _validateWritablePath('Reference.onDisconnect', this._delegate._path);
  17276. return new OnDisconnect(new OnDisconnect_1(this._delegate._repo, this._delegate._path));
  17277. }
  17278. get key() {
  17279. return this.getKey();
  17280. }
  17281. get parent() {
  17282. return this.getParent();
  17283. }
  17284. get root() {
  17285. return this.getRoot();
  17286. }
  17287. }
  17288. /**
  17289. * @license
  17290. * Copyright 2017 Google LLC
  17291. *
  17292. * Licensed under the Apache License, Version 2.0 (the "License");
  17293. * you may not use this file except in compliance with the License.
  17294. * You may obtain a copy of the License at
  17295. *
  17296. * http://www.apache.org/licenses/LICENSE-2.0
  17297. *
  17298. * Unless required by applicable law or agreed to in writing, software
  17299. * distributed under the License is distributed on an "AS IS" BASIS,
  17300. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17301. * See the License for the specific language governing permissions and
  17302. * limitations under the License.
  17303. */
  17304. /**
  17305. * Class representing a firebase database.
  17306. */
  17307. class Database {
  17308. /**
  17309. * The constructor should not be called by users of our public API.
  17310. */
  17311. constructor(_delegate, app) {
  17312. this._delegate = _delegate;
  17313. this.app = app;
  17314. this.INTERNAL = {
  17315. delete: () => this._delegate._delete(),
  17316. forceWebSockets: forceWebSockets_1,
  17317. forceLongPolling: forceLongPolling_1
  17318. };
  17319. }
  17320. /**
  17321. * Modify this instance to communicate with the Realtime Database emulator.
  17322. *
  17323. * <p>Note: This method must be called before performing any other operation.
  17324. *
  17325. * @param host - the emulator host (ex: localhost)
  17326. * @param port - the emulator port (ex: 8080)
  17327. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  17328. */
  17329. useEmulator(host, port, options = {}) {
  17330. connectDatabaseEmulator_1(this._delegate, host, port, options);
  17331. }
  17332. ref(path) {
  17333. require$$1$3.validateArgCount('database.ref', 0, 1, arguments.length);
  17334. if (path instanceof Reference) {
  17335. const childRef = refFromURL_1(this._delegate, path.toString());
  17336. return new Reference(this, childRef);
  17337. }
  17338. else {
  17339. const childRef = ref_1(this._delegate, path);
  17340. return new Reference(this, childRef);
  17341. }
  17342. }
  17343. /**
  17344. * Returns a reference to the root or the path specified in url.
  17345. * We throw a exception if the url is not in the same domain as the
  17346. * current repo.
  17347. * @returns Firebase reference.
  17348. */
  17349. refFromURL(url) {
  17350. const apiName = 'database.refFromURL';
  17351. require$$1$3.validateArgCount(apiName, 1, 1, arguments.length);
  17352. const childRef = refFromURL_1(this._delegate, url);
  17353. return new Reference(this, childRef);
  17354. }
  17355. // Make individual repo go offline.
  17356. goOffline() {
  17357. require$$1$3.validateArgCount('database.goOffline', 0, 0, arguments.length);
  17358. return goOffline_1(this._delegate);
  17359. }
  17360. goOnline() {
  17361. require$$1$3.validateArgCount('database.goOnline', 0, 0, arguments.length);
  17362. return goOnline_1(this._delegate);
  17363. }
  17364. }
  17365. Database.ServerValue = {
  17366. TIMESTAMP: serverTimestamp_1(),
  17367. increment: (delta) => increment_1(delta)
  17368. };
  17369. /**
  17370. * Used by console to create a database based on the app,
  17371. * passed database URL and a custom auth implementation.
  17372. *
  17373. * @param app - A valid FirebaseApp-like object
  17374. * @param url - A valid Firebase databaseURL
  17375. * @param version - custom version e.g. firebase-admin version
  17376. * @param customAuthImpl - custom auth implementation
  17377. */
  17378. function initStandalone$1({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin = false }) {
  17379. _setSDKVersion(version);
  17380. const container = new require$$3.ComponentContainer('database-standalone');
  17381. /**
  17382. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  17383. * any actual function.
  17384. */
  17385. const authProvider = new require$$3.Provider('auth-internal', container);
  17386. authProvider.setComponent(new require$$3.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  17387. let appCheckProvider = undefined;
  17388. if (customAppCheckImpl) {
  17389. appCheckProvider = new require$$3.Provider('app-check-internal', container);
  17390. appCheckProvider.setComponent(new require$$3.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  17391. }
  17392. return {
  17393. instance: new Database(_repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin), app),
  17394. namespace
  17395. };
  17396. }
  17397. var INTERNAL = /*#__PURE__*/Object.freeze({
  17398. __proto__: null,
  17399. initStandalone: initStandalone$1
  17400. });
  17401. /**
  17402. * @license
  17403. * Copyright 2021 Google LLC
  17404. *
  17405. * Licensed under the Apache License, Version 2.0 (the "License");
  17406. * you may not use this file except in compliance with the License.
  17407. * You may obtain a copy of the License at
  17408. *
  17409. * http://www.apache.org/licenses/LICENSE-2.0
  17410. *
  17411. * Unless required by applicable law or agreed to in writing, software
  17412. * distributed under the License is distributed on an "AS IS" BASIS,
  17413. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17414. * See the License for the specific language governing permissions and
  17415. * limitations under the License.
  17416. */
  17417. const ServerValue = Database.ServerValue;
  17418. /**
  17419. * A one off register function which returns a database based on the app and
  17420. * passed database URL. (Used by the Admin SDK)
  17421. *
  17422. * @param app - A valid FirebaseApp-like object
  17423. * @param url - A valid Firebase databaseURL
  17424. * @param version - custom version e.g. firebase-admin version
  17425. * @param nodeAdmin - true if the SDK is being initialized from Firebase Admin.
  17426. */
  17427. function initStandalone(app, url, version, nodeAdmin = true) {
  17428. require$$1$3.CONSTANTS.NODE_ADMIN = nodeAdmin;
  17429. return initStandalone$1({
  17430. app,
  17431. url,
  17432. version,
  17433. // firebase-admin-node's app.INTERNAL implements FirebaseAuthInternal interface
  17434. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  17435. customAuthImpl: app.INTERNAL,
  17436. namespace: {
  17437. Reference,
  17438. Query,
  17439. Database,
  17440. DataSnapshot,
  17441. enableLogging: enableLogging_1,
  17442. INTERNAL,
  17443. ServerValue
  17444. },
  17445. nodeAdmin
  17446. });
  17447. }
  17448. exports.DataSnapshot = DataSnapshot;
  17449. exports.Database = Database;
  17450. exports.OnDisconnect = OnDisconnect_1;
  17451. exports.Query = Query;
  17452. exports.Reference = Reference;
  17453. exports.ServerValue = ServerValue;
  17454. exports.enableLogging = enableLogging_1;
  17455. exports.initStandalone = initStandalone;
  17456. //# sourceMappingURL=index.standalone.js.map