index.node.cjs.js 589 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var Websocket = require('faye-websocket');
  4. var util = require('@firebase/util');
  5. var tslib = require('tslib');
  6. var logger$1 = require('@firebase/logger');
  7. var app = require('@firebase/app');
  8. var component = require('@firebase/component');
  9. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  10. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket);
  11. /**
  12. * @license
  13. * Copyright 2017 Google LLC
  14. *
  15. * Licensed under the Apache License, Version 2.0 (the "License");
  16. * you may not use this file except in compliance with the License.
  17. * You may obtain a copy of the License at
  18. *
  19. * http://www.apache.org/licenses/LICENSE-2.0
  20. *
  21. * Unless required by applicable law or agreed to in writing, software
  22. * distributed under the License is distributed on an "AS IS" BASIS,
  23. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. * See the License for the specific language governing permissions and
  25. * limitations under the License.
  26. */
  27. var PROTOCOL_VERSION = '5';
  28. var VERSION_PARAM = 'v';
  29. var TRANSPORT_SESSION_PARAM = 's';
  30. var REFERER_PARAM = 'r';
  31. var FORGE_REF = 'f';
  32. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  33. // firebase.corp.google.com
  34. var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  35. var LAST_SESSION_PARAM = 'ls';
  36. var APPLICATION_ID_PARAM = 'p';
  37. var APP_CHECK_TOKEN_PARAM = 'ac';
  38. var WEBSOCKET = 'websocket';
  39. var LONG_POLLING = 'long_polling';
  40. /**
  41. * @license
  42. * Copyright 2017 Google LLC
  43. *
  44. * Licensed under the Apache License, Version 2.0 (the "License");
  45. * you may not use this file except in compliance with the License.
  46. * You may obtain a copy of the License at
  47. *
  48. * http://www.apache.org/licenses/LICENSE-2.0
  49. *
  50. * Unless required by applicable law or agreed to in writing, software
  51. * distributed under the License is distributed on an "AS IS" BASIS,
  52. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  53. * See the License for the specific language governing permissions and
  54. * limitations under the License.
  55. */
  56. /**
  57. * Wraps a DOM Storage object and:
  58. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  59. * - prefixes names with "firebase:" to avoid collisions with app data.
  60. *
  61. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  62. * and one for localStorage.
  63. *
  64. */
  65. var DOMStorageWrapper = /** @class */ (function () {
  66. /**
  67. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  68. */
  69. function DOMStorageWrapper(domStorage_) {
  70. this.domStorage_ = domStorage_;
  71. // Use a prefix to avoid collisions with other stuff saved by the app.
  72. this.prefix_ = 'firebase:';
  73. }
  74. /**
  75. * @param key - The key to save the value under
  76. * @param value - The value being stored, or null to remove the key.
  77. */
  78. DOMStorageWrapper.prototype.set = function (key, value) {
  79. if (value == null) {
  80. this.domStorage_.removeItem(this.prefixedName_(key));
  81. }
  82. else {
  83. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  84. }
  85. };
  86. /**
  87. * @returns The value that was stored under this key, or null
  88. */
  89. DOMStorageWrapper.prototype.get = function (key) {
  90. var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  91. if (storedVal == null) {
  92. return null;
  93. }
  94. else {
  95. return util.jsonEval(storedVal);
  96. }
  97. };
  98. DOMStorageWrapper.prototype.remove = function (key) {
  99. this.domStorage_.removeItem(this.prefixedName_(key));
  100. };
  101. DOMStorageWrapper.prototype.prefixedName_ = function (name) {
  102. return this.prefix_ + name;
  103. };
  104. DOMStorageWrapper.prototype.toString = function () {
  105. return this.domStorage_.toString();
  106. };
  107. return DOMStorageWrapper;
  108. }());
  109. /**
  110. * @license
  111. * Copyright 2017 Google LLC
  112. *
  113. * Licensed under the Apache License, Version 2.0 (the "License");
  114. * you may not use this file except in compliance with the License.
  115. * You may obtain a copy of the License at
  116. *
  117. * http://www.apache.org/licenses/LICENSE-2.0
  118. *
  119. * Unless required by applicable law or agreed to in writing, software
  120. * distributed under the License is distributed on an "AS IS" BASIS,
  121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  122. * See the License for the specific language governing permissions and
  123. * limitations under the License.
  124. */
  125. /**
  126. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  127. * (TODO: create interface for both to implement).
  128. */
  129. var MemoryStorage = /** @class */ (function () {
  130. function MemoryStorage() {
  131. this.cache_ = {};
  132. this.isInMemoryStorage = true;
  133. }
  134. MemoryStorage.prototype.set = function (key, value) {
  135. if (value == null) {
  136. delete this.cache_[key];
  137. }
  138. else {
  139. this.cache_[key] = value;
  140. }
  141. };
  142. MemoryStorage.prototype.get = function (key) {
  143. if (util.contains(this.cache_, key)) {
  144. return this.cache_[key];
  145. }
  146. return null;
  147. };
  148. MemoryStorage.prototype.remove = function (key) {
  149. delete this.cache_[key];
  150. };
  151. return MemoryStorage;
  152. }());
  153. /**
  154. * @license
  155. * Copyright 2017 Google LLC
  156. *
  157. * Licensed under the Apache License, Version 2.0 (the "License");
  158. * you may not use this file except in compliance with the License.
  159. * You may obtain a copy of the License at
  160. *
  161. * http://www.apache.org/licenses/LICENSE-2.0
  162. *
  163. * Unless required by applicable law or agreed to in writing, software
  164. * distributed under the License is distributed on an "AS IS" BASIS,
  165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  166. * See the License for the specific language governing permissions and
  167. * limitations under the License.
  168. */
  169. /**
  170. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  171. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  172. * to reflect this type
  173. *
  174. * @param domStorageName - Name of the underlying storage object
  175. * (e.g. 'localStorage' or 'sessionStorage').
  176. * @returns Turning off type information until a common interface is defined.
  177. */
  178. var createStoragefor = function (domStorageName) {
  179. try {
  180. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  181. // so it must be inside the try/catch.
  182. if (typeof window !== 'undefined' &&
  183. typeof window[domStorageName] !== 'undefined') {
  184. // Need to test cache. Just because it's here doesn't mean it works
  185. var domStorage = window[domStorageName];
  186. domStorage.setItem('firebase:sentinel', 'cache');
  187. domStorage.removeItem('firebase:sentinel');
  188. return new DOMStorageWrapper(domStorage);
  189. }
  190. }
  191. catch (e) { }
  192. // Failed to create wrapper. Just return in-memory storage.
  193. // TODO: log?
  194. return new MemoryStorage();
  195. };
  196. /** A storage object that lasts across sessions */
  197. var PersistentStorage = createStoragefor('localStorage');
  198. /** A storage object that only lasts one session */
  199. var SessionStorage = createStoragefor('sessionStorage');
  200. /**
  201. * @license
  202. * Copyright 2017 Google LLC
  203. *
  204. * Licensed under the Apache License, Version 2.0 (the "License");
  205. * you may not use this file except in compliance with the License.
  206. * You may obtain a copy of the License at
  207. *
  208. * http://www.apache.org/licenses/LICENSE-2.0
  209. *
  210. * Unless required by applicable law or agreed to in writing, software
  211. * distributed under the License is distributed on an "AS IS" BASIS,
  212. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  213. * See the License for the specific language governing permissions and
  214. * limitations under the License.
  215. */
  216. var logClient = new logger$1.Logger('@firebase/database');
  217. /**
  218. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  219. */
  220. var LUIDGenerator = (function () {
  221. var id = 1;
  222. return function () {
  223. return id++;
  224. };
  225. })();
  226. /**
  227. * Sha1 hash of the input string
  228. * @param str - The string to hash
  229. * @returns {!string} The resulting hash
  230. */
  231. var sha1 = function (str) {
  232. var utf8Bytes = util.stringToByteArray(str);
  233. var sha1 = new util.Sha1();
  234. sha1.update(utf8Bytes);
  235. var sha1Bytes = sha1.digest();
  236. return util.base64.encodeByteArray(sha1Bytes);
  237. };
  238. var buildLogMessage_ = function () {
  239. var varArgs = [];
  240. for (var _i = 0; _i < arguments.length; _i++) {
  241. varArgs[_i] = arguments[_i];
  242. }
  243. var message = '';
  244. for (var i = 0; i < varArgs.length; i++) {
  245. var arg = varArgs[i];
  246. if (Array.isArray(arg) ||
  247. (arg &&
  248. typeof arg === 'object' &&
  249. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  250. typeof arg.length === 'number')) {
  251. message += buildLogMessage_.apply(null, arg);
  252. }
  253. else if (typeof arg === 'object') {
  254. message += util.stringify(arg);
  255. }
  256. else {
  257. message += arg;
  258. }
  259. message += ' ';
  260. }
  261. return message;
  262. };
  263. /**
  264. * Use this for all debug messages in Firebase.
  265. */
  266. var logger = null;
  267. /**
  268. * Flag to check for log availability on first log message
  269. */
  270. var firstLog_ = true;
  271. /**
  272. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  273. * @param logger_ - A flag to turn on logging, or a custom logger
  274. * @param persistent - Whether or not to persist logging settings across refreshes
  275. */
  276. var enableLogging$1 = function (logger_, persistent) {
  277. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  278. if (logger_ === true) {
  279. logClient.logLevel = logger$1.LogLevel.VERBOSE;
  280. logger = logClient.log.bind(logClient);
  281. if (persistent) {
  282. SessionStorage.set('logging_enabled', true);
  283. }
  284. }
  285. else if (typeof logger_ === 'function') {
  286. logger = logger_;
  287. }
  288. else {
  289. logger = null;
  290. SessionStorage.remove('logging_enabled');
  291. }
  292. };
  293. var log = function () {
  294. var varArgs = [];
  295. for (var _i = 0; _i < arguments.length; _i++) {
  296. varArgs[_i] = arguments[_i];
  297. }
  298. if (firstLog_ === true) {
  299. firstLog_ = false;
  300. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  301. enableLogging$1(true);
  302. }
  303. }
  304. if (logger) {
  305. var message = buildLogMessage_.apply(null, varArgs);
  306. logger(message);
  307. }
  308. };
  309. var logWrapper = function (prefix) {
  310. return function () {
  311. var varArgs = [];
  312. for (var _i = 0; _i < arguments.length; _i++) {
  313. varArgs[_i] = arguments[_i];
  314. }
  315. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  316. };
  317. };
  318. var error = function () {
  319. var varArgs = [];
  320. for (var _i = 0; _i < arguments.length; _i++) {
  321. varArgs[_i] = arguments[_i];
  322. }
  323. var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  324. logClient.error(message);
  325. };
  326. var fatal = function () {
  327. var varArgs = [];
  328. for (var _i = 0; _i < arguments.length; _i++) {
  329. varArgs[_i] = arguments[_i];
  330. }
  331. var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false)));
  332. logClient.error(message);
  333. throw new Error(message);
  334. };
  335. var warn = function () {
  336. var varArgs = [];
  337. for (var _i = 0; _i < arguments.length; _i++) {
  338. varArgs[_i] = arguments[_i];
  339. }
  340. var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  341. logClient.warn(message);
  342. };
  343. /**
  344. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  345. * does not use https.
  346. */
  347. var warnIfPageIsSecure = function () {
  348. // Be very careful accessing browser globals. Who knows what may or may not exist.
  349. if (typeof window !== 'undefined' &&
  350. window.location &&
  351. window.location.protocol &&
  352. window.location.protocol.indexOf('https:') !== -1) {
  353. warn('Insecure Firebase access from a secure page. ' +
  354. 'Please use https in calls to new Firebase().');
  355. }
  356. };
  357. /**
  358. * Returns true if data is NaN, or +/- Infinity.
  359. */
  360. var isInvalidJSONNumber = function (data) {
  361. return (typeof data === 'number' &&
  362. (data !== data || // NaN
  363. data === Number.POSITIVE_INFINITY ||
  364. data === Number.NEGATIVE_INFINITY));
  365. };
  366. var executeWhenDOMReady = function (fn) {
  367. if (util.isNodeSdk() || document.readyState === 'complete') {
  368. fn();
  369. }
  370. else {
  371. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  372. // fire before onload), but fall back to onload.
  373. var called_1 = false;
  374. var wrappedFn_1 = function () {
  375. if (!document.body) {
  376. setTimeout(wrappedFn_1, Math.floor(10));
  377. return;
  378. }
  379. if (!called_1) {
  380. called_1 = true;
  381. fn();
  382. }
  383. };
  384. if (document.addEventListener) {
  385. document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
  386. // fallback to onload.
  387. window.addEventListener('load', wrappedFn_1, false);
  388. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  389. }
  390. else if (document.attachEvent) {
  391. // IE.
  392. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  393. document.attachEvent('onreadystatechange', function () {
  394. if (document.readyState === 'complete') {
  395. wrappedFn_1();
  396. }
  397. });
  398. // fallback to onload.
  399. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  400. window.attachEvent('onload', wrappedFn_1);
  401. // jQuery has an extra hack for IE that we could employ (based on
  402. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  403. // I'm hoping we don't need it.
  404. }
  405. }
  406. };
  407. /**
  408. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  409. */
  410. var MIN_NAME = '[MIN_NAME]';
  411. /**
  412. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  413. */
  414. var MAX_NAME = '[MAX_NAME]';
  415. /**
  416. * Compares valid Firebase key names, plus min and max name
  417. */
  418. var nameCompare = function (a, b) {
  419. if (a === b) {
  420. return 0;
  421. }
  422. else if (a === MIN_NAME || b === MAX_NAME) {
  423. return -1;
  424. }
  425. else if (b === MIN_NAME || a === MAX_NAME) {
  426. return 1;
  427. }
  428. else {
  429. var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  430. if (aAsInt !== null) {
  431. if (bAsInt !== null) {
  432. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  433. }
  434. else {
  435. return -1;
  436. }
  437. }
  438. else if (bAsInt !== null) {
  439. return 1;
  440. }
  441. else {
  442. return a < b ? -1 : 1;
  443. }
  444. }
  445. };
  446. /**
  447. * @returns {!number} comparison result.
  448. */
  449. var stringCompare = function (a, b) {
  450. if (a === b) {
  451. return 0;
  452. }
  453. else if (a < b) {
  454. return -1;
  455. }
  456. else {
  457. return 1;
  458. }
  459. };
  460. var requireKey = function (key, obj) {
  461. if (obj && key in obj) {
  462. return obj[key];
  463. }
  464. else {
  465. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  466. }
  467. };
  468. var ObjectToUniqueKey = function (obj) {
  469. if (typeof obj !== 'object' || obj === null) {
  470. return util.stringify(obj);
  471. }
  472. var keys = [];
  473. // eslint-disable-next-line guard-for-in
  474. for (var k in obj) {
  475. keys.push(k);
  476. }
  477. // Export as json, but with the keys sorted.
  478. keys.sort();
  479. var key = '{';
  480. for (var i = 0; i < keys.length; i++) {
  481. if (i !== 0) {
  482. key += ',';
  483. }
  484. key += util.stringify(keys[i]);
  485. key += ':';
  486. key += ObjectToUniqueKey(obj[keys[i]]);
  487. }
  488. key += '}';
  489. return key;
  490. };
  491. /**
  492. * Splits a string into a number of smaller segments of maximum size
  493. * @param str - The string
  494. * @param segsize - The maximum number of chars in the string.
  495. * @returns The string, split into appropriately-sized chunks
  496. */
  497. var splitStringBySize = function (str, segsize) {
  498. var len = str.length;
  499. if (len <= segsize) {
  500. return [str];
  501. }
  502. var dataSegs = [];
  503. for (var c = 0; c < len; c += segsize) {
  504. if (c + segsize > len) {
  505. dataSegs.push(str.substring(c, len));
  506. }
  507. else {
  508. dataSegs.push(str.substring(c, c + segsize));
  509. }
  510. }
  511. return dataSegs;
  512. };
  513. /**
  514. * Apply a function to each (key, value) pair in an object or
  515. * apply a function to each (index, value) pair in an array
  516. * @param obj - The object or array to iterate over
  517. * @param fn - The function to apply
  518. */
  519. function each(obj, fn) {
  520. for (var key in obj) {
  521. if (obj.hasOwnProperty(key)) {
  522. fn(key, obj[key]);
  523. }
  524. }
  525. }
  526. /**
  527. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  528. * I made one modification at the end and removed the NaN / Infinity
  529. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  530. * @param v - A double
  531. *
  532. */
  533. var doubleToIEEE754String = function (v) {
  534. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  535. var ebits = 11, fbits = 52;
  536. var bias = (1 << (ebits - 1)) - 1;
  537. var s, e, f, ln, i;
  538. // Compute sign, exponent, fraction
  539. // Skip NaN / Infinity handling --MJL.
  540. if (v === 0) {
  541. e = 0;
  542. f = 0;
  543. s = 1 / v === -Infinity ? 1 : 0;
  544. }
  545. else {
  546. s = v < 0;
  547. v = Math.abs(v);
  548. if (v >= Math.pow(2, 1 - bias)) {
  549. // Normalized
  550. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  551. e = ln + bias;
  552. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  553. }
  554. else {
  555. // Denormalized
  556. e = 0;
  557. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  558. }
  559. }
  560. // Pack sign, exponent, fraction
  561. var bits = [];
  562. for (i = fbits; i; i -= 1) {
  563. bits.push(f % 2 ? 1 : 0);
  564. f = Math.floor(f / 2);
  565. }
  566. for (i = ebits; i; i -= 1) {
  567. bits.push(e % 2 ? 1 : 0);
  568. e = Math.floor(e / 2);
  569. }
  570. bits.push(s ? 1 : 0);
  571. bits.reverse();
  572. var str = bits.join('');
  573. // Return the data as a hex string. --MJL
  574. var hexByteString = '';
  575. for (i = 0; i < 64; i += 8) {
  576. var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  577. if (hexByte.length === 1) {
  578. hexByte = '0' + hexByte;
  579. }
  580. hexByteString = hexByteString + hexByte;
  581. }
  582. return hexByteString.toLowerCase();
  583. };
  584. /**
  585. * Used to detect if we're in a Chrome content script (which executes in an
  586. * isolated environment where long-polling doesn't work).
  587. */
  588. var isChromeExtensionContentScript = function () {
  589. return !!(typeof window === 'object' &&
  590. window['chrome'] &&
  591. window['chrome']['extension'] &&
  592. !/^chrome/.test(window.location.href));
  593. };
  594. /**
  595. * Used to detect if we're in a Windows 8 Store app.
  596. */
  597. var isWindowsStoreApp = function () {
  598. // Check for the presence of a couple WinRT globals
  599. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  600. };
  601. /**
  602. * Converts a server error code to a Javascript Error
  603. */
  604. function errorForServerCode(code, query) {
  605. var reason = 'Unknown Error';
  606. if (code === 'too_big') {
  607. reason =
  608. 'The data requested exceeds the maximum size ' +
  609. 'that can be accessed with a single request.';
  610. }
  611. else if (code === 'permission_denied') {
  612. reason = "Client doesn't have permission to access the desired data.";
  613. }
  614. else if (code === 'unavailable') {
  615. reason = 'The service is unavailable';
  616. }
  617. var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  618. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  619. error.code = code.toUpperCase();
  620. return error;
  621. }
  622. /**
  623. * Used to test for integer-looking strings
  624. */
  625. var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  626. /**
  627. * For use in keys, the minimum possible 32-bit integer.
  628. */
  629. var INTEGER_32_MIN = -2147483648;
  630. /**
  631. * For use in kyes, the maximum possible 32-bit integer.
  632. */
  633. var INTEGER_32_MAX = 2147483647;
  634. /**
  635. * If the string contains a 32-bit integer, return it. Else return null.
  636. */
  637. var tryParseInt = function (str) {
  638. if (INTEGER_REGEXP_.test(str)) {
  639. var intVal = Number(str);
  640. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  641. return intVal;
  642. }
  643. }
  644. return null;
  645. };
  646. /**
  647. * Helper to run some code but catch any exceptions and re-throw them later.
  648. * Useful for preventing user callbacks from breaking internal code.
  649. *
  650. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  651. * convenient (we don't have to try to figure out when is a safe point to
  652. * re-throw it), and the behavior seems reasonable:
  653. *
  654. * * If you aren't pausing on exceptions, you get an error in the console with
  655. * the correct stack trace.
  656. * * If you're pausing on all exceptions, the debugger will pause on your
  657. * exception and then again when we rethrow it.
  658. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  659. * on us re-throwing it.
  660. *
  661. * @param fn - The code to guard.
  662. */
  663. var exceptionGuard = function (fn) {
  664. try {
  665. fn();
  666. }
  667. catch (e) {
  668. // Re-throw exception when it's safe.
  669. setTimeout(function () {
  670. // It used to be that "throw e" would result in a good console error with
  671. // relevant context, but as of Chrome 39, you just get the firebase.js
  672. // file/line number where we re-throw it, which is useless. So we log
  673. // e.stack explicitly.
  674. var stack = e.stack || '';
  675. warn('Exception was thrown by user callback.', stack);
  676. throw e;
  677. }, Math.floor(0));
  678. }
  679. };
  680. /**
  681. * @returns {boolean} true if we think we're currently being crawled.
  682. */
  683. var beingCrawled = function () {
  684. var userAgent = (typeof window === 'object' &&
  685. window['navigator'] &&
  686. window['navigator']['userAgent']) ||
  687. '';
  688. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  689. // believe to support JavaScript/AJAX rendering.
  690. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  691. // would have seen the page" is flaky if we don't treat it as a crawler.
  692. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  693. };
  694. /**
  695. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  696. *
  697. * It is removed with clearTimeout() as normal.
  698. *
  699. * @param fn - Function to run.
  700. * @param time - Milliseconds to wait before running.
  701. * @returns The setTimeout() return value.
  702. */
  703. var setTimeoutNonBlocking = function (fn, time) {
  704. var timeout = setTimeout(fn, time);
  705. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  706. if (typeof timeout === 'number' &&
  707. // @ts-ignore Is only defined in Deno environments.
  708. typeof Deno !== 'undefined' &&
  709. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  710. Deno['unrefTimer']) {
  711. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  712. Deno.unrefTimer(timeout);
  713. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  714. }
  715. else if (typeof timeout === 'object' && timeout['unref']) {
  716. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  717. timeout['unref']();
  718. }
  719. return timeout;
  720. };
  721. /**
  722. * @license
  723. * Copyright 2017 Google LLC
  724. *
  725. * Licensed under the Apache License, Version 2.0 (the "License");
  726. * you may not use this file except in compliance with the License.
  727. * You may obtain a copy of the License at
  728. *
  729. * http://www.apache.org/licenses/LICENSE-2.0
  730. *
  731. * Unless required by applicable law or agreed to in writing, software
  732. * distributed under the License is distributed on an "AS IS" BASIS,
  733. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  734. * See the License for the specific language governing permissions and
  735. * limitations under the License.
  736. */
  737. /**
  738. * A class that holds metadata about a Repo object
  739. */
  740. var RepoInfo = /** @class */ (function () {
  741. /**
  742. * @param host - Hostname portion of the url for the repo
  743. * @param secure - Whether or not this repo is accessed over ssl
  744. * @param namespace - The namespace represented by the repo
  745. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  746. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  747. * @param persistenceKey - Override the default session persistence storage key
  748. */
  749. function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams, isUsingEmulator) {
  750. if (nodeAdmin === void 0) { nodeAdmin = false; }
  751. if (persistenceKey === void 0) { persistenceKey = ''; }
  752. if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
  753. if (isUsingEmulator === void 0) { isUsingEmulator = false; }
  754. this.secure = secure;
  755. this.namespace = namespace;
  756. this.webSocketOnly = webSocketOnly;
  757. this.nodeAdmin = nodeAdmin;
  758. this.persistenceKey = persistenceKey;
  759. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  760. this.isUsingEmulator = isUsingEmulator;
  761. this._host = host.toLowerCase();
  762. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  763. this.internalHost =
  764. PersistentStorage.get('host:' + host) || this._host;
  765. }
  766. RepoInfo.prototype.isCacheableHost = function () {
  767. return this.internalHost.substr(0, 2) === 's-';
  768. };
  769. RepoInfo.prototype.isCustomHost = function () {
  770. return (this._domain !== 'firebaseio.com' &&
  771. this._domain !== 'firebaseio-demo.com');
  772. };
  773. Object.defineProperty(RepoInfo.prototype, "host", {
  774. get: function () {
  775. return this._host;
  776. },
  777. set: function (newHost) {
  778. if (newHost !== this.internalHost) {
  779. this.internalHost = newHost;
  780. if (this.isCacheableHost()) {
  781. PersistentStorage.set('host:' + this._host, this.internalHost);
  782. }
  783. }
  784. },
  785. enumerable: false,
  786. configurable: true
  787. });
  788. RepoInfo.prototype.toString = function () {
  789. var str = this.toURLString();
  790. if (this.persistenceKey) {
  791. str += '<' + this.persistenceKey + '>';
  792. }
  793. return str;
  794. };
  795. RepoInfo.prototype.toURLString = function () {
  796. var protocol = this.secure ? 'https://' : 'http://';
  797. var query = this.includeNamespaceInQueryParams
  798. ? "?ns=".concat(this.namespace)
  799. : '';
  800. return "".concat(protocol).concat(this.host, "/").concat(query);
  801. };
  802. return RepoInfo;
  803. }());
  804. function repoInfoNeedsQueryParam(repoInfo) {
  805. return (repoInfo.host !== repoInfo.internalHost ||
  806. repoInfo.isCustomHost() ||
  807. repoInfo.includeNamespaceInQueryParams);
  808. }
  809. /**
  810. * Returns the websocket URL for this repo
  811. * @param repoInfo - RepoInfo object
  812. * @param type - of connection
  813. * @param params - list
  814. * @returns The URL for this repo
  815. */
  816. function repoInfoConnectionURL(repoInfo, type, params) {
  817. util.assert(typeof type === 'string', 'typeof type must == string');
  818. util.assert(typeof params === 'object', 'typeof params must == object');
  819. var connURL;
  820. if (type === WEBSOCKET) {
  821. connURL =
  822. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  823. }
  824. else if (type === LONG_POLLING) {
  825. connURL =
  826. (repoInfo.secure ? 'https://' : 'http://') +
  827. repoInfo.internalHost +
  828. '/.lp?';
  829. }
  830. else {
  831. throw new Error('Unknown connection type: ' + type);
  832. }
  833. if (repoInfoNeedsQueryParam(repoInfo)) {
  834. params['ns'] = repoInfo.namespace;
  835. }
  836. var pairs = [];
  837. each(params, function (key, value) {
  838. pairs.push(key + '=' + value);
  839. });
  840. return connURL + pairs.join('&');
  841. }
  842. /**
  843. * @license
  844. * Copyright 2017 Google LLC
  845. *
  846. * Licensed under the Apache License, Version 2.0 (the "License");
  847. * you may not use this file except in compliance with the License.
  848. * You may obtain a copy of the License at
  849. *
  850. * http://www.apache.org/licenses/LICENSE-2.0
  851. *
  852. * Unless required by applicable law or agreed to in writing, software
  853. * distributed under the License is distributed on an "AS IS" BASIS,
  854. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  855. * See the License for the specific language governing permissions and
  856. * limitations under the License.
  857. */
  858. /**
  859. * Tracks a collection of stats.
  860. */
  861. var StatsCollection = /** @class */ (function () {
  862. function StatsCollection() {
  863. this.counters_ = {};
  864. }
  865. StatsCollection.prototype.incrementCounter = function (name, amount) {
  866. if (amount === void 0) { amount = 1; }
  867. if (!util.contains(this.counters_, name)) {
  868. this.counters_[name] = 0;
  869. }
  870. this.counters_[name] += amount;
  871. };
  872. StatsCollection.prototype.get = function () {
  873. return util.deepCopy(this.counters_);
  874. };
  875. return StatsCollection;
  876. }());
  877. /**
  878. * @license
  879. * Copyright 2017 Google LLC
  880. *
  881. * Licensed under the Apache License, Version 2.0 (the "License");
  882. * you may not use this file except in compliance with the License.
  883. * You may obtain a copy of the License at
  884. *
  885. * http://www.apache.org/licenses/LICENSE-2.0
  886. *
  887. * Unless required by applicable law or agreed to in writing, software
  888. * distributed under the License is distributed on an "AS IS" BASIS,
  889. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  890. * See the License for the specific language governing permissions and
  891. * limitations under the License.
  892. */
  893. var collections = {};
  894. var reporters = {};
  895. function statsManagerGetCollection(repoInfo) {
  896. var hashString = repoInfo.toString();
  897. if (!collections[hashString]) {
  898. collections[hashString] = new StatsCollection();
  899. }
  900. return collections[hashString];
  901. }
  902. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  903. var hashString = repoInfo.toString();
  904. if (!reporters[hashString]) {
  905. reporters[hashString] = creatorFunction();
  906. }
  907. return reporters[hashString];
  908. }
  909. /**
  910. * @license
  911. * Copyright 2019 Google LLC
  912. *
  913. * Licensed under the Apache License, Version 2.0 (the "License");
  914. * you may not use this file except in compliance with the License.
  915. * You may obtain a copy of the License at
  916. *
  917. * http://www.apache.org/licenses/LICENSE-2.0
  918. *
  919. * Unless required by applicable law or agreed to in writing, software
  920. * distributed under the License is distributed on an "AS IS" BASIS,
  921. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  922. * See the License for the specific language governing permissions and
  923. * limitations under the License.
  924. */
  925. /** The semver (www.semver.org) version of the SDK. */
  926. var SDK_VERSION = '';
  927. /**
  928. * SDK_VERSION should be set before any database instance is created
  929. * @internal
  930. */
  931. function setSDKVersion(version) {
  932. SDK_VERSION = version;
  933. }
  934. /**
  935. * @license
  936. * Copyright 2017 Google LLC
  937. *
  938. * Licensed under the Apache License, Version 2.0 (the "License");
  939. * you may not use this file except in compliance with the License.
  940. * You may obtain a copy of the License at
  941. *
  942. * http://www.apache.org/licenses/LICENSE-2.0
  943. *
  944. * Unless required by applicable law or agreed to in writing, software
  945. * distributed under the License is distributed on an "AS IS" BASIS,
  946. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  947. * See the License for the specific language governing permissions and
  948. * limitations under the License.
  949. */
  950. var WEBSOCKET_MAX_FRAME_SIZE = 16384;
  951. var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  952. var WebSocketImpl = null;
  953. if (typeof MozWebSocket !== 'undefined') {
  954. WebSocketImpl = MozWebSocket;
  955. }
  956. else if (typeof WebSocket !== 'undefined') {
  957. WebSocketImpl = WebSocket;
  958. }
  959. function setWebSocketImpl(impl) {
  960. WebSocketImpl = impl;
  961. }
  962. /**
  963. * Create a new websocket connection with the given callbacks.
  964. */
  965. var WebSocketConnection = /** @class */ (function () {
  966. /**
  967. * @param connId identifier for this transport
  968. * @param repoInfo The info for the websocket endpoint.
  969. * @param applicationId The Firebase App ID for this project.
  970. * @param appCheckToken The App Check Token for this client.
  971. * @param authToken The Auth Token for this client.
  972. * @param transportSessionId Optional transportSessionId if this is connecting
  973. * to an existing transport session
  974. * @param lastSessionId Optional lastSessionId if there was a previous
  975. * connection
  976. */
  977. function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  978. this.connId = connId;
  979. this.applicationId = applicationId;
  980. this.appCheckToken = appCheckToken;
  981. this.authToken = authToken;
  982. this.keepaliveTimer = null;
  983. this.frames = null;
  984. this.totalFrames = 0;
  985. this.bytesSent = 0;
  986. this.bytesReceived = 0;
  987. this.log_ = logWrapper(this.connId);
  988. this.stats_ = statsManagerGetCollection(repoInfo);
  989. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  990. this.nodeAdmin = repoInfo.nodeAdmin;
  991. }
  992. /**
  993. * @param repoInfo - The info for the websocket endpoint.
  994. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  995. * session
  996. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  997. * @returns connection url
  998. */
  999. WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  1000. var urlParams = {};
  1001. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1002. if (!util.isNodeSdk() &&
  1003. typeof location !== 'undefined' &&
  1004. location.hostname &&
  1005. FORGE_DOMAIN_RE.test(location.hostname)) {
  1006. urlParams[REFERER_PARAM] = FORGE_REF;
  1007. }
  1008. if (transportSessionId) {
  1009. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1010. }
  1011. if (lastSessionId) {
  1012. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1013. }
  1014. if (appCheckToken) {
  1015. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1016. }
  1017. if (applicationId) {
  1018. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1019. }
  1020. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1021. };
  1022. /**
  1023. * @param onMessage - Callback when messages arrive
  1024. * @param onDisconnect - Callback with connection lost.
  1025. */
  1026. WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
  1027. var _this = this;
  1028. this.onDisconnect = onDisconnect;
  1029. this.onMessage = onMessage;
  1030. this.log_('Websocket connecting to ' + this.connURL);
  1031. this.everConnected_ = false;
  1032. // Assume failure until proven otherwise.
  1033. PersistentStorage.set('previous_websocket_failure', true);
  1034. try {
  1035. var options = void 0;
  1036. if (util.isNodeSdk()) {
  1037. var device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1038. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1039. options = {
  1040. headers: {
  1041. 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
  1042. 'X-Firebase-GMPID': this.applicationId || ''
  1043. }
  1044. };
  1045. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1046. // Note that we send the credentials here even if they aren't admin credentials, which is
  1047. // not a problem.
  1048. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1049. // through the websocket connection once it is established.
  1050. if (this.authToken) {
  1051. options.headers['Authorization'] = "Bearer ".concat(this.authToken);
  1052. }
  1053. if (this.appCheckToken) {
  1054. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1055. }
  1056. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1057. var env = process['env'];
  1058. var proxy = this.connURL.indexOf('wss://') === 0
  1059. ? env['HTTPS_PROXY'] || env['https_proxy']
  1060. : env['HTTP_PROXY'] || env['http_proxy'];
  1061. if (proxy) {
  1062. options['proxy'] = { origin: proxy };
  1063. }
  1064. }
  1065. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1066. }
  1067. catch (e) {
  1068. this.log_('Error instantiating WebSocket.');
  1069. var error = e.message || e.data;
  1070. if (error) {
  1071. this.log_(error);
  1072. }
  1073. this.onClosed_();
  1074. return;
  1075. }
  1076. this.mySock.onopen = function () {
  1077. _this.log_('Websocket connected.');
  1078. _this.everConnected_ = true;
  1079. };
  1080. this.mySock.onclose = function () {
  1081. _this.log_('Websocket connection was disconnected.');
  1082. _this.mySock = null;
  1083. _this.onClosed_();
  1084. };
  1085. this.mySock.onmessage = function (m) {
  1086. _this.handleIncomingFrame(m);
  1087. };
  1088. this.mySock.onerror = function (e) {
  1089. _this.log_('WebSocket error. Closing connection.');
  1090. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1091. var error = e.message || e.data;
  1092. if (error) {
  1093. _this.log_(error);
  1094. }
  1095. _this.onClosed_();
  1096. };
  1097. };
  1098. /**
  1099. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1100. */
  1101. WebSocketConnection.prototype.start = function () { };
  1102. WebSocketConnection.forceDisallow = function () {
  1103. WebSocketConnection.forceDisallow_ = true;
  1104. };
  1105. WebSocketConnection.isAvailable = function () {
  1106. var isOldAndroid = false;
  1107. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1108. var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1109. var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1110. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1111. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1112. isOldAndroid = true;
  1113. }
  1114. }
  1115. }
  1116. return (!isOldAndroid &&
  1117. WebSocketImpl !== null &&
  1118. !WebSocketConnection.forceDisallow_);
  1119. };
  1120. /**
  1121. * Returns true if we previously failed to connect with this transport.
  1122. */
  1123. WebSocketConnection.previouslyFailed = function () {
  1124. // If our persistent storage is actually only in-memory storage,
  1125. // we default to assuming that it previously failed to be safe.
  1126. return (PersistentStorage.isInMemoryStorage ||
  1127. PersistentStorage.get('previous_websocket_failure') === true);
  1128. };
  1129. WebSocketConnection.prototype.markConnectionHealthy = function () {
  1130. PersistentStorage.remove('previous_websocket_failure');
  1131. };
  1132. WebSocketConnection.prototype.appendFrame_ = function (data) {
  1133. this.frames.push(data);
  1134. if (this.frames.length === this.totalFrames) {
  1135. var fullMess = this.frames.join('');
  1136. this.frames = null;
  1137. var jsonMess = util.jsonEval(fullMess);
  1138. //handle the message
  1139. this.onMessage(jsonMess);
  1140. }
  1141. };
  1142. /**
  1143. * @param frameCount - The number of frames we are expecting from the server
  1144. */
  1145. WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
  1146. this.totalFrames = frameCount;
  1147. this.frames = [];
  1148. };
  1149. /**
  1150. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1151. * @returns Any remaining data to be process, or null if there is none
  1152. */
  1153. WebSocketConnection.prototype.extractFrameCount_ = function (data) {
  1154. util.assert(this.frames === null, 'We already have a frame buffer');
  1155. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1156. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1157. if (data.length <= 6) {
  1158. var frameCount = Number(data);
  1159. if (!isNaN(frameCount)) {
  1160. this.handleNewFrameCount_(frameCount);
  1161. return null;
  1162. }
  1163. }
  1164. this.handleNewFrameCount_(1);
  1165. return data;
  1166. };
  1167. /**
  1168. * Process a websocket frame that has arrived from the server.
  1169. * @param mess - The frame data
  1170. */
  1171. WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
  1172. if (this.mySock === null) {
  1173. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1174. }
  1175. var data = mess['data'];
  1176. this.bytesReceived += data.length;
  1177. this.stats_.incrementCounter('bytes_received', data.length);
  1178. this.resetKeepAlive();
  1179. if (this.frames !== null) {
  1180. // we're buffering
  1181. this.appendFrame_(data);
  1182. }
  1183. else {
  1184. // try to parse out a frame count, otherwise, assume 1 and process it
  1185. var remainingData = this.extractFrameCount_(data);
  1186. if (remainingData !== null) {
  1187. this.appendFrame_(remainingData);
  1188. }
  1189. }
  1190. };
  1191. /**
  1192. * Send a message to the server
  1193. * @param data - The JSON object to transmit
  1194. */
  1195. WebSocketConnection.prototype.send = function (data) {
  1196. this.resetKeepAlive();
  1197. var dataStr = util.stringify(data);
  1198. this.bytesSent += dataStr.length;
  1199. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1200. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1201. //up into multiple pieces if it doesn't fit in one request.
  1202. var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1203. //Send the length header
  1204. if (dataSegs.length > 1) {
  1205. this.sendString_(String(dataSegs.length));
  1206. }
  1207. //Send the actual data in segments.
  1208. for (var i = 0; i < dataSegs.length; i++) {
  1209. this.sendString_(dataSegs[i]);
  1210. }
  1211. };
  1212. WebSocketConnection.prototype.shutdown_ = function () {
  1213. this.isClosed_ = true;
  1214. if (this.keepaliveTimer) {
  1215. clearInterval(this.keepaliveTimer);
  1216. this.keepaliveTimer = null;
  1217. }
  1218. if (this.mySock) {
  1219. this.mySock.close();
  1220. this.mySock = null;
  1221. }
  1222. };
  1223. WebSocketConnection.prototype.onClosed_ = function () {
  1224. if (!this.isClosed_) {
  1225. this.log_('WebSocket is closing itself');
  1226. this.shutdown_();
  1227. // since this is an internal close, trigger the close listener
  1228. if (this.onDisconnect) {
  1229. this.onDisconnect(this.everConnected_);
  1230. this.onDisconnect = null;
  1231. }
  1232. }
  1233. };
  1234. /**
  1235. * External-facing close handler.
  1236. * Close the websocket and kill the connection.
  1237. */
  1238. WebSocketConnection.prototype.close = function () {
  1239. if (!this.isClosed_) {
  1240. this.log_('WebSocket is being closed');
  1241. this.shutdown_();
  1242. }
  1243. };
  1244. /**
  1245. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1246. * the last activity.
  1247. */
  1248. WebSocketConnection.prototype.resetKeepAlive = function () {
  1249. var _this = this;
  1250. clearInterval(this.keepaliveTimer);
  1251. this.keepaliveTimer = setInterval(function () {
  1252. //If there has been no websocket activity for a while, send a no-op
  1253. if (_this.mySock) {
  1254. _this.sendString_('0');
  1255. }
  1256. _this.resetKeepAlive();
  1257. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1258. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1259. };
  1260. /**
  1261. * Send a string over the websocket.
  1262. *
  1263. * @param str - String to send.
  1264. */
  1265. WebSocketConnection.prototype.sendString_ = function (str) {
  1266. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1267. // calls for some unknown reason. We treat these as an error and disconnect.
  1268. // See https://app.asana.com/0/58926111402292/68021340250410
  1269. try {
  1270. this.mySock.send(str);
  1271. }
  1272. catch (e) {
  1273. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1274. setTimeout(this.onClosed_.bind(this), 0);
  1275. }
  1276. };
  1277. /**
  1278. * Number of response before we consider the connection "healthy."
  1279. */
  1280. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1281. /**
  1282. * Time to wait for the connection te become healthy before giving up.
  1283. */
  1284. WebSocketConnection.healthyTimeout = 30000;
  1285. return WebSocketConnection;
  1286. }());
  1287. var name = "@firebase/database";
  1288. var version = "0.14.4";
  1289. /**
  1290. * @license
  1291. * Copyright 2021 Google LLC
  1292. *
  1293. * Licensed under the Apache License, Version 2.0 (the "License");
  1294. * you may not use this file except in compliance with the License.
  1295. * You may obtain a copy of the License at
  1296. *
  1297. * http://www.apache.org/licenses/LICENSE-2.0
  1298. *
  1299. * Unless required by applicable law or agreed to in writing, software
  1300. * distributed under the License is distributed on an "AS IS" BASIS,
  1301. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1302. * See the License for the specific language governing permissions and
  1303. * limitations under the License.
  1304. */
  1305. /**
  1306. * Abstraction around AppCheck's token fetching capabilities.
  1307. */
  1308. var AppCheckTokenProvider = /** @class */ (function () {
  1309. function AppCheckTokenProvider(appName_, appCheckProvider) {
  1310. var _this = this;
  1311. this.appName_ = appName_;
  1312. this.appCheckProvider = appCheckProvider;
  1313. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1314. if (!this.appCheck) {
  1315. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
  1316. }
  1317. }
  1318. AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
  1319. var _this = this;
  1320. if (!this.appCheck) {
  1321. return new Promise(function (resolve, reject) {
  1322. // Support delayed initialization of FirebaseAppCheck. This allows our
  1323. // customers to initialize the RTDB SDK before initializing Firebase
  1324. // AppCheck and ensures that all requests are authenticated if a token
  1325. // becomes available before the timoeout below expires.
  1326. setTimeout(function () {
  1327. if (_this.appCheck) {
  1328. _this.getToken(forceRefresh).then(resolve, reject);
  1329. }
  1330. else {
  1331. resolve(null);
  1332. }
  1333. }, 0);
  1334. });
  1335. }
  1336. return this.appCheck.getToken(forceRefresh);
  1337. };
  1338. AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1339. var _a;
  1340. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
  1341. };
  1342. AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
  1343. warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
  1344. 'are invalid. This usually indicates your app was not initialized correctly.');
  1345. };
  1346. return AppCheckTokenProvider;
  1347. }());
  1348. /**
  1349. * @license
  1350. * Copyright 2017 Google LLC
  1351. *
  1352. * Licensed under the Apache License, Version 2.0 (the "License");
  1353. * you may not use this file except in compliance with the License.
  1354. * You may obtain a copy of the License at
  1355. *
  1356. * http://www.apache.org/licenses/LICENSE-2.0
  1357. *
  1358. * Unless required by applicable law or agreed to in writing, software
  1359. * distributed under the License is distributed on an "AS IS" BASIS,
  1360. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1361. * See the License for the specific language governing permissions and
  1362. * limitations under the License.
  1363. */
  1364. /**
  1365. * Abstraction around FirebaseApp's token fetching capabilities.
  1366. */
  1367. var FirebaseAuthTokenProvider = /** @class */ (function () {
  1368. function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
  1369. var _this = this;
  1370. this.appName_ = appName_;
  1371. this.firebaseOptions_ = firebaseOptions_;
  1372. this.authProvider_ = authProvider_;
  1373. this.auth_ = null;
  1374. this.auth_ = authProvider_.getImmediate({ optional: true });
  1375. if (!this.auth_) {
  1376. authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
  1377. }
  1378. }
  1379. FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
  1380. var _this = this;
  1381. if (!this.auth_) {
  1382. return new Promise(function (resolve, reject) {
  1383. // Support delayed initialization of FirebaseAuth. This allows our
  1384. // customers to initialize the RTDB SDK before initializing Firebase
  1385. // Auth and ensures that all requests are authenticated if a token
  1386. // becomes available before the timoeout below expires.
  1387. setTimeout(function () {
  1388. if (_this.auth_) {
  1389. _this.getToken(forceRefresh).then(resolve, reject);
  1390. }
  1391. else {
  1392. resolve(null);
  1393. }
  1394. }, 0);
  1395. });
  1396. }
  1397. return this.auth_.getToken(forceRefresh).catch(function (error) {
  1398. // TODO: Need to figure out all the cases this is raised and whether
  1399. // this makes sense.
  1400. if (error && error.code === 'auth/token-not-initialized') {
  1401. log('Got auth/token-not-initialized error. Treating as null token.');
  1402. return null;
  1403. }
  1404. else {
  1405. return Promise.reject(error);
  1406. }
  1407. });
  1408. };
  1409. FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1410. // TODO: We might want to wrap the listener and call it with no args to
  1411. // avoid a leaky abstraction, but that makes removing the listener harder.
  1412. if (this.auth_) {
  1413. this.auth_.addAuthTokenListener(listener);
  1414. }
  1415. else {
  1416. this.authProvider_
  1417. .get()
  1418. .then(function (auth) { return auth.addAuthTokenListener(listener); });
  1419. }
  1420. };
  1421. FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
  1422. this.authProvider_
  1423. .get()
  1424. .then(function (auth) { return auth.removeAuthTokenListener(listener); });
  1425. };
  1426. FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
  1427. var errorMessage = 'Provided authentication credentials for the app named "' +
  1428. this.appName_ +
  1429. '" are invalid. This usually indicates your app was not ' +
  1430. 'initialized correctly. ';
  1431. if ('credential' in this.firebaseOptions_) {
  1432. errorMessage +=
  1433. 'Make sure the "credential" property provided to initializeApp() ' +
  1434. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1435. 'project.';
  1436. }
  1437. else if ('serviceAccount' in this.firebaseOptions_) {
  1438. errorMessage +=
  1439. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1440. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1441. 'project.';
  1442. }
  1443. else {
  1444. errorMessage +=
  1445. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1446. 'initializeApp() match the values provided for your app at ' +
  1447. 'https://console.firebase.google.com/.';
  1448. }
  1449. warn(errorMessage);
  1450. };
  1451. return FirebaseAuthTokenProvider;
  1452. }());
  1453. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1454. var EmulatorTokenProvider = /** @class */ (function () {
  1455. function EmulatorTokenProvider(accessToken) {
  1456. this.accessToken = accessToken;
  1457. }
  1458. EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
  1459. return Promise.resolve({
  1460. accessToken: this.accessToken
  1461. });
  1462. };
  1463. EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1464. // Invoke the listener immediately to match the behavior in Firebase Auth
  1465. // (see packages/auth/src/auth.js#L1807)
  1466. listener(this.accessToken);
  1467. };
  1468. EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
  1469. EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
  1470. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1471. EmulatorTokenProvider.OWNER = 'owner';
  1472. return EmulatorTokenProvider;
  1473. }());
  1474. /**
  1475. * @license
  1476. * Copyright 2017 Google LLC
  1477. *
  1478. * Licensed under the Apache License, Version 2.0 (the "License");
  1479. * you may not use this file except in compliance with the License.
  1480. * You may obtain a copy of the License at
  1481. *
  1482. * http://www.apache.org/licenses/LICENSE-2.0
  1483. *
  1484. * Unless required by applicable law or agreed to in writing, software
  1485. * distributed under the License is distributed on an "AS IS" BASIS,
  1486. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1487. * See the License for the specific language governing permissions and
  1488. * limitations under the License.
  1489. */
  1490. /**
  1491. * This class ensures the packets from the server arrive in order
  1492. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1493. */
  1494. var PacketReceiver = /** @class */ (function () {
  1495. /**
  1496. * @param onMessage_
  1497. */
  1498. function PacketReceiver(onMessage_) {
  1499. this.onMessage_ = onMessage_;
  1500. this.pendingResponses = [];
  1501. this.currentResponseNum = 0;
  1502. this.closeAfterResponse = -1;
  1503. this.onClose = null;
  1504. }
  1505. PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
  1506. this.closeAfterResponse = responseNum;
  1507. this.onClose = callback;
  1508. if (this.closeAfterResponse < this.currentResponseNum) {
  1509. this.onClose();
  1510. this.onClose = null;
  1511. }
  1512. };
  1513. /**
  1514. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1515. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1516. * browsers will respond in the same order as the requests we sent
  1517. */
  1518. PacketReceiver.prototype.handleResponse = function (requestNum, data) {
  1519. var _this = this;
  1520. this.pendingResponses[requestNum] = data;
  1521. var _loop_1 = function () {
  1522. var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
  1523. delete this_1.pendingResponses[this_1.currentResponseNum];
  1524. var _loop_2 = function (i) {
  1525. if (toProcess[i]) {
  1526. exceptionGuard(function () {
  1527. _this.onMessage_(toProcess[i]);
  1528. });
  1529. }
  1530. };
  1531. for (var i = 0; i < toProcess.length; ++i) {
  1532. _loop_2(i);
  1533. }
  1534. if (this_1.currentResponseNum === this_1.closeAfterResponse) {
  1535. if (this_1.onClose) {
  1536. this_1.onClose();
  1537. this_1.onClose = null;
  1538. }
  1539. return "break";
  1540. }
  1541. this_1.currentResponseNum++;
  1542. };
  1543. var this_1 = this;
  1544. while (this.pendingResponses[this.currentResponseNum]) {
  1545. var state_1 = _loop_1();
  1546. if (state_1 === "break")
  1547. break;
  1548. }
  1549. };
  1550. return PacketReceiver;
  1551. }());
  1552. /**
  1553. * @license
  1554. * Copyright 2017 Google LLC
  1555. *
  1556. * Licensed under the Apache License, Version 2.0 (the "License");
  1557. * you may not use this file except in compliance with the License.
  1558. * You may obtain a copy of the License at
  1559. *
  1560. * http://www.apache.org/licenses/LICENSE-2.0
  1561. *
  1562. * Unless required by applicable law or agreed to in writing, software
  1563. * distributed under the License is distributed on an "AS IS" BASIS,
  1564. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1565. * See the License for the specific language governing permissions and
  1566. * limitations under the License.
  1567. */
  1568. // URL query parameters associated with longpolling
  1569. var FIREBASE_LONGPOLL_START_PARAM = 'start';
  1570. var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1571. var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1572. var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1573. var FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1574. var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1575. var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1576. var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1577. var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1578. var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1579. var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1580. var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1581. //Data size constants.
  1582. //TODO: Perf: the maximum length actually differs from browser to browser.
  1583. // We should check what browser we're on and set accordingly.
  1584. var MAX_URL_DATA_SIZE = 1870;
  1585. var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1586. var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1587. /**
  1588. * Keepalive period
  1589. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1590. * length of 30 seconds that we can't exceed.
  1591. */
  1592. var KEEPALIVE_REQUEST_INTERVAL = 25000;
  1593. /**
  1594. * How long to wait before aborting a long-polling connection attempt.
  1595. */
  1596. var LP_CONNECT_TIMEOUT = 30000;
  1597. /**
  1598. * This class manages a single long-polling connection.
  1599. */
  1600. var BrowserPollConnection = /** @class */ (function () {
  1601. /**
  1602. * @param connId An identifier for this connection, used for logging
  1603. * @param repoInfo The info for the endpoint to send data to.
  1604. * @param applicationId The Firebase App ID for this project.
  1605. * @param appCheckToken The AppCheck token for this client.
  1606. * @param authToken The AuthToken to use for this connection.
  1607. * @param transportSessionId Optional transportSessionid if we are
  1608. * reconnecting for an existing transport session
  1609. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1610. * already created a connection previously
  1611. */
  1612. function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1613. var _this = this;
  1614. this.connId = connId;
  1615. this.repoInfo = repoInfo;
  1616. this.applicationId = applicationId;
  1617. this.appCheckToken = appCheckToken;
  1618. this.authToken = authToken;
  1619. this.transportSessionId = transportSessionId;
  1620. this.lastSessionId = lastSessionId;
  1621. this.bytesSent = 0;
  1622. this.bytesReceived = 0;
  1623. this.everConnected_ = false;
  1624. this.log_ = logWrapper(connId);
  1625. this.stats_ = statsManagerGetCollection(repoInfo);
  1626. this.urlFn = function (params) {
  1627. // Always add the token if we have one.
  1628. if (_this.appCheckToken) {
  1629. params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1630. }
  1631. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1632. };
  1633. }
  1634. /**
  1635. * @param onMessage - Callback when messages arrive
  1636. * @param onDisconnect - Callback with connection lost.
  1637. */
  1638. BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
  1639. var _this = this;
  1640. this.curSegmentNum = 0;
  1641. this.onDisconnect_ = onDisconnect;
  1642. this.myPacketOrderer = new PacketReceiver(onMessage);
  1643. this.isClosed_ = false;
  1644. this.connectTimeoutTimer_ = setTimeout(function () {
  1645. _this.log_('Timed out trying to connect.');
  1646. // Make sure we clear the host cache
  1647. _this.onClosed_();
  1648. _this.connectTimeoutTimer_ = null;
  1649. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1650. }, Math.floor(LP_CONNECT_TIMEOUT));
  1651. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1652. executeWhenDOMReady(function () {
  1653. if (_this.isClosed_) {
  1654. return;
  1655. }
  1656. //Set up a callback that gets triggered once a connection is set up.
  1657. _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
  1658. var args = [];
  1659. for (var _i = 0; _i < arguments.length; _i++) {
  1660. args[_i] = arguments[_i];
  1661. }
  1662. var _a = tslib.__read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
  1663. _this.incrementIncomingBytes_(args);
  1664. if (!_this.scriptTagHolder) {
  1665. return; // we closed the connection.
  1666. }
  1667. if (_this.connectTimeoutTimer_) {
  1668. clearTimeout(_this.connectTimeoutTimer_);
  1669. _this.connectTimeoutTimer_ = null;
  1670. }
  1671. _this.everConnected_ = true;
  1672. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1673. _this.id = arg1;
  1674. _this.password = arg2;
  1675. }
  1676. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1677. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1678. if (arg1) {
  1679. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1680. // through our already open polls), so don't send any more.
  1681. _this.scriptTagHolder.sendNewPolls = false;
  1682. // arg1 in this case is the last response number sent by the server. We should try to receive
  1683. // all of the responses up to this one before closing
  1684. _this.myPacketOrderer.closeAfter(arg1, function () {
  1685. _this.onClosed_();
  1686. });
  1687. }
  1688. else {
  1689. _this.onClosed_();
  1690. }
  1691. }
  1692. else {
  1693. throw new Error('Unrecognized command received: ' + command);
  1694. }
  1695. }, function () {
  1696. var args = [];
  1697. for (var _i = 0; _i < arguments.length; _i++) {
  1698. args[_i] = arguments[_i];
  1699. }
  1700. var _a = tslib.__read(args, 2), pN = _a[0], data = _a[1];
  1701. _this.incrementIncomingBytes_(args);
  1702. _this.myPacketOrderer.handleResponse(pN, data);
  1703. }, function () {
  1704. _this.onClosed_();
  1705. }, _this.urlFn);
  1706. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1707. //from cache.
  1708. var urlParams = {};
  1709. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1710. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1711. if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
  1712. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1713. _this.scriptTagHolder.uniqueCallbackIdentifier;
  1714. }
  1715. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1716. if (_this.transportSessionId) {
  1717. urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
  1718. }
  1719. if (_this.lastSessionId) {
  1720. urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
  1721. }
  1722. if (_this.applicationId) {
  1723. urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
  1724. }
  1725. if (_this.appCheckToken) {
  1726. urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1727. }
  1728. if (typeof location !== 'undefined' &&
  1729. location.hostname &&
  1730. FORGE_DOMAIN_RE.test(location.hostname)) {
  1731. urlParams[REFERER_PARAM] = FORGE_REF;
  1732. }
  1733. var connectURL = _this.urlFn(urlParams);
  1734. _this.log_('Connecting via long-poll to ' + connectURL);
  1735. _this.scriptTagHolder.addTag(connectURL, function () {
  1736. /* do nothing */
  1737. });
  1738. });
  1739. };
  1740. /**
  1741. * Call this when a handshake has completed successfully and we want to consider the connection established
  1742. */
  1743. BrowserPollConnection.prototype.start = function () {
  1744. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1745. this.addDisconnectPingFrame(this.id, this.password);
  1746. };
  1747. /**
  1748. * Forces long polling to be considered as a potential transport
  1749. */
  1750. BrowserPollConnection.forceAllow = function () {
  1751. BrowserPollConnection.forceAllow_ = true;
  1752. };
  1753. /**
  1754. * Forces longpolling to not be considered as a potential transport
  1755. */
  1756. BrowserPollConnection.forceDisallow = function () {
  1757. BrowserPollConnection.forceDisallow_ = true;
  1758. };
  1759. // Static method, use string literal so it can be accessed in a generic way
  1760. BrowserPollConnection.isAvailable = function () {
  1761. if (util.isNodeSdk()) {
  1762. return false;
  1763. }
  1764. else if (BrowserPollConnection.forceAllow_) {
  1765. return true;
  1766. }
  1767. else {
  1768. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1769. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1770. return (!BrowserPollConnection.forceDisallow_ &&
  1771. typeof document !== 'undefined' &&
  1772. document.createElement != null &&
  1773. !isChromeExtensionContentScript() &&
  1774. !isWindowsStoreApp());
  1775. }
  1776. };
  1777. /**
  1778. * No-op for polling
  1779. */
  1780. BrowserPollConnection.prototype.markConnectionHealthy = function () { };
  1781. /**
  1782. * Stops polling and cleans up the iframe
  1783. */
  1784. BrowserPollConnection.prototype.shutdown_ = function () {
  1785. this.isClosed_ = true;
  1786. if (this.scriptTagHolder) {
  1787. this.scriptTagHolder.close();
  1788. this.scriptTagHolder = null;
  1789. }
  1790. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1791. if (this.myDisconnFrame) {
  1792. document.body.removeChild(this.myDisconnFrame);
  1793. this.myDisconnFrame = null;
  1794. }
  1795. if (this.connectTimeoutTimer_) {
  1796. clearTimeout(this.connectTimeoutTimer_);
  1797. this.connectTimeoutTimer_ = null;
  1798. }
  1799. };
  1800. /**
  1801. * Triggered when this transport is closed
  1802. */
  1803. BrowserPollConnection.prototype.onClosed_ = function () {
  1804. if (!this.isClosed_) {
  1805. this.log_('Longpoll is closing itself');
  1806. this.shutdown_();
  1807. if (this.onDisconnect_) {
  1808. this.onDisconnect_(this.everConnected_);
  1809. this.onDisconnect_ = null;
  1810. }
  1811. }
  1812. };
  1813. /**
  1814. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1815. * that we've left.
  1816. */
  1817. BrowserPollConnection.prototype.close = function () {
  1818. if (!this.isClosed_) {
  1819. this.log_('Longpoll is being closed.');
  1820. this.shutdown_();
  1821. }
  1822. };
  1823. /**
  1824. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1825. * broken into chunks (since URLs have a small maximum length).
  1826. * @param data - The JSON data to transmit.
  1827. */
  1828. BrowserPollConnection.prototype.send = function (data) {
  1829. var dataStr = util.stringify(data);
  1830. this.bytesSent += dataStr.length;
  1831. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1832. //first, lets get the base64-encoded data
  1833. var base64data = util.base64Encode(dataStr);
  1834. //We can only fit a certain amount in each URL, so we need to split this request
  1835. //up into multiple pieces if it doesn't fit in one request.
  1836. var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1837. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1838. //of segments so that we can reassemble the packet on the server.
  1839. for (var i = 0; i < dataSegs.length; i++) {
  1840. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1841. this.curSegmentNum++;
  1842. }
  1843. };
  1844. /**
  1845. * This is how we notify the server that we're leaving.
  1846. * We aren't able to send requests with DHTML on a window close event, but we can
  1847. * trigger XHR requests in some browsers (everything but Opera basically).
  1848. */
  1849. BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
  1850. if (util.isNodeSdk()) {
  1851. return;
  1852. }
  1853. this.myDisconnFrame = document.createElement('iframe');
  1854. var urlParams = {};
  1855. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1856. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1857. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1858. this.myDisconnFrame.src = this.urlFn(urlParams);
  1859. this.myDisconnFrame.style.display = 'none';
  1860. document.body.appendChild(this.myDisconnFrame);
  1861. };
  1862. /**
  1863. * Used to track the bytes received by this client
  1864. */
  1865. BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
  1866. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1867. var bytesReceived = util.stringify(args).length;
  1868. this.bytesReceived += bytesReceived;
  1869. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1870. };
  1871. return BrowserPollConnection;
  1872. }());
  1873. /*********************************************************************************************
  1874. * A wrapper around an iframe that is used as a long-polling script holder.
  1875. *********************************************************************************************/
  1876. var FirebaseIFrameScriptHolder = /** @class */ (function () {
  1877. /**
  1878. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1879. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1880. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1881. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1882. */
  1883. function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
  1884. this.onDisconnect = onDisconnect;
  1885. this.urlFn = urlFn;
  1886. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1887. //problems in some browsers.
  1888. this.outstandingRequests = new Set();
  1889. //A queue of the pending segments waiting for transmission to the server.
  1890. this.pendingSegs = [];
  1891. //A serial number. We use this for two things:
  1892. // 1) A way to ensure the browser doesn't cache responses to polls
  1893. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1894. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1895. // JSONP code in the order it was added to the iframe.
  1896. this.currentSerial = Math.floor(Math.random() * 100000000);
  1897. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1898. // incoming data from the server that we're waiting for).
  1899. this.sendNewPolls = true;
  1900. if (!util.isNodeSdk()) {
  1901. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1902. //iframes where we put the long-polling script tags. We have two callbacks:
  1903. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1904. // 2) Message Callback - Triggered when new data arrives.
  1905. this.uniqueCallbackIdentifier = LUIDGenerator();
  1906. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1907. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1908. onMessageCB;
  1909. //Create an iframe for us to add script tags to.
  1910. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1911. // Set the iframe's contents.
  1912. var script = '';
  1913. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1914. // for ie9, but ie8 needs to do it again in the document itself.
  1915. if (this.myIFrame.src &&
  1916. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1917. var currentDomain = document.domain;
  1918. script = '<script>document.domain="' + currentDomain + '";</script>';
  1919. }
  1920. var iframeContents = '<html><body>' + script + '</body></html>';
  1921. try {
  1922. this.myIFrame.doc.open();
  1923. this.myIFrame.doc.write(iframeContents);
  1924. this.myIFrame.doc.close();
  1925. }
  1926. catch (e) {
  1927. log('frame writing exception');
  1928. if (e.stack) {
  1929. log(e.stack);
  1930. }
  1931. log(e);
  1932. }
  1933. }
  1934. else {
  1935. this.commandCB = commandCB;
  1936. this.onMessageCB = onMessageCB;
  1937. }
  1938. }
  1939. /**
  1940. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1941. * actually use.
  1942. */
  1943. FirebaseIFrameScriptHolder.createIFrame_ = function () {
  1944. var iframe = document.createElement('iframe');
  1945. iframe.style.display = 'none';
  1946. // This is necessary in order to initialize the document inside the iframe
  1947. if (document.body) {
  1948. document.body.appendChild(iframe);
  1949. try {
  1950. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1951. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1952. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1953. var a = iframe.contentWindow.document;
  1954. if (!a) {
  1955. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1956. log('No IE domain setting required');
  1957. }
  1958. }
  1959. catch (e) {
  1960. var domain = document.domain;
  1961. iframe.src =
  1962. "javascript:void((function(){document.open();document.domain='" +
  1963. domain +
  1964. "';document.close();})())";
  1965. }
  1966. }
  1967. else {
  1968. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1969. // never gets hit.
  1970. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1971. }
  1972. // Get the document of the iframe in a browser-specific way.
  1973. if (iframe.contentDocument) {
  1974. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1975. }
  1976. else if (iframe.contentWindow) {
  1977. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1978. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1979. }
  1980. else if (iframe.document) {
  1981. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1982. iframe.doc = iframe.document; //others?
  1983. }
  1984. return iframe;
  1985. };
  1986. /**
  1987. * Cancel all outstanding queries and remove the frame.
  1988. */
  1989. FirebaseIFrameScriptHolder.prototype.close = function () {
  1990. var _this = this;
  1991. //Mark this iframe as dead, so no new requests are sent.
  1992. this.alive = false;
  1993. if (this.myIFrame) {
  1994. //We have to actually remove all of the html inside this iframe before removing it from the
  1995. //window, or IE will continue loading and executing the script tags we've already added, which
  1996. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1997. this.myIFrame.doc.body.textContent = '';
  1998. setTimeout(function () {
  1999. if (_this.myIFrame !== null) {
  2000. document.body.removeChild(_this.myIFrame);
  2001. _this.myIFrame = null;
  2002. }
  2003. }, Math.floor(0));
  2004. }
  2005. // Protect from being called recursively.
  2006. var onDisconnect = this.onDisconnect;
  2007. if (onDisconnect) {
  2008. this.onDisconnect = null;
  2009. onDisconnect();
  2010. }
  2011. };
  2012. /**
  2013. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  2014. * @param id - The ID of this connection
  2015. * @param pw - The password for this connection
  2016. */
  2017. FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
  2018. this.myID = id;
  2019. this.myPW = pw;
  2020. this.alive = true;
  2021. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  2022. while (this.newRequest_()) { }
  2023. };
  2024. /**
  2025. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  2026. * too many outstanding requests and we are still alive.
  2027. *
  2028. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  2029. * needed.
  2030. */
  2031. FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
  2032. // We keep one outstanding request open all the time to receive data, but if we need to send data
  2033. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  2034. // close the old request.
  2035. if (this.alive &&
  2036. this.sendNewPolls &&
  2037. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  2038. //construct our url
  2039. this.currentSerial++;
  2040. var urlParams = {};
  2041. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  2042. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  2043. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  2044. var theURL = this.urlFn(urlParams);
  2045. //Now add as much data as we can.
  2046. var curDataString = '';
  2047. var i = 0;
  2048. while (this.pendingSegs.length > 0) {
  2049. //first, lets see if the next segment will fit.
  2050. var nextSeg = this.pendingSegs[0];
  2051. if (nextSeg.d.length +
  2052. SEG_HEADER_SIZE +
  2053. curDataString.length <=
  2054. MAX_URL_DATA_SIZE) {
  2055. //great, the segment will fit. Lets append it.
  2056. var theSeg = this.pendingSegs.shift();
  2057. curDataString =
  2058. curDataString +
  2059. '&' +
  2060. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  2061. i +
  2062. '=' +
  2063. theSeg.seg +
  2064. '&' +
  2065. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  2066. i +
  2067. '=' +
  2068. theSeg.ts +
  2069. '&' +
  2070. FIREBASE_LONGPOLL_DATA_PARAM +
  2071. i +
  2072. '=' +
  2073. theSeg.d;
  2074. i++;
  2075. }
  2076. else {
  2077. break;
  2078. }
  2079. }
  2080. theURL = theURL + curDataString;
  2081. this.addLongPollTag_(theURL, this.currentSerial);
  2082. return true;
  2083. }
  2084. else {
  2085. return false;
  2086. }
  2087. };
  2088. /**
  2089. * Queue a packet for transmission to the server.
  2090. * @param segnum - A sequential id for this packet segment used for reassembly
  2091. * @param totalsegs - The total number of segments in this packet
  2092. * @param data - The data for this segment.
  2093. */
  2094. FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
  2095. //add this to the queue of segments to send.
  2096. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2097. //send the data immediately if there isn't already data being transmitted, unless
  2098. //startLongPoll hasn't been called yet.
  2099. if (this.alive) {
  2100. this.newRequest_();
  2101. }
  2102. };
  2103. /**
  2104. * Add a script tag for a regular long-poll request.
  2105. * @param url - The URL of the script tag.
  2106. * @param serial - The serial number of the request.
  2107. */
  2108. FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
  2109. var _this = this;
  2110. //remember that we sent this request.
  2111. this.outstandingRequests.add(serial);
  2112. var doNewRequest = function () {
  2113. _this.outstandingRequests.delete(serial);
  2114. _this.newRequest_();
  2115. };
  2116. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2117. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2118. var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2119. var readyStateCB = function () {
  2120. // Request completed. Cancel the keepalive.
  2121. clearTimeout(keepaliveTimeout);
  2122. // Trigger a new request so we can continue receiving data.
  2123. doNewRequest();
  2124. };
  2125. this.addTag(url, readyStateCB);
  2126. };
  2127. /**
  2128. * Add an arbitrary script tag to the iframe.
  2129. * @param url - The URL for the script tag source.
  2130. * @param loadCB - A callback to be triggered once the script has loaded.
  2131. */
  2132. FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
  2133. var _this = this;
  2134. if (util.isNodeSdk()) {
  2135. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2136. this.doNodeLongPoll(url, loadCB);
  2137. }
  2138. else {
  2139. setTimeout(function () {
  2140. try {
  2141. // if we're already closed, don't add this poll
  2142. if (!_this.sendNewPolls) {
  2143. return;
  2144. }
  2145. var newScript_1 = _this.myIFrame.doc.createElement('script');
  2146. newScript_1.type = 'text/javascript';
  2147. newScript_1.async = true;
  2148. newScript_1.src = url;
  2149. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2150. newScript_1.onload = newScript_1.onreadystatechange =
  2151. function () {
  2152. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2153. var rstate = newScript_1.readyState;
  2154. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2155. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2156. newScript_1.onload = newScript_1.onreadystatechange = null;
  2157. if (newScript_1.parentNode) {
  2158. newScript_1.parentNode.removeChild(newScript_1);
  2159. }
  2160. loadCB();
  2161. }
  2162. };
  2163. newScript_1.onerror = function () {
  2164. log('Long-poll script failed to load: ' + url);
  2165. _this.sendNewPolls = false;
  2166. _this.close();
  2167. };
  2168. _this.myIFrame.doc.body.appendChild(newScript_1);
  2169. }
  2170. catch (e) {
  2171. // TODO: we should make this error visible somehow
  2172. }
  2173. }, Math.floor(1));
  2174. }
  2175. };
  2176. return FirebaseIFrameScriptHolder;
  2177. }());
  2178. /**
  2179. * @license
  2180. * Copyright 2017 Google LLC
  2181. *
  2182. * Licensed under the Apache License, Version 2.0 (the "License");
  2183. * you may not use this file except in compliance with the License.
  2184. * You may obtain a copy of the License at
  2185. *
  2186. * http://www.apache.org/licenses/LICENSE-2.0
  2187. *
  2188. * Unless required by applicable law or agreed to in writing, software
  2189. * distributed under the License is distributed on an "AS IS" BASIS,
  2190. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2191. * See the License for the specific language governing permissions and
  2192. * limitations under the License.
  2193. */
  2194. /**
  2195. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2196. * lifecycle.
  2197. *
  2198. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2199. * they are available.
  2200. */
  2201. var TransportManager = /** @class */ (function () {
  2202. /**
  2203. * @param repoInfo - Metadata around the namespace we're connecting to
  2204. */
  2205. function TransportManager(repoInfo) {
  2206. this.initTransports_(repoInfo);
  2207. }
  2208. Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
  2209. get: function () {
  2210. return [BrowserPollConnection, WebSocketConnection];
  2211. },
  2212. enumerable: false,
  2213. configurable: true
  2214. });
  2215. Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
  2216. /**
  2217. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2218. * TransportManager has already set up transports_
  2219. */
  2220. get: function () {
  2221. return this.globalTransportInitialized_;
  2222. },
  2223. enumerable: false,
  2224. configurable: true
  2225. });
  2226. TransportManager.prototype.initTransports_ = function (repoInfo) {
  2227. var e_1, _a;
  2228. var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2229. var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2230. if (repoInfo.webSocketOnly) {
  2231. if (!isWebSocketsAvailable) {
  2232. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2233. }
  2234. isSkipPollConnection = true;
  2235. }
  2236. if (isSkipPollConnection) {
  2237. this.transports_ = [WebSocketConnection];
  2238. }
  2239. else {
  2240. var transports = (this.transports_ = []);
  2241. try {
  2242. for (var _b = tslib.__values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
  2243. var transport = _c.value;
  2244. if (transport && transport['isAvailable']()) {
  2245. transports.push(transport);
  2246. }
  2247. }
  2248. }
  2249. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2250. finally {
  2251. try {
  2252. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  2253. }
  2254. finally { if (e_1) throw e_1.error; }
  2255. }
  2256. TransportManager.globalTransportInitialized_ = true;
  2257. }
  2258. };
  2259. /**
  2260. * @returns The constructor for the initial transport to use
  2261. */
  2262. TransportManager.prototype.initialTransport = function () {
  2263. if (this.transports_.length > 0) {
  2264. return this.transports_[0];
  2265. }
  2266. else {
  2267. throw new Error('No transports available');
  2268. }
  2269. };
  2270. /**
  2271. * @returns The constructor for the next transport, or null
  2272. */
  2273. TransportManager.prototype.upgradeTransport = function () {
  2274. if (this.transports_.length > 1) {
  2275. return this.transports_[1];
  2276. }
  2277. else {
  2278. return null;
  2279. }
  2280. };
  2281. // Keeps track of whether the TransportManager has already chosen a transport to use
  2282. TransportManager.globalTransportInitialized_ = false;
  2283. return TransportManager;
  2284. }());
  2285. /**
  2286. * @license
  2287. * Copyright 2017 Google LLC
  2288. *
  2289. * Licensed under the Apache License, Version 2.0 (the "License");
  2290. * you may not use this file except in compliance with the License.
  2291. * You may obtain a copy of the License at
  2292. *
  2293. * http://www.apache.org/licenses/LICENSE-2.0
  2294. *
  2295. * Unless required by applicable law or agreed to in writing, software
  2296. * distributed under the License is distributed on an "AS IS" BASIS,
  2297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2298. * See the License for the specific language governing permissions and
  2299. * limitations under the License.
  2300. */
  2301. // Abort upgrade attempt if it takes longer than 60s.
  2302. var UPGRADE_TIMEOUT = 60000;
  2303. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2304. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2305. var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2306. // 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)
  2307. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2308. // but we've sent/received enough bytes, we don't cancel the connection.
  2309. var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2310. var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2311. var MESSAGE_TYPE = 't';
  2312. var MESSAGE_DATA = 'd';
  2313. var CONTROL_SHUTDOWN = 's';
  2314. var CONTROL_RESET = 'r';
  2315. var CONTROL_ERROR = 'e';
  2316. var CONTROL_PONG = 'o';
  2317. var SWITCH_ACK = 'a';
  2318. var END_TRANSMISSION = 'n';
  2319. var PING = 'p';
  2320. var SERVER_HELLO = 'h';
  2321. /**
  2322. * Creates a new real-time connection to the server using whichever method works
  2323. * best in the current browser.
  2324. */
  2325. var Connection = /** @class */ (function () {
  2326. /**
  2327. * @param id - an id for this connection
  2328. * @param repoInfo_ - the info for the endpoint to connect to
  2329. * @param applicationId_ - the Firebase App ID for this project
  2330. * @param appCheckToken_ - The App Check Token for this device.
  2331. * @param authToken_ - The auth token for this session.
  2332. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2333. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2334. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2335. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2336. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2337. */
  2338. function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2339. this.id = id;
  2340. this.repoInfo_ = repoInfo_;
  2341. this.applicationId_ = applicationId_;
  2342. this.appCheckToken_ = appCheckToken_;
  2343. this.authToken_ = authToken_;
  2344. this.onMessage_ = onMessage_;
  2345. this.onReady_ = onReady_;
  2346. this.onDisconnect_ = onDisconnect_;
  2347. this.onKill_ = onKill_;
  2348. this.lastSessionId = lastSessionId;
  2349. this.connectionCount = 0;
  2350. this.pendingDataMessages = [];
  2351. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2352. this.log_ = logWrapper('c:' + this.id + ':');
  2353. this.transportManager_ = new TransportManager(repoInfo_);
  2354. this.log_('Connection created');
  2355. this.start_();
  2356. }
  2357. /**
  2358. * Starts a connection attempt
  2359. */
  2360. Connection.prototype.start_ = function () {
  2361. var _this = this;
  2362. var conn = this.transportManager_.initialTransport();
  2363. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2364. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2365. // can consider the transport healthy.
  2366. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2367. var onMessageReceived = this.connReceiver_(this.conn_);
  2368. var onConnectionLost = this.disconnReceiver_(this.conn_);
  2369. this.tx_ = this.conn_;
  2370. this.rx_ = this.conn_;
  2371. this.secondaryConn_ = null;
  2372. this.isHealthy_ = false;
  2373. /*
  2374. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2375. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2376. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2377. * still have the context of your originating frame.
  2378. */
  2379. setTimeout(function () {
  2380. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2381. _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
  2382. }, Math.floor(0));
  2383. var healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2384. if (healthyTimeoutMS > 0) {
  2385. this.healthyTimeout_ = setTimeoutNonBlocking(function () {
  2386. _this.healthyTimeout_ = null;
  2387. if (!_this.isHealthy_) {
  2388. if (_this.conn_ &&
  2389. _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2390. _this.log_('Connection exceeded healthy timeout but has received ' +
  2391. _this.conn_.bytesReceived +
  2392. ' bytes. Marking connection healthy.');
  2393. _this.isHealthy_ = true;
  2394. _this.conn_.markConnectionHealthy();
  2395. }
  2396. else if (_this.conn_ &&
  2397. _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2398. _this.log_('Connection exceeded healthy timeout but has sent ' +
  2399. _this.conn_.bytesSent +
  2400. ' bytes. Leaving connection alive.');
  2401. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2402. // the server.
  2403. }
  2404. else {
  2405. _this.log_('Closing unhealthy connection after timeout.');
  2406. _this.close();
  2407. }
  2408. }
  2409. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2410. }, Math.floor(healthyTimeoutMS));
  2411. }
  2412. };
  2413. Connection.prototype.nextTransportId_ = function () {
  2414. return 'c:' + this.id + ':' + this.connectionCount++;
  2415. };
  2416. Connection.prototype.disconnReceiver_ = function (conn) {
  2417. var _this = this;
  2418. return function (everConnected) {
  2419. if (conn === _this.conn_) {
  2420. _this.onConnectionLost_(everConnected);
  2421. }
  2422. else if (conn === _this.secondaryConn_) {
  2423. _this.log_('Secondary connection lost.');
  2424. _this.onSecondaryConnectionLost_();
  2425. }
  2426. else {
  2427. _this.log_('closing an old connection');
  2428. }
  2429. };
  2430. };
  2431. Connection.prototype.connReceiver_ = function (conn) {
  2432. var _this = this;
  2433. return function (message) {
  2434. if (_this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2435. if (conn === _this.rx_) {
  2436. _this.onPrimaryMessageReceived_(message);
  2437. }
  2438. else if (conn === _this.secondaryConn_) {
  2439. _this.onSecondaryMessageReceived_(message);
  2440. }
  2441. else {
  2442. _this.log_('message on old connection');
  2443. }
  2444. }
  2445. };
  2446. };
  2447. /**
  2448. * @param dataMsg - An arbitrary data message to be sent to the server
  2449. */
  2450. Connection.prototype.sendRequest = function (dataMsg) {
  2451. // wrap in a data message envelope and send it on
  2452. var msg = { t: 'd', d: dataMsg };
  2453. this.sendData_(msg);
  2454. };
  2455. Connection.prototype.tryCleanupConnection = function () {
  2456. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2457. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2458. this.conn_ = this.secondaryConn_;
  2459. this.secondaryConn_ = null;
  2460. // the server will shutdown the old connection
  2461. }
  2462. };
  2463. Connection.prototype.onSecondaryControl_ = function (controlData) {
  2464. if (MESSAGE_TYPE in controlData) {
  2465. var cmd = controlData[MESSAGE_TYPE];
  2466. if (cmd === SWITCH_ACK) {
  2467. this.upgradeIfSecondaryHealthy_();
  2468. }
  2469. else if (cmd === CONTROL_RESET) {
  2470. // Most likely the session wasn't valid. Abandon the switch attempt
  2471. this.log_('Got a reset on secondary, closing it');
  2472. this.secondaryConn_.close();
  2473. // If we were already using this connection for something, than we need to fully close
  2474. if (this.tx_ === this.secondaryConn_ ||
  2475. this.rx_ === this.secondaryConn_) {
  2476. this.close();
  2477. }
  2478. }
  2479. else if (cmd === CONTROL_PONG) {
  2480. this.log_('got pong on secondary.');
  2481. this.secondaryResponsesRequired_--;
  2482. this.upgradeIfSecondaryHealthy_();
  2483. }
  2484. }
  2485. };
  2486. Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
  2487. var layer = requireKey('t', parsedData);
  2488. var data = requireKey('d', parsedData);
  2489. if (layer === 'c') {
  2490. this.onSecondaryControl_(data);
  2491. }
  2492. else if (layer === 'd') {
  2493. // got a data message, but we're still second connection. Need to buffer it up
  2494. this.pendingDataMessages.push(data);
  2495. }
  2496. else {
  2497. throw new Error('Unknown protocol layer: ' + layer);
  2498. }
  2499. };
  2500. Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
  2501. if (this.secondaryResponsesRequired_ <= 0) {
  2502. this.log_('Secondary connection is healthy.');
  2503. this.isHealthy_ = true;
  2504. this.secondaryConn_.markConnectionHealthy();
  2505. this.proceedWithUpgrade_();
  2506. }
  2507. else {
  2508. // Send a ping to make sure the connection is healthy.
  2509. this.log_('sending ping on secondary.');
  2510. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2511. }
  2512. };
  2513. Connection.prototype.proceedWithUpgrade_ = function () {
  2514. // tell this connection to consider itself open
  2515. this.secondaryConn_.start();
  2516. // send ack
  2517. this.log_('sending client ack on secondary');
  2518. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2519. // send end packet on primary transport, switch to sending on this one
  2520. // can receive on this one, buffer responses until end received on primary transport
  2521. this.log_('Ending transmission on primary');
  2522. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2523. this.tx_ = this.secondaryConn_;
  2524. this.tryCleanupConnection();
  2525. };
  2526. Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
  2527. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2528. var layer = requireKey('t', parsedData);
  2529. var data = requireKey('d', parsedData);
  2530. if (layer === 'c') {
  2531. this.onControl_(data);
  2532. }
  2533. else if (layer === 'd') {
  2534. this.onDataMessage_(data);
  2535. }
  2536. };
  2537. Connection.prototype.onDataMessage_ = function (message) {
  2538. this.onPrimaryResponse_();
  2539. // We don't do anything with data messages, just kick them up a level
  2540. this.onMessage_(message);
  2541. };
  2542. Connection.prototype.onPrimaryResponse_ = function () {
  2543. if (!this.isHealthy_) {
  2544. this.primaryResponsesRequired_--;
  2545. if (this.primaryResponsesRequired_ <= 0) {
  2546. this.log_('Primary connection is healthy.');
  2547. this.isHealthy_ = true;
  2548. this.conn_.markConnectionHealthy();
  2549. }
  2550. }
  2551. };
  2552. Connection.prototype.onControl_ = function (controlData) {
  2553. var cmd = requireKey(MESSAGE_TYPE, controlData);
  2554. if (MESSAGE_DATA in controlData) {
  2555. var payload = controlData[MESSAGE_DATA];
  2556. if (cmd === SERVER_HELLO) {
  2557. var handshakePayload = tslib.__assign({}, payload);
  2558. if (this.repoInfo_.isUsingEmulator) {
  2559. // 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.
  2560. handshakePayload.h = this.repoInfo_.host;
  2561. }
  2562. this.onHandshake_(handshakePayload);
  2563. }
  2564. else if (cmd === END_TRANSMISSION) {
  2565. this.log_('recvd end transmission on primary');
  2566. this.rx_ = this.secondaryConn_;
  2567. for (var i = 0; i < this.pendingDataMessages.length; ++i) {
  2568. this.onDataMessage_(this.pendingDataMessages[i]);
  2569. }
  2570. this.pendingDataMessages = [];
  2571. this.tryCleanupConnection();
  2572. }
  2573. else if (cmd === CONTROL_SHUTDOWN) {
  2574. // This was previously the 'onKill' callback passed to the lower-level connection
  2575. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2576. this.onConnectionShutdown_(payload);
  2577. }
  2578. else if (cmd === CONTROL_RESET) {
  2579. // payload in this case is the host we should contact
  2580. this.onReset_(payload);
  2581. }
  2582. else if (cmd === CONTROL_ERROR) {
  2583. error('Server Error: ' + payload);
  2584. }
  2585. else if (cmd === CONTROL_PONG) {
  2586. this.log_('got pong on primary.');
  2587. this.onPrimaryResponse_();
  2588. this.sendPingOnPrimaryIfNecessary_();
  2589. }
  2590. else {
  2591. error('Unknown control packet command: ' + cmd);
  2592. }
  2593. }
  2594. };
  2595. /**
  2596. * @param handshake - The handshake data returned from the server
  2597. */
  2598. Connection.prototype.onHandshake_ = function (handshake) {
  2599. var timestamp = handshake.ts;
  2600. var version = handshake.v;
  2601. var host = handshake.h;
  2602. this.sessionId = handshake.s;
  2603. this.repoInfo_.host = host;
  2604. // if we've already closed the connection, then don't bother trying to progress further
  2605. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2606. this.conn_.start();
  2607. this.onConnectionEstablished_(this.conn_, timestamp);
  2608. if (PROTOCOL_VERSION !== version) {
  2609. warn('Protocol version mismatch detected');
  2610. }
  2611. // TODO: do we want to upgrade? when? maybe a delay?
  2612. this.tryStartUpgrade_();
  2613. }
  2614. };
  2615. Connection.prototype.tryStartUpgrade_ = function () {
  2616. var conn = this.transportManager_.upgradeTransport();
  2617. if (conn) {
  2618. this.startUpgrade_(conn);
  2619. }
  2620. };
  2621. Connection.prototype.startUpgrade_ = function (conn) {
  2622. var _this = this;
  2623. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2624. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2625. // can consider the transport healthy.
  2626. this.secondaryResponsesRequired_ =
  2627. conn['responsesRequiredToBeHealthy'] || 0;
  2628. var onMessage = this.connReceiver_(this.secondaryConn_);
  2629. var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2630. this.secondaryConn_.open(onMessage, onDisconnect);
  2631. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2632. setTimeoutNonBlocking(function () {
  2633. if (_this.secondaryConn_) {
  2634. _this.log_('Timed out trying to upgrade.');
  2635. _this.secondaryConn_.close();
  2636. }
  2637. }, Math.floor(UPGRADE_TIMEOUT));
  2638. };
  2639. Connection.prototype.onReset_ = function (host) {
  2640. this.log_('Reset packet received. New host: ' + host);
  2641. this.repoInfo_.host = host;
  2642. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2643. // We don't currently support resets after the connection has already been established
  2644. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2645. this.close();
  2646. }
  2647. else {
  2648. // Close whatever connections we have open and start again.
  2649. this.closeConnections_();
  2650. this.start_();
  2651. }
  2652. };
  2653. Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
  2654. var _this = this;
  2655. this.log_('Realtime connection established.');
  2656. this.conn_ = conn;
  2657. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2658. if (this.onReady_) {
  2659. this.onReady_(timestamp, this.sessionId);
  2660. this.onReady_ = null;
  2661. }
  2662. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2663. // send some pings.
  2664. if (this.primaryResponsesRequired_ === 0) {
  2665. this.log_('Primary connection is healthy.');
  2666. this.isHealthy_ = true;
  2667. }
  2668. else {
  2669. setTimeoutNonBlocking(function () {
  2670. _this.sendPingOnPrimaryIfNecessary_();
  2671. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2672. }
  2673. };
  2674. Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
  2675. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2676. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2677. this.log_('sending ping on primary.');
  2678. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2679. }
  2680. };
  2681. Connection.prototype.onSecondaryConnectionLost_ = function () {
  2682. var conn = this.secondaryConn_;
  2683. this.secondaryConn_ = null;
  2684. if (this.tx_ === conn || this.rx_ === conn) {
  2685. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2686. this.close();
  2687. }
  2688. };
  2689. /**
  2690. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2691. * we should flush the host cache
  2692. */
  2693. Connection.prototype.onConnectionLost_ = function (everConnected) {
  2694. this.conn_ = null;
  2695. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2696. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2697. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2698. this.log_('Realtime connection failed.');
  2699. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2700. if (this.repoInfo_.isCacheableHost()) {
  2701. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2702. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2703. this.repoInfo_.internalHost = this.repoInfo_.host;
  2704. }
  2705. }
  2706. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2707. this.log_('Realtime connection lost.');
  2708. }
  2709. this.close();
  2710. };
  2711. Connection.prototype.onConnectionShutdown_ = function (reason) {
  2712. this.log_('Connection shutdown command received. Shutting down...');
  2713. if (this.onKill_) {
  2714. this.onKill_(reason);
  2715. this.onKill_ = null;
  2716. }
  2717. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2718. // so clear the callback.
  2719. this.onDisconnect_ = null;
  2720. this.close();
  2721. };
  2722. Connection.prototype.sendData_ = function (data) {
  2723. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2724. throw 'Connection is not connected';
  2725. }
  2726. else {
  2727. this.tx_.send(data);
  2728. }
  2729. };
  2730. /**
  2731. * Cleans up this connection, calling the appropriate callbacks
  2732. */
  2733. Connection.prototype.close = function () {
  2734. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2735. this.log_('Closing realtime connection.');
  2736. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2737. this.closeConnections_();
  2738. if (this.onDisconnect_) {
  2739. this.onDisconnect_();
  2740. this.onDisconnect_ = null;
  2741. }
  2742. }
  2743. };
  2744. Connection.prototype.closeConnections_ = function () {
  2745. this.log_('Shutting down all connections');
  2746. if (this.conn_) {
  2747. this.conn_.close();
  2748. this.conn_ = null;
  2749. }
  2750. if (this.secondaryConn_) {
  2751. this.secondaryConn_.close();
  2752. this.secondaryConn_ = null;
  2753. }
  2754. if (this.healthyTimeout_) {
  2755. clearTimeout(this.healthyTimeout_);
  2756. this.healthyTimeout_ = null;
  2757. }
  2758. };
  2759. return Connection;
  2760. }());
  2761. /**
  2762. * @license
  2763. * Copyright 2017 Google LLC
  2764. *
  2765. * Licensed under the Apache License, Version 2.0 (the "License");
  2766. * you may not use this file except in compliance with the License.
  2767. * You may obtain a copy of the License at
  2768. *
  2769. * http://www.apache.org/licenses/LICENSE-2.0
  2770. *
  2771. * Unless required by applicable law or agreed to in writing, software
  2772. * distributed under the License is distributed on an "AS IS" BASIS,
  2773. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2774. * See the License for the specific language governing permissions and
  2775. * limitations under the License.
  2776. */
  2777. /**
  2778. * Interface defining the set of actions that can be performed against the Firebase server
  2779. * (basically corresponds to our wire protocol).
  2780. *
  2781. * @interface
  2782. */
  2783. var ServerActions = /** @class */ (function () {
  2784. function ServerActions() {
  2785. }
  2786. ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
  2787. ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
  2788. /**
  2789. * Refreshes the auth token for the current connection.
  2790. * @param token - The authentication token
  2791. */
  2792. ServerActions.prototype.refreshAuthToken = function (token) { };
  2793. /**
  2794. * Refreshes the app check token for the current connection.
  2795. * @param token The app check token
  2796. */
  2797. ServerActions.prototype.refreshAppCheckToken = function (token) { };
  2798. ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
  2799. ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
  2800. ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
  2801. ServerActions.prototype.reportStats = function (stats) { };
  2802. return ServerActions;
  2803. }());
  2804. /**
  2805. * @license
  2806. * Copyright 2017 Google LLC
  2807. *
  2808. * Licensed under the Apache License, Version 2.0 (the "License");
  2809. * you may not use this file except in compliance with the License.
  2810. * You may obtain a copy of the License at
  2811. *
  2812. * http://www.apache.org/licenses/LICENSE-2.0
  2813. *
  2814. * Unless required by applicable law or agreed to in writing, software
  2815. * distributed under the License is distributed on an "AS IS" BASIS,
  2816. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2817. * See the License for the specific language governing permissions and
  2818. * limitations under the License.
  2819. */
  2820. /**
  2821. * Base class to be used if you want to emit events. Call the constructor with
  2822. * the set of allowed event names.
  2823. */
  2824. var EventEmitter = /** @class */ (function () {
  2825. function EventEmitter(allowedEvents_) {
  2826. this.allowedEvents_ = allowedEvents_;
  2827. this.listeners_ = {};
  2828. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2829. }
  2830. /**
  2831. * To be called by derived classes to trigger events.
  2832. */
  2833. EventEmitter.prototype.trigger = function (eventType) {
  2834. var varArgs = [];
  2835. for (var _i = 1; _i < arguments.length; _i++) {
  2836. varArgs[_i - 1] = arguments[_i];
  2837. }
  2838. if (Array.isArray(this.listeners_[eventType])) {
  2839. // Clone the list, since callbacks could add/remove listeners.
  2840. var listeners = tslib.__spreadArray([], tslib.__read(this.listeners_[eventType]), false);
  2841. for (var i = 0; i < listeners.length; i++) {
  2842. listeners[i].callback.apply(listeners[i].context, varArgs);
  2843. }
  2844. }
  2845. };
  2846. EventEmitter.prototype.on = function (eventType, callback, context) {
  2847. this.validateEventType_(eventType);
  2848. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2849. this.listeners_[eventType].push({ callback: callback, context: context });
  2850. var eventData = this.getInitialEvent(eventType);
  2851. if (eventData) {
  2852. callback.apply(context, eventData);
  2853. }
  2854. };
  2855. EventEmitter.prototype.off = function (eventType, callback, context) {
  2856. this.validateEventType_(eventType);
  2857. var listeners = this.listeners_[eventType] || [];
  2858. for (var i = 0; i < listeners.length; i++) {
  2859. if (listeners[i].callback === callback &&
  2860. (!context || context === listeners[i].context)) {
  2861. listeners.splice(i, 1);
  2862. return;
  2863. }
  2864. }
  2865. };
  2866. EventEmitter.prototype.validateEventType_ = function (eventType) {
  2867. util.assert(this.allowedEvents_.find(function (et) {
  2868. return et === eventType;
  2869. }), 'Unknown event: ' + eventType);
  2870. };
  2871. return EventEmitter;
  2872. }());
  2873. /**
  2874. * @license
  2875. * Copyright 2017 Google LLC
  2876. *
  2877. * Licensed under the Apache License, Version 2.0 (the "License");
  2878. * you may not use this file except in compliance with the License.
  2879. * You may obtain a copy of the License at
  2880. *
  2881. * http://www.apache.org/licenses/LICENSE-2.0
  2882. *
  2883. * Unless required by applicable law or agreed to in writing, software
  2884. * distributed under the License is distributed on an "AS IS" BASIS,
  2885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2886. * See the License for the specific language governing permissions and
  2887. * limitations under the License.
  2888. */
  2889. /**
  2890. * Monitors online state (as reported by window.online/offline events).
  2891. *
  2892. * The expectation is that this could have many false positives (thinks we are online
  2893. * when we're not), but no false negatives. So we can safely use it to determine when
  2894. * we definitely cannot reach the internet.
  2895. */
  2896. var OnlineMonitor = /** @class */ (function (_super) {
  2897. tslib.__extends(OnlineMonitor, _super);
  2898. function OnlineMonitor() {
  2899. var _this = _super.call(this, ['online']) || this;
  2900. _this.online_ = true;
  2901. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2902. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2903. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2904. // for Cordova.
  2905. if (typeof window !== 'undefined' &&
  2906. typeof window.addEventListener !== 'undefined' &&
  2907. !util.isMobileCordova()) {
  2908. window.addEventListener('online', function () {
  2909. if (!_this.online_) {
  2910. _this.online_ = true;
  2911. _this.trigger('online', true);
  2912. }
  2913. }, false);
  2914. window.addEventListener('offline', function () {
  2915. if (_this.online_) {
  2916. _this.online_ = false;
  2917. _this.trigger('online', false);
  2918. }
  2919. }, false);
  2920. }
  2921. return _this;
  2922. }
  2923. OnlineMonitor.getInstance = function () {
  2924. return new OnlineMonitor();
  2925. };
  2926. OnlineMonitor.prototype.getInitialEvent = function (eventType) {
  2927. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2928. return [this.online_];
  2929. };
  2930. OnlineMonitor.prototype.currentlyOnline = function () {
  2931. return this.online_;
  2932. };
  2933. return OnlineMonitor;
  2934. }(EventEmitter));
  2935. /**
  2936. * @license
  2937. * Copyright 2017 Google LLC
  2938. *
  2939. * Licensed under the Apache License, Version 2.0 (the "License");
  2940. * you may not use this file except in compliance with the License.
  2941. * You may obtain a copy of the License at
  2942. *
  2943. * http://www.apache.org/licenses/LICENSE-2.0
  2944. *
  2945. * Unless required by applicable law or agreed to in writing, software
  2946. * distributed under the License is distributed on an "AS IS" BASIS,
  2947. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2948. * See the License for the specific language governing permissions and
  2949. * limitations under the License.
  2950. */
  2951. /** Maximum key depth. */
  2952. var MAX_PATH_DEPTH = 32;
  2953. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2954. var MAX_PATH_LENGTH_BYTES = 768;
  2955. /**
  2956. * An immutable object representing a parsed path. It's immutable so that you
  2957. * can pass them around to other functions without worrying about them changing
  2958. * it.
  2959. */
  2960. var Path = /** @class */ (function () {
  2961. /**
  2962. * @param pathOrString - Path string to parse, or another path, or the raw
  2963. * tokens array
  2964. */
  2965. function Path(pathOrString, pieceNum) {
  2966. if (pieceNum === void 0) {
  2967. this.pieces_ = pathOrString.split('/');
  2968. // Remove empty pieces.
  2969. var copyTo = 0;
  2970. for (var i = 0; i < this.pieces_.length; i++) {
  2971. if (this.pieces_[i].length > 0) {
  2972. this.pieces_[copyTo] = this.pieces_[i];
  2973. copyTo++;
  2974. }
  2975. }
  2976. this.pieces_.length = copyTo;
  2977. this.pieceNum_ = 0;
  2978. }
  2979. else {
  2980. this.pieces_ = pathOrString;
  2981. this.pieceNum_ = pieceNum;
  2982. }
  2983. }
  2984. Path.prototype.toString = function () {
  2985. var pathString = '';
  2986. for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
  2987. if (this.pieces_[i] !== '') {
  2988. pathString += '/' + this.pieces_[i];
  2989. }
  2990. }
  2991. return pathString || '/';
  2992. };
  2993. return Path;
  2994. }());
  2995. function newEmptyPath() {
  2996. return new Path('');
  2997. }
  2998. function pathGetFront(path) {
  2999. if (path.pieceNum_ >= path.pieces_.length) {
  3000. return null;
  3001. }
  3002. return path.pieces_[path.pieceNum_];
  3003. }
  3004. /**
  3005. * @returns The number of segments in this path
  3006. */
  3007. function pathGetLength(path) {
  3008. return path.pieces_.length - path.pieceNum_;
  3009. }
  3010. function pathPopFront(path) {
  3011. var pieceNum = path.pieceNum_;
  3012. if (pieceNum < path.pieces_.length) {
  3013. pieceNum++;
  3014. }
  3015. return new Path(path.pieces_, pieceNum);
  3016. }
  3017. function pathGetBack(path) {
  3018. if (path.pieceNum_ < path.pieces_.length) {
  3019. return path.pieces_[path.pieces_.length - 1];
  3020. }
  3021. return null;
  3022. }
  3023. function pathToUrlEncodedString(path) {
  3024. var pathString = '';
  3025. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3026. if (path.pieces_[i] !== '') {
  3027. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  3028. }
  3029. }
  3030. return pathString || '/';
  3031. }
  3032. /**
  3033. * Shallow copy of the parts of the path.
  3034. *
  3035. */
  3036. function pathSlice(path, begin) {
  3037. if (begin === void 0) { begin = 0; }
  3038. return path.pieces_.slice(path.pieceNum_ + begin);
  3039. }
  3040. function pathParent(path) {
  3041. if (path.pieceNum_ >= path.pieces_.length) {
  3042. return null;
  3043. }
  3044. var pieces = [];
  3045. for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  3046. pieces.push(path.pieces_[i]);
  3047. }
  3048. return new Path(pieces, 0);
  3049. }
  3050. function pathChild(path, childPathObj) {
  3051. var pieces = [];
  3052. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3053. pieces.push(path.pieces_[i]);
  3054. }
  3055. if (childPathObj instanceof Path) {
  3056. for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  3057. pieces.push(childPathObj.pieces_[i]);
  3058. }
  3059. }
  3060. else {
  3061. var childPieces = childPathObj.split('/');
  3062. for (var i = 0; i < childPieces.length; i++) {
  3063. if (childPieces[i].length > 0) {
  3064. pieces.push(childPieces[i]);
  3065. }
  3066. }
  3067. }
  3068. return new Path(pieces, 0);
  3069. }
  3070. /**
  3071. * @returns True if there are no segments in this path
  3072. */
  3073. function pathIsEmpty(path) {
  3074. return path.pieceNum_ >= path.pieces_.length;
  3075. }
  3076. /**
  3077. * @returns The path from outerPath to innerPath
  3078. */
  3079. function newRelativePath(outerPath, innerPath) {
  3080. var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  3081. if (outer === null) {
  3082. return innerPath;
  3083. }
  3084. else if (outer === inner) {
  3085. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  3086. }
  3087. else {
  3088. throw new Error('INTERNAL ERROR: innerPath (' +
  3089. innerPath +
  3090. ') is not within ' +
  3091. 'outerPath (' +
  3092. outerPath +
  3093. ')');
  3094. }
  3095. }
  3096. /**
  3097. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  3098. */
  3099. function pathCompare(left, right) {
  3100. var leftKeys = pathSlice(left, 0);
  3101. var rightKeys = pathSlice(right, 0);
  3102. for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  3103. var cmp = nameCompare(leftKeys[i], rightKeys[i]);
  3104. if (cmp !== 0) {
  3105. return cmp;
  3106. }
  3107. }
  3108. if (leftKeys.length === rightKeys.length) {
  3109. return 0;
  3110. }
  3111. return leftKeys.length < rightKeys.length ? -1 : 1;
  3112. }
  3113. /**
  3114. * @returns true if paths are the same.
  3115. */
  3116. function pathEquals(path, other) {
  3117. if (pathGetLength(path) !== pathGetLength(other)) {
  3118. return false;
  3119. }
  3120. for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3121. if (path.pieces_[i] !== other.pieces_[j]) {
  3122. return false;
  3123. }
  3124. }
  3125. return true;
  3126. }
  3127. /**
  3128. * @returns True if this path is a parent of (or the same as) other
  3129. */
  3130. function pathContains(path, other) {
  3131. var i = path.pieceNum_;
  3132. var j = other.pieceNum_;
  3133. if (pathGetLength(path) > pathGetLength(other)) {
  3134. return false;
  3135. }
  3136. while (i < path.pieces_.length) {
  3137. if (path.pieces_[i] !== other.pieces_[j]) {
  3138. return false;
  3139. }
  3140. ++i;
  3141. ++j;
  3142. }
  3143. return true;
  3144. }
  3145. /**
  3146. * Dynamic (mutable) path used to count path lengths.
  3147. *
  3148. * This class is used to efficiently check paths for valid
  3149. * length (in UTF8 bytes) and depth (used in path validation).
  3150. *
  3151. * Throws Error exception if path is ever invalid.
  3152. *
  3153. * The definition of a path always begins with '/'.
  3154. */
  3155. var ValidationPath = /** @class */ (function () {
  3156. /**
  3157. * @param path - Initial Path.
  3158. * @param errorPrefix_ - Prefix for any error messages.
  3159. */
  3160. function ValidationPath(path, errorPrefix_) {
  3161. this.errorPrefix_ = errorPrefix_;
  3162. this.parts_ = pathSlice(path, 0);
  3163. /** Initialize to number of '/' chars needed in path. */
  3164. this.byteLength_ = Math.max(1, this.parts_.length);
  3165. for (var i = 0; i < this.parts_.length; i++) {
  3166. this.byteLength_ += util.stringLength(this.parts_[i]);
  3167. }
  3168. validationPathCheckValid(this);
  3169. }
  3170. return ValidationPath;
  3171. }());
  3172. function validationPathPush(validationPath, child) {
  3173. // Count the needed '/'
  3174. if (validationPath.parts_.length > 0) {
  3175. validationPath.byteLength_ += 1;
  3176. }
  3177. validationPath.parts_.push(child);
  3178. validationPath.byteLength_ += util.stringLength(child);
  3179. validationPathCheckValid(validationPath);
  3180. }
  3181. function validationPathPop(validationPath) {
  3182. var last = validationPath.parts_.pop();
  3183. validationPath.byteLength_ -= util.stringLength(last);
  3184. // Un-count the previous '/'
  3185. if (validationPath.parts_.length > 0) {
  3186. validationPath.byteLength_ -= 1;
  3187. }
  3188. }
  3189. function validationPathCheckValid(validationPath) {
  3190. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3191. throw new Error(validationPath.errorPrefix_ +
  3192. 'has a key path longer than ' +
  3193. MAX_PATH_LENGTH_BYTES +
  3194. ' bytes (' +
  3195. validationPath.byteLength_ +
  3196. ').');
  3197. }
  3198. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3199. throw new Error(validationPath.errorPrefix_ +
  3200. 'path specified exceeds the maximum depth that can be written (' +
  3201. MAX_PATH_DEPTH +
  3202. ') or object contains a cycle ' +
  3203. validationPathToErrorString(validationPath));
  3204. }
  3205. }
  3206. /**
  3207. * String for use in error messages - uses '.' notation for path.
  3208. */
  3209. function validationPathToErrorString(validationPath) {
  3210. if (validationPath.parts_.length === 0) {
  3211. return '';
  3212. }
  3213. return "in property '" + validationPath.parts_.join('.') + "'";
  3214. }
  3215. /**
  3216. * @license
  3217. * Copyright 2017 Google LLC
  3218. *
  3219. * Licensed under the Apache License, Version 2.0 (the "License");
  3220. * you may not use this file except in compliance with the License.
  3221. * You may obtain a copy of the License at
  3222. *
  3223. * http://www.apache.org/licenses/LICENSE-2.0
  3224. *
  3225. * Unless required by applicable law or agreed to in writing, software
  3226. * distributed under the License is distributed on an "AS IS" BASIS,
  3227. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3228. * See the License for the specific language governing permissions and
  3229. * limitations under the License.
  3230. */
  3231. var VisibilityMonitor = /** @class */ (function (_super) {
  3232. tslib.__extends(VisibilityMonitor, _super);
  3233. function VisibilityMonitor() {
  3234. var _this = _super.call(this, ['visible']) || this;
  3235. var hidden;
  3236. var visibilityChange;
  3237. if (typeof document !== 'undefined' &&
  3238. typeof document.addEventListener !== 'undefined') {
  3239. if (typeof document['hidden'] !== 'undefined') {
  3240. // Opera 12.10 and Firefox 18 and later support
  3241. visibilityChange = 'visibilitychange';
  3242. hidden = 'hidden';
  3243. }
  3244. else if (typeof document['mozHidden'] !== 'undefined') {
  3245. visibilityChange = 'mozvisibilitychange';
  3246. hidden = 'mozHidden';
  3247. }
  3248. else if (typeof document['msHidden'] !== 'undefined') {
  3249. visibilityChange = 'msvisibilitychange';
  3250. hidden = 'msHidden';
  3251. }
  3252. else if (typeof document['webkitHidden'] !== 'undefined') {
  3253. visibilityChange = 'webkitvisibilitychange';
  3254. hidden = 'webkitHidden';
  3255. }
  3256. }
  3257. // Initially, we always assume we are visible. This ensures that in browsers
  3258. // without page visibility support or in cases where we are never visible
  3259. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3260. // reconnects
  3261. _this.visible_ = true;
  3262. if (visibilityChange) {
  3263. document.addEventListener(visibilityChange, function () {
  3264. var visible = !document[hidden];
  3265. if (visible !== _this.visible_) {
  3266. _this.visible_ = visible;
  3267. _this.trigger('visible', visible);
  3268. }
  3269. }, false);
  3270. }
  3271. return _this;
  3272. }
  3273. VisibilityMonitor.getInstance = function () {
  3274. return new VisibilityMonitor();
  3275. };
  3276. VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
  3277. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3278. return [this.visible_];
  3279. };
  3280. return VisibilityMonitor;
  3281. }(EventEmitter));
  3282. /**
  3283. * @license
  3284. * Copyright 2017 Google LLC
  3285. *
  3286. * Licensed under the Apache License, Version 2.0 (the "License");
  3287. * you may not use this file except in compliance with the License.
  3288. * You may obtain a copy of the License at
  3289. *
  3290. * http://www.apache.org/licenses/LICENSE-2.0
  3291. *
  3292. * Unless required by applicable law or agreed to in writing, software
  3293. * distributed under the License is distributed on an "AS IS" BASIS,
  3294. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3295. * See the License for the specific language governing permissions and
  3296. * limitations under the License.
  3297. */
  3298. var RECONNECT_MIN_DELAY = 1000;
  3299. var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3300. var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3301. var RECONNECT_DELAY_MULTIPLIER = 1.3;
  3302. var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3303. var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3304. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3305. var INVALID_TOKEN_THRESHOLD = 3;
  3306. /**
  3307. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3308. *
  3309. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3310. * in quotes to make sure the closure compiler does not minify them.
  3311. */
  3312. var PersistentConnection = /** @class */ (function (_super) {
  3313. tslib.__extends(PersistentConnection, _super);
  3314. /**
  3315. * @param repoInfo_ - Data about the namespace we are connecting to
  3316. * @param applicationId_ - The Firebase App ID for this project
  3317. * @param onDataUpdate_ - A callback for new data from the server
  3318. */
  3319. function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3320. var _this = _super.call(this) || this;
  3321. _this.repoInfo_ = repoInfo_;
  3322. _this.applicationId_ = applicationId_;
  3323. _this.onDataUpdate_ = onDataUpdate_;
  3324. _this.onConnectStatus_ = onConnectStatus_;
  3325. _this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3326. _this.authTokenProvider_ = authTokenProvider_;
  3327. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3328. _this.authOverride_ = authOverride_;
  3329. // Used for diagnostic logging.
  3330. _this.id = PersistentConnection.nextPersistentConnectionId_++;
  3331. _this.log_ = logWrapper('p:' + _this.id + ':');
  3332. _this.interruptReasons_ = {};
  3333. _this.listens = new Map();
  3334. _this.outstandingPuts_ = [];
  3335. _this.outstandingGets_ = [];
  3336. _this.outstandingPutCount_ = 0;
  3337. _this.outstandingGetCount_ = 0;
  3338. _this.onDisconnectRequestQueue_ = [];
  3339. _this.connected_ = false;
  3340. _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3341. _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3342. _this.securityDebugCallback_ = null;
  3343. _this.lastSessionId = null;
  3344. _this.establishConnectionTimer_ = null;
  3345. _this.visible_ = false;
  3346. // Before we get connected, we keep a queue of pending messages to send.
  3347. _this.requestCBHash_ = {};
  3348. _this.requestNumber_ = 0;
  3349. _this.realtime_ = null;
  3350. _this.authToken_ = null;
  3351. _this.appCheckToken_ = null;
  3352. _this.forceTokenRefresh_ = false;
  3353. _this.invalidAuthTokenCount_ = 0;
  3354. _this.invalidAppCheckTokenCount_ = 0;
  3355. _this.firstConnection_ = true;
  3356. _this.lastConnectionAttemptTime_ = null;
  3357. _this.lastConnectionEstablishedTime_ = null;
  3358. if (authOverride_ && !util.isNodeSdk()) {
  3359. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3360. }
  3361. VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
  3362. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3363. OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
  3364. }
  3365. return _this;
  3366. }
  3367. PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
  3368. var curReqNum = ++this.requestNumber_;
  3369. var msg = { r: curReqNum, a: action, b: body };
  3370. this.log_(util.stringify(msg));
  3371. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3372. this.realtime_.sendRequest(msg);
  3373. if (onResponse) {
  3374. this.requestCBHash_[curReqNum] = onResponse;
  3375. }
  3376. };
  3377. PersistentConnection.prototype.get = function (query) {
  3378. this.initConnection_();
  3379. var deferred = new util.Deferred();
  3380. var request = {
  3381. p: query._path.toString(),
  3382. q: query._queryObject
  3383. };
  3384. var outstandingGet = {
  3385. action: 'g',
  3386. request: request,
  3387. onComplete: function (message) {
  3388. var payload = message['d'];
  3389. if (message['s'] === 'ok') {
  3390. deferred.resolve(payload);
  3391. }
  3392. else {
  3393. deferred.reject(payload);
  3394. }
  3395. }
  3396. };
  3397. this.outstandingGets_.push(outstandingGet);
  3398. this.outstandingGetCount_++;
  3399. var index = this.outstandingGets_.length - 1;
  3400. if (this.connected_) {
  3401. this.sendGet_(index);
  3402. }
  3403. return deferred.promise;
  3404. };
  3405. PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  3406. this.initConnection_();
  3407. var queryId = query._queryIdentifier;
  3408. var pathString = query._path.toString();
  3409. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3410. if (!this.listens.has(pathString)) {
  3411. this.listens.set(pathString, new Map());
  3412. }
  3413. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3414. util.assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
  3415. var listenSpec = {
  3416. onComplete: onComplete,
  3417. hashFn: currentHashFn,
  3418. query: query,
  3419. tag: tag
  3420. };
  3421. this.listens.get(pathString).set(queryId, listenSpec);
  3422. if (this.connected_) {
  3423. this.sendListen_(listenSpec);
  3424. }
  3425. };
  3426. PersistentConnection.prototype.sendGet_ = function (index) {
  3427. var _this = this;
  3428. var get = this.outstandingGets_[index];
  3429. this.sendRequest('g', get.request, function (message) {
  3430. delete _this.outstandingGets_[index];
  3431. _this.outstandingGetCount_--;
  3432. if (_this.outstandingGetCount_ === 0) {
  3433. _this.outstandingGets_ = [];
  3434. }
  3435. if (get.onComplete) {
  3436. get.onComplete(message);
  3437. }
  3438. });
  3439. };
  3440. PersistentConnection.prototype.sendListen_ = function (listenSpec) {
  3441. var _this = this;
  3442. var query = listenSpec.query;
  3443. var pathString = query._path.toString();
  3444. var queryId = query._queryIdentifier;
  3445. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3446. var req = { /*path*/ p: pathString };
  3447. var action = 'q';
  3448. // Only bother to send query if it's non-default.
  3449. if (listenSpec.tag) {
  3450. req['q'] = query._queryObject;
  3451. req['t'] = listenSpec.tag;
  3452. }
  3453. req[ /*hash*/'h'] = listenSpec.hashFn();
  3454. this.sendRequest(action, req, function (message) {
  3455. var payload = message[ /*data*/'d'];
  3456. var status = message[ /*status*/'s'];
  3457. // print warnings in any case...
  3458. PersistentConnection.warnOnListenWarnings_(payload, query);
  3459. var currentListenSpec = _this.listens.get(pathString) &&
  3460. _this.listens.get(pathString).get(queryId);
  3461. // only trigger actions if the listen hasn't been removed and readded
  3462. if (currentListenSpec === listenSpec) {
  3463. _this.log_('listen response', message);
  3464. if (status !== 'ok') {
  3465. _this.removeListen_(pathString, queryId);
  3466. }
  3467. if (listenSpec.onComplete) {
  3468. listenSpec.onComplete(status, payload);
  3469. }
  3470. }
  3471. });
  3472. };
  3473. PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
  3474. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  3475. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3476. var warnings = util.safeGet(payload, 'w');
  3477. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3478. var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3479. var indexPath = query._path.toString();
  3480. warn("Using an unspecified index. Your data will be downloaded and " +
  3481. "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
  3482. "".concat(indexPath, " to your security rules for better performance."));
  3483. }
  3484. }
  3485. };
  3486. PersistentConnection.prototype.refreshAuthToken = function (token) {
  3487. this.authToken_ = token;
  3488. this.log_('Auth token refreshed');
  3489. if (this.authToken_) {
  3490. this.tryAuth();
  3491. }
  3492. else {
  3493. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3494. //the credential so we dont become authenticated next time we connect.
  3495. if (this.connected_) {
  3496. this.sendRequest('unauth', {}, function () { });
  3497. }
  3498. }
  3499. this.reduceReconnectDelayIfAdminCredential_(token);
  3500. };
  3501. PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
  3502. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3503. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3504. var isFirebaseSecret = credential && credential.length === 40;
  3505. if (isFirebaseSecret || util.isAdmin(credential)) {
  3506. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3507. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3508. }
  3509. };
  3510. PersistentConnection.prototype.refreshAppCheckToken = function (token) {
  3511. this.appCheckToken_ = token;
  3512. this.log_('App check token refreshed');
  3513. if (this.appCheckToken_) {
  3514. this.tryAppCheck();
  3515. }
  3516. else {
  3517. //If we're connected we want to let the server know to unauthenticate us.
  3518. //If we're not connected, simply delete the credential so we dont become
  3519. // authenticated next time we connect.
  3520. if (this.connected_) {
  3521. this.sendRequest('unappeck', {}, function () { });
  3522. }
  3523. }
  3524. };
  3525. /**
  3526. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3527. * a auth revoked (the connection is closed).
  3528. */
  3529. PersistentConnection.prototype.tryAuth = function () {
  3530. var _this = this;
  3531. if (this.connected_ && this.authToken_) {
  3532. var token_1 = this.authToken_;
  3533. var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';
  3534. var requestData = { cred: token_1 };
  3535. if (this.authOverride_ === null) {
  3536. requestData['noauth'] = true;
  3537. }
  3538. else if (typeof this.authOverride_ === 'object') {
  3539. requestData['authvar'] = this.authOverride_;
  3540. }
  3541. this.sendRequest(authMethod, requestData, function (res) {
  3542. var status = res[ /*status*/'s'];
  3543. var data = res[ /*data*/'d'] || 'error';
  3544. if (_this.authToken_ === token_1) {
  3545. if (status === 'ok') {
  3546. _this.invalidAuthTokenCount_ = 0;
  3547. }
  3548. else {
  3549. // Triggers reconnect and force refresh for auth token
  3550. _this.onAuthRevoked_(status, data);
  3551. }
  3552. }
  3553. });
  3554. }
  3555. };
  3556. /**
  3557. * Attempts to authenticate with the given token. If the authentication
  3558. * attempt fails, it's triggered like the token was revoked (the connection is
  3559. * closed).
  3560. */
  3561. PersistentConnection.prototype.tryAppCheck = function () {
  3562. var _this = this;
  3563. if (this.connected_ && this.appCheckToken_) {
  3564. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
  3565. var status = res[ /*status*/'s'];
  3566. var data = res[ /*data*/'d'] || 'error';
  3567. if (status === 'ok') {
  3568. _this.invalidAppCheckTokenCount_ = 0;
  3569. }
  3570. else {
  3571. _this.onAppCheckRevoked_(status, data);
  3572. }
  3573. });
  3574. }
  3575. };
  3576. /**
  3577. * @inheritDoc
  3578. */
  3579. PersistentConnection.prototype.unlisten = function (query, tag) {
  3580. var pathString = query._path.toString();
  3581. var queryId = query._queryIdentifier;
  3582. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3583. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3584. var listen = this.removeListen_(pathString, queryId);
  3585. if (listen && this.connected_) {
  3586. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3587. }
  3588. };
  3589. PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
  3590. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3591. var req = { /*path*/ p: pathString };
  3592. var action = 'n';
  3593. // Only bother sending queryId if it's non-default.
  3594. if (tag) {
  3595. req['q'] = queryObj;
  3596. req['t'] = tag;
  3597. }
  3598. this.sendRequest(action, req);
  3599. };
  3600. PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
  3601. this.initConnection_();
  3602. if (this.connected_) {
  3603. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3604. }
  3605. else {
  3606. this.onDisconnectRequestQueue_.push({
  3607. pathString: pathString,
  3608. action: 'o',
  3609. data: data,
  3610. onComplete: onComplete
  3611. });
  3612. }
  3613. };
  3614. PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
  3615. this.initConnection_();
  3616. if (this.connected_) {
  3617. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3618. }
  3619. else {
  3620. this.onDisconnectRequestQueue_.push({
  3621. pathString: pathString,
  3622. action: 'om',
  3623. data: data,
  3624. onComplete: onComplete
  3625. });
  3626. }
  3627. };
  3628. PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
  3629. this.initConnection_();
  3630. if (this.connected_) {
  3631. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3632. }
  3633. else {
  3634. this.onDisconnectRequestQueue_.push({
  3635. pathString: pathString,
  3636. action: 'oc',
  3637. data: null,
  3638. onComplete: onComplete
  3639. });
  3640. }
  3641. };
  3642. PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
  3643. var request = { /*path*/ p: pathString, /*data*/ d: data };
  3644. this.log_('onDisconnect ' + action, request);
  3645. this.sendRequest(action, request, function (response) {
  3646. if (onComplete) {
  3647. setTimeout(function () {
  3648. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3649. }, Math.floor(0));
  3650. }
  3651. });
  3652. };
  3653. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  3654. this.putInternal('p', pathString, data, onComplete, hash);
  3655. };
  3656. PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
  3657. this.putInternal('m', pathString, data, onComplete, hash);
  3658. };
  3659. PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
  3660. this.initConnection_();
  3661. var request = {
  3662. /*path*/ p: pathString,
  3663. /*data*/ d: data
  3664. };
  3665. if (hash !== undefined) {
  3666. request[ /*hash*/'h'] = hash;
  3667. }
  3668. // TODO: Only keep track of the most recent put for a given path?
  3669. this.outstandingPuts_.push({
  3670. action: action,
  3671. request: request,
  3672. onComplete: onComplete
  3673. });
  3674. this.outstandingPutCount_++;
  3675. var index = this.outstandingPuts_.length - 1;
  3676. if (this.connected_) {
  3677. this.sendPut_(index);
  3678. }
  3679. else {
  3680. this.log_('Buffering put: ' + pathString);
  3681. }
  3682. };
  3683. PersistentConnection.prototype.sendPut_ = function (index) {
  3684. var _this = this;
  3685. var action = this.outstandingPuts_[index].action;
  3686. var request = this.outstandingPuts_[index].request;
  3687. var onComplete = this.outstandingPuts_[index].onComplete;
  3688. this.outstandingPuts_[index].queued = this.connected_;
  3689. this.sendRequest(action, request, function (message) {
  3690. _this.log_(action + ' response', message);
  3691. delete _this.outstandingPuts_[index];
  3692. _this.outstandingPutCount_--;
  3693. // Clean up array occasionally.
  3694. if (_this.outstandingPutCount_ === 0) {
  3695. _this.outstandingPuts_ = [];
  3696. }
  3697. if (onComplete) {
  3698. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3699. }
  3700. });
  3701. };
  3702. PersistentConnection.prototype.reportStats = function (stats) {
  3703. var _this = this;
  3704. // If we're not connected, we just drop the stats.
  3705. if (this.connected_) {
  3706. var request = { /*counters*/ c: stats };
  3707. this.log_('reportStats', request);
  3708. this.sendRequest(/*stats*/ 's', request, function (result) {
  3709. var status = result[ /*status*/'s'];
  3710. if (status !== 'ok') {
  3711. var errorReason = result[ /* data */'d'];
  3712. _this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3713. }
  3714. });
  3715. }
  3716. };
  3717. PersistentConnection.prototype.onDataMessage_ = function (message) {
  3718. if ('r' in message) {
  3719. // this is a response
  3720. this.log_('from server: ' + util.stringify(message));
  3721. var reqNum = message['r'];
  3722. var onResponse = this.requestCBHash_[reqNum];
  3723. if (onResponse) {
  3724. delete this.requestCBHash_[reqNum];
  3725. onResponse(message[ /*body*/'b']);
  3726. }
  3727. }
  3728. else if ('error' in message) {
  3729. throw 'A server-side error has occurred: ' + message['error'];
  3730. }
  3731. else if ('a' in message) {
  3732. // a and b are action and body, respectively
  3733. this.onDataPush_(message['a'], message['b']);
  3734. }
  3735. };
  3736. PersistentConnection.prototype.onDataPush_ = function (action, body) {
  3737. this.log_('handleServerMessage', action, body);
  3738. if (action === 'd') {
  3739. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3740. /*isMerge*/ false, body['t']);
  3741. }
  3742. else if (action === 'm') {
  3743. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3744. /*isMerge=*/ true, body['t']);
  3745. }
  3746. else if (action === 'c') {
  3747. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3748. }
  3749. else if (action === 'ac') {
  3750. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3751. }
  3752. else if (action === 'apc') {
  3753. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3754. }
  3755. else if (action === 'sd') {
  3756. this.onSecurityDebugPacket_(body);
  3757. }
  3758. else {
  3759. error('Unrecognized action received from server: ' +
  3760. util.stringify(action) +
  3761. '\nAre you using the latest client?');
  3762. }
  3763. };
  3764. PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
  3765. this.log_('connection ready');
  3766. this.connected_ = true;
  3767. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3768. this.handleTimestamp_(timestamp);
  3769. this.lastSessionId = sessionId;
  3770. if (this.firstConnection_) {
  3771. this.sendConnectStats_();
  3772. }
  3773. this.restoreState_();
  3774. this.firstConnection_ = false;
  3775. this.onConnectStatus_(true);
  3776. };
  3777. PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
  3778. var _this = this;
  3779. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3780. if (this.establishConnectionTimer_) {
  3781. clearTimeout(this.establishConnectionTimer_);
  3782. }
  3783. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3784. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3785. this.establishConnectionTimer_ = setTimeout(function () {
  3786. _this.establishConnectionTimer_ = null;
  3787. _this.establishConnection_();
  3788. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3789. }, Math.floor(timeout));
  3790. };
  3791. PersistentConnection.prototype.initConnection_ = function () {
  3792. if (!this.realtime_ && this.firstConnection_) {
  3793. this.scheduleConnect_(0);
  3794. }
  3795. };
  3796. PersistentConnection.prototype.onVisible_ = function (visible) {
  3797. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3798. if (visible &&
  3799. !this.visible_ &&
  3800. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3801. this.log_('Window became visible. Reducing delay.');
  3802. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3803. if (!this.realtime_) {
  3804. this.scheduleConnect_(0);
  3805. }
  3806. }
  3807. this.visible_ = visible;
  3808. };
  3809. PersistentConnection.prototype.onOnline_ = function (online) {
  3810. if (online) {
  3811. this.log_('Browser went online.');
  3812. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3813. if (!this.realtime_) {
  3814. this.scheduleConnect_(0);
  3815. }
  3816. }
  3817. else {
  3818. this.log_('Browser went offline. Killing connection.');
  3819. if (this.realtime_) {
  3820. this.realtime_.close();
  3821. }
  3822. }
  3823. };
  3824. PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
  3825. this.log_('data client disconnected');
  3826. this.connected_ = false;
  3827. this.realtime_ = null;
  3828. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3829. this.cancelSentTransactions_();
  3830. // Clear out the pending requests.
  3831. this.requestCBHash_ = {};
  3832. if (this.shouldReconnect_()) {
  3833. if (!this.visible_) {
  3834. this.log_("Window isn't visible. Delaying reconnect.");
  3835. this.reconnectDelay_ = this.maxReconnectDelay_;
  3836. this.lastConnectionAttemptTime_ = new Date().getTime();
  3837. }
  3838. else if (this.lastConnectionEstablishedTime_) {
  3839. // If we've been connected long enough, reset reconnect delay to minimum.
  3840. var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3841. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3842. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3843. }
  3844. this.lastConnectionEstablishedTime_ = null;
  3845. }
  3846. var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3847. var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3848. reconnectDelay = Math.random() * reconnectDelay;
  3849. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3850. this.scheduleConnect_(reconnectDelay);
  3851. // Adjust reconnect delay for next time.
  3852. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3853. }
  3854. this.onConnectStatus_(false);
  3855. };
  3856. PersistentConnection.prototype.establishConnection_ = function () {
  3857. return tslib.__awaiter(this, void 0, void 0, function () {
  3858. var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
  3859. var _this = this;
  3860. return tslib.__generator(this, function (_b) {
  3861. switch (_b.label) {
  3862. case 0:
  3863. if (!this.shouldReconnect_()) return [3 /*break*/, 4];
  3864. this.log_('Making a connection attempt');
  3865. this.lastConnectionAttemptTime_ = new Date().getTime();
  3866. this.lastConnectionEstablishedTime_ = null;
  3867. onDataMessage = this.onDataMessage_.bind(this);
  3868. onReady = this.onReady_.bind(this);
  3869. onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
  3870. connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3871. lastSessionId = this.lastSessionId;
  3872. canceled_1 = false;
  3873. connection_1 = null;
  3874. closeFn = function () {
  3875. if (connection_1) {
  3876. connection_1.close();
  3877. }
  3878. else {
  3879. canceled_1 = true;
  3880. onDisconnect_1();
  3881. }
  3882. };
  3883. sendRequestFn = function (msg) {
  3884. util.assert(connection_1, "sendRequest call when we're not connected not allowed.");
  3885. connection_1.sendRequest(msg);
  3886. };
  3887. this.realtime_ = {
  3888. close: closeFn,
  3889. sendRequest: sendRequestFn
  3890. };
  3891. forceRefresh = this.forceTokenRefresh_;
  3892. this.forceTokenRefresh_ = false;
  3893. _b.label = 1;
  3894. case 1:
  3895. _b.trys.push([1, 3, , 4]);
  3896. return [4 /*yield*/, Promise.all([
  3897. this.authTokenProvider_.getToken(forceRefresh),
  3898. this.appCheckTokenProvider_.getToken(forceRefresh)
  3899. ])];
  3900. case 2:
  3901. _a = tslib.__read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
  3902. if (!canceled_1) {
  3903. log('getToken() completed. Creating connection.');
  3904. this.authToken_ = authToken && authToken.accessToken;
  3905. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3906. connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
  3907. /* onKill= */ function (reason) {
  3908. warn(reason + ' (' + _this.repoInfo_.toString() + ')');
  3909. _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3910. }, lastSessionId);
  3911. }
  3912. else {
  3913. log('getToken() completed but was canceled');
  3914. }
  3915. return [3 /*break*/, 4];
  3916. case 3:
  3917. error_1 = _b.sent();
  3918. this.log_('Failed to get token: ' + error_1);
  3919. if (!canceled_1) {
  3920. if (this.repoInfo_.nodeAdmin) {
  3921. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3922. // But getToken() may also just have temporarily failed, so we still want to
  3923. // continue retrying.
  3924. warn(error_1);
  3925. }
  3926. closeFn();
  3927. }
  3928. return [3 /*break*/, 4];
  3929. case 4: return [2 /*return*/];
  3930. }
  3931. });
  3932. });
  3933. };
  3934. PersistentConnection.prototype.interrupt = function (reason) {
  3935. log('Interrupting connection for reason: ' + reason);
  3936. this.interruptReasons_[reason] = true;
  3937. if (this.realtime_) {
  3938. this.realtime_.close();
  3939. }
  3940. else {
  3941. if (this.establishConnectionTimer_) {
  3942. clearTimeout(this.establishConnectionTimer_);
  3943. this.establishConnectionTimer_ = null;
  3944. }
  3945. if (this.connected_) {
  3946. this.onRealtimeDisconnect_();
  3947. }
  3948. }
  3949. };
  3950. PersistentConnection.prototype.resume = function (reason) {
  3951. log('Resuming connection for reason: ' + reason);
  3952. delete this.interruptReasons_[reason];
  3953. if (util.isEmpty(this.interruptReasons_)) {
  3954. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3955. if (!this.realtime_) {
  3956. this.scheduleConnect_(0);
  3957. }
  3958. }
  3959. };
  3960. PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
  3961. var delta = timestamp - new Date().getTime();
  3962. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3963. };
  3964. PersistentConnection.prototype.cancelSentTransactions_ = function () {
  3965. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  3966. var put = this.outstandingPuts_[i];
  3967. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3968. if (put.onComplete) {
  3969. put.onComplete('disconnect');
  3970. }
  3971. delete this.outstandingPuts_[i];
  3972. this.outstandingPutCount_--;
  3973. }
  3974. }
  3975. // Clean up array occasionally.
  3976. if (this.outstandingPutCount_ === 0) {
  3977. this.outstandingPuts_ = [];
  3978. }
  3979. };
  3980. PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
  3981. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3982. var queryId;
  3983. if (!query) {
  3984. queryId = 'default';
  3985. }
  3986. else {
  3987. queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
  3988. }
  3989. var listen = this.removeListen_(pathString, queryId);
  3990. if (listen && listen.onComplete) {
  3991. listen.onComplete('permission_denied');
  3992. }
  3993. };
  3994. PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
  3995. var normalizedPathString = new Path(pathString).toString(); // normalize path.
  3996. var listen;
  3997. if (this.listens.has(normalizedPathString)) {
  3998. var map = this.listens.get(normalizedPathString);
  3999. listen = map.get(queryId);
  4000. map.delete(queryId);
  4001. if (map.size === 0) {
  4002. this.listens.delete(normalizedPathString);
  4003. }
  4004. }
  4005. else {
  4006. // all listens for this path has already been removed
  4007. listen = undefined;
  4008. }
  4009. return listen;
  4010. };
  4011. PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
  4012. log('Auth token revoked: ' + statusCode + '/' + explanation);
  4013. this.authToken_ = null;
  4014. this.forceTokenRefresh_ = true;
  4015. this.realtime_.close();
  4016. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4017. // We'll wait a couple times before logging the warning / increasing the
  4018. // retry period since oauth tokens will report as "invalid" if they're
  4019. // just expired. Plus there may be transient issues that resolve themselves.
  4020. this.invalidAuthTokenCount_++;
  4021. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4022. // Set a long reconnect delay because recovery is unlikely
  4023. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  4024. // Notify the auth token provider that the token is invalid, which will log
  4025. // a warning
  4026. this.authTokenProvider_.notifyForInvalidToken();
  4027. }
  4028. }
  4029. };
  4030. PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
  4031. log('App check token revoked: ' + statusCode + '/' + explanation);
  4032. this.appCheckToken_ = null;
  4033. this.forceTokenRefresh_ = true;
  4034. // Note: We don't close the connection as the developer may not have
  4035. // enforcement enabled. The backend closes connections with enforcements.
  4036. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4037. // We'll wait a couple times before logging the warning / increasing the
  4038. // retry period since oauth tokens will report as "invalid" if they're
  4039. // just expired. Plus there may be transient issues that resolve themselves.
  4040. this.invalidAppCheckTokenCount_++;
  4041. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4042. this.appCheckTokenProvider_.notifyForInvalidToken();
  4043. }
  4044. }
  4045. };
  4046. PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
  4047. if (this.securityDebugCallback_) {
  4048. this.securityDebugCallback_(body);
  4049. }
  4050. else {
  4051. if ('msg' in body) {
  4052. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  4053. }
  4054. }
  4055. };
  4056. PersistentConnection.prototype.restoreState_ = function () {
  4057. var e_1, _a, e_2, _b;
  4058. //Re-authenticate ourselves if we have a credential stored.
  4059. this.tryAuth();
  4060. this.tryAppCheck();
  4061. try {
  4062. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  4063. // make sure to send listens before puts.
  4064. for (var _c = tslib.__values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
  4065. var queries = _d.value;
  4066. try {
  4067. for (var _e = (e_2 = void 0, tslib.__values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
  4068. var listenSpec = _f.value;
  4069. this.sendListen_(listenSpec);
  4070. }
  4071. }
  4072. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  4073. finally {
  4074. try {
  4075. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  4076. }
  4077. finally { if (e_2) throw e_2.error; }
  4078. }
  4079. }
  4080. }
  4081. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4082. finally {
  4083. try {
  4084. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  4085. }
  4086. finally { if (e_1) throw e_1.error; }
  4087. }
  4088. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  4089. if (this.outstandingPuts_[i]) {
  4090. this.sendPut_(i);
  4091. }
  4092. }
  4093. while (this.onDisconnectRequestQueue_.length) {
  4094. var request = this.onDisconnectRequestQueue_.shift();
  4095. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  4096. }
  4097. for (var i = 0; i < this.outstandingGets_.length; i++) {
  4098. if (this.outstandingGets_[i]) {
  4099. this.sendGet_(i);
  4100. }
  4101. }
  4102. };
  4103. /**
  4104. * Sends client stats for first connection
  4105. */
  4106. PersistentConnection.prototype.sendConnectStats_ = function () {
  4107. var stats = {};
  4108. var clientName = 'js';
  4109. if (util.isNodeSdk()) {
  4110. if (this.repoInfo_.nodeAdmin) {
  4111. clientName = 'admin_node';
  4112. }
  4113. else {
  4114. clientName = 'node';
  4115. }
  4116. }
  4117. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  4118. if (util.isMobileCordova()) {
  4119. stats['framework.cordova'] = 1;
  4120. }
  4121. else if (util.isReactNative()) {
  4122. stats['framework.reactnative'] = 1;
  4123. }
  4124. this.reportStats(stats);
  4125. };
  4126. PersistentConnection.prototype.shouldReconnect_ = function () {
  4127. var online = OnlineMonitor.getInstance().currentlyOnline();
  4128. return util.isEmpty(this.interruptReasons_) && online;
  4129. };
  4130. PersistentConnection.nextPersistentConnectionId_ = 0;
  4131. /**
  4132. * Counter for number of connections created. Mainly used for tagging in the logs
  4133. */
  4134. PersistentConnection.nextConnectionId_ = 0;
  4135. return PersistentConnection;
  4136. }(ServerActions));
  4137. /**
  4138. * @license
  4139. * Copyright 2017 Google LLC
  4140. *
  4141. * Licensed under the Apache License, Version 2.0 (the "License");
  4142. * you may not use this file except in compliance with the License.
  4143. * You may obtain a copy of the License at
  4144. *
  4145. * http://www.apache.org/licenses/LICENSE-2.0
  4146. *
  4147. * Unless required by applicable law or agreed to in writing, software
  4148. * distributed under the License is distributed on an "AS IS" BASIS,
  4149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4150. * See the License for the specific language governing permissions and
  4151. * limitations under the License.
  4152. */
  4153. var NamedNode = /** @class */ (function () {
  4154. function NamedNode(name, node) {
  4155. this.name = name;
  4156. this.node = node;
  4157. }
  4158. NamedNode.Wrap = function (name, node) {
  4159. return new NamedNode(name, node);
  4160. };
  4161. return NamedNode;
  4162. }());
  4163. /**
  4164. * @license
  4165. * Copyright 2017 Google LLC
  4166. *
  4167. * Licensed under the Apache License, Version 2.0 (the "License");
  4168. * you may not use this file except in compliance with the License.
  4169. * You may obtain a copy of the License at
  4170. *
  4171. * http://www.apache.org/licenses/LICENSE-2.0
  4172. *
  4173. * Unless required by applicable law or agreed to in writing, software
  4174. * distributed under the License is distributed on an "AS IS" BASIS,
  4175. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4176. * See the License for the specific language governing permissions and
  4177. * limitations under the License.
  4178. */
  4179. var Index = /** @class */ (function () {
  4180. function Index() {
  4181. }
  4182. /**
  4183. * @returns A standalone comparison function for
  4184. * this index
  4185. */
  4186. Index.prototype.getCompare = function () {
  4187. return this.compare.bind(this);
  4188. };
  4189. /**
  4190. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4191. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4192. *
  4193. *
  4194. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4195. */
  4196. Index.prototype.indexedValueChanged = function (oldNode, newNode) {
  4197. var oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4198. var newWrapped = new NamedNode(MIN_NAME, newNode);
  4199. return this.compare(oldWrapped, newWrapped) !== 0;
  4200. };
  4201. /**
  4202. * @returns a node wrapper that will sort equal to or less than
  4203. * any other node wrapper, using this index
  4204. */
  4205. Index.prototype.minPost = function () {
  4206. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4207. return NamedNode.MIN;
  4208. };
  4209. return Index;
  4210. }());
  4211. /**
  4212. * @license
  4213. * Copyright 2017 Google LLC
  4214. *
  4215. * Licensed under the Apache License, Version 2.0 (the "License");
  4216. * you may not use this file except in compliance with the License.
  4217. * You may obtain a copy of the License at
  4218. *
  4219. * http://www.apache.org/licenses/LICENSE-2.0
  4220. *
  4221. * Unless required by applicable law or agreed to in writing, software
  4222. * distributed under the License is distributed on an "AS IS" BASIS,
  4223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4224. * See the License for the specific language governing permissions and
  4225. * limitations under the License.
  4226. */
  4227. var __EMPTY_NODE;
  4228. var KeyIndex = /** @class */ (function (_super) {
  4229. tslib.__extends(KeyIndex, _super);
  4230. function KeyIndex() {
  4231. return _super !== null && _super.apply(this, arguments) || this;
  4232. }
  4233. Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
  4234. get: function () {
  4235. return __EMPTY_NODE;
  4236. },
  4237. set: function (val) {
  4238. __EMPTY_NODE = val;
  4239. },
  4240. enumerable: false,
  4241. configurable: true
  4242. });
  4243. KeyIndex.prototype.compare = function (a, b) {
  4244. return nameCompare(a.name, b.name);
  4245. };
  4246. KeyIndex.prototype.isDefinedOn = function (node) {
  4247. // We could probably return true here (since every node has a key), but it's never called
  4248. // so just leaving unimplemented for now.
  4249. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4250. };
  4251. KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  4252. return false; // The key for a node never changes.
  4253. };
  4254. KeyIndex.prototype.minPost = function () {
  4255. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4256. return NamedNode.MIN;
  4257. };
  4258. KeyIndex.prototype.maxPost = function () {
  4259. // TODO: This should really be created once and cached in a static property, but
  4260. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4261. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4262. };
  4263. KeyIndex.prototype.makePost = function (indexValue, name) {
  4264. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4265. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4266. return new NamedNode(indexValue, __EMPTY_NODE);
  4267. };
  4268. /**
  4269. * @returns String representation for inclusion in a query spec
  4270. */
  4271. KeyIndex.prototype.toString = function () {
  4272. return '.key';
  4273. };
  4274. return KeyIndex;
  4275. }(Index));
  4276. var KEY_INDEX = new KeyIndex();
  4277. /**
  4278. * @license
  4279. * Copyright 2017 Google LLC
  4280. *
  4281. * Licensed under the Apache License, Version 2.0 (the "License");
  4282. * you may not use this file except in compliance with the License.
  4283. * You may obtain a copy of the License at
  4284. *
  4285. * http://www.apache.org/licenses/LICENSE-2.0
  4286. *
  4287. * Unless required by applicable law or agreed to in writing, software
  4288. * distributed under the License is distributed on an "AS IS" BASIS,
  4289. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4290. * See the License for the specific language governing permissions and
  4291. * limitations under the License.
  4292. */
  4293. /**
  4294. * An iterator over an LLRBNode.
  4295. */
  4296. var SortedMapIterator = /** @class */ (function () {
  4297. /**
  4298. * @param node - Node to iterate.
  4299. * @param isReverse_ - Whether or not to iterate in reverse
  4300. */
  4301. function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
  4302. if (resultGenerator_ === void 0) { resultGenerator_ = null; }
  4303. this.isReverse_ = isReverse_;
  4304. this.resultGenerator_ = resultGenerator_;
  4305. this.nodeStack_ = [];
  4306. var cmp = 1;
  4307. while (!node.isEmpty()) {
  4308. node = node;
  4309. cmp = startKey ? comparator(node.key, startKey) : 1;
  4310. // flip the comparison if we're going in reverse
  4311. if (isReverse_) {
  4312. cmp *= -1;
  4313. }
  4314. if (cmp < 0) {
  4315. // This node is less than our start key. ignore it
  4316. if (this.isReverse_) {
  4317. node = node.left;
  4318. }
  4319. else {
  4320. node = node.right;
  4321. }
  4322. }
  4323. else if (cmp === 0) {
  4324. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4325. this.nodeStack_.push(node);
  4326. break;
  4327. }
  4328. else {
  4329. // This node is greater than our start key, add it to the stack and move to the next one
  4330. this.nodeStack_.push(node);
  4331. if (this.isReverse_) {
  4332. node = node.right;
  4333. }
  4334. else {
  4335. node = node.left;
  4336. }
  4337. }
  4338. }
  4339. }
  4340. SortedMapIterator.prototype.getNext = function () {
  4341. if (this.nodeStack_.length === 0) {
  4342. return null;
  4343. }
  4344. var node = this.nodeStack_.pop();
  4345. var result;
  4346. if (this.resultGenerator_) {
  4347. result = this.resultGenerator_(node.key, node.value);
  4348. }
  4349. else {
  4350. result = { key: node.key, value: node.value };
  4351. }
  4352. if (this.isReverse_) {
  4353. node = node.left;
  4354. while (!node.isEmpty()) {
  4355. this.nodeStack_.push(node);
  4356. node = node.right;
  4357. }
  4358. }
  4359. else {
  4360. node = node.right;
  4361. while (!node.isEmpty()) {
  4362. this.nodeStack_.push(node);
  4363. node = node.left;
  4364. }
  4365. }
  4366. return result;
  4367. };
  4368. SortedMapIterator.prototype.hasNext = function () {
  4369. return this.nodeStack_.length > 0;
  4370. };
  4371. SortedMapIterator.prototype.peek = function () {
  4372. if (this.nodeStack_.length === 0) {
  4373. return null;
  4374. }
  4375. var node = this.nodeStack_[this.nodeStack_.length - 1];
  4376. if (this.resultGenerator_) {
  4377. return this.resultGenerator_(node.key, node.value);
  4378. }
  4379. else {
  4380. return { key: node.key, value: node.value };
  4381. }
  4382. };
  4383. return SortedMapIterator;
  4384. }());
  4385. /**
  4386. * Represents a node in a Left-leaning Red-Black tree.
  4387. */
  4388. var LLRBNode = /** @class */ (function () {
  4389. /**
  4390. * @param key - Key associated with this node.
  4391. * @param value - Value associated with this node.
  4392. * @param color - Whether this node is red.
  4393. * @param left - Left child.
  4394. * @param right - Right child.
  4395. */
  4396. function LLRBNode(key, value, color, left, right) {
  4397. this.key = key;
  4398. this.value = value;
  4399. this.color = color != null ? color : LLRBNode.RED;
  4400. this.left =
  4401. left != null ? left : SortedMap.EMPTY_NODE;
  4402. this.right =
  4403. right != null ? right : SortedMap.EMPTY_NODE;
  4404. }
  4405. /**
  4406. * Returns a copy of the current node, optionally replacing pieces of it.
  4407. *
  4408. * @param key - New key for the node, or null.
  4409. * @param value - New value for the node, or null.
  4410. * @param color - New color for the node, or null.
  4411. * @param left - New left child for the node, or null.
  4412. * @param right - New right child for the node, or null.
  4413. * @returns The node copy.
  4414. */
  4415. LLRBNode.prototype.copy = function (key, value, color, left, right) {
  4416. 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);
  4417. };
  4418. /**
  4419. * @returns The total number of nodes in the tree.
  4420. */
  4421. LLRBNode.prototype.count = function () {
  4422. return this.left.count() + 1 + this.right.count();
  4423. };
  4424. /**
  4425. * @returns True if the tree is empty.
  4426. */
  4427. LLRBNode.prototype.isEmpty = function () {
  4428. return false;
  4429. };
  4430. /**
  4431. * Traverses the tree in key order and calls the specified action function
  4432. * for each node.
  4433. *
  4434. * @param action - Callback function to be called for each
  4435. * node. If it returns true, traversal is aborted.
  4436. * @returns The first truthy value returned by action, or the last falsey
  4437. * value returned by action
  4438. */
  4439. LLRBNode.prototype.inorderTraversal = function (action) {
  4440. return (this.left.inorderTraversal(action) ||
  4441. !!action(this.key, this.value) ||
  4442. this.right.inorderTraversal(action));
  4443. };
  4444. /**
  4445. * Traverses the tree in reverse key order and calls the specified action function
  4446. * for each node.
  4447. *
  4448. * @param action - Callback function to be called for each
  4449. * node. If it returns true, traversal is aborted.
  4450. * @returns True if traversal was aborted.
  4451. */
  4452. LLRBNode.prototype.reverseTraversal = function (action) {
  4453. return (this.right.reverseTraversal(action) ||
  4454. action(this.key, this.value) ||
  4455. this.left.reverseTraversal(action));
  4456. };
  4457. /**
  4458. * @returns The minimum node in the tree.
  4459. */
  4460. LLRBNode.prototype.min_ = function () {
  4461. if (this.left.isEmpty()) {
  4462. return this;
  4463. }
  4464. else {
  4465. return this.left.min_();
  4466. }
  4467. };
  4468. /**
  4469. * @returns The maximum key in the tree.
  4470. */
  4471. LLRBNode.prototype.minKey = function () {
  4472. return this.min_().key;
  4473. };
  4474. /**
  4475. * @returns The maximum key in the tree.
  4476. */
  4477. LLRBNode.prototype.maxKey = function () {
  4478. if (this.right.isEmpty()) {
  4479. return this.key;
  4480. }
  4481. else {
  4482. return this.right.maxKey();
  4483. }
  4484. };
  4485. /**
  4486. * @param key - Key to insert.
  4487. * @param value - Value to insert.
  4488. * @param comparator - Comparator.
  4489. * @returns New tree, with the key/value added.
  4490. */
  4491. LLRBNode.prototype.insert = function (key, value, comparator) {
  4492. var n = this;
  4493. var cmp = comparator(key, n.key);
  4494. if (cmp < 0) {
  4495. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4496. }
  4497. else if (cmp === 0) {
  4498. n = n.copy(null, value, null, null, null);
  4499. }
  4500. else {
  4501. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4502. }
  4503. return n.fixUp_();
  4504. };
  4505. /**
  4506. * @returns New tree, with the minimum key removed.
  4507. */
  4508. LLRBNode.prototype.removeMin_ = function () {
  4509. if (this.left.isEmpty()) {
  4510. return SortedMap.EMPTY_NODE;
  4511. }
  4512. var n = this;
  4513. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4514. n = n.moveRedLeft_();
  4515. }
  4516. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4517. return n.fixUp_();
  4518. };
  4519. /**
  4520. * @param key - The key of the item to remove.
  4521. * @param comparator - Comparator.
  4522. * @returns New tree, with the specified item removed.
  4523. */
  4524. LLRBNode.prototype.remove = function (key, comparator) {
  4525. var n, smallest;
  4526. n = this;
  4527. if (comparator(key, n.key) < 0) {
  4528. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4529. n = n.moveRedLeft_();
  4530. }
  4531. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4532. }
  4533. else {
  4534. if (n.left.isRed_()) {
  4535. n = n.rotateRight_();
  4536. }
  4537. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4538. n = n.moveRedRight_();
  4539. }
  4540. if (comparator(key, n.key) === 0) {
  4541. if (n.right.isEmpty()) {
  4542. return SortedMap.EMPTY_NODE;
  4543. }
  4544. else {
  4545. smallest = n.right.min_();
  4546. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4547. }
  4548. }
  4549. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4550. }
  4551. return n.fixUp_();
  4552. };
  4553. /**
  4554. * @returns Whether this is a RED node.
  4555. */
  4556. LLRBNode.prototype.isRed_ = function () {
  4557. return this.color;
  4558. };
  4559. /**
  4560. * @returns New tree after performing any needed rotations.
  4561. */
  4562. LLRBNode.prototype.fixUp_ = function () {
  4563. var n = this;
  4564. if (n.right.isRed_() && !n.left.isRed_()) {
  4565. n = n.rotateLeft_();
  4566. }
  4567. if (n.left.isRed_() && n.left.left.isRed_()) {
  4568. n = n.rotateRight_();
  4569. }
  4570. if (n.left.isRed_() && n.right.isRed_()) {
  4571. n = n.colorFlip_();
  4572. }
  4573. return n;
  4574. };
  4575. /**
  4576. * @returns New tree, after moveRedLeft.
  4577. */
  4578. LLRBNode.prototype.moveRedLeft_ = function () {
  4579. var n = this.colorFlip_();
  4580. if (n.right.left.isRed_()) {
  4581. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4582. n = n.rotateLeft_();
  4583. n = n.colorFlip_();
  4584. }
  4585. return n;
  4586. };
  4587. /**
  4588. * @returns New tree, after moveRedRight.
  4589. */
  4590. LLRBNode.prototype.moveRedRight_ = function () {
  4591. var n = this.colorFlip_();
  4592. if (n.left.left.isRed_()) {
  4593. n = n.rotateRight_();
  4594. n = n.colorFlip_();
  4595. }
  4596. return n;
  4597. };
  4598. /**
  4599. * @returns New tree, after rotateLeft.
  4600. */
  4601. LLRBNode.prototype.rotateLeft_ = function () {
  4602. var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4603. return this.right.copy(null, null, this.color, nl, null);
  4604. };
  4605. /**
  4606. * @returns New tree, after rotateRight.
  4607. */
  4608. LLRBNode.prototype.rotateRight_ = function () {
  4609. var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4610. return this.left.copy(null, null, this.color, null, nr);
  4611. };
  4612. /**
  4613. * @returns Newt ree, after colorFlip.
  4614. */
  4615. LLRBNode.prototype.colorFlip_ = function () {
  4616. var left = this.left.copy(null, null, !this.left.color, null, null);
  4617. var right = this.right.copy(null, null, !this.right.color, null, null);
  4618. return this.copy(null, null, !this.color, left, right);
  4619. };
  4620. /**
  4621. * For testing.
  4622. *
  4623. * @returns True if all is well.
  4624. */
  4625. LLRBNode.prototype.checkMaxDepth_ = function () {
  4626. var blackDepth = this.check_();
  4627. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4628. };
  4629. LLRBNode.prototype.check_ = function () {
  4630. if (this.isRed_() && this.left.isRed_()) {
  4631. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4632. }
  4633. if (this.right.isRed_()) {
  4634. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4635. }
  4636. var blackDepth = this.left.check_();
  4637. if (blackDepth !== this.right.check_()) {
  4638. throw new Error('Black depths differ');
  4639. }
  4640. else {
  4641. return blackDepth + (this.isRed_() ? 0 : 1);
  4642. }
  4643. };
  4644. LLRBNode.RED = true;
  4645. LLRBNode.BLACK = false;
  4646. return LLRBNode;
  4647. }());
  4648. /**
  4649. * Represents an empty node (a leaf node in the Red-Black Tree).
  4650. */
  4651. var LLRBEmptyNode = /** @class */ (function () {
  4652. function LLRBEmptyNode() {
  4653. }
  4654. /**
  4655. * Returns a copy of the current node.
  4656. *
  4657. * @returns The node copy.
  4658. */
  4659. LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
  4660. return this;
  4661. };
  4662. /**
  4663. * Returns a copy of the tree, with the specified key/value added.
  4664. *
  4665. * @param key - Key to be added.
  4666. * @param value - Value to be added.
  4667. * @param comparator - Comparator.
  4668. * @returns New tree, with item added.
  4669. */
  4670. LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
  4671. return new LLRBNode(key, value, null);
  4672. };
  4673. /**
  4674. * Returns a copy of the tree, with the specified key removed.
  4675. *
  4676. * @param key - The key to remove.
  4677. * @param comparator - Comparator.
  4678. * @returns New tree, with item removed.
  4679. */
  4680. LLRBEmptyNode.prototype.remove = function (key, comparator) {
  4681. return this;
  4682. };
  4683. /**
  4684. * @returns The total number of nodes in the tree.
  4685. */
  4686. LLRBEmptyNode.prototype.count = function () {
  4687. return 0;
  4688. };
  4689. /**
  4690. * @returns True if the tree is empty.
  4691. */
  4692. LLRBEmptyNode.prototype.isEmpty = function () {
  4693. return true;
  4694. };
  4695. /**
  4696. * Traverses the tree in key order and calls the specified action function
  4697. * for each node.
  4698. *
  4699. * @param action - Callback function to be called for each
  4700. * node. If it returns true, traversal is aborted.
  4701. * @returns True if traversal was aborted.
  4702. */
  4703. LLRBEmptyNode.prototype.inorderTraversal = function (action) {
  4704. return false;
  4705. };
  4706. /**
  4707. * Traverses the tree in reverse key order and calls the specified action function
  4708. * for each node.
  4709. *
  4710. * @param action - Callback function to be called for each
  4711. * node. If it returns true, traversal is aborted.
  4712. * @returns True if traversal was aborted.
  4713. */
  4714. LLRBEmptyNode.prototype.reverseTraversal = function (action) {
  4715. return false;
  4716. };
  4717. LLRBEmptyNode.prototype.minKey = function () {
  4718. return null;
  4719. };
  4720. LLRBEmptyNode.prototype.maxKey = function () {
  4721. return null;
  4722. };
  4723. LLRBEmptyNode.prototype.check_ = function () {
  4724. return 0;
  4725. };
  4726. /**
  4727. * @returns Whether this node is red.
  4728. */
  4729. LLRBEmptyNode.prototype.isRed_ = function () {
  4730. return false;
  4731. };
  4732. return LLRBEmptyNode;
  4733. }());
  4734. /**
  4735. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4736. * tree.
  4737. */
  4738. var SortedMap = /** @class */ (function () {
  4739. /**
  4740. * @param comparator_ - Key comparator.
  4741. * @param root_ - Optional root node for the map.
  4742. */
  4743. function SortedMap(comparator_, root_) {
  4744. if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
  4745. this.comparator_ = comparator_;
  4746. this.root_ = root_;
  4747. }
  4748. /**
  4749. * Returns a copy of the map, with the specified key/value added or replaced.
  4750. * (TODO: We should perhaps rename this method to 'put')
  4751. *
  4752. * @param key - Key to be added.
  4753. * @param value - Value to be added.
  4754. * @returns New map, with item added.
  4755. */
  4756. SortedMap.prototype.insert = function (key, value) {
  4757. return new SortedMap(this.comparator_, this.root_
  4758. .insert(key, value, this.comparator_)
  4759. .copy(null, null, LLRBNode.BLACK, null, null));
  4760. };
  4761. /**
  4762. * Returns a copy of the map, with the specified key removed.
  4763. *
  4764. * @param key - The key to remove.
  4765. * @returns New map, with item removed.
  4766. */
  4767. SortedMap.prototype.remove = function (key) {
  4768. return new SortedMap(this.comparator_, this.root_
  4769. .remove(key, this.comparator_)
  4770. .copy(null, null, LLRBNode.BLACK, null, null));
  4771. };
  4772. /**
  4773. * Returns the value of the node with the given key, or null.
  4774. *
  4775. * @param key - The key to look up.
  4776. * @returns The value of the node with the given key, or null if the
  4777. * key doesn't exist.
  4778. */
  4779. SortedMap.prototype.get = function (key) {
  4780. var cmp;
  4781. var node = this.root_;
  4782. while (!node.isEmpty()) {
  4783. cmp = this.comparator_(key, node.key);
  4784. if (cmp === 0) {
  4785. return node.value;
  4786. }
  4787. else if (cmp < 0) {
  4788. node = node.left;
  4789. }
  4790. else if (cmp > 0) {
  4791. node = node.right;
  4792. }
  4793. }
  4794. return null;
  4795. };
  4796. /**
  4797. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4798. * @param key - The key to find the predecessor of
  4799. * @returns The predecessor key.
  4800. */
  4801. SortedMap.prototype.getPredecessorKey = function (key) {
  4802. var cmp, node = this.root_, rightParent = null;
  4803. while (!node.isEmpty()) {
  4804. cmp = this.comparator_(key, node.key);
  4805. if (cmp === 0) {
  4806. if (!node.left.isEmpty()) {
  4807. node = node.left;
  4808. while (!node.right.isEmpty()) {
  4809. node = node.right;
  4810. }
  4811. return node.key;
  4812. }
  4813. else if (rightParent) {
  4814. return rightParent.key;
  4815. }
  4816. else {
  4817. return null; // first item.
  4818. }
  4819. }
  4820. else if (cmp < 0) {
  4821. node = node.left;
  4822. }
  4823. else if (cmp > 0) {
  4824. rightParent = node;
  4825. node = node.right;
  4826. }
  4827. }
  4828. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4829. };
  4830. /**
  4831. * @returns True if the map is empty.
  4832. */
  4833. SortedMap.prototype.isEmpty = function () {
  4834. return this.root_.isEmpty();
  4835. };
  4836. /**
  4837. * @returns The total number of nodes in the map.
  4838. */
  4839. SortedMap.prototype.count = function () {
  4840. return this.root_.count();
  4841. };
  4842. /**
  4843. * @returns The minimum key in the map.
  4844. */
  4845. SortedMap.prototype.minKey = function () {
  4846. return this.root_.minKey();
  4847. };
  4848. /**
  4849. * @returns The maximum key in the map.
  4850. */
  4851. SortedMap.prototype.maxKey = function () {
  4852. return this.root_.maxKey();
  4853. };
  4854. /**
  4855. * Traverses the map in key order and calls the specified action function
  4856. * for each key/value pair.
  4857. *
  4858. * @param action - Callback function to be called
  4859. * for each key/value pair. If action returns true, traversal is aborted.
  4860. * @returns The first truthy value returned by action, or the last falsey
  4861. * value returned by action
  4862. */
  4863. SortedMap.prototype.inorderTraversal = function (action) {
  4864. return this.root_.inorderTraversal(action);
  4865. };
  4866. /**
  4867. * Traverses the map in reverse key order and calls the specified action function
  4868. * for each key/value pair.
  4869. *
  4870. * @param action - Callback function to be called
  4871. * for each key/value pair. If action returns true, traversal is aborted.
  4872. * @returns True if the traversal was aborted.
  4873. */
  4874. SortedMap.prototype.reverseTraversal = function (action) {
  4875. return this.root_.reverseTraversal(action);
  4876. };
  4877. /**
  4878. * Returns an iterator over the SortedMap.
  4879. * @returns The iterator.
  4880. */
  4881. SortedMap.prototype.getIterator = function (resultGenerator) {
  4882. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4883. };
  4884. SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
  4885. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4886. };
  4887. SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
  4888. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4889. };
  4890. SortedMap.prototype.getReverseIterator = function (resultGenerator) {
  4891. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4892. };
  4893. /**
  4894. * Always use the same empty node, to reduce memory.
  4895. */
  4896. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4897. return SortedMap;
  4898. }());
  4899. /**
  4900. * @license
  4901. * Copyright 2017 Google LLC
  4902. *
  4903. * Licensed under the Apache License, Version 2.0 (the "License");
  4904. * you may not use this file except in compliance with the License.
  4905. * You may obtain a copy of the License at
  4906. *
  4907. * http://www.apache.org/licenses/LICENSE-2.0
  4908. *
  4909. * Unless required by applicable law or agreed to in writing, software
  4910. * distributed under the License is distributed on an "AS IS" BASIS,
  4911. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4912. * See the License for the specific language governing permissions and
  4913. * limitations under the License.
  4914. */
  4915. function NAME_ONLY_COMPARATOR(left, right) {
  4916. return nameCompare(left.name, right.name);
  4917. }
  4918. function NAME_COMPARATOR(left, right) {
  4919. return nameCompare(left, right);
  4920. }
  4921. /**
  4922. * @license
  4923. * Copyright 2017 Google LLC
  4924. *
  4925. * Licensed under the Apache License, Version 2.0 (the "License");
  4926. * you may not use this file except in compliance with the License.
  4927. * You may obtain a copy of the License at
  4928. *
  4929. * http://www.apache.org/licenses/LICENSE-2.0
  4930. *
  4931. * Unless required by applicable law or agreed to in writing, software
  4932. * distributed under the License is distributed on an "AS IS" BASIS,
  4933. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4934. * See the License for the specific language governing permissions and
  4935. * limitations under the License.
  4936. */
  4937. var MAX_NODE$2;
  4938. function setMaxNode$1(val) {
  4939. MAX_NODE$2 = val;
  4940. }
  4941. var priorityHashText = function (priority) {
  4942. if (typeof priority === 'number') {
  4943. return 'number:' + doubleToIEEE754String(priority);
  4944. }
  4945. else {
  4946. return 'string:' + priority;
  4947. }
  4948. };
  4949. /**
  4950. * Validates that a priority snapshot Node is valid.
  4951. */
  4952. var validatePriorityNode = function (priorityNode) {
  4953. if (priorityNode.isLeafNode()) {
  4954. var val = priorityNode.val();
  4955. util.assert(typeof val === 'string' ||
  4956. typeof val === 'number' ||
  4957. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  4958. }
  4959. else {
  4960. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4961. }
  4962. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4963. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4964. };
  4965. /**
  4966. * @license
  4967. * Copyright 2017 Google LLC
  4968. *
  4969. * Licensed under the Apache License, Version 2.0 (the "License");
  4970. * you may not use this file except in compliance with the License.
  4971. * You may obtain a copy of the License at
  4972. *
  4973. * http://www.apache.org/licenses/LICENSE-2.0
  4974. *
  4975. * Unless required by applicable law or agreed to in writing, software
  4976. * distributed under the License is distributed on an "AS IS" BASIS,
  4977. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4978. * See the License for the specific language governing permissions and
  4979. * limitations under the License.
  4980. */
  4981. var __childrenNodeConstructor;
  4982. /**
  4983. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4984. * implements Node and stores the value of the node (a string,
  4985. * number, or boolean) accessible via getValue().
  4986. */
  4987. var LeafNode = /** @class */ (function () {
  4988. /**
  4989. * @param value_ - The value to store in this leaf node. The object type is
  4990. * possible in the event of a deferred value
  4991. * @param priorityNode_ - The priority of this node.
  4992. */
  4993. function LeafNode(value_, priorityNode_) {
  4994. if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
  4995. this.value_ = value_;
  4996. this.priorityNode_ = priorityNode_;
  4997. this.lazyHash_ = null;
  4998. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4999. validatePriorityNode(this.priorityNode_);
  5000. }
  5001. Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
  5002. get: function () {
  5003. return __childrenNodeConstructor;
  5004. },
  5005. set: function (val) {
  5006. __childrenNodeConstructor = val;
  5007. },
  5008. enumerable: false,
  5009. configurable: true
  5010. });
  5011. /** @inheritDoc */
  5012. LeafNode.prototype.isLeafNode = function () {
  5013. return true;
  5014. };
  5015. /** @inheritDoc */
  5016. LeafNode.prototype.getPriority = function () {
  5017. return this.priorityNode_;
  5018. };
  5019. /** @inheritDoc */
  5020. LeafNode.prototype.updatePriority = function (newPriorityNode) {
  5021. return new LeafNode(this.value_, newPriorityNode);
  5022. };
  5023. /** @inheritDoc */
  5024. LeafNode.prototype.getImmediateChild = function (childName) {
  5025. // Hack to treat priority as a regular child
  5026. if (childName === '.priority') {
  5027. return this.priorityNode_;
  5028. }
  5029. else {
  5030. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5031. }
  5032. };
  5033. /** @inheritDoc */
  5034. LeafNode.prototype.getChild = function (path) {
  5035. if (pathIsEmpty(path)) {
  5036. return this;
  5037. }
  5038. else if (pathGetFront(path) === '.priority') {
  5039. return this.priorityNode_;
  5040. }
  5041. else {
  5042. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5043. }
  5044. };
  5045. LeafNode.prototype.hasChild = function () {
  5046. return false;
  5047. };
  5048. /** @inheritDoc */
  5049. LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
  5050. return null;
  5051. };
  5052. /** @inheritDoc */
  5053. LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5054. if (childName === '.priority') {
  5055. return this.updatePriority(newChildNode);
  5056. }
  5057. else if (newChildNode.isEmpty() && childName !== '.priority') {
  5058. return this;
  5059. }
  5060. else {
  5061. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  5062. }
  5063. };
  5064. /** @inheritDoc */
  5065. LeafNode.prototype.updateChild = function (path, newChildNode) {
  5066. var front = pathGetFront(path);
  5067. if (front === null) {
  5068. return newChildNode;
  5069. }
  5070. else if (newChildNode.isEmpty() && front !== '.priority') {
  5071. return this;
  5072. }
  5073. else {
  5074. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5075. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  5076. }
  5077. };
  5078. /** @inheritDoc */
  5079. LeafNode.prototype.isEmpty = function () {
  5080. return false;
  5081. };
  5082. /** @inheritDoc */
  5083. LeafNode.prototype.numChildren = function () {
  5084. return 0;
  5085. };
  5086. /** @inheritDoc */
  5087. LeafNode.prototype.forEachChild = function (index, action) {
  5088. return false;
  5089. };
  5090. LeafNode.prototype.val = function (exportFormat) {
  5091. if (exportFormat && !this.getPriority().isEmpty()) {
  5092. return {
  5093. '.value': this.getValue(),
  5094. '.priority': this.getPriority().val()
  5095. };
  5096. }
  5097. else {
  5098. return this.getValue();
  5099. }
  5100. };
  5101. /** @inheritDoc */
  5102. LeafNode.prototype.hash = function () {
  5103. if (this.lazyHash_ === null) {
  5104. var toHash = '';
  5105. if (!this.priorityNode_.isEmpty()) {
  5106. toHash +=
  5107. 'priority:' +
  5108. priorityHashText(this.priorityNode_.val()) +
  5109. ':';
  5110. }
  5111. var type = typeof this.value_;
  5112. toHash += type + ':';
  5113. if (type === 'number') {
  5114. toHash += doubleToIEEE754String(this.value_);
  5115. }
  5116. else {
  5117. toHash += this.value_;
  5118. }
  5119. this.lazyHash_ = sha1(toHash);
  5120. }
  5121. return this.lazyHash_;
  5122. };
  5123. /**
  5124. * Returns the value of the leaf node.
  5125. * @returns The value of the node.
  5126. */
  5127. LeafNode.prototype.getValue = function () {
  5128. return this.value_;
  5129. };
  5130. LeafNode.prototype.compareTo = function (other) {
  5131. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  5132. return 1;
  5133. }
  5134. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  5135. return -1;
  5136. }
  5137. else {
  5138. util.assert(other.isLeafNode(), 'Unknown node type');
  5139. return this.compareToLeafNode_(other);
  5140. }
  5141. };
  5142. /**
  5143. * Comparison specifically for two leaf nodes
  5144. */
  5145. LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
  5146. var otherLeafType = typeof otherLeaf.value_;
  5147. var thisLeafType = typeof this.value_;
  5148. var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  5149. var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  5150. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  5151. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  5152. if (otherIndex === thisIndex) {
  5153. // Same type, compare values
  5154. if (thisLeafType === 'object') {
  5155. // Deferred value nodes are all equal, but we should also never get to this point...
  5156. return 0;
  5157. }
  5158. else {
  5159. // Note that this works because true > false, all others are number or string comparisons
  5160. if (this.value_ < otherLeaf.value_) {
  5161. return -1;
  5162. }
  5163. else if (this.value_ === otherLeaf.value_) {
  5164. return 0;
  5165. }
  5166. else {
  5167. return 1;
  5168. }
  5169. }
  5170. }
  5171. else {
  5172. return thisIndex - otherIndex;
  5173. }
  5174. };
  5175. LeafNode.prototype.withIndex = function () {
  5176. return this;
  5177. };
  5178. LeafNode.prototype.isIndexed = function () {
  5179. return true;
  5180. };
  5181. LeafNode.prototype.equals = function (other) {
  5182. if (other === this) {
  5183. return true;
  5184. }
  5185. else if (other.isLeafNode()) {
  5186. var otherLeaf = other;
  5187. return (this.value_ === otherLeaf.value_ &&
  5188. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5189. }
  5190. else {
  5191. return false;
  5192. }
  5193. };
  5194. /**
  5195. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5196. * the same type, the comparison falls back to their value
  5197. */
  5198. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5199. return LeafNode;
  5200. }());
  5201. /**
  5202. * @license
  5203. * Copyright 2017 Google LLC
  5204. *
  5205. * Licensed under the Apache License, Version 2.0 (the "License");
  5206. * you may not use this file except in compliance with the License.
  5207. * You may obtain a copy of the License at
  5208. *
  5209. * http://www.apache.org/licenses/LICENSE-2.0
  5210. *
  5211. * Unless required by applicable law or agreed to in writing, software
  5212. * distributed under the License is distributed on an "AS IS" BASIS,
  5213. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5214. * See the License for the specific language governing permissions and
  5215. * limitations under the License.
  5216. */
  5217. var nodeFromJSON$1;
  5218. var MAX_NODE$1;
  5219. function setNodeFromJSON(val) {
  5220. nodeFromJSON$1 = val;
  5221. }
  5222. function setMaxNode(val) {
  5223. MAX_NODE$1 = val;
  5224. }
  5225. var PriorityIndex = /** @class */ (function (_super) {
  5226. tslib.__extends(PriorityIndex, _super);
  5227. function PriorityIndex() {
  5228. return _super !== null && _super.apply(this, arguments) || this;
  5229. }
  5230. PriorityIndex.prototype.compare = function (a, b) {
  5231. var aPriority = a.node.getPriority();
  5232. var bPriority = b.node.getPriority();
  5233. var indexCmp = aPriority.compareTo(bPriority);
  5234. if (indexCmp === 0) {
  5235. return nameCompare(a.name, b.name);
  5236. }
  5237. else {
  5238. return indexCmp;
  5239. }
  5240. };
  5241. PriorityIndex.prototype.isDefinedOn = function (node) {
  5242. return !node.getPriority().isEmpty();
  5243. };
  5244. PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  5245. return !oldNode.getPriority().equals(newNode.getPriority());
  5246. };
  5247. PriorityIndex.prototype.minPost = function () {
  5248. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5249. return NamedNode.MIN;
  5250. };
  5251. PriorityIndex.prototype.maxPost = function () {
  5252. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5253. };
  5254. PriorityIndex.prototype.makePost = function (indexValue, name) {
  5255. var priorityNode = nodeFromJSON$1(indexValue);
  5256. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5257. };
  5258. /**
  5259. * @returns String representation for inclusion in a query spec
  5260. */
  5261. PriorityIndex.prototype.toString = function () {
  5262. return '.priority';
  5263. };
  5264. return PriorityIndex;
  5265. }(Index));
  5266. var PRIORITY_INDEX = new PriorityIndex();
  5267. /**
  5268. * @license
  5269. * Copyright 2017 Google LLC
  5270. *
  5271. * Licensed under the Apache License, Version 2.0 (the "License");
  5272. * you may not use this file except in compliance with the License.
  5273. * You may obtain a copy of the License at
  5274. *
  5275. * http://www.apache.org/licenses/LICENSE-2.0
  5276. *
  5277. * Unless required by applicable law or agreed to in writing, software
  5278. * distributed under the License is distributed on an "AS IS" BASIS,
  5279. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5280. * See the License for the specific language governing permissions and
  5281. * limitations under the License.
  5282. */
  5283. var LOG_2 = Math.log(2);
  5284. var Base12Num = /** @class */ (function () {
  5285. function Base12Num(length) {
  5286. var logBase2 = function (num) {
  5287. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5288. return parseInt((Math.log(num) / LOG_2), 10);
  5289. };
  5290. var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
  5291. this.count = logBase2(length + 1);
  5292. this.current_ = this.count - 1;
  5293. var mask = bitMask(this.count);
  5294. this.bits_ = (length + 1) & mask;
  5295. }
  5296. Base12Num.prototype.nextBitIsOne = function () {
  5297. //noinspection JSBitwiseOperatorUsage
  5298. var result = !(this.bits_ & (0x1 << this.current_));
  5299. this.current_--;
  5300. return result;
  5301. };
  5302. return Base12Num;
  5303. }());
  5304. /**
  5305. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5306. * function
  5307. *
  5308. * Uses the algorithm described in the paper linked here:
  5309. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5310. *
  5311. * @param childList - Unsorted list of children
  5312. * @param cmp - The comparison method to be used
  5313. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5314. * type is not NamedNode
  5315. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5316. */
  5317. var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5318. childList.sort(cmp);
  5319. var buildBalancedTree = function (low, high) {
  5320. var length = high - low;
  5321. var namedNode;
  5322. var key;
  5323. if (length === 0) {
  5324. return null;
  5325. }
  5326. else if (length === 1) {
  5327. namedNode = childList[low];
  5328. key = keyFn ? keyFn(namedNode) : namedNode;
  5329. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5330. }
  5331. else {
  5332. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5333. var middle = parseInt((length / 2), 10) + low;
  5334. var left = buildBalancedTree(low, middle);
  5335. var right = buildBalancedTree(middle + 1, high);
  5336. namedNode = childList[middle];
  5337. key = keyFn ? keyFn(namedNode) : namedNode;
  5338. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5339. }
  5340. };
  5341. var buildFrom12Array = function (base12) {
  5342. var node = null;
  5343. var root = null;
  5344. var index = childList.length;
  5345. var buildPennant = function (chunkSize, color) {
  5346. var low = index - chunkSize;
  5347. var high = index;
  5348. index -= chunkSize;
  5349. var childTree = buildBalancedTree(low + 1, high);
  5350. var namedNode = childList[low];
  5351. var key = keyFn ? keyFn(namedNode) : namedNode;
  5352. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5353. };
  5354. var attachPennant = function (pennant) {
  5355. if (node) {
  5356. node.left = pennant;
  5357. node = pennant;
  5358. }
  5359. else {
  5360. root = pennant;
  5361. node = pennant;
  5362. }
  5363. };
  5364. for (var i = 0; i < base12.count; ++i) {
  5365. var isOne = base12.nextBitIsOne();
  5366. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5367. var chunkSize = Math.pow(2, base12.count - (i + 1));
  5368. if (isOne) {
  5369. buildPennant(chunkSize, LLRBNode.BLACK);
  5370. }
  5371. else {
  5372. // current == 2
  5373. buildPennant(chunkSize, LLRBNode.BLACK);
  5374. buildPennant(chunkSize, LLRBNode.RED);
  5375. }
  5376. }
  5377. return root;
  5378. };
  5379. var base12 = new Base12Num(childList.length);
  5380. var root = buildFrom12Array(base12);
  5381. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5382. return new SortedMap(mapSortFn || cmp, root);
  5383. };
  5384. /**
  5385. * @license
  5386. * Copyright 2017 Google LLC
  5387. *
  5388. * Licensed under the Apache License, Version 2.0 (the "License");
  5389. * you may not use this file except in compliance with the License.
  5390. * You may obtain a copy of the License at
  5391. *
  5392. * http://www.apache.org/licenses/LICENSE-2.0
  5393. *
  5394. * Unless required by applicable law or agreed to in writing, software
  5395. * distributed under the License is distributed on an "AS IS" BASIS,
  5396. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5397. * See the License for the specific language governing permissions and
  5398. * limitations under the License.
  5399. */
  5400. var _defaultIndexMap;
  5401. var fallbackObject = {};
  5402. var IndexMap = /** @class */ (function () {
  5403. function IndexMap(indexes_, indexSet_) {
  5404. this.indexes_ = indexes_;
  5405. this.indexSet_ = indexSet_;
  5406. }
  5407. Object.defineProperty(IndexMap, "Default", {
  5408. /**
  5409. * The default IndexMap for nodes without a priority
  5410. */
  5411. get: function () {
  5412. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5413. _defaultIndexMap =
  5414. _defaultIndexMap ||
  5415. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5416. return _defaultIndexMap;
  5417. },
  5418. enumerable: false,
  5419. configurable: true
  5420. });
  5421. IndexMap.prototype.get = function (indexKey) {
  5422. var sortedMap = util.safeGet(this.indexes_, indexKey);
  5423. if (!sortedMap) {
  5424. throw new Error('No index defined for ' + indexKey);
  5425. }
  5426. if (sortedMap instanceof SortedMap) {
  5427. return sortedMap;
  5428. }
  5429. else {
  5430. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5431. // regular child map
  5432. return null;
  5433. }
  5434. };
  5435. IndexMap.prototype.hasIndex = function (indexDefinition) {
  5436. return util.contains(this.indexSet_, indexDefinition.toString());
  5437. };
  5438. IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
  5439. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5440. var childList = [];
  5441. var sawIndexedValue = false;
  5442. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5443. var next = iter.getNext();
  5444. while (next) {
  5445. sawIndexedValue =
  5446. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5447. childList.push(next);
  5448. next = iter.getNext();
  5449. }
  5450. var newIndex;
  5451. if (sawIndexedValue) {
  5452. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5453. }
  5454. else {
  5455. newIndex = fallbackObject;
  5456. }
  5457. var indexName = indexDefinition.toString();
  5458. var newIndexSet = tslib.__assign({}, this.indexSet_);
  5459. newIndexSet[indexName] = indexDefinition;
  5460. var newIndexes = tslib.__assign({}, this.indexes_);
  5461. newIndexes[indexName] = newIndex;
  5462. return new IndexMap(newIndexes, newIndexSet);
  5463. };
  5464. /**
  5465. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5466. */
  5467. IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
  5468. var _this = this;
  5469. var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) {
  5470. var index = util.safeGet(_this.indexSet_, indexName);
  5471. util.assert(index, 'Missing index implementation for ' + indexName);
  5472. if (indexedChildren === fallbackObject) {
  5473. // Check to see if we need to index everything
  5474. if (index.isDefinedOn(namedNode.node)) {
  5475. // We need to build this index
  5476. var childList = [];
  5477. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5478. var next = iter.getNext();
  5479. while (next) {
  5480. if (next.name !== namedNode.name) {
  5481. childList.push(next);
  5482. }
  5483. next = iter.getNext();
  5484. }
  5485. childList.push(namedNode);
  5486. return buildChildSet(childList, index.getCompare());
  5487. }
  5488. else {
  5489. // No change, this remains a fallback
  5490. return fallbackObject;
  5491. }
  5492. }
  5493. else {
  5494. var existingSnap = existingChildren.get(namedNode.name);
  5495. var newChildren = indexedChildren;
  5496. if (existingSnap) {
  5497. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5498. }
  5499. return newChildren.insert(namedNode, namedNode.node);
  5500. }
  5501. });
  5502. return new IndexMap(newIndexes, this.indexSet_);
  5503. };
  5504. /**
  5505. * Create a new IndexMap instance with the given value removed
  5506. */
  5507. IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
  5508. var newIndexes = util.map(this.indexes_, function (indexedChildren) {
  5509. if (indexedChildren === fallbackObject) {
  5510. // This is the fallback. Just return it, nothing to do in this case
  5511. return indexedChildren;
  5512. }
  5513. else {
  5514. var existingSnap = existingChildren.get(namedNode.name);
  5515. if (existingSnap) {
  5516. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5517. }
  5518. else {
  5519. // No record of this child
  5520. return indexedChildren;
  5521. }
  5522. }
  5523. });
  5524. return new IndexMap(newIndexes, this.indexSet_);
  5525. };
  5526. return IndexMap;
  5527. }());
  5528. /**
  5529. * @license
  5530. * Copyright 2017 Google LLC
  5531. *
  5532. * Licensed under the Apache License, Version 2.0 (the "License");
  5533. * you may not use this file except in compliance with the License.
  5534. * You may obtain a copy of the License at
  5535. *
  5536. * http://www.apache.org/licenses/LICENSE-2.0
  5537. *
  5538. * Unless required by applicable law or agreed to in writing, software
  5539. * distributed under the License is distributed on an "AS IS" BASIS,
  5540. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5541. * See the License for the specific language governing permissions and
  5542. * limitations under the License.
  5543. */
  5544. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5545. var EMPTY_NODE;
  5546. /**
  5547. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5548. * (i.e. nodes with children). It implements Node and stores the
  5549. * list of children in the children property, sorted by child name.
  5550. */
  5551. var ChildrenNode = /** @class */ (function () {
  5552. /**
  5553. * @param children_ - List of children of this node..
  5554. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5555. */
  5556. function ChildrenNode(children_, priorityNode_, indexMap_) {
  5557. this.children_ = children_;
  5558. this.priorityNode_ = priorityNode_;
  5559. this.indexMap_ = indexMap_;
  5560. this.lazyHash_ = null;
  5561. /**
  5562. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5563. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5564. * class instead of an empty ChildrenNode.
  5565. */
  5566. if (this.priorityNode_) {
  5567. validatePriorityNode(this.priorityNode_);
  5568. }
  5569. if (this.children_.isEmpty()) {
  5570. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5571. }
  5572. }
  5573. Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
  5574. get: function () {
  5575. return (EMPTY_NODE ||
  5576. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5577. },
  5578. enumerable: false,
  5579. configurable: true
  5580. });
  5581. /** @inheritDoc */
  5582. ChildrenNode.prototype.isLeafNode = function () {
  5583. return false;
  5584. };
  5585. /** @inheritDoc */
  5586. ChildrenNode.prototype.getPriority = function () {
  5587. return this.priorityNode_ || EMPTY_NODE;
  5588. };
  5589. /** @inheritDoc */
  5590. ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
  5591. if (this.children_.isEmpty()) {
  5592. // Don't allow priorities on empty nodes
  5593. return this;
  5594. }
  5595. else {
  5596. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5597. }
  5598. };
  5599. /** @inheritDoc */
  5600. ChildrenNode.prototype.getImmediateChild = function (childName) {
  5601. // Hack to treat priority as a regular child
  5602. if (childName === '.priority') {
  5603. return this.getPriority();
  5604. }
  5605. else {
  5606. var child = this.children_.get(childName);
  5607. return child === null ? EMPTY_NODE : child;
  5608. }
  5609. };
  5610. /** @inheritDoc */
  5611. ChildrenNode.prototype.getChild = function (path) {
  5612. var front = pathGetFront(path);
  5613. if (front === null) {
  5614. return this;
  5615. }
  5616. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5617. };
  5618. /** @inheritDoc */
  5619. ChildrenNode.prototype.hasChild = function (childName) {
  5620. return this.children_.get(childName) !== null;
  5621. };
  5622. /** @inheritDoc */
  5623. ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5624. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  5625. if (childName === '.priority') {
  5626. return this.updatePriority(newChildNode);
  5627. }
  5628. else {
  5629. var namedNode = new NamedNode(childName, newChildNode);
  5630. var newChildren = void 0, newIndexMap = void 0;
  5631. if (newChildNode.isEmpty()) {
  5632. newChildren = this.children_.remove(childName);
  5633. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5634. }
  5635. else {
  5636. newChildren = this.children_.insert(childName, newChildNode);
  5637. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5638. }
  5639. var newPriority = newChildren.isEmpty()
  5640. ? EMPTY_NODE
  5641. : this.priorityNode_;
  5642. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5643. }
  5644. };
  5645. /** @inheritDoc */
  5646. ChildrenNode.prototype.updateChild = function (path, newChildNode) {
  5647. var front = pathGetFront(path);
  5648. if (front === null) {
  5649. return newChildNode;
  5650. }
  5651. else {
  5652. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5653. var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5654. return this.updateImmediateChild(front, newImmediateChild);
  5655. }
  5656. };
  5657. /** @inheritDoc */
  5658. ChildrenNode.prototype.isEmpty = function () {
  5659. return this.children_.isEmpty();
  5660. };
  5661. /** @inheritDoc */
  5662. ChildrenNode.prototype.numChildren = function () {
  5663. return this.children_.count();
  5664. };
  5665. /** @inheritDoc */
  5666. ChildrenNode.prototype.val = function (exportFormat) {
  5667. if (this.isEmpty()) {
  5668. return null;
  5669. }
  5670. var obj = {};
  5671. var numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5672. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5673. obj[key] = childNode.val(exportFormat);
  5674. numKeys++;
  5675. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5676. maxKey = Math.max(maxKey, Number(key));
  5677. }
  5678. else {
  5679. allIntegerKeys = false;
  5680. }
  5681. });
  5682. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5683. // convert to array.
  5684. var array = [];
  5685. // eslint-disable-next-line guard-for-in
  5686. for (var key in obj) {
  5687. array[key] = obj[key];
  5688. }
  5689. return array;
  5690. }
  5691. else {
  5692. if (exportFormat && !this.getPriority().isEmpty()) {
  5693. obj['.priority'] = this.getPriority().val();
  5694. }
  5695. return obj;
  5696. }
  5697. };
  5698. /** @inheritDoc */
  5699. ChildrenNode.prototype.hash = function () {
  5700. if (this.lazyHash_ === null) {
  5701. var toHash_1 = '';
  5702. if (!this.getPriority().isEmpty()) {
  5703. toHash_1 +=
  5704. 'priority:' +
  5705. priorityHashText(this.getPriority().val()) +
  5706. ':';
  5707. }
  5708. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5709. var childHash = childNode.hash();
  5710. if (childHash !== '') {
  5711. toHash_1 += ':' + key + ':' + childHash;
  5712. }
  5713. });
  5714. this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
  5715. }
  5716. return this.lazyHash_;
  5717. };
  5718. /** @inheritDoc */
  5719. ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
  5720. var idx = this.resolveIndex_(index);
  5721. if (idx) {
  5722. var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5723. return predecessor ? predecessor.name : null;
  5724. }
  5725. else {
  5726. return this.children_.getPredecessorKey(childName);
  5727. }
  5728. };
  5729. ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
  5730. var idx = this.resolveIndex_(indexDefinition);
  5731. if (idx) {
  5732. var minKey = idx.minKey();
  5733. return minKey && minKey.name;
  5734. }
  5735. else {
  5736. return this.children_.minKey();
  5737. }
  5738. };
  5739. ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
  5740. var minKey = this.getFirstChildName(indexDefinition);
  5741. if (minKey) {
  5742. return new NamedNode(minKey, this.children_.get(minKey));
  5743. }
  5744. else {
  5745. return null;
  5746. }
  5747. };
  5748. /**
  5749. * Given an index, return the key name of the largest value we have, according to that index
  5750. */
  5751. ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
  5752. var idx = this.resolveIndex_(indexDefinition);
  5753. if (idx) {
  5754. var maxKey = idx.maxKey();
  5755. return maxKey && maxKey.name;
  5756. }
  5757. else {
  5758. return this.children_.maxKey();
  5759. }
  5760. };
  5761. ChildrenNode.prototype.getLastChild = function (indexDefinition) {
  5762. var maxKey = this.getLastChildName(indexDefinition);
  5763. if (maxKey) {
  5764. return new NamedNode(maxKey, this.children_.get(maxKey));
  5765. }
  5766. else {
  5767. return null;
  5768. }
  5769. };
  5770. ChildrenNode.prototype.forEachChild = function (index, action) {
  5771. var idx = this.resolveIndex_(index);
  5772. if (idx) {
  5773. return idx.inorderTraversal(function (wrappedNode) {
  5774. return action(wrappedNode.name, wrappedNode.node);
  5775. });
  5776. }
  5777. else {
  5778. return this.children_.inorderTraversal(action);
  5779. }
  5780. };
  5781. ChildrenNode.prototype.getIterator = function (indexDefinition) {
  5782. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5783. };
  5784. ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
  5785. var idx = this.resolveIndex_(indexDefinition);
  5786. if (idx) {
  5787. return idx.getIteratorFrom(startPost, function (key) { return key; });
  5788. }
  5789. else {
  5790. var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5791. var next = iterator.peek();
  5792. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5793. iterator.getNext();
  5794. next = iterator.peek();
  5795. }
  5796. return iterator;
  5797. }
  5798. };
  5799. ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
  5800. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5801. };
  5802. ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
  5803. var idx = this.resolveIndex_(indexDefinition);
  5804. if (idx) {
  5805. return idx.getReverseIteratorFrom(endPost, function (key) {
  5806. return key;
  5807. });
  5808. }
  5809. else {
  5810. var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5811. var next = iterator.peek();
  5812. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5813. iterator.getNext();
  5814. next = iterator.peek();
  5815. }
  5816. return iterator;
  5817. }
  5818. };
  5819. ChildrenNode.prototype.compareTo = function (other) {
  5820. if (this.isEmpty()) {
  5821. if (other.isEmpty()) {
  5822. return 0;
  5823. }
  5824. else {
  5825. return -1;
  5826. }
  5827. }
  5828. else if (other.isLeafNode() || other.isEmpty()) {
  5829. return 1;
  5830. }
  5831. else if (other === MAX_NODE) {
  5832. return -1;
  5833. }
  5834. else {
  5835. // Must be another node with children.
  5836. return 0;
  5837. }
  5838. };
  5839. ChildrenNode.prototype.withIndex = function (indexDefinition) {
  5840. if (indexDefinition === KEY_INDEX ||
  5841. this.indexMap_.hasIndex(indexDefinition)) {
  5842. return this;
  5843. }
  5844. else {
  5845. var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5846. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5847. }
  5848. };
  5849. ChildrenNode.prototype.isIndexed = function (index) {
  5850. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5851. };
  5852. ChildrenNode.prototype.equals = function (other) {
  5853. if (other === this) {
  5854. return true;
  5855. }
  5856. else if (other.isLeafNode()) {
  5857. return false;
  5858. }
  5859. else {
  5860. var otherChildrenNode = other;
  5861. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5862. return false;
  5863. }
  5864. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5865. var thisIter = this.getIterator(PRIORITY_INDEX);
  5866. var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5867. var thisCurrent = thisIter.getNext();
  5868. var otherCurrent = otherIter.getNext();
  5869. while (thisCurrent && otherCurrent) {
  5870. if (thisCurrent.name !== otherCurrent.name ||
  5871. !thisCurrent.node.equals(otherCurrent.node)) {
  5872. return false;
  5873. }
  5874. thisCurrent = thisIter.getNext();
  5875. otherCurrent = otherIter.getNext();
  5876. }
  5877. return thisCurrent === null && otherCurrent === null;
  5878. }
  5879. else {
  5880. return false;
  5881. }
  5882. }
  5883. };
  5884. /**
  5885. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5886. * instead.
  5887. *
  5888. */
  5889. ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
  5890. if (indexDefinition === KEY_INDEX) {
  5891. return null;
  5892. }
  5893. else {
  5894. return this.indexMap_.get(indexDefinition.toString());
  5895. }
  5896. };
  5897. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5898. return ChildrenNode;
  5899. }());
  5900. var MaxNode = /** @class */ (function (_super) {
  5901. tslib.__extends(MaxNode, _super);
  5902. function MaxNode() {
  5903. return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
  5904. }
  5905. MaxNode.prototype.compareTo = function (other) {
  5906. if (other === this) {
  5907. return 0;
  5908. }
  5909. else {
  5910. return 1;
  5911. }
  5912. };
  5913. MaxNode.prototype.equals = function (other) {
  5914. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5915. return other === this;
  5916. };
  5917. MaxNode.prototype.getPriority = function () {
  5918. return this;
  5919. };
  5920. MaxNode.prototype.getImmediateChild = function (childName) {
  5921. return ChildrenNode.EMPTY_NODE;
  5922. };
  5923. MaxNode.prototype.isEmpty = function () {
  5924. return false;
  5925. };
  5926. return MaxNode;
  5927. }(ChildrenNode));
  5928. /**
  5929. * Marker that will sort higher than any other snapshot.
  5930. */
  5931. var MAX_NODE = new MaxNode();
  5932. Object.defineProperties(NamedNode, {
  5933. MIN: {
  5934. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5935. },
  5936. MAX: {
  5937. value: new NamedNode(MAX_NAME, MAX_NODE)
  5938. }
  5939. });
  5940. /**
  5941. * Reference Extensions
  5942. */
  5943. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5944. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5945. setMaxNode$1(MAX_NODE);
  5946. setMaxNode(MAX_NODE);
  5947. /**
  5948. * @license
  5949. * Copyright 2017 Google LLC
  5950. *
  5951. * Licensed under the Apache License, Version 2.0 (the "License");
  5952. * you may not use this file except in compliance with the License.
  5953. * You may obtain a copy of the License at
  5954. *
  5955. * http://www.apache.org/licenses/LICENSE-2.0
  5956. *
  5957. * Unless required by applicable law or agreed to in writing, software
  5958. * distributed under the License is distributed on an "AS IS" BASIS,
  5959. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5960. * See the License for the specific language governing permissions and
  5961. * limitations under the License.
  5962. */
  5963. var USE_HINZE = true;
  5964. /**
  5965. * Constructs a snapshot node representing the passed JSON and returns it.
  5966. * @param json - JSON to create a node for.
  5967. * @param priority - Optional priority to use. This will be ignored if the
  5968. * passed JSON contains a .priority property.
  5969. */
  5970. function nodeFromJSON(json, priority) {
  5971. if (priority === void 0) { priority = null; }
  5972. if (json === null) {
  5973. return ChildrenNode.EMPTY_NODE;
  5974. }
  5975. if (typeof json === 'object' && '.priority' in json) {
  5976. priority = json['.priority'];
  5977. }
  5978. util.assert(priority === null ||
  5979. typeof priority === 'string' ||
  5980. typeof priority === 'number' ||
  5981. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5982. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5983. json = json['.value'];
  5984. }
  5985. // Valid leaf nodes include non-objects or server-value wrapper objects
  5986. if (typeof json !== 'object' || '.sv' in json) {
  5987. var jsonLeaf = json;
  5988. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5989. }
  5990. if (!(json instanceof Array) && USE_HINZE) {
  5991. var children_1 = [];
  5992. var childrenHavePriority_1 = false;
  5993. var hinzeJsonObj = json;
  5994. each(hinzeJsonObj, function (key, child) {
  5995. if (key.substring(0, 1) !== '.') {
  5996. // Ignore metadata nodes
  5997. var childNode = nodeFromJSON(child);
  5998. if (!childNode.isEmpty()) {
  5999. childrenHavePriority_1 =
  6000. childrenHavePriority_1 || !childNode.getPriority().isEmpty();
  6001. children_1.push(new NamedNode(key, childNode));
  6002. }
  6003. }
  6004. });
  6005. if (children_1.length === 0) {
  6006. return ChildrenNode.EMPTY_NODE;
  6007. }
  6008. var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
  6009. if (childrenHavePriority_1) {
  6010. var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
  6011. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  6012. }
  6013. else {
  6014. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  6015. }
  6016. }
  6017. else {
  6018. var node_1 = ChildrenNode.EMPTY_NODE;
  6019. each(json, function (key, childData) {
  6020. if (util.contains(json, key)) {
  6021. if (key.substring(0, 1) !== '.') {
  6022. // ignore metadata nodes.
  6023. var childNode = nodeFromJSON(childData);
  6024. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  6025. node_1 = node_1.updateImmediateChild(key, childNode);
  6026. }
  6027. }
  6028. }
  6029. });
  6030. return node_1.updatePriority(nodeFromJSON(priority));
  6031. }
  6032. }
  6033. setNodeFromJSON(nodeFromJSON);
  6034. /**
  6035. * @license
  6036. * Copyright 2017 Google LLC
  6037. *
  6038. * Licensed under the Apache License, Version 2.0 (the "License");
  6039. * you may not use this file except in compliance with the License.
  6040. * You may obtain a copy of the License at
  6041. *
  6042. * http://www.apache.org/licenses/LICENSE-2.0
  6043. *
  6044. * Unless required by applicable law or agreed to in writing, software
  6045. * distributed under the License is distributed on an "AS IS" BASIS,
  6046. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6047. * See the License for the specific language governing permissions and
  6048. * limitations under the License.
  6049. */
  6050. var PathIndex = /** @class */ (function (_super) {
  6051. tslib.__extends(PathIndex, _super);
  6052. function PathIndex(indexPath_) {
  6053. var _this = _super.call(this) || this;
  6054. _this.indexPath_ = indexPath_;
  6055. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  6056. return _this;
  6057. }
  6058. PathIndex.prototype.extractChild = function (snap) {
  6059. return snap.getChild(this.indexPath_);
  6060. };
  6061. PathIndex.prototype.isDefinedOn = function (node) {
  6062. return !node.getChild(this.indexPath_).isEmpty();
  6063. };
  6064. PathIndex.prototype.compare = function (a, b) {
  6065. var aChild = this.extractChild(a.node);
  6066. var bChild = this.extractChild(b.node);
  6067. var indexCmp = aChild.compareTo(bChild);
  6068. if (indexCmp === 0) {
  6069. return nameCompare(a.name, b.name);
  6070. }
  6071. else {
  6072. return indexCmp;
  6073. }
  6074. };
  6075. PathIndex.prototype.makePost = function (indexValue, name) {
  6076. var valueNode = nodeFromJSON(indexValue);
  6077. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  6078. return new NamedNode(name, node);
  6079. };
  6080. PathIndex.prototype.maxPost = function () {
  6081. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  6082. return new NamedNode(MAX_NAME, node);
  6083. };
  6084. PathIndex.prototype.toString = function () {
  6085. return pathSlice(this.indexPath_, 0).join('/');
  6086. };
  6087. return PathIndex;
  6088. }(Index));
  6089. /**
  6090. * @license
  6091. * Copyright 2017 Google LLC
  6092. *
  6093. * Licensed under the Apache License, Version 2.0 (the "License");
  6094. * you may not use this file except in compliance with the License.
  6095. * You may obtain a copy of the License at
  6096. *
  6097. * http://www.apache.org/licenses/LICENSE-2.0
  6098. *
  6099. * Unless required by applicable law or agreed to in writing, software
  6100. * distributed under the License is distributed on an "AS IS" BASIS,
  6101. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6102. * See the License for the specific language governing permissions and
  6103. * limitations under the License.
  6104. */
  6105. var ValueIndex = /** @class */ (function (_super) {
  6106. tslib.__extends(ValueIndex, _super);
  6107. function ValueIndex() {
  6108. return _super !== null && _super.apply(this, arguments) || this;
  6109. }
  6110. ValueIndex.prototype.compare = function (a, b) {
  6111. var indexCmp = a.node.compareTo(b.node);
  6112. if (indexCmp === 0) {
  6113. return nameCompare(a.name, b.name);
  6114. }
  6115. else {
  6116. return indexCmp;
  6117. }
  6118. };
  6119. ValueIndex.prototype.isDefinedOn = function (node) {
  6120. return true;
  6121. };
  6122. ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  6123. return !oldNode.equals(newNode);
  6124. };
  6125. ValueIndex.prototype.minPost = function () {
  6126. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6127. return NamedNode.MIN;
  6128. };
  6129. ValueIndex.prototype.maxPost = function () {
  6130. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6131. return NamedNode.MAX;
  6132. };
  6133. ValueIndex.prototype.makePost = function (indexValue, name) {
  6134. var valueNode = nodeFromJSON(indexValue);
  6135. return new NamedNode(name, valueNode);
  6136. };
  6137. /**
  6138. * @returns String representation for inclusion in a query spec
  6139. */
  6140. ValueIndex.prototype.toString = function () {
  6141. return '.value';
  6142. };
  6143. return ValueIndex;
  6144. }(Index));
  6145. var VALUE_INDEX = new ValueIndex();
  6146. /**
  6147. * @license
  6148. * Copyright 2017 Google LLC
  6149. *
  6150. * Licensed under the Apache License, Version 2.0 (the "License");
  6151. * you may not use this file except in compliance with the License.
  6152. * You may obtain a copy of the License at
  6153. *
  6154. * http://www.apache.org/licenses/LICENSE-2.0
  6155. *
  6156. * Unless required by applicable law or agreed to in writing, software
  6157. * distributed under the License is distributed on an "AS IS" BASIS,
  6158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6159. * See the License for the specific language governing permissions and
  6160. * limitations under the License.
  6161. */
  6162. function changeValue(snapshotNode) {
  6163. return { type: "value" /* ChangeType.VALUE */, snapshotNode: snapshotNode };
  6164. }
  6165. function changeChildAdded(childName, snapshotNode) {
  6166. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode: snapshotNode, childName: childName };
  6167. }
  6168. function changeChildRemoved(childName, snapshotNode) {
  6169. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode: snapshotNode, childName: childName };
  6170. }
  6171. function changeChildChanged(childName, snapshotNode, oldSnap) {
  6172. return {
  6173. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  6174. snapshotNode: snapshotNode,
  6175. childName: childName,
  6176. oldSnap: oldSnap
  6177. };
  6178. }
  6179. function changeChildMoved(childName, snapshotNode) {
  6180. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode: snapshotNode, childName: childName };
  6181. }
  6182. /**
  6183. * @license
  6184. * Copyright 2017 Google LLC
  6185. *
  6186. * Licensed under the Apache License, Version 2.0 (the "License");
  6187. * you may not use this file except in compliance with the License.
  6188. * You may obtain a copy of the License at
  6189. *
  6190. * http://www.apache.org/licenses/LICENSE-2.0
  6191. *
  6192. * Unless required by applicable law or agreed to in writing, software
  6193. * distributed under the License is distributed on an "AS IS" BASIS,
  6194. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6195. * See the License for the specific language governing permissions and
  6196. * limitations under the License.
  6197. */
  6198. /**
  6199. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  6200. */
  6201. var IndexedFilter = /** @class */ (function () {
  6202. function IndexedFilter(index_) {
  6203. this.index_ = index_;
  6204. }
  6205. IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6206. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  6207. var oldChild = snap.getImmediateChild(key);
  6208. // Check if anything actually changed.
  6209. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  6210. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  6211. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  6212. // to avoid treating these cases as "nothing changed."
  6213. if (oldChild.isEmpty() === newChild.isEmpty()) {
  6214. // Nothing changed.
  6215. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  6216. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  6217. return snap;
  6218. }
  6219. }
  6220. if (optChangeAccumulator != null) {
  6221. if (newChild.isEmpty()) {
  6222. if (snap.hasChild(key)) {
  6223. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6224. }
  6225. else {
  6226. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6227. }
  6228. }
  6229. else if (oldChild.isEmpty()) {
  6230. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6231. }
  6232. else {
  6233. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6234. }
  6235. }
  6236. if (snap.isLeafNode() && newChild.isEmpty()) {
  6237. return snap;
  6238. }
  6239. else {
  6240. // Make sure the node is indexed
  6241. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6242. }
  6243. };
  6244. IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6245. if (optChangeAccumulator != null) {
  6246. if (!oldSnap.isLeafNode()) {
  6247. oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6248. if (!newSnap.hasChild(key)) {
  6249. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6250. }
  6251. });
  6252. }
  6253. if (!newSnap.isLeafNode()) {
  6254. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6255. if (oldSnap.hasChild(key)) {
  6256. var oldChild = oldSnap.getImmediateChild(key);
  6257. if (!oldChild.equals(childNode)) {
  6258. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6259. }
  6260. }
  6261. else {
  6262. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6263. }
  6264. });
  6265. }
  6266. }
  6267. return newSnap.withIndex(this.index_);
  6268. };
  6269. IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6270. if (oldSnap.isEmpty()) {
  6271. return ChildrenNode.EMPTY_NODE;
  6272. }
  6273. else {
  6274. return oldSnap.updatePriority(newPriority);
  6275. }
  6276. };
  6277. IndexedFilter.prototype.filtersNodes = function () {
  6278. return false;
  6279. };
  6280. IndexedFilter.prototype.getIndexedFilter = function () {
  6281. return this;
  6282. };
  6283. IndexedFilter.prototype.getIndex = function () {
  6284. return this.index_;
  6285. };
  6286. return IndexedFilter;
  6287. }());
  6288. /**
  6289. * @license
  6290. * Copyright 2017 Google LLC
  6291. *
  6292. * Licensed under the Apache License, Version 2.0 (the "License");
  6293. * you may not use this file except in compliance with the License.
  6294. * You may obtain a copy of the License at
  6295. *
  6296. * http://www.apache.org/licenses/LICENSE-2.0
  6297. *
  6298. * Unless required by applicable law or agreed to in writing, software
  6299. * distributed under the License is distributed on an "AS IS" BASIS,
  6300. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6301. * See the License for the specific language governing permissions and
  6302. * limitations under the License.
  6303. */
  6304. /**
  6305. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6306. */
  6307. var RangedFilter = /** @class */ (function () {
  6308. function RangedFilter(params) {
  6309. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6310. this.index_ = params.getIndex();
  6311. this.startPost_ = RangedFilter.getStartPost_(params);
  6312. this.endPost_ = RangedFilter.getEndPost_(params);
  6313. this.startIsInclusive_ = !params.startAfterSet_;
  6314. this.endIsInclusive_ = !params.endBeforeSet_;
  6315. }
  6316. RangedFilter.prototype.getStartPost = function () {
  6317. return this.startPost_;
  6318. };
  6319. RangedFilter.prototype.getEndPost = function () {
  6320. return this.endPost_;
  6321. };
  6322. RangedFilter.prototype.matches = function (node) {
  6323. var isWithinStart = this.startIsInclusive_
  6324. ? this.index_.compare(this.getStartPost(), node) <= 0
  6325. : this.index_.compare(this.getStartPost(), node) < 0;
  6326. var isWithinEnd = this.endIsInclusive_
  6327. ? this.index_.compare(node, this.getEndPost()) <= 0
  6328. : this.index_.compare(node, this.getEndPost()) < 0;
  6329. return isWithinStart && isWithinEnd;
  6330. };
  6331. RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6332. if (!this.matches(new NamedNode(key, newChild))) {
  6333. newChild = ChildrenNode.EMPTY_NODE;
  6334. }
  6335. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6336. };
  6337. RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6338. if (newSnap.isLeafNode()) {
  6339. // Make sure we have a children node with the correct index, not a leaf node;
  6340. newSnap = ChildrenNode.EMPTY_NODE;
  6341. }
  6342. var filtered = newSnap.withIndex(this.index_);
  6343. // Don't support priorities on queries
  6344. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6345. var self = this;
  6346. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6347. if (!self.matches(new NamedNode(key, childNode))) {
  6348. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6349. }
  6350. });
  6351. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6352. };
  6353. RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6354. // Don't support priorities on queries
  6355. return oldSnap;
  6356. };
  6357. RangedFilter.prototype.filtersNodes = function () {
  6358. return true;
  6359. };
  6360. RangedFilter.prototype.getIndexedFilter = function () {
  6361. return this.indexedFilter_;
  6362. };
  6363. RangedFilter.prototype.getIndex = function () {
  6364. return this.index_;
  6365. };
  6366. RangedFilter.getStartPost_ = function (params) {
  6367. if (params.hasStart()) {
  6368. var startName = params.getIndexStartName();
  6369. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6370. }
  6371. else {
  6372. return params.getIndex().minPost();
  6373. }
  6374. };
  6375. RangedFilter.getEndPost_ = function (params) {
  6376. if (params.hasEnd()) {
  6377. var endName = params.getIndexEndName();
  6378. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6379. }
  6380. else {
  6381. return params.getIndex().maxPost();
  6382. }
  6383. };
  6384. return RangedFilter;
  6385. }());
  6386. /**
  6387. * @license
  6388. * Copyright 2017 Google LLC
  6389. *
  6390. * Licensed under the Apache License, Version 2.0 (the "License");
  6391. * you may not use this file except in compliance with the License.
  6392. * You may obtain a copy of the License at
  6393. *
  6394. * http://www.apache.org/licenses/LICENSE-2.0
  6395. *
  6396. * Unless required by applicable law or agreed to in writing, software
  6397. * distributed under the License is distributed on an "AS IS" BASIS,
  6398. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6399. * See the License for the specific language governing permissions and
  6400. * limitations under the License.
  6401. */
  6402. /**
  6403. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6404. */
  6405. var LimitedFilter = /** @class */ (function () {
  6406. function LimitedFilter(params) {
  6407. var _this = this;
  6408. this.withinDirectionalStart = function (node) {
  6409. return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
  6410. };
  6411. this.withinDirectionalEnd = function (node) {
  6412. return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
  6413. };
  6414. this.withinStartPost = function (node) {
  6415. var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
  6416. return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6417. };
  6418. this.withinEndPost = function (node) {
  6419. var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
  6420. return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6421. };
  6422. this.rangedFilter_ = new RangedFilter(params);
  6423. this.index_ = params.getIndex();
  6424. this.limit_ = params.getLimit();
  6425. this.reverse_ = !params.isViewFromLeft();
  6426. this.startIsInclusive_ = !params.startAfterSet_;
  6427. this.endIsInclusive_ = !params.endBeforeSet_;
  6428. }
  6429. LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6430. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6431. newChild = ChildrenNode.EMPTY_NODE;
  6432. }
  6433. if (snap.getImmediateChild(key).equals(newChild)) {
  6434. // No change
  6435. return snap;
  6436. }
  6437. else if (snap.numChildren() < this.limit_) {
  6438. return this.rangedFilter_
  6439. .getIndexedFilter()
  6440. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6441. }
  6442. else {
  6443. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6444. }
  6445. };
  6446. LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6447. var filtered;
  6448. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6449. // Make sure we have a children node with the correct index, not a leaf node;
  6450. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6451. }
  6452. else {
  6453. if (this.limit_ * 2 < newSnap.numChildren() &&
  6454. newSnap.isIndexed(this.index_)) {
  6455. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6456. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6457. // anchor to the startPost, endPost, or last element as appropriate
  6458. var iterator = void 0;
  6459. if (this.reverse_) {
  6460. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6461. }
  6462. else {
  6463. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6464. }
  6465. var count = 0;
  6466. while (iterator.hasNext() && count < this.limit_) {
  6467. var next = iterator.getNext();
  6468. if (!this.withinDirectionalStart(next)) {
  6469. // if we have not reached the start, skip to the next element
  6470. continue;
  6471. }
  6472. else if (!this.withinDirectionalEnd(next)) {
  6473. // if we have reached the end, stop adding elements
  6474. break;
  6475. }
  6476. else {
  6477. filtered = filtered.updateImmediateChild(next.name, next.node);
  6478. count++;
  6479. }
  6480. }
  6481. }
  6482. else {
  6483. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6484. filtered = newSnap.withIndex(this.index_);
  6485. // Don't support priorities on queries
  6486. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6487. var iterator = void 0;
  6488. if (this.reverse_) {
  6489. iterator = filtered.getReverseIterator(this.index_);
  6490. }
  6491. else {
  6492. iterator = filtered.getIterator(this.index_);
  6493. }
  6494. var count = 0;
  6495. while (iterator.hasNext()) {
  6496. var next = iterator.getNext();
  6497. var inRange = count < this.limit_ &&
  6498. this.withinDirectionalStart(next) &&
  6499. this.withinDirectionalEnd(next);
  6500. if (inRange) {
  6501. count++;
  6502. }
  6503. else {
  6504. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6505. }
  6506. }
  6507. }
  6508. }
  6509. return this.rangedFilter_
  6510. .getIndexedFilter()
  6511. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6512. };
  6513. LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6514. // Don't support priorities on queries
  6515. return oldSnap;
  6516. };
  6517. LimitedFilter.prototype.filtersNodes = function () {
  6518. return true;
  6519. };
  6520. LimitedFilter.prototype.getIndexedFilter = function () {
  6521. return this.rangedFilter_.getIndexedFilter();
  6522. };
  6523. LimitedFilter.prototype.getIndex = function () {
  6524. return this.index_;
  6525. };
  6526. LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
  6527. // TODO: rename all cache stuff etc to general snap terminology
  6528. var cmp;
  6529. if (this.reverse_) {
  6530. var indexCmp_1 = this.index_.getCompare();
  6531. cmp = function (a, b) { return indexCmp_1(b, a); };
  6532. }
  6533. else {
  6534. cmp = this.index_.getCompare();
  6535. }
  6536. var oldEventCache = snap;
  6537. util.assert(oldEventCache.numChildren() === this.limit_, '');
  6538. var newChildNamedNode = new NamedNode(childKey, childSnap);
  6539. var windowBoundary = this.reverse_
  6540. ? oldEventCache.getFirstChild(this.index_)
  6541. : oldEventCache.getLastChild(this.index_);
  6542. var inRange = this.rangedFilter_.matches(newChildNamedNode);
  6543. if (oldEventCache.hasChild(childKey)) {
  6544. var oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6545. var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6546. while (nextChild != null &&
  6547. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6548. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6549. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6550. // the limited filter...
  6551. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6552. }
  6553. var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6554. var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6555. if (remainsInWindow) {
  6556. if (changeAccumulator != null) {
  6557. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6558. }
  6559. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6560. }
  6561. else {
  6562. if (changeAccumulator != null) {
  6563. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6564. }
  6565. var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6566. var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6567. if (nextChildInRange) {
  6568. if (changeAccumulator != null) {
  6569. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6570. }
  6571. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6572. }
  6573. else {
  6574. return newEventCache;
  6575. }
  6576. }
  6577. }
  6578. else if (childSnap.isEmpty()) {
  6579. // we're deleting a node, but it was not in the window, so ignore it
  6580. return snap;
  6581. }
  6582. else if (inRange) {
  6583. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6584. if (changeAccumulator != null) {
  6585. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6586. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6587. }
  6588. return oldEventCache
  6589. .updateImmediateChild(childKey, childSnap)
  6590. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6591. }
  6592. else {
  6593. return snap;
  6594. }
  6595. }
  6596. else {
  6597. return snap;
  6598. }
  6599. };
  6600. return LimitedFilter;
  6601. }());
  6602. /**
  6603. * @license
  6604. * Copyright 2017 Google LLC
  6605. *
  6606. * Licensed under the Apache License, Version 2.0 (the "License");
  6607. * you may not use this file except in compliance with the License.
  6608. * You may obtain a copy of the License at
  6609. *
  6610. * http://www.apache.org/licenses/LICENSE-2.0
  6611. *
  6612. * Unless required by applicable law or agreed to in writing, software
  6613. * distributed under the License is distributed on an "AS IS" BASIS,
  6614. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6615. * See the License for the specific language governing permissions and
  6616. * limitations under the License.
  6617. */
  6618. /**
  6619. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6620. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6621. * user-facing API level, so it is not done here.
  6622. *
  6623. * @internal
  6624. */
  6625. var QueryParams = /** @class */ (function () {
  6626. function QueryParams() {
  6627. this.limitSet_ = false;
  6628. this.startSet_ = false;
  6629. this.startNameSet_ = false;
  6630. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6631. this.endSet_ = false;
  6632. this.endNameSet_ = false;
  6633. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6634. this.limit_ = 0;
  6635. this.viewFrom_ = '';
  6636. this.indexStartValue_ = null;
  6637. this.indexStartName_ = '';
  6638. this.indexEndValue_ = null;
  6639. this.indexEndName_ = '';
  6640. this.index_ = PRIORITY_INDEX;
  6641. }
  6642. QueryParams.prototype.hasStart = function () {
  6643. return this.startSet_;
  6644. };
  6645. /**
  6646. * @returns True if it would return from left.
  6647. */
  6648. QueryParams.prototype.isViewFromLeft = function () {
  6649. if (this.viewFrom_ === '') {
  6650. // limit(), rather than limitToFirst or limitToLast was called.
  6651. // This means that only one of startSet_ and endSet_ is true. Use them
  6652. // to calculate which side of the view to anchor to. If neither is set,
  6653. // anchor to the end.
  6654. return this.startSet_;
  6655. }
  6656. else {
  6657. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6658. }
  6659. };
  6660. /**
  6661. * Only valid to call if hasStart() returns true
  6662. */
  6663. QueryParams.prototype.getIndexStartValue = function () {
  6664. util.assert(this.startSet_, 'Only valid if start has been set');
  6665. return this.indexStartValue_;
  6666. };
  6667. /**
  6668. * Only valid to call if hasStart() returns true.
  6669. * Returns the starting key name for the range defined by these query parameters
  6670. */
  6671. QueryParams.prototype.getIndexStartName = function () {
  6672. util.assert(this.startSet_, 'Only valid if start has been set');
  6673. if (this.startNameSet_) {
  6674. return this.indexStartName_;
  6675. }
  6676. else {
  6677. return MIN_NAME;
  6678. }
  6679. };
  6680. QueryParams.prototype.hasEnd = function () {
  6681. return this.endSet_;
  6682. };
  6683. /**
  6684. * Only valid to call if hasEnd() returns true.
  6685. */
  6686. QueryParams.prototype.getIndexEndValue = function () {
  6687. util.assert(this.endSet_, 'Only valid if end has been set');
  6688. return this.indexEndValue_;
  6689. };
  6690. /**
  6691. * Only valid to call if hasEnd() returns true.
  6692. * Returns the end key name for the range defined by these query parameters
  6693. */
  6694. QueryParams.prototype.getIndexEndName = function () {
  6695. util.assert(this.endSet_, 'Only valid if end has been set');
  6696. if (this.endNameSet_) {
  6697. return this.indexEndName_;
  6698. }
  6699. else {
  6700. return MAX_NAME;
  6701. }
  6702. };
  6703. QueryParams.prototype.hasLimit = function () {
  6704. return this.limitSet_;
  6705. };
  6706. /**
  6707. * @returns True if a limit has been set and it has been explicitly anchored
  6708. */
  6709. QueryParams.prototype.hasAnchoredLimit = function () {
  6710. return this.limitSet_ && this.viewFrom_ !== '';
  6711. };
  6712. /**
  6713. * Only valid to call if hasLimit() returns true
  6714. */
  6715. QueryParams.prototype.getLimit = function () {
  6716. util.assert(this.limitSet_, 'Only valid if limit has been set');
  6717. return this.limit_;
  6718. };
  6719. QueryParams.prototype.getIndex = function () {
  6720. return this.index_;
  6721. };
  6722. QueryParams.prototype.loadsAllData = function () {
  6723. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6724. };
  6725. QueryParams.prototype.isDefault = function () {
  6726. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6727. };
  6728. QueryParams.prototype.copy = function () {
  6729. var copy = new QueryParams();
  6730. copy.limitSet_ = this.limitSet_;
  6731. copy.limit_ = this.limit_;
  6732. copy.startSet_ = this.startSet_;
  6733. copy.startAfterSet_ = this.startAfterSet_;
  6734. copy.indexStartValue_ = this.indexStartValue_;
  6735. copy.startNameSet_ = this.startNameSet_;
  6736. copy.indexStartName_ = this.indexStartName_;
  6737. copy.endSet_ = this.endSet_;
  6738. copy.endBeforeSet_ = this.endBeforeSet_;
  6739. copy.indexEndValue_ = this.indexEndValue_;
  6740. copy.endNameSet_ = this.endNameSet_;
  6741. copy.indexEndName_ = this.indexEndName_;
  6742. copy.index_ = this.index_;
  6743. copy.viewFrom_ = this.viewFrom_;
  6744. return copy;
  6745. };
  6746. return QueryParams;
  6747. }());
  6748. function queryParamsGetNodeFilter(queryParams) {
  6749. if (queryParams.loadsAllData()) {
  6750. return new IndexedFilter(queryParams.getIndex());
  6751. }
  6752. else if (queryParams.hasLimit()) {
  6753. return new LimitedFilter(queryParams);
  6754. }
  6755. else {
  6756. return new RangedFilter(queryParams);
  6757. }
  6758. }
  6759. function queryParamsLimitToFirst(queryParams, newLimit) {
  6760. var newParams = queryParams.copy();
  6761. newParams.limitSet_ = true;
  6762. newParams.limit_ = newLimit;
  6763. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6764. return newParams;
  6765. }
  6766. function queryParamsLimitToLast(queryParams, newLimit) {
  6767. var newParams = queryParams.copy();
  6768. newParams.limitSet_ = true;
  6769. newParams.limit_ = newLimit;
  6770. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6771. return newParams;
  6772. }
  6773. function queryParamsStartAt(queryParams, indexValue, key) {
  6774. var newParams = queryParams.copy();
  6775. newParams.startSet_ = true;
  6776. if (indexValue === undefined) {
  6777. indexValue = null;
  6778. }
  6779. newParams.indexStartValue_ = indexValue;
  6780. if (key != null) {
  6781. newParams.startNameSet_ = true;
  6782. newParams.indexStartName_ = key;
  6783. }
  6784. else {
  6785. newParams.startNameSet_ = false;
  6786. newParams.indexStartName_ = '';
  6787. }
  6788. return newParams;
  6789. }
  6790. function queryParamsStartAfter(queryParams, indexValue, key) {
  6791. var params;
  6792. if (queryParams.index_ === KEY_INDEX || !!key) {
  6793. params = queryParamsStartAt(queryParams, indexValue, key);
  6794. }
  6795. else {
  6796. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6797. }
  6798. params.startAfterSet_ = true;
  6799. return params;
  6800. }
  6801. function queryParamsEndAt(queryParams, indexValue, key) {
  6802. var newParams = queryParams.copy();
  6803. newParams.endSet_ = true;
  6804. if (indexValue === undefined) {
  6805. indexValue = null;
  6806. }
  6807. newParams.indexEndValue_ = indexValue;
  6808. if (key !== undefined) {
  6809. newParams.endNameSet_ = true;
  6810. newParams.indexEndName_ = key;
  6811. }
  6812. else {
  6813. newParams.endNameSet_ = false;
  6814. newParams.indexEndName_ = '';
  6815. }
  6816. return newParams;
  6817. }
  6818. function queryParamsEndBefore(queryParams, indexValue, key) {
  6819. var params;
  6820. if (queryParams.index_ === KEY_INDEX || !!key) {
  6821. params = queryParamsEndAt(queryParams, indexValue, key);
  6822. }
  6823. else {
  6824. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6825. }
  6826. params.endBeforeSet_ = true;
  6827. return params;
  6828. }
  6829. function queryParamsOrderBy(queryParams, index) {
  6830. var newParams = queryParams.copy();
  6831. newParams.index_ = index;
  6832. return newParams;
  6833. }
  6834. /**
  6835. * Returns a set of REST query string parameters representing this query.
  6836. *
  6837. * @returns query string parameters
  6838. */
  6839. function queryParamsToRestQueryStringParameters(queryParams) {
  6840. var qs = {};
  6841. if (queryParams.isDefault()) {
  6842. return qs;
  6843. }
  6844. var orderBy;
  6845. if (queryParams.index_ === PRIORITY_INDEX) {
  6846. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6847. }
  6848. else if (queryParams.index_ === VALUE_INDEX) {
  6849. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6850. }
  6851. else if (queryParams.index_ === KEY_INDEX) {
  6852. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6853. }
  6854. else {
  6855. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6856. orderBy = queryParams.index_.toString();
  6857. }
  6858. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  6859. if (queryParams.startSet_) {
  6860. var startParam = queryParams.startAfterSet_
  6861. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6862. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6863. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  6864. if (queryParams.startNameSet_) {
  6865. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  6866. }
  6867. }
  6868. if (queryParams.endSet_) {
  6869. var endParam = queryParams.endBeforeSet_
  6870. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6871. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6872. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  6873. if (queryParams.endNameSet_) {
  6874. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  6875. }
  6876. }
  6877. if (queryParams.limitSet_) {
  6878. if (queryParams.isViewFromLeft()) {
  6879. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6880. }
  6881. else {
  6882. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6883. }
  6884. }
  6885. return qs;
  6886. }
  6887. function queryParamsGetQueryObject(queryParams) {
  6888. var obj = {};
  6889. if (queryParams.startSet_) {
  6890. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6891. queryParams.indexStartValue_;
  6892. if (queryParams.startNameSet_) {
  6893. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6894. queryParams.indexStartName_;
  6895. }
  6896. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6897. !queryParams.startAfterSet_;
  6898. }
  6899. if (queryParams.endSet_) {
  6900. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6901. if (queryParams.endNameSet_) {
  6902. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6903. }
  6904. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6905. !queryParams.endBeforeSet_;
  6906. }
  6907. if (queryParams.limitSet_) {
  6908. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6909. var viewFrom = queryParams.viewFrom_;
  6910. if (viewFrom === '') {
  6911. if (queryParams.isViewFromLeft()) {
  6912. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6913. }
  6914. else {
  6915. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6916. }
  6917. }
  6918. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6919. }
  6920. // For now, priority index is the default, so we only specify if it's some other index
  6921. if (queryParams.index_ !== PRIORITY_INDEX) {
  6922. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6923. }
  6924. return obj;
  6925. }
  6926. /**
  6927. * @license
  6928. * Copyright 2017 Google LLC
  6929. *
  6930. * Licensed under the Apache License, Version 2.0 (the "License");
  6931. * you may not use this file except in compliance with the License.
  6932. * You may obtain a copy of the License at
  6933. *
  6934. * http://www.apache.org/licenses/LICENSE-2.0
  6935. *
  6936. * Unless required by applicable law or agreed to in writing, software
  6937. * distributed under the License is distributed on an "AS IS" BASIS,
  6938. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6939. * See the License for the specific language governing permissions and
  6940. * limitations under the License.
  6941. */
  6942. /**
  6943. * An implementation of ServerActions that communicates with the server via REST requests.
  6944. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6945. * persistent connection (using WebSockets or long-polling)
  6946. */
  6947. var ReadonlyRestClient = /** @class */ (function (_super) {
  6948. tslib.__extends(ReadonlyRestClient, _super);
  6949. /**
  6950. * @param repoInfo_ - Data about the namespace we are connecting to
  6951. * @param onDataUpdate_ - A callback for new data from the server
  6952. */
  6953. function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6954. var _this = _super.call(this) || this;
  6955. _this.repoInfo_ = repoInfo_;
  6956. _this.onDataUpdate_ = onDataUpdate_;
  6957. _this.authTokenProvider_ = authTokenProvider_;
  6958. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6959. /** @private {function(...[*])} */
  6960. _this.log_ = logWrapper('p:rest:');
  6961. /**
  6962. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6963. * that's been removed. :-/
  6964. */
  6965. _this.listens_ = {};
  6966. return _this;
  6967. }
  6968. ReadonlyRestClient.prototype.reportStats = function (stats) {
  6969. throw new Error('Method not implemented.');
  6970. };
  6971. ReadonlyRestClient.getListenId_ = function (query, tag) {
  6972. if (tag !== undefined) {
  6973. return 'tag$' + tag;
  6974. }
  6975. else {
  6976. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6977. return query._path.toString();
  6978. }
  6979. };
  6980. /** @inheritDoc */
  6981. ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  6982. var _this = this;
  6983. var pathString = query._path.toString();
  6984. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6985. // Mark this listener so we can tell if it's removed.
  6986. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  6987. var thisListen = {};
  6988. this.listens_[listenId] = thisListen;
  6989. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6990. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  6991. var data = result;
  6992. if (error === 404) {
  6993. data = null;
  6994. error = null;
  6995. }
  6996. if (error === null) {
  6997. _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6998. }
  6999. if (util.safeGet(_this.listens_, listenId) === thisListen) {
  7000. var status_1;
  7001. if (!error) {
  7002. status_1 = 'ok';
  7003. }
  7004. else if (error === 401) {
  7005. status_1 = 'permission_denied';
  7006. }
  7007. else {
  7008. status_1 = 'rest_error:' + error;
  7009. }
  7010. onComplete(status_1, null);
  7011. }
  7012. });
  7013. };
  7014. /** @inheritDoc */
  7015. ReadonlyRestClient.prototype.unlisten = function (query, tag) {
  7016. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  7017. delete this.listens_[listenId];
  7018. };
  7019. ReadonlyRestClient.prototype.get = function (query) {
  7020. var _this = this;
  7021. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  7022. var pathString = query._path.toString();
  7023. var deferred = new util.Deferred();
  7024. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  7025. var data = result;
  7026. if (error === 404) {
  7027. data = null;
  7028. error = null;
  7029. }
  7030. if (error === null) {
  7031. _this.onDataUpdate_(pathString, data,
  7032. /*isMerge=*/ false,
  7033. /*tag=*/ null);
  7034. deferred.resolve(data);
  7035. }
  7036. else {
  7037. deferred.reject(new Error(data));
  7038. }
  7039. });
  7040. return deferred.promise;
  7041. };
  7042. /** @inheritDoc */
  7043. ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
  7044. // no-op since we just always call getToken.
  7045. };
  7046. /**
  7047. * Performs a REST request to the given path, with the provided query string parameters,
  7048. * and any auth credentials we have.
  7049. */
  7050. ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
  7051. var _this = this;
  7052. if (queryStringParameters === void 0) { queryStringParameters = {}; }
  7053. queryStringParameters['format'] = 'export';
  7054. return Promise.all([
  7055. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  7056. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  7057. ]).then(function (_a) {
  7058. var _b = tslib.__read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
  7059. if (authToken && authToken.accessToken) {
  7060. queryStringParameters['auth'] = authToken.accessToken;
  7061. }
  7062. if (appCheckToken && appCheckToken.token) {
  7063. queryStringParameters['ac'] = appCheckToken.token;
  7064. }
  7065. var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
  7066. _this.repoInfo_.host +
  7067. pathString +
  7068. '?' +
  7069. 'ns=' +
  7070. _this.repoInfo_.namespace +
  7071. util.querystring(queryStringParameters);
  7072. _this.log_('Sending REST request for ' + url);
  7073. var xhr = new XMLHttpRequest();
  7074. xhr.onreadystatechange = function () {
  7075. if (callback && xhr.readyState === 4) {
  7076. _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  7077. var res = null;
  7078. if (xhr.status >= 200 && xhr.status < 300) {
  7079. try {
  7080. res = util.jsonEval(xhr.responseText);
  7081. }
  7082. catch (e) {
  7083. warn('Failed to parse JSON response for ' +
  7084. url +
  7085. ': ' +
  7086. xhr.responseText);
  7087. }
  7088. callback(null, res);
  7089. }
  7090. else {
  7091. // 401 and 404 are expected.
  7092. if (xhr.status !== 401 && xhr.status !== 404) {
  7093. warn('Got unsuccessful REST response for ' +
  7094. url +
  7095. ' Status: ' +
  7096. xhr.status);
  7097. }
  7098. callback(xhr.status);
  7099. }
  7100. callback = null;
  7101. }
  7102. };
  7103. xhr.open('GET', url, /*asynchronous=*/ true);
  7104. xhr.send();
  7105. });
  7106. };
  7107. return ReadonlyRestClient;
  7108. }(ServerActions));
  7109. /**
  7110. * @license
  7111. * Copyright 2017 Google LLC
  7112. *
  7113. * Licensed under the Apache License, Version 2.0 (the "License");
  7114. * you may not use this file except in compliance with the License.
  7115. * You may obtain a copy of the License at
  7116. *
  7117. * http://www.apache.org/licenses/LICENSE-2.0
  7118. *
  7119. * Unless required by applicable law or agreed to in writing, software
  7120. * distributed under the License is distributed on an "AS IS" BASIS,
  7121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7122. * See the License for the specific language governing permissions and
  7123. * limitations under the License.
  7124. */
  7125. /**
  7126. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  7127. */
  7128. var SnapshotHolder = /** @class */ (function () {
  7129. function SnapshotHolder() {
  7130. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  7131. }
  7132. SnapshotHolder.prototype.getNode = function (path) {
  7133. return this.rootNode_.getChild(path);
  7134. };
  7135. SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
  7136. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  7137. };
  7138. return SnapshotHolder;
  7139. }());
  7140. /**
  7141. * @license
  7142. * Copyright 2017 Google LLC
  7143. *
  7144. * Licensed under the Apache License, Version 2.0 (the "License");
  7145. * you may not use this file except in compliance with the License.
  7146. * You may obtain a copy of the License at
  7147. *
  7148. * http://www.apache.org/licenses/LICENSE-2.0
  7149. *
  7150. * Unless required by applicable law or agreed to in writing, software
  7151. * distributed under the License is distributed on an "AS IS" BASIS,
  7152. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7153. * See the License for the specific language governing permissions and
  7154. * limitations under the License.
  7155. */
  7156. function newSparseSnapshotTree() {
  7157. return {
  7158. value: null,
  7159. children: new Map()
  7160. };
  7161. }
  7162. /**
  7163. * Stores the given node at the specified path. If there is already a node
  7164. * at a shallower path, it merges the new data into that snapshot node.
  7165. *
  7166. * @param path - Path to look up snapshot for.
  7167. * @param data - The new data, or null.
  7168. */
  7169. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  7170. if (pathIsEmpty(path)) {
  7171. sparseSnapshotTree.value = data;
  7172. sparseSnapshotTree.children.clear();
  7173. }
  7174. else if (sparseSnapshotTree.value !== null) {
  7175. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  7176. }
  7177. else {
  7178. var childKey = pathGetFront(path);
  7179. if (!sparseSnapshotTree.children.has(childKey)) {
  7180. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  7181. }
  7182. var child = sparseSnapshotTree.children.get(childKey);
  7183. path = pathPopFront(path);
  7184. sparseSnapshotTreeRemember(child, path, data);
  7185. }
  7186. }
  7187. /**
  7188. * Purge the data at path from the cache.
  7189. *
  7190. * @param path - Path to look up snapshot for.
  7191. * @returns True if this node should now be removed.
  7192. */
  7193. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  7194. if (pathIsEmpty(path)) {
  7195. sparseSnapshotTree.value = null;
  7196. sparseSnapshotTree.children.clear();
  7197. return true;
  7198. }
  7199. else {
  7200. if (sparseSnapshotTree.value !== null) {
  7201. if (sparseSnapshotTree.value.isLeafNode()) {
  7202. // We're trying to forget a node that doesn't exist
  7203. return false;
  7204. }
  7205. else {
  7206. var value = sparseSnapshotTree.value;
  7207. sparseSnapshotTree.value = null;
  7208. value.forEachChild(PRIORITY_INDEX, function (key, tree) {
  7209. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  7210. });
  7211. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  7212. }
  7213. }
  7214. else if (sparseSnapshotTree.children.size > 0) {
  7215. var childKey = pathGetFront(path);
  7216. path = pathPopFront(path);
  7217. if (sparseSnapshotTree.children.has(childKey)) {
  7218. var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  7219. if (safeToRemove) {
  7220. sparseSnapshotTree.children.delete(childKey);
  7221. }
  7222. }
  7223. return sparseSnapshotTree.children.size === 0;
  7224. }
  7225. else {
  7226. return true;
  7227. }
  7228. }
  7229. }
  7230. /**
  7231. * Recursively iterates through all of the stored tree and calls the
  7232. * callback on each one.
  7233. *
  7234. * @param prefixPath - Path to look up node for.
  7235. * @param func - The function to invoke for each tree.
  7236. */
  7237. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7238. if (sparseSnapshotTree.value !== null) {
  7239. func(prefixPath, sparseSnapshotTree.value);
  7240. }
  7241. else {
  7242. sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
  7243. var path = new Path(prefixPath.toString() + '/' + key);
  7244. sparseSnapshotTreeForEachTree(tree, path, func);
  7245. });
  7246. }
  7247. }
  7248. /**
  7249. * Iterates through each immediate child and triggers the callback.
  7250. * Only seems to be used in tests.
  7251. *
  7252. * @param func - The function to invoke for each child.
  7253. */
  7254. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7255. sparseSnapshotTree.children.forEach(function (tree, key) {
  7256. func(key, tree);
  7257. });
  7258. }
  7259. /**
  7260. * @license
  7261. * Copyright 2017 Google LLC
  7262. *
  7263. * Licensed under the Apache License, Version 2.0 (the "License");
  7264. * you may not use this file except in compliance with the License.
  7265. * You may obtain a copy of the License at
  7266. *
  7267. * http://www.apache.org/licenses/LICENSE-2.0
  7268. *
  7269. * Unless required by applicable law or agreed to in writing, software
  7270. * distributed under the License is distributed on an "AS IS" BASIS,
  7271. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7272. * See the License for the specific language governing permissions and
  7273. * limitations under the License.
  7274. */
  7275. /**
  7276. * Returns the delta from the previous call to get stats.
  7277. *
  7278. * @param collection_ - The collection to "listen" to.
  7279. */
  7280. var StatsListener = /** @class */ (function () {
  7281. function StatsListener(collection_) {
  7282. this.collection_ = collection_;
  7283. this.last_ = null;
  7284. }
  7285. StatsListener.prototype.get = function () {
  7286. var newStats = this.collection_.get();
  7287. var delta = tslib.__assign({}, newStats);
  7288. if (this.last_) {
  7289. each(this.last_, function (stat, value) {
  7290. delta[stat] = delta[stat] - value;
  7291. });
  7292. }
  7293. this.last_ = newStats;
  7294. return delta;
  7295. };
  7296. return StatsListener;
  7297. }());
  7298. /**
  7299. * @license
  7300. * Copyright 2017 Google LLC
  7301. *
  7302. * Licensed under the Apache License, Version 2.0 (the "License");
  7303. * you may not use this file except in compliance with the License.
  7304. * You may obtain a copy of the License at
  7305. *
  7306. * http://www.apache.org/licenses/LICENSE-2.0
  7307. *
  7308. * Unless required by applicable law or agreed to in writing, software
  7309. * distributed under the License is distributed on an "AS IS" BASIS,
  7310. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7311. * See the License for the specific language governing permissions and
  7312. * limitations under the License.
  7313. */
  7314. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7315. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7316. // seconds to try to ensure the Firebase connection is established / settled.
  7317. var FIRST_STATS_MIN_TIME = 10 * 1000;
  7318. var FIRST_STATS_MAX_TIME = 30 * 1000;
  7319. // We'll continue to report stats on average every 5 minutes.
  7320. var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7321. var StatsReporter = /** @class */ (function () {
  7322. function StatsReporter(collection, server_) {
  7323. this.server_ = server_;
  7324. this.statsToReport_ = {};
  7325. this.statsListener_ = new StatsListener(collection);
  7326. var timeout = FIRST_STATS_MIN_TIME +
  7327. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7328. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7329. }
  7330. StatsReporter.prototype.reportStats_ = function () {
  7331. var _this = this;
  7332. var stats = this.statsListener_.get();
  7333. var reportedStats = {};
  7334. var haveStatsToReport = false;
  7335. each(stats, function (stat, value) {
  7336. if (value > 0 && util.contains(_this.statsToReport_, stat)) {
  7337. reportedStats[stat] = value;
  7338. haveStatsToReport = true;
  7339. }
  7340. });
  7341. if (haveStatsToReport) {
  7342. this.server_.reportStats(reportedStats);
  7343. }
  7344. // queue our next run.
  7345. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7346. };
  7347. return StatsReporter;
  7348. }());
  7349. /**
  7350. * @license
  7351. * Copyright 2017 Google LLC
  7352. *
  7353. * Licensed under the Apache License, Version 2.0 (the "License");
  7354. * you may not use this file except in compliance with the License.
  7355. * You may obtain a copy of the License at
  7356. *
  7357. * http://www.apache.org/licenses/LICENSE-2.0
  7358. *
  7359. * Unless required by applicable law or agreed to in writing, software
  7360. * distributed under the License is distributed on an "AS IS" BASIS,
  7361. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7362. * See the License for the specific language governing permissions and
  7363. * limitations under the License.
  7364. */
  7365. /**
  7366. *
  7367. * @enum
  7368. */
  7369. var OperationType;
  7370. (function (OperationType) {
  7371. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7372. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7373. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7374. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7375. })(OperationType || (OperationType = {}));
  7376. function newOperationSourceUser() {
  7377. return {
  7378. fromUser: true,
  7379. fromServer: false,
  7380. queryId: null,
  7381. tagged: false
  7382. };
  7383. }
  7384. function newOperationSourceServer() {
  7385. return {
  7386. fromUser: false,
  7387. fromServer: true,
  7388. queryId: null,
  7389. tagged: false
  7390. };
  7391. }
  7392. function newOperationSourceServerTaggedQuery(queryId) {
  7393. return {
  7394. fromUser: false,
  7395. fromServer: true,
  7396. queryId: queryId,
  7397. tagged: true
  7398. };
  7399. }
  7400. /**
  7401. * @license
  7402. * Copyright 2017 Google LLC
  7403. *
  7404. * Licensed under the Apache License, Version 2.0 (the "License");
  7405. * you may not use this file except in compliance with the License.
  7406. * You may obtain a copy of the License at
  7407. *
  7408. * http://www.apache.org/licenses/LICENSE-2.0
  7409. *
  7410. * Unless required by applicable law or agreed to in writing, software
  7411. * distributed under the License is distributed on an "AS IS" BASIS,
  7412. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7413. * See the License for the specific language governing permissions and
  7414. * limitations under the License.
  7415. */
  7416. var AckUserWrite = /** @class */ (function () {
  7417. /**
  7418. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7419. */
  7420. function AckUserWrite(
  7421. /** @inheritDoc */ path,
  7422. /** @inheritDoc */ affectedTree,
  7423. /** @inheritDoc */ revert) {
  7424. this.path = path;
  7425. this.affectedTree = affectedTree;
  7426. this.revert = revert;
  7427. /** @inheritDoc */
  7428. this.type = OperationType.ACK_USER_WRITE;
  7429. /** @inheritDoc */
  7430. this.source = newOperationSourceUser();
  7431. }
  7432. AckUserWrite.prototype.operationForChild = function (childName) {
  7433. if (!pathIsEmpty(this.path)) {
  7434. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7435. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7436. }
  7437. else if (this.affectedTree.value != null) {
  7438. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7439. // All child locations are affected as well; just return same operation.
  7440. return this;
  7441. }
  7442. else {
  7443. var childTree = this.affectedTree.subtree(new Path(childName));
  7444. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7445. }
  7446. };
  7447. return AckUserWrite;
  7448. }());
  7449. /**
  7450. * @license
  7451. * Copyright 2017 Google LLC
  7452. *
  7453. * Licensed under the Apache License, Version 2.0 (the "License");
  7454. * you may not use this file except in compliance with the License.
  7455. * You may obtain a copy of the License at
  7456. *
  7457. * http://www.apache.org/licenses/LICENSE-2.0
  7458. *
  7459. * Unless required by applicable law or agreed to in writing, software
  7460. * distributed under the License is distributed on an "AS IS" BASIS,
  7461. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7462. * See the License for the specific language governing permissions and
  7463. * limitations under the License.
  7464. */
  7465. var ListenComplete = /** @class */ (function () {
  7466. function ListenComplete(source, path) {
  7467. this.source = source;
  7468. this.path = path;
  7469. /** @inheritDoc */
  7470. this.type = OperationType.LISTEN_COMPLETE;
  7471. }
  7472. ListenComplete.prototype.operationForChild = function (childName) {
  7473. if (pathIsEmpty(this.path)) {
  7474. return new ListenComplete(this.source, newEmptyPath());
  7475. }
  7476. else {
  7477. return new ListenComplete(this.source, pathPopFront(this.path));
  7478. }
  7479. };
  7480. return ListenComplete;
  7481. }());
  7482. /**
  7483. * @license
  7484. * Copyright 2017 Google LLC
  7485. *
  7486. * Licensed under the Apache License, Version 2.0 (the "License");
  7487. * you may not use this file except in compliance with the License.
  7488. * You may obtain a copy of the License at
  7489. *
  7490. * http://www.apache.org/licenses/LICENSE-2.0
  7491. *
  7492. * Unless required by applicable law or agreed to in writing, software
  7493. * distributed under the License is distributed on an "AS IS" BASIS,
  7494. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7495. * See the License for the specific language governing permissions and
  7496. * limitations under the License.
  7497. */
  7498. var Overwrite = /** @class */ (function () {
  7499. function Overwrite(source, path, snap) {
  7500. this.source = source;
  7501. this.path = path;
  7502. this.snap = snap;
  7503. /** @inheritDoc */
  7504. this.type = OperationType.OVERWRITE;
  7505. }
  7506. Overwrite.prototype.operationForChild = function (childName) {
  7507. if (pathIsEmpty(this.path)) {
  7508. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7509. }
  7510. else {
  7511. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7512. }
  7513. };
  7514. return Overwrite;
  7515. }());
  7516. /**
  7517. * @license
  7518. * Copyright 2017 Google LLC
  7519. *
  7520. * Licensed under the Apache License, Version 2.0 (the "License");
  7521. * you may not use this file except in compliance with the License.
  7522. * You may obtain a copy of the License at
  7523. *
  7524. * http://www.apache.org/licenses/LICENSE-2.0
  7525. *
  7526. * Unless required by applicable law or agreed to in writing, software
  7527. * distributed under the License is distributed on an "AS IS" BASIS,
  7528. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7529. * See the License for the specific language governing permissions and
  7530. * limitations under the License.
  7531. */
  7532. var Merge = /** @class */ (function () {
  7533. function Merge(
  7534. /** @inheritDoc */ source,
  7535. /** @inheritDoc */ path,
  7536. /** @inheritDoc */ children) {
  7537. this.source = source;
  7538. this.path = path;
  7539. this.children = children;
  7540. /** @inheritDoc */
  7541. this.type = OperationType.MERGE;
  7542. }
  7543. Merge.prototype.operationForChild = function (childName) {
  7544. if (pathIsEmpty(this.path)) {
  7545. var childTree = this.children.subtree(new Path(childName));
  7546. if (childTree.isEmpty()) {
  7547. // This child is unaffected
  7548. return null;
  7549. }
  7550. else if (childTree.value) {
  7551. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7552. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7553. }
  7554. else {
  7555. // This is a merge at a deeper level
  7556. return new Merge(this.source, newEmptyPath(), childTree);
  7557. }
  7558. }
  7559. else {
  7560. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7561. return new Merge(this.source, pathPopFront(this.path), this.children);
  7562. }
  7563. };
  7564. Merge.prototype.toString = function () {
  7565. return ('Operation(' +
  7566. this.path +
  7567. ': ' +
  7568. this.source.toString() +
  7569. ' merge: ' +
  7570. this.children.toString() +
  7571. ')');
  7572. };
  7573. return Merge;
  7574. }());
  7575. /**
  7576. * @license
  7577. * Copyright 2017 Google LLC
  7578. *
  7579. * Licensed under the Apache License, Version 2.0 (the "License");
  7580. * you may not use this file except in compliance with the License.
  7581. * You may obtain a copy of the License at
  7582. *
  7583. * http://www.apache.org/licenses/LICENSE-2.0
  7584. *
  7585. * Unless required by applicable law or agreed to in writing, software
  7586. * distributed under the License is distributed on an "AS IS" BASIS,
  7587. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7588. * See the License for the specific language governing permissions and
  7589. * limitations under the License.
  7590. */
  7591. /**
  7592. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7593. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7594. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7595. * whether a node potentially had children removed due to a filter.
  7596. */
  7597. var CacheNode = /** @class */ (function () {
  7598. function CacheNode(node_, fullyInitialized_, filtered_) {
  7599. this.node_ = node_;
  7600. this.fullyInitialized_ = fullyInitialized_;
  7601. this.filtered_ = filtered_;
  7602. }
  7603. /**
  7604. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7605. */
  7606. CacheNode.prototype.isFullyInitialized = function () {
  7607. return this.fullyInitialized_;
  7608. };
  7609. /**
  7610. * Returns whether this node is potentially missing children due to a filter applied to the node
  7611. */
  7612. CacheNode.prototype.isFiltered = function () {
  7613. return this.filtered_;
  7614. };
  7615. CacheNode.prototype.isCompleteForPath = function (path) {
  7616. if (pathIsEmpty(path)) {
  7617. return this.isFullyInitialized() && !this.filtered_;
  7618. }
  7619. var childKey = pathGetFront(path);
  7620. return this.isCompleteForChild(childKey);
  7621. };
  7622. CacheNode.prototype.isCompleteForChild = function (key) {
  7623. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7624. };
  7625. CacheNode.prototype.getNode = function () {
  7626. return this.node_;
  7627. };
  7628. return CacheNode;
  7629. }());
  7630. /**
  7631. * @license
  7632. * Copyright 2017 Google LLC
  7633. *
  7634. * Licensed under the Apache License, Version 2.0 (the "License");
  7635. * you may not use this file except in compliance with the License.
  7636. * You may obtain a copy of the License at
  7637. *
  7638. * http://www.apache.org/licenses/LICENSE-2.0
  7639. *
  7640. * Unless required by applicable law or agreed to in writing, software
  7641. * distributed under the License is distributed on an "AS IS" BASIS,
  7642. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7643. * See the License for the specific language governing permissions and
  7644. * limitations under the License.
  7645. */
  7646. /**
  7647. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7648. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7649. * for details.
  7650. *
  7651. */
  7652. var EventGenerator = /** @class */ (function () {
  7653. function EventGenerator(query_) {
  7654. this.query_ = query_;
  7655. this.index_ = this.query_._queryParams.getIndex();
  7656. }
  7657. return EventGenerator;
  7658. }());
  7659. /**
  7660. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7661. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7662. *
  7663. * Notes:
  7664. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7665. * our index.
  7666. * - prevName will be calculated based on the index ordering.
  7667. */
  7668. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7669. var events = [];
  7670. var moves = [];
  7671. changes.forEach(function (change) {
  7672. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7673. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7674. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7675. }
  7676. });
  7677. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7678. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7679. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7680. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7681. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7682. return events;
  7683. }
  7684. /**
  7685. * Given changes of a single change type, generate the corresponding events.
  7686. */
  7687. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7688. var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
  7689. filteredChanges.sort(function (a, b) {
  7690. return eventGeneratorCompareChanges(eventGenerator, a, b);
  7691. });
  7692. filteredChanges.forEach(function (change) {
  7693. var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7694. registrations.forEach(function (registration) {
  7695. if (registration.respondsTo(change.type)) {
  7696. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7697. }
  7698. });
  7699. });
  7700. }
  7701. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7702. if (change.type === 'value' || change.type === 'child_removed') {
  7703. return change;
  7704. }
  7705. else {
  7706. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7707. return change;
  7708. }
  7709. }
  7710. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7711. if (a.childName == null || b.childName == null) {
  7712. throw util.assertionError('Should only compare child_ events.');
  7713. }
  7714. var aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7715. var bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7716. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7717. }
  7718. /**
  7719. * @license
  7720. * Copyright 2017 Google LLC
  7721. *
  7722. * Licensed under the Apache License, Version 2.0 (the "License");
  7723. * you may not use this file except in compliance with the License.
  7724. * You may obtain a copy of the License at
  7725. *
  7726. * http://www.apache.org/licenses/LICENSE-2.0
  7727. *
  7728. * Unless required by applicable law or agreed to in writing, software
  7729. * distributed under the License is distributed on an "AS IS" BASIS,
  7730. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7731. * See the License for the specific language governing permissions and
  7732. * limitations under the License.
  7733. */
  7734. function newViewCache(eventCache, serverCache) {
  7735. return { eventCache: eventCache, serverCache: serverCache };
  7736. }
  7737. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7738. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7739. }
  7740. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7741. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7742. }
  7743. function viewCacheGetCompleteEventSnap(viewCache) {
  7744. return viewCache.eventCache.isFullyInitialized()
  7745. ? viewCache.eventCache.getNode()
  7746. : null;
  7747. }
  7748. function viewCacheGetCompleteServerSnap(viewCache) {
  7749. return viewCache.serverCache.isFullyInitialized()
  7750. ? viewCache.serverCache.getNode()
  7751. : null;
  7752. }
  7753. /**
  7754. * @license
  7755. * Copyright 2017 Google LLC
  7756. *
  7757. * Licensed under the Apache License, Version 2.0 (the "License");
  7758. * you may not use this file except in compliance with the License.
  7759. * You may obtain a copy of the License at
  7760. *
  7761. * http://www.apache.org/licenses/LICENSE-2.0
  7762. *
  7763. * Unless required by applicable law or agreed to in writing, software
  7764. * distributed under the License is distributed on an "AS IS" BASIS,
  7765. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7766. * See the License for the specific language governing permissions and
  7767. * limitations under the License.
  7768. */
  7769. var emptyChildrenSingleton;
  7770. /**
  7771. * Singleton empty children collection.
  7772. *
  7773. */
  7774. var EmptyChildren = function () {
  7775. if (!emptyChildrenSingleton) {
  7776. emptyChildrenSingleton = new SortedMap(stringCompare);
  7777. }
  7778. return emptyChildrenSingleton;
  7779. };
  7780. /**
  7781. * A tree with immutable elements.
  7782. */
  7783. var ImmutableTree = /** @class */ (function () {
  7784. function ImmutableTree(value, children) {
  7785. if (children === void 0) { children = EmptyChildren(); }
  7786. this.value = value;
  7787. this.children = children;
  7788. }
  7789. ImmutableTree.fromObject = function (obj) {
  7790. var tree = new ImmutableTree(null);
  7791. each(obj, function (childPath, childSnap) {
  7792. tree = tree.set(new Path(childPath), childSnap);
  7793. });
  7794. return tree;
  7795. };
  7796. /**
  7797. * True if the value is empty and there are no children
  7798. */
  7799. ImmutableTree.prototype.isEmpty = function () {
  7800. return this.value === null && this.children.isEmpty();
  7801. };
  7802. /**
  7803. * Given a path and predicate, return the first node and the path to that node
  7804. * where the predicate returns true.
  7805. *
  7806. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7807. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7808. *
  7809. * @param relativePath - The remainder of the path
  7810. * @param predicate - The predicate to satisfy to return a node
  7811. */
  7812. ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
  7813. if (this.value != null && predicate(this.value)) {
  7814. return { path: newEmptyPath(), value: this.value };
  7815. }
  7816. else {
  7817. if (pathIsEmpty(relativePath)) {
  7818. return null;
  7819. }
  7820. else {
  7821. var front = pathGetFront(relativePath);
  7822. var child = this.children.get(front);
  7823. if (child !== null) {
  7824. var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7825. if (childExistingPathAndValue != null) {
  7826. var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7827. return { path: fullPath, value: childExistingPathAndValue.value };
  7828. }
  7829. else {
  7830. return null;
  7831. }
  7832. }
  7833. else {
  7834. return null;
  7835. }
  7836. }
  7837. }
  7838. };
  7839. /**
  7840. * Find, if it exists, the shortest subpath of the given path that points a defined
  7841. * value in the tree
  7842. */
  7843. ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
  7844. return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
  7845. };
  7846. /**
  7847. * @returns The subtree at the given path
  7848. */
  7849. ImmutableTree.prototype.subtree = function (relativePath) {
  7850. if (pathIsEmpty(relativePath)) {
  7851. return this;
  7852. }
  7853. else {
  7854. var front = pathGetFront(relativePath);
  7855. var childTree = this.children.get(front);
  7856. if (childTree !== null) {
  7857. return childTree.subtree(pathPopFront(relativePath));
  7858. }
  7859. else {
  7860. return new ImmutableTree(null);
  7861. }
  7862. }
  7863. };
  7864. /**
  7865. * Sets a value at the specified path.
  7866. *
  7867. * @param relativePath - Path to set value at.
  7868. * @param toSet - Value to set.
  7869. * @returns Resulting tree.
  7870. */
  7871. ImmutableTree.prototype.set = function (relativePath, toSet) {
  7872. if (pathIsEmpty(relativePath)) {
  7873. return new ImmutableTree(toSet, this.children);
  7874. }
  7875. else {
  7876. var front = pathGetFront(relativePath);
  7877. var child = this.children.get(front) || new ImmutableTree(null);
  7878. var newChild = child.set(pathPopFront(relativePath), toSet);
  7879. var newChildren = this.children.insert(front, newChild);
  7880. return new ImmutableTree(this.value, newChildren);
  7881. }
  7882. };
  7883. /**
  7884. * Removes the value at the specified path.
  7885. *
  7886. * @param relativePath - Path to value to remove.
  7887. * @returns Resulting tree.
  7888. */
  7889. ImmutableTree.prototype.remove = function (relativePath) {
  7890. if (pathIsEmpty(relativePath)) {
  7891. if (this.children.isEmpty()) {
  7892. return new ImmutableTree(null);
  7893. }
  7894. else {
  7895. return new ImmutableTree(null, this.children);
  7896. }
  7897. }
  7898. else {
  7899. var front = pathGetFront(relativePath);
  7900. var child = this.children.get(front);
  7901. if (child) {
  7902. var newChild = child.remove(pathPopFront(relativePath));
  7903. var newChildren = void 0;
  7904. if (newChild.isEmpty()) {
  7905. newChildren = this.children.remove(front);
  7906. }
  7907. else {
  7908. newChildren = this.children.insert(front, newChild);
  7909. }
  7910. if (this.value === null && newChildren.isEmpty()) {
  7911. return new ImmutableTree(null);
  7912. }
  7913. else {
  7914. return new ImmutableTree(this.value, newChildren);
  7915. }
  7916. }
  7917. else {
  7918. return this;
  7919. }
  7920. }
  7921. };
  7922. /**
  7923. * Gets a value from the tree.
  7924. *
  7925. * @param relativePath - Path to get value for.
  7926. * @returns Value at path, or null.
  7927. */
  7928. ImmutableTree.prototype.get = function (relativePath) {
  7929. if (pathIsEmpty(relativePath)) {
  7930. return this.value;
  7931. }
  7932. else {
  7933. var front = pathGetFront(relativePath);
  7934. var child = this.children.get(front);
  7935. if (child) {
  7936. return child.get(pathPopFront(relativePath));
  7937. }
  7938. else {
  7939. return null;
  7940. }
  7941. }
  7942. };
  7943. /**
  7944. * Replace the subtree at the specified path with the given new tree.
  7945. *
  7946. * @param relativePath - Path to replace subtree for.
  7947. * @param newTree - New tree.
  7948. * @returns Resulting tree.
  7949. */
  7950. ImmutableTree.prototype.setTree = function (relativePath, newTree) {
  7951. if (pathIsEmpty(relativePath)) {
  7952. return newTree;
  7953. }
  7954. else {
  7955. var front = pathGetFront(relativePath);
  7956. var child = this.children.get(front) || new ImmutableTree(null);
  7957. var newChild = child.setTree(pathPopFront(relativePath), newTree);
  7958. var newChildren = void 0;
  7959. if (newChild.isEmpty()) {
  7960. newChildren = this.children.remove(front);
  7961. }
  7962. else {
  7963. newChildren = this.children.insert(front, newChild);
  7964. }
  7965. return new ImmutableTree(this.value, newChildren);
  7966. }
  7967. };
  7968. /**
  7969. * Performs a depth first fold on this tree. Transforms a tree into a single
  7970. * value, given a function that operates on the path to a node, an optional
  7971. * current value, and a map of child names to folded subtrees
  7972. */
  7973. ImmutableTree.prototype.fold = function (fn) {
  7974. return this.fold_(newEmptyPath(), fn);
  7975. };
  7976. /**
  7977. * Recursive helper for public-facing fold() method
  7978. */
  7979. ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
  7980. var accum = {};
  7981. this.children.inorderTraversal(function (childKey, childTree) {
  7982. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7983. });
  7984. return fn(pathSoFar, this.value, accum);
  7985. };
  7986. /**
  7987. * Find the first matching value on the given path. Return the result of applying f to it.
  7988. */
  7989. ImmutableTree.prototype.findOnPath = function (path, f) {
  7990. return this.findOnPath_(path, newEmptyPath(), f);
  7991. };
  7992. ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
  7993. var result = this.value ? f(pathSoFar, this.value) : false;
  7994. if (result) {
  7995. return result;
  7996. }
  7997. else {
  7998. if (pathIsEmpty(pathToFollow)) {
  7999. return null;
  8000. }
  8001. else {
  8002. var front = pathGetFront(pathToFollow);
  8003. var nextChild = this.children.get(front);
  8004. if (nextChild) {
  8005. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  8006. }
  8007. else {
  8008. return null;
  8009. }
  8010. }
  8011. }
  8012. };
  8013. ImmutableTree.prototype.foreachOnPath = function (path, f) {
  8014. return this.foreachOnPath_(path, newEmptyPath(), f);
  8015. };
  8016. ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
  8017. if (pathIsEmpty(pathToFollow)) {
  8018. return this;
  8019. }
  8020. else {
  8021. if (this.value) {
  8022. f(currentRelativePath, this.value);
  8023. }
  8024. var front = pathGetFront(pathToFollow);
  8025. var nextChild = this.children.get(front);
  8026. if (nextChild) {
  8027. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  8028. }
  8029. else {
  8030. return new ImmutableTree(null);
  8031. }
  8032. }
  8033. };
  8034. /**
  8035. * Calls the given function for each node in the tree that has a value.
  8036. *
  8037. * @param f - A function to be called with the path from the root of the tree to
  8038. * a node, and the value at that node. Called in depth-first order.
  8039. */
  8040. ImmutableTree.prototype.foreach = function (f) {
  8041. this.foreach_(newEmptyPath(), f);
  8042. };
  8043. ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
  8044. this.children.inorderTraversal(function (childName, childTree) {
  8045. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  8046. });
  8047. if (this.value) {
  8048. f(currentRelativePath, this.value);
  8049. }
  8050. };
  8051. ImmutableTree.prototype.foreachChild = function (f) {
  8052. this.children.inorderTraversal(function (childName, childTree) {
  8053. if (childTree.value) {
  8054. f(childName, childTree.value);
  8055. }
  8056. });
  8057. };
  8058. return ImmutableTree;
  8059. }());
  8060. /**
  8061. * @license
  8062. * Copyright 2017 Google LLC
  8063. *
  8064. * Licensed under the Apache License, Version 2.0 (the "License");
  8065. * you may not use this file except in compliance with the License.
  8066. * You may obtain a copy of the License at
  8067. *
  8068. * http://www.apache.org/licenses/LICENSE-2.0
  8069. *
  8070. * Unless required by applicable law or agreed to in writing, software
  8071. * distributed under the License is distributed on an "AS IS" BASIS,
  8072. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8073. * See the License for the specific language governing permissions and
  8074. * limitations under the License.
  8075. */
  8076. /**
  8077. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  8078. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  8079. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  8080. * to reflect the write added.
  8081. */
  8082. var CompoundWrite = /** @class */ (function () {
  8083. function CompoundWrite(writeTree_) {
  8084. this.writeTree_ = writeTree_;
  8085. }
  8086. CompoundWrite.empty = function () {
  8087. return new CompoundWrite(new ImmutableTree(null));
  8088. };
  8089. return CompoundWrite;
  8090. }());
  8091. function compoundWriteAddWrite(compoundWrite, path, node) {
  8092. if (pathIsEmpty(path)) {
  8093. return new CompoundWrite(new ImmutableTree(node));
  8094. }
  8095. else {
  8096. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8097. if (rootmost != null) {
  8098. var rootMostPath = rootmost.path;
  8099. var value = rootmost.value;
  8100. var relativePath = newRelativePath(rootMostPath, path);
  8101. value = value.updateChild(relativePath, node);
  8102. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  8103. }
  8104. else {
  8105. var subtree = new ImmutableTree(node);
  8106. var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  8107. return new CompoundWrite(newWriteTree);
  8108. }
  8109. }
  8110. }
  8111. function compoundWriteAddWrites(compoundWrite, path, updates) {
  8112. var newWrite = compoundWrite;
  8113. each(updates, function (childKey, node) {
  8114. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  8115. });
  8116. return newWrite;
  8117. }
  8118. /**
  8119. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  8120. * location, which must be removed by calling this method with that path.
  8121. *
  8122. * @param compoundWrite - The CompoundWrite to remove.
  8123. * @param path - The path at which a write and all deeper writes should be removed
  8124. * @returns The new CompoundWrite with the removed path
  8125. */
  8126. function compoundWriteRemoveWrite(compoundWrite, path) {
  8127. if (pathIsEmpty(path)) {
  8128. return CompoundWrite.empty();
  8129. }
  8130. else {
  8131. var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  8132. return new CompoundWrite(newWriteTree);
  8133. }
  8134. }
  8135. /**
  8136. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  8137. * considered "complete".
  8138. *
  8139. * @param compoundWrite - The CompoundWrite to check.
  8140. * @param path - The path to check for
  8141. * @returns Whether there is a complete write at that path
  8142. */
  8143. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  8144. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  8145. }
  8146. /**
  8147. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  8148. * writes from deeper paths, but will return child nodes from a more shallow path.
  8149. *
  8150. * @param compoundWrite - The CompoundWrite to get the node from.
  8151. * @param path - The path to get a complete write
  8152. * @returns The node if complete at that path, or null otherwise.
  8153. */
  8154. function compoundWriteGetCompleteNode(compoundWrite, path) {
  8155. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8156. if (rootmost != null) {
  8157. return compoundWrite.writeTree_
  8158. .get(rootmost.path)
  8159. .getChild(newRelativePath(rootmost.path, path));
  8160. }
  8161. else {
  8162. return null;
  8163. }
  8164. }
  8165. /**
  8166. * Returns all children that are guaranteed to be a complete overwrite.
  8167. *
  8168. * @param compoundWrite - The CompoundWrite to get children from.
  8169. * @returns A list of all complete children.
  8170. */
  8171. function compoundWriteGetCompleteChildren(compoundWrite) {
  8172. var children = [];
  8173. var node = compoundWrite.writeTree_.value;
  8174. if (node != null) {
  8175. // If it's a leaf node, it has no children; so nothing to do.
  8176. if (!node.isLeafNode()) {
  8177. node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8178. children.push(new NamedNode(childName, childNode));
  8179. });
  8180. }
  8181. }
  8182. else {
  8183. compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
  8184. if (childTree.value != null) {
  8185. children.push(new NamedNode(childName, childTree.value));
  8186. }
  8187. });
  8188. }
  8189. return children;
  8190. }
  8191. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  8192. if (pathIsEmpty(path)) {
  8193. return compoundWrite;
  8194. }
  8195. else {
  8196. var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  8197. if (shadowingNode != null) {
  8198. return new CompoundWrite(new ImmutableTree(shadowingNode));
  8199. }
  8200. else {
  8201. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  8202. }
  8203. }
  8204. }
  8205. /**
  8206. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  8207. * @returns Whether this CompoundWrite is empty
  8208. */
  8209. function compoundWriteIsEmpty(compoundWrite) {
  8210. return compoundWrite.writeTree_.isEmpty();
  8211. }
  8212. /**
  8213. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  8214. * node
  8215. * @param node - The node to apply this CompoundWrite to
  8216. * @returns The node with all writes applied
  8217. */
  8218. function compoundWriteApply(compoundWrite, node) {
  8219. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  8220. }
  8221. function applySubtreeWrite(relativePath, writeTree, node) {
  8222. if (writeTree.value != null) {
  8223. // Since there a write is always a leaf, we're done here
  8224. return node.updateChild(relativePath, writeTree.value);
  8225. }
  8226. else {
  8227. var priorityWrite_1 = null;
  8228. writeTree.children.inorderTraversal(function (childKey, childTree) {
  8229. if (childKey === '.priority') {
  8230. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  8231. // to apply priorities to empty nodes that are later filled
  8232. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  8233. priorityWrite_1 = childTree.value;
  8234. }
  8235. else {
  8236. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  8237. }
  8238. });
  8239. // If there was a priority write, we only apply it if the node is not empty
  8240. if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
  8241. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
  8242. }
  8243. return node;
  8244. }
  8245. }
  8246. /**
  8247. * @license
  8248. * Copyright 2017 Google LLC
  8249. *
  8250. * Licensed under the Apache License, Version 2.0 (the "License");
  8251. * you may not use this file except in compliance with the License.
  8252. * You may obtain a copy of the License at
  8253. *
  8254. * http://www.apache.org/licenses/LICENSE-2.0
  8255. *
  8256. * Unless required by applicable law or agreed to in writing, software
  8257. * distributed under the License is distributed on an "AS IS" BASIS,
  8258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8259. * See the License for the specific language governing permissions and
  8260. * limitations under the License.
  8261. */
  8262. /**
  8263. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8264. *
  8265. */
  8266. function writeTreeChildWrites(writeTree, path) {
  8267. return newWriteTreeRef(path, writeTree);
  8268. }
  8269. /**
  8270. * Record a new overwrite from user code.
  8271. *
  8272. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8273. */
  8274. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8275. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8276. if (visible === undefined) {
  8277. visible = true;
  8278. }
  8279. writeTree.allWrites.push({
  8280. path: path,
  8281. snap: snap,
  8282. writeId: writeId,
  8283. visible: visible
  8284. });
  8285. if (visible) {
  8286. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8287. }
  8288. writeTree.lastWriteId = writeId;
  8289. }
  8290. /**
  8291. * Record a new merge from user code.
  8292. */
  8293. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8294. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8295. writeTree.allWrites.push({
  8296. path: path,
  8297. children: changedChildren,
  8298. writeId: writeId,
  8299. visible: true
  8300. });
  8301. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8302. writeTree.lastWriteId = writeId;
  8303. }
  8304. function writeTreeGetWrite(writeTree, writeId) {
  8305. for (var i = 0; i < writeTree.allWrites.length; i++) {
  8306. var record = writeTree.allWrites[i];
  8307. if (record.writeId === writeId) {
  8308. return record;
  8309. }
  8310. }
  8311. return null;
  8312. }
  8313. /**
  8314. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8315. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8316. *
  8317. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8318. * events as a result).
  8319. */
  8320. function writeTreeRemoveWrite(writeTree, writeId) {
  8321. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8322. // out of order.
  8323. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8324. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8325. var idx = writeTree.allWrites.findIndex(function (s) {
  8326. return s.writeId === writeId;
  8327. });
  8328. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8329. var writeToRemove = writeTree.allWrites[idx];
  8330. writeTree.allWrites.splice(idx, 1);
  8331. var removedWriteWasVisible = writeToRemove.visible;
  8332. var removedWriteOverlapsWithOtherWrites = false;
  8333. var i = writeTree.allWrites.length - 1;
  8334. while (removedWriteWasVisible && i >= 0) {
  8335. var currentWrite = writeTree.allWrites[i];
  8336. if (currentWrite.visible) {
  8337. if (i >= idx &&
  8338. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8339. // The removed write was completely shadowed by a subsequent write.
  8340. removedWriteWasVisible = false;
  8341. }
  8342. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8343. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8344. removedWriteOverlapsWithOtherWrites = true;
  8345. }
  8346. }
  8347. i--;
  8348. }
  8349. if (!removedWriteWasVisible) {
  8350. return false;
  8351. }
  8352. else if (removedWriteOverlapsWithOtherWrites) {
  8353. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8354. writeTreeResetTree_(writeTree);
  8355. return true;
  8356. }
  8357. else {
  8358. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8359. if (writeToRemove.snap) {
  8360. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8361. }
  8362. else {
  8363. var children = writeToRemove.children;
  8364. each(children, function (childName) {
  8365. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8366. });
  8367. }
  8368. return true;
  8369. }
  8370. }
  8371. function writeTreeRecordContainsPath_(writeRecord, path) {
  8372. if (writeRecord.snap) {
  8373. return pathContains(writeRecord.path, path);
  8374. }
  8375. else {
  8376. for (var childName in writeRecord.children) {
  8377. if (writeRecord.children.hasOwnProperty(childName) &&
  8378. pathContains(pathChild(writeRecord.path, childName), path)) {
  8379. return true;
  8380. }
  8381. }
  8382. return false;
  8383. }
  8384. }
  8385. /**
  8386. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8387. */
  8388. function writeTreeResetTree_(writeTree) {
  8389. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8390. if (writeTree.allWrites.length > 0) {
  8391. writeTree.lastWriteId =
  8392. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8393. }
  8394. else {
  8395. writeTree.lastWriteId = -1;
  8396. }
  8397. }
  8398. /**
  8399. * The default filter used when constructing the tree. Keep everything that's visible.
  8400. */
  8401. function writeTreeDefaultFilter_(write) {
  8402. return write.visible;
  8403. }
  8404. /**
  8405. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8406. * event data at that path.
  8407. */
  8408. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8409. var compoundWrite = CompoundWrite.empty();
  8410. for (var i = 0; i < writes.length; ++i) {
  8411. var write = writes[i];
  8412. // Theory, a later set will either:
  8413. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8414. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8415. if (filter(write)) {
  8416. var writePath = write.path;
  8417. var relativePath = void 0;
  8418. if (write.snap) {
  8419. if (pathContains(treeRoot, writePath)) {
  8420. relativePath = newRelativePath(treeRoot, writePath);
  8421. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8422. }
  8423. else if (pathContains(writePath, treeRoot)) {
  8424. relativePath = newRelativePath(writePath, treeRoot);
  8425. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8426. }
  8427. else ;
  8428. }
  8429. else if (write.children) {
  8430. if (pathContains(treeRoot, writePath)) {
  8431. relativePath = newRelativePath(treeRoot, writePath);
  8432. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8433. }
  8434. else if (pathContains(writePath, treeRoot)) {
  8435. relativePath = newRelativePath(writePath, treeRoot);
  8436. if (pathIsEmpty(relativePath)) {
  8437. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8438. }
  8439. else {
  8440. var child = util.safeGet(write.children, pathGetFront(relativePath));
  8441. if (child) {
  8442. // There exists a child in this node that matches the root path
  8443. var deepNode = child.getChild(pathPopFront(relativePath));
  8444. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8445. }
  8446. }
  8447. }
  8448. else ;
  8449. }
  8450. else {
  8451. throw util.assertionError('WriteRecord should have .snap or .children');
  8452. }
  8453. }
  8454. }
  8455. return compoundWrite;
  8456. }
  8457. /**
  8458. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8459. * writes), attempt to calculate a complete snapshot for the given path
  8460. *
  8461. * @param writeIdsToExclude - An optional set to be excluded
  8462. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8463. */
  8464. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8465. if (!writeIdsToExclude && !includeHiddenWrites) {
  8466. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8467. if (shadowingNode != null) {
  8468. return shadowingNode;
  8469. }
  8470. else {
  8471. var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8472. if (compoundWriteIsEmpty(subMerge)) {
  8473. return completeServerCache;
  8474. }
  8475. else if (completeServerCache == null &&
  8476. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8477. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8478. return null;
  8479. }
  8480. else {
  8481. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8482. return compoundWriteApply(subMerge, layeredCache);
  8483. }
  8484. }
  8485. }
  8486. else {
  8487. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8488. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8489. return completeServerCache;
  8490. }
  8491. else {
  8492. // If the server cache is null, and we don't have a complete cache, we need to return null
  8493. if (!includeHiddenWrites &&
  8494. completeServerCache == null &&
  8495. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8496. return null;
  8497. }
  8498. else {
  8499. var filter = function (write) {
  8500. return ((write.visible || includeHiddenWrites) &&
  8501. (!writeIdsToExclude ||
  8502. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8503. (pathContains(write.path, treePath) ||
  8504. pathContains(treePath, write.path)));
  8505. };
  8506. var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8507. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8508. return compoundWriteApply(mergeAtPath, layeredCache);
  8509. }
  8510. }
  8511. }
  8512. }
  8513. /**
  8514. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8515. * Used when creating new views, to pre-fill their complete event children snapshot.
  8516. */
  8517. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8518. var completeChildren = ChildrenNode.EMPTY_NODE;
  8519. var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8520. if (topLevelSet) {
  8521. if (!topLevelSet.isLeafNode()) {
  8522. // we're shadowing everything. Return the children.
  8523. topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
  8524. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8525. });
  8526. }
  8527. return completeChildren;
  8528. }
  8529. else if (completeServerChildren) {
  8530. // Layer any children we have on top of this
  8531. // We know we don't have a top-level set, so just enumerate existing children
  8532. var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8533. completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8534. var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
  8535. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8536. });
  8537. // Add any complete children we have from the set
  8538. compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
  8539. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8540. });
  8541. return completeChildren;
  8542. }
  8543. else {
  8544. // We don't have anything to layer on top of. Layer on any children we have
  8545. // Note that we can return an empty snap if we have a defined delete
  8546. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8547. compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
  8548. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8549. });
  8550. return completeChildren;
  8551. }
  8552. }
  8553. /**
  8554. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8555. * applied to the event cache.
  8556. *
  8557. * Possibilities:
  8558. *
  8559. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8560. *
  8561. * 2. Some write is completely shadowing. No events to be raised
  8562. *
  8563. * 3. Is partially shadowed. Events
  8564. *
  8565. * Either existingEventSnap or existingServerSnap must exist
  8566. */
  8567. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8568. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8569. var path = pathChild(treePath, childPath);
  8570. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8571. // At this point we can probably guarantee that we're in case 2, meaning no events
  8572. // May need to check visibility while doing the findRootMostValueAndPath call
  8573. return null;
  8574. }
  8575. else {
  8576. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8577. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8578. if (compoundWriteIsEmpty(childMerge)) {
  8579. // We're not shadowing at all. Case 1
  8580. return existingServerSnap.getChild(childPath);
  8581. }
  8582. else {
  8583. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8584. // However this is tricky to find out, since user updates don't necessary change the server
  8585. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8586. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8587. // only check if the updates change the serverNode.
  8588. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8589. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8590. }
  8591. }
  8592. }
  8593. /**
  8594. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8595. * complete child for this ChildKey.
  8596. */
  8597. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8598. var path = pathChild(treePath, childKey);
  8599. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8600. if (shadowingNode != null) {
  8601. return shadowingNode;
  8602. }
  8603. else {
  8604. if (existingServerSnap.isCompleteForChild(childKey)) {
  8605. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8606. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8607. }
  8608. else {
  8609. return null;
  8610. }
  8611. }
  8612. }
  8613. /**
  8614. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8615. * a higher path, this will return the child of that write relative to the write and this path.
  8616. * Returns null if there is no write at this path.
  8617. */
  8618. function writeTreeShadowingWrite(writeTree, path) {
  8619. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8620. }
  8621. /**
  8622. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8623. * the window, but may now be in the window.
  8624. */
  8625. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8626. var toIterate;
  8627. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8628. var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8629. if (shadowingNode != null) {
  8630. toIterate = shadowingNode;
  8631. }
  8632. else if (completeServerData != null) {
  8633. toIterate = compoundWriteApply(merge, completeServerData);
  8634. }
  8635. else {
  8636. // no children to iterate on
  8637. return [];
  8638. }
  8639. toIterate = toIterate.withIndex(index);
  8640. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8641. var nodes = [];
  8642. var cmp = index.getCompare();
  8643. var iter = reverse
  8644. ? toIterate.getReverseIteratorFrom(startPost, index)
  8645. : toIterate.getIteratorFrom(startPost, index);
  8646. var next = iter.getNext();
  8647. while (next && nodes.length < count) {
  8648. if (cmp(next, startPost) !== 0) {
  8649. nodes.push(next);
  8650. }
  8651. next = iter.getNext();
  8652. }
  8653. return nodes;
  8654. }
  8655. else {
  8656. return [];
  8657. }
  8658. }
  8659. function newWriteTree() {
  8660. return {
  8661. visibleWrites: CompoundWrite.empty(),
  8662. allWrites: [],
  8663. lastWriteId: -1
  8664. };
  8665. }
  8666. /**
  8667. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8668. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8669. * can lead to a more expensive calculation.
  8670. *
  8671. * @param writeIdsToExclude - Optional writes to exclude.
  8672. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8673. */
  8674. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8675. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8676. }
  8677. /**
  8678. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8679. * mix of the given server data and write data.
  8680. *
  8681. */
  8682. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8683. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8684. }
  8685. /**
  8686. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8687. * if anything, needs to be applied to the event cache.
  8688. *
  8689. * Possibilities:
  8690. *
  8691. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8692. *
  8693. * 2. Some write is completely shadowing. No events to be raised
  8694. *
  8695. * 3. Is partially shadowed. Events should be raised
  8696. *
  8697. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8698. *
  8699. *
  8700. */
  8701. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8702. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8703. }
  8704. /**
  8705. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8706. * a higher path, this will return the child of that write relative to the write and this path.
  8707. * Returns null if there is no write at this path.
  8708. *
  8709. */
  8710. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8711. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8712. }
  8713. /**
  8714. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8715. * the window, but may now be in the window
  8716. */
  8717. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8718. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8719. }
  8720. /**
  8721. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8722. * complete child for this ChildKey.
  8723. */
  8724. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8725. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8726. }
  8727. /**
  8728. * Return a WriteTreeRef for a child.
  8729. */
  8730. function writeTreeRefChild(writeTreeRef, childName) {
  8731. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8732. }
  8733. function newWriteTreeRef(path, writeTree) {
  8734. return {
  8735. treePath: path,
  8736. writeTree: writeTree
  8737. };
  8738. }
  8739. /**
  8740. * @license
  8741. * Copyright 2017 Google LLC
  8742. *
  8743. * Licensed under the Apache License, Version 2.0 (the "License");
  8744. * you may not use this file except in compliance with the License.
  8745. * You may obtain a copy of the License at
  8746. *
  8747. * http://www.apache.org/licenses/LICENSE-2.0
  8748. *
  8749. * Unless required by applicable law or agreed to in writing, software
  8750. * distributed under the License is distributed on an "AS IS" BASIS,
  8751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8752. * See the License for the specific language governing permissions and
  8753. * limitations under the License.
  8754. */
  8755. var ChildChangeAccumulator = /** @class */ (function () {
  8756. function ChildChangeAccumulator() {
  8757. this.changeMap = new Map();
  8758. }
  8759. ChildChangeAccumulator.prototype.trackChildChange = function (change) {
  8760. var type = change.type;
  8761. var childKey = change.childName;
  8762. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8763. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8764. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8765. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8766. var oldChange = this.changeMap.get(childKey);
  8767. if (oldChange) {
  8768. var oldType = oldChange.type;
  8769. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8770. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8771. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8772. }
  8773. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8774. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8775. this.changeMap.delete(childKey);
  8776. }
  8777. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8778. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8779. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8780. }
  8781. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8782. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8783. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8784. }
  8785. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8786. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8787. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8788. }
  8789. else {
  8790. throw util.assertionError('Illegal combination of changes: ' +
  8791. change +
  8792. ' occurred after ' +
  8793. oldChange);
  8794. }
  8795. }
  8796. else {
  8797. this.changeMap.set(childKey, change);
  8798. }
  8799. };
  8800. ChildChangeAccumulator.prototype.getChanges = function () {
  8801. return Array.from(this.changeMap.values());
  8802. };
  8803. return ChildChangeAccumulator;
  8804. }());
  8805. /**
  8806. * @license
  8807. * Copyright 2017 Google LLC
  8808. *
  8809. * Licensed under the Apache License, Version 2.0 (the "License");
  8810. * you may not use this file except in compliance with the License.
  8811. * You may obtain a copy of the License at
  8812. *
  8813. * http://www.apache.org/licenses/LICENSE-2.0
  8814. *
  8815. * Unless required by applicable law or agreed to in writing, software
  8816. * distributed under the License is distributed on an "AS IS" BASIS,
  8817. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8818. * See the License for the specific language governing permissions and
  8819. * limitations under the License.
  8820. */
  8821. /**
  8822. * An implementation of CompleteChildSource that never returns any additional children
  8823. */
  8824. // eslint-disable-next-line @typescript-eslint/naming-convention
  8825. var NoCompleteChildSource_ = /** @class */ (function () {
  8826. function NoCompleteChildSource_() {
  8827. }
  8828. NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
  8829. return null;
  8830. };
  8831. NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
  8832. return null;
  8833. };
  8834. return NoCompleteChildSource_;
  8835. }());
  8836. /**
  8837. * Singleton instance.
  8838. */
  8839. var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8840. /**
  8841. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8842. * old event caches available to calculate complete children.
  8843. */
  8844. var WriteTreeCompleteChildSource = /** @class */ (function () {
  8845. function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
  8846. if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
  8847. this.writes_ = writes_;
  8848. this.viewCache_ = viewCache_;
  8849. this.optCompleteServerCache_ = optCompleteServerCache_;
  8850. }
  8851. WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
  8852. var node = this.viewCache_.eventCache;
  8853. if (node.isCompleteForChild(childKey)) {
  8854. return node.getNode().getImmediateChild(childKey);
  8855. }
  8856. else {
  8857. var serverNode = this.optCompleteServerCache_ != null
  8858. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8859. : this.viewCache_.serverCache;
  8860. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8861. }
  8862. };
  8863. WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
  8864. var completeServerData = this.optCompleteServerCache_ != null
  8865. ? this.optCompleteServerCache_
  8866. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8867. var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8868. if (nodes.length === 0) {
  8869. return null;
  8870. }
  8871. else {
  8872. return nodes[0];
  8873. }
  8874. };
  8875. return WriteTreeCompleteChildSource;
  8876. }());
  8877. /**
  8878. * @license
  8879. * Copyright 2017 Google LLC
  8880. *
  8881. * Licensed under the Apache License, Version 2.0 (the "License");
  8882. * you may not use this file except in compliance with the License.
  8883. * You may obtain a copy of the License at
  8884. *
  8885. * http://www.apache.org/licenses/LICENSE-2.0
  8886. *
  8887. * Unless required by applicable law or agreed to in writing, software
  8888. * distributed under the License is distributed on an "AS IS" BASIS,
  8889. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8890. * See the License for the specific language governing permissions and
  8891. * limitations under the License.
  8892. */
  8893. function newViewProcessor(filter) {
  8894. return { filter: filter };
  8895. }
  8896. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8897. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8898. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8899. }
  8900. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8901. var accumulator = new ChildChangeAccumulator();
  8902. var newViewCache, filterServerNode;
  8903. if (operation.type === OperationType.OVERWRITE) {
  8904. var overwrite = operation;
  8905. if (overwrite.source.fromUser) {
  8906. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8907. }
  8908. else {
  8909. util.assert(overwrite.source.fromServer, 'Unknown source.');
  8910. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8911. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8912. // again
  8913. filterServerNode =
  8914. overwrite.source.tagged ||
  8915. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8916. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8917. }
  8918. }
  8919. else if (operation.type === OperationType.MERGE) {
  8920. var merge = operation;
  8921. if (merge.source.fromUser) {
  8922. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8923. }
  8924. else {
  8925. util.assert(merge.source.fromServer, 'Unknown source.');
  8926. // We filter the node if it's a tagged update or the node has been previously filtered
  8927. filterServerNode =
  8928. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8929. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8930. }
  8931. }
  8932. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8933. var ackUserWrite = operation;
  8934. if (!ackUserWrite.revert) {
  8935. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8936. }
  8937. else {
  8938. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8939. }
  8940. }
  8941. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8942. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8943. }
  8944. else {
  8945. throw util.assertionError('Unknown operation type: ' + operation.type);
  8946. }
  8947. var changes = accumulator.getChanges();
  8948. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8949. return { viewCache: newViewCache, changes: changes };
  8950. }
  8951. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8952. var eventSnap = newViewCache.eventCache;
  8953. if (eventSnap.isFullyInitialized()) {
  8954. var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8955. var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8956. if (accumulator.length > 0 ||
  8957. !oldViewCache.eventCache.isFullyInitialized() ||
  8958. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8959. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8960. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8961. }
  8962. }
  8963. }
  8964. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8965. var oldEventSnap = viewCache.eventCache;
  8966. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8967. // we have a shadowing write, ignore changes
  8968. return viewCache;
  8969. }
  8970. else {
  8971. var newEventCache = void 0, serverNode = void 0;
  8972. if (pathIsEmpty(changePath)) {
  8973. // TODO: figure out how this plays with "sliding ack windows"
  8974. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8975. if (viewCache.serverCache.isFiltered()) {
  8976. // We need to special case this, because we need to only apply writes to complete children, or
  8977. // we might end up raising events for incomplete children. If the server data is filtered deep
  8978. // writes cannot be guaranteed to be complete
  8979. var serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8980. var completeChildren = serverCache instanceof ChildrenNode
  8981. ? serverCache
  8982. : ChildrenNode.EMPTY_NODE;
  8983. var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8984. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8985. }
  8986. else {
  8987. var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8988. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8989. }
  8990. }
  8991. else {
  8992. var childKey = pathGetFront(changePath);
  8993. if (childKey === '.priority') {
  8994. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8995. var oldEventNode = oldEventSnap.getNode();
  8996. serverNode = viewCache.serverCache.getNode();
  8997. // we might have overwrites for this priority
  8998. var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8999. if (updatedPriority != null) {
  9000. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  9001. }
  9002. else {
  9003. // priority didn't change, keep old node
  9004. newEventCache = oldEventSnap.getNode();
  9005. }
  9006. }
  9007. else {
  9008. var childChangePath = pathPopFront(changePath);
  9009. // update child
  9010. var newEventChild = void 0;
  9011. if (oldEventSnap.isCompleteForChild(childKey)) {
  9012. serverNode = viewCache.serverCache.getNode();
  9013. var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  9014. if (eventChildUpdate != null) {
  9015. newEventChild = oldEventSnap
  9016. .getNode()
  9017. .getImmediateChild(childKey)
  9018. .updateChild(childChangePath, eventChildUpdate);
  9019. }
  9020. else {
  9021. // Nothing changed, just keep the old child
  9022. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9023. }
  9024. }
  9025. else {
  9026. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9027. }
  9028. if (newEventChild != null) {
  9029. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  9030. }
  9031. else {
  9032. // no complete child available or no change
  9033. newEventCache = oldEventSnap.getNode();
  9034. }
  9035. }
  9036. }
  9037. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  9038. }
  9039. }
  9040. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  9041. var oldServerSnap = oldViewCache.serverCache;
  9042. var newServerCache;
  9043. var serverFilter = filterServerNode
  9044. ? viewProcessor.filter
  9045. : viewProcessor.filter.getIndexedFilter();
  9046. if (pathIsEmpty(changePath)) {
  9047. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  9048. }
  9049. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  9050. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  9051. var newServerNode = oldServerSnap
  9052. .getNode()
  9053. .updateChild(changePath, changedSnap);
  9054. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  9055. }
  9056. else {
  9057. var childKey = pathGetFront(changePath);
  9058. if (!oldServerSnap.isCompleteForPath(changePath) &&
  9059. pathGetLength(changePath) > 1) {
  9060. // We don't update incomplete nodes with updates intended for other listeners
  9061. return oldViewCache;
  9062. }
  9063. var childChangePath = pathPopFront(changePath);
  9064. var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  9065. var newChildNode = childNode.updateChild(childChangePath, changedSnap);
  9066. if (childKey === '.priority') {
  9067. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  9068. }
  9069. else {
  9070. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  9071. }
  9072. }
  9073. var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  9074. var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  9075. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  9076. }
  9077. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  9078. var oldEventSnap = oldViewCache.eventCache;
  9079. var newViewCache, newEventCache;
  9080. var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  9081. if (pathIsEmpty(changePath)) {
  9082. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  9083. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  9084. }
  9085. else {
  9086. var childKey = pathGetFront(changePath);
  9087. if (childKey === '.priority') {
  9088. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  9089. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  9090. }
  9091. else {
  9092. var childChangePath = pathPopFront(changePath);
  9093. var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9094. var newChild = void 0;
  9095. if (pathIsEmpty(childChangePath)) {
  9096. // Child overwrite, we can replace the child
  9097. newChild = changedSnap;
  9098. }
  9099. else {
  9100. var childNode = source.getCompleteChild(childKey);
  9101. if (childNode != null) {
  9102. if (pathGetBack(childChangePath) === '.priority' &&
  9103. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  9104. // This is a priority update on an empty node. If this node exists on the server, the
  9105. // server will send down the priority in the update, so ignore for now
  9106. newChild = childNode;
  9107. }
  9108. else {
  9109. newChild = childNode.updateChild(childChangePath, changedSnap);
  9110. }
  9111. }
  9112. else {
  9113. // There is no complete child node available
  9114. newChild = ChildrenNode.EMPTY_NODE;
  9115. }
  9116. }
  9117. if (!oldChild.equals(newChild)) {
  9118. var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  9119. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  9120. }
  9121. else {
  9122. newViewCache = oldViewCache;
  9123. }
  9124. }
  9125. }
  9126. return newViewCache;
  9127. }
  9128. function viewProcessorCacheHasChild(viewCache, childKey) {
  9129. return viewCache.eventCache.isCompleteForChild(childKey);
  9130. }
  9131. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  9132. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9133. // window leaving room for new items. It's important we process these changes first, so we
  9134. // iterate the changes twice, first processing any that affect items currently in view.
  9135. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9136. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9137. // not the other.
  9138. var curViewCache = viewCache;
  9139. changedChildren.foreach(function (relativePath, childNode) {
  9140. var writePath = pathChild(path, relativePath);
  9141. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9142. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9143. }
  9144. });
  9145. changedChildren.foreach(function (relativePath, childNode) {
  9146. var writePath = pathChild(path, relativePath);
  9147. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9148. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9149. }
  9150. });
  9151. return curViewCache;
  9152. }
  9153. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  9154. merge.foreach(function (relativePath, childNode) {
  9155. node = node.updateChild(relativePath, childNode);
  9156. });
  9157. return node;
  9158. }
  9159. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  9160. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  9161. // wait for the complete data update coming soon.
  9162. if (viewCache.serverCache.getNode().isEmpty() &&
  9163. !viewCache.serverCache.isFullyInitialized()) {
  9164. return viewCache;
  9165. }
  9166. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9167. // window leaving room for new items. It's important we process these changes first, so we
  9168. // iterate the changes twice, first processing any that affect items currently in view.
  9169. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9170. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9171. // not the other.
  9172. var curViewCache = viewCache;
  9173. var viewMergeTree;
  9174. if (pathIsEmpty(path)) {
  9175. viewMergeTree = changedChildren;
  9176. }
  9177. else {
  9178. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  9179. }
  9180. var serverNode = viewCache.serverCache.getNode();
  9181. viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
  9182. if (serverNode.hasChild(childKey)) {
  9183. var serverChild = viewCache.serverCache
  9184. .getNode()
  9185. .getImmediateChild(childKey);
  9186. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  9187. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9188. }
  9189. });
  9190. viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
  9191. var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  9192. childMergeTree.value === null;
  9193. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  9194. var serverChild = viewCache.serverCache
  9195. .getNode()
  9196. .getImmediateChild(childKey);
  9197. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  9198. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9199. }
  9200. });
  9201. return curViewCache;
  9202. }
  9203. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  9204. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  9205. return viewCache;
  9206. }
  9207. // Only filter server node if it is currently filtered
  9208. var filterServerNode = viewCache.serverCache.isFiltered();
  9209. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  9210. // now that it won't be shadowed.
  9211. var serverCache = viewCache.serverCache;
  9212. if (affectedTree.value != null) {
  9213. // This is an overwrite.
  9214. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  9215. serverCache.isCompleteForPath(ackPath)) {
  9216. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  9217. }
  9218. else if (pathIsEmpty(ackPath)) {
  9219. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  9220. // should just re-apply whatever we have in our cache as a merge.
  9221. var changedChildren_1 = new ImmutableTree(null);
  9222. serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
  9223. changedChildren_1 = changedChildren_1.set(new Path(name), node);
  9224. });
  9225. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
  9226. }
  9227. else {
  9228. return viewCache;
  9229. }
  9230. }
  9231. else {
  9232. // This is a merge.
  9233. var changedChildren_2 = new ImmutableTree(null);
  9234. affectedTree.foreach(function (mergePath, value) {
  9235. var serverCachePath = pathChild(ackPath, mergePath);
  9236. if (serverCache.isCompleteForPath(serverCachePath)) {
  9237. changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  9238. }
  9239. });
  9240. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
  9241. }
  9242. }
  9243. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  9244. var oldServerNode = viewCache.serverCache;
  9245. var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  9246. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  9247. }
  9248. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  9249. var complete;
  9250. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  9251. return viewCache;
  9252. }
  9253. else {
  9254. var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  9255. var oldEventCache = viewCache.eventCache.getNode();
  9256. var newEventCache = void 0;
  9257. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9258. var newNode = void 0;
  9259. if (viewCache.serverCache.isFullyInitialized()) {
  9260. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9261. }
  9262. else {
  9263. var serverChildren = viewCache.serverCache.getNode();
  9264. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9265. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9266. }
  9267. newNode = newNode;
  9268. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9269. }
  9270. else {
  9271. var childKey = pathGetFront(path);
  9272. var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9273. if (newChild == null &&
  9274. viewCache.serverCache.isCompleteForChild(childKey)) {
  9275. newChild = oldEventCache.getImmediateChild(childKey);
  9276. }
  9277. if (newChild != null) {
  9278. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9279. }
  9280. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9281. // No complete child available, delete the existing one, if any
  9282. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9283. }
  9284. else {
  9285. newEventCache = oldEventCache;
  9286. }
  9287. if (newEventCache.isEmpty() &&
  9288. viewCache.serverCache.isFullyInitialized()) {
  9289. // We might have reverted all child writes. Maybe the old event was a leaf node
  9290. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9291. if (complete.isLeafNode()) {
  9292. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9293. }
  9294. }
  9295. }
  9296. complete =
  9297. viewCache.serverCache.isFullyInitialized() ||
  9298. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9299. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9300. }
  9301. }
  9302. /**
  9303. * @license
  9304. * Copyright 2017 Google LLC
  9305. *
  9306. * Licensed under the Apache License, Version 2.0 (the "License");
  9307. * you may not use this file except in compliance with the License.
  9308. * You may obtain a copy of the License at
  9309. *
  9310. * http://www.apache.org/licenses/LICENSE-2.0
  9311. *
  9312. * Unless required by applicable law or agreed to in writing, software
  9313. * distributed under the License is distributed on an "AS IS" BASIS,
  9314. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9315. * See the License for the specific language governing permissions and
  9316. * limitations under the License.
  9317. */
  9318. /**
  9319. * A view represents a specific location and query that has 1 or more event registrations.
  9320. *
  9321. * It does several things:
  9322. * - Maintains the list of event registrations for this location/query.
  9323. * - Maintains a cache of the data visible for this location/query.
  9324. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9325. * registrations returns the set of events to be raised.
  9326. */
  9327. var View = /** @class */ (function () {
  9328. function View(query_, initialViewCache) {
  9329. this.query_ = query_;
  9330. this.eventRegistrations_ = [];
  9331. var params = this.query_._queryParams;
  9332. var indexFilter = new IndexedFilter(params.getIndex());
  9333. var filter = queryParamsGetNodeFilter(params);
  9334. this.processor_ = newViewProcessor(filter);
  9335. var initialServerCache = initialViewCache.serverCache;
  9336. var initialEventCache = initialViewCache.eventCache;
  9337. // Don't filter server node with other filter than index, wait for tagged listen
  9338. var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9339. var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9340. var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9341. var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9342. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9343. this.eventGenerator_ = new EventGenerator(this.query_);
  9344. }
  9345. Object.defineProperty(View.prototype, "query", {
  9346. get: function () {
  9347. return this.query_;
  9348. },
  9349. enumerable: false,
  9350. configurable: true
  9351. });
  9352. return View;
  9353. }());
  9354. function viewGetServerCache(view) {
  9355. return view.viewCache_.serverCache.getNode();
  9356. }
  9357. function viewGetCompleteNode(view) {
  9358. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9359. }
  9360. function viewGetCompleteServerCache(view, path) {
  9361. var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9362. if (cache) {
  9363. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9364. // we need to see if it contains the child we're interested in.
  9365. if (view.query._queryParams.loadsAllData() ||
  9366. (!pathIsEmpty(path) &&
  9367. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9368. return cache.getChild(path);
  9369. }
  9370. }
  9371. return null;
  9372. }
  9373. function viewIsEmpty(view) {
  9374. return view.eventRegistrations_.length === 0;
  9375. }
  9376. function viewAddEventRegistration(view, eventRegistration) {
  9377. view.eventRegistrations_.push(eventRegistration);
  9378. }
  9379. /**
  9380. * @param eventRegistration - If null, remove all callbacks.
  9381. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9382. * @returns Cancel events, if cancelError was provided.
  9383. */
  9384. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9385. var cancelEvents = [];
  9386. if (cancelError) {
  9387. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9388. var path_1 = view.query._path;
  9389. view.eventRegistrations_.forEach(function (registration) {
  9390. var maybeEvent = registration.createCancelEvent(cancelError, path_1);
  9391. if (maybeEvent) {
  9392. cancelEvents.push(maybeEvent);
  9393. }
  9394. });
  9395. }
  9396. if (eventRegistration) {
  9397. var remaining = [];
  9398. for (var i = 0; i < view.eventRegistrations_.length; ++i) {
  9399. var existing = view.eventRegistrations_[i];
  9400. if (!existing.matches(eventRegistration)) {
  9401. remaining.push(existing);
  9402. }
  9403. else if (eventRegistration.hasAnyCallback()) {
  9404. // We're removing just this one
  9405. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9406. break;
  9407. }
  9408. }
  9409. view.eventRegistrations_ = remaining;
  9410. }
  9411. else {
  9412. view.eventRegistrations_ = [];
  9413. }
  9414. return cancelEvents;
  9415. }
  9416. /**
  9417. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9418. */
  9419. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9420. if (operation.type === OperationType.MERGE &&
  9421. operation.source.queryId !== null) {
  9422. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9423. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9424. }
  9425. var oldViewCache = view.viewCache_;
  9426. var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9427. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9428. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  9429. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9430. view.viewCache_ = result.viewCache;
  9431. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9432. }
  9433. function viewGetInitialEvents(view, registration) {
  9434. var eventSnap = view.viewCache_.eventCache;
  9435. var initialChanges = [];
  9436. if (!eventSnap.getNode().isLeafNode()) {
  9437. var eventNode = eventSnap.getNode();
  9438. eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  9439. initialChanges.push(changeChildAdded(key, childNode));
  9440. });
  9441. }
  9442. if (eventSnap.isFullyInitialized()) {
  9443. initialChanges.push(changeValue(eventSnap.getNode()));
  9444. }
  9445. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9446. }
  9447. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9448. var registrations = eventRegistration
  9449. ? [eventRegistration]
  9450. : view.eventRegistrations_;
  9451. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9452. }
  9453. /**
  9454. * @license
  9455. * Copyright 2017 Google LLC
  9456. *
  9457. * Licensed under the Apache License, Version 2.0 (the "License");
  9458. * you may not use this file except in compliance with the License.
  9459. * You may obtain a copy of the License at
  9460. *
  9461. * http://www.apache.org/licenses/LICENSE-2.0
  9462. *
  9463. * Unless required by applicable law or agreed to in writing, software
  9464. * distributed under the License is distributed on an "AS IS" BASIS,
  9465. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9466. * See the License for the specific language governing permissions and
  9467. * limitations under the License.
  9468. */
  9469. var referenceConstructor$1;
  9470. /**
  9471. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9472. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9473. * and user writes (set, transaction, update).
  9474. *
  9475. * It's responsible for:
  9476. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9477. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9478. * applyUserOverwrite, etc.)
  9479. */
  9480. var SyncPoint = /** @class */ (function () {
  9481. function SyncPoint() {
  9482. /**
  9483. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9484. * queryId and the value is the View for that query.
  9485. *
  9486. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9487. */
  9488. this.views = new Map();
  9489. }
  9490. return SyncPoint;
  9491. }());
  9492. function syncPointSetReferenceConstructor(val) {
  9493. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9494. referenceConstructor$1 = val;
  9495. }
  9496. function syncPointGetReferenceConstructor() {
  9497. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9498. return referenceConstructor$1;
  9499. }
  9500. function syncPointIsEmpty(syncPoint) {
  9501. return syncPoint.views.size === 0;
  9502. }
  9503. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9504. var e_1, _a;
  9505. var queryId = operation.source.queryId;
  9506. if (queryId !== null) {
  9507. var view = syncPoint.views.get(queryId);
  9508. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9509. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9510. }
  9511. else {
  9512. var events = [];
  9513. try {
  9514. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9515. var view = _c.value;
  9516. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9517. }
  9518. }
  9519. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  9520. finally {
  9521. try {
  9522. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9523. }
  9524. finally { if (e_1) throw e_1.error; }
  9525. }
  9526. return events;
  9527. }
  9528. }
  9529. /**
  9530. * Get a view for the specified query.
  9531. *
  9532. * @param query - The query to return a view for
  9533. * @param writesCache
  9534. * @param serverCache
  9535. * @param serverCacheComplete
  9536. * @returns Events to raise.
  9537. */
  9538. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9539. var queryId = query._queryIdentifier;
  9540. var view = syncPoint.views.get(queryId);
  9541. if (!view) {
  9542. // TODO: make writesCache take flag for complete server node
  9543. var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9544. var eventCacheComplete = false;
  9545. if (eventCache) {
  9546. eventCacheComplete = true;
  9547. }
  9548. else if (serverCache instanceof ChildrenNode) {
  9549. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9550. eventCacheComplete = false;
  9551. }
  9552. else {
  9553. eventCache = ChildrenNode.EMPTY_NODE;
  9554. eventCacheComplete = false;
  9555. }
  9556. var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9557. return new View(query, viewCache);
  9558. }
  9559. return view;
  9560. }
  9561. /**
  9562. * Add an event callback for the specified query.
  9563. *
  9564. * @param query
  9565. * @param eventRegistration
  9566. * @param writesCache
  9567. * @param serverCache - Complete server cache, if we have it.
  9568. * @param serverCacheComplete
  9569. * @returns Events to raise.
  9570. */
  9571. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9572. var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9573. if (!syncPoint.views.has(query._queryIdentifier)) {
  9574. syncPoint.views.set(query._queryIdentifier, view);
  9575. }
  9576. // This is guaranteed to exist now, we just created anything that was missing
  9577. viewAddEventRegistration(view, eventRegistration);
  9578. return viewGetInitialEvents(view, eventRegistration);
  9579. }
  9580. /**
  9581. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9582. *
  9583. * If query is the default query, we'll check all views for the specified eventRegistration.
  9584. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9585. *
  9586. * @param eventRegistration - If null, remove all callbacks.
  9587. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9588. * @returns removed queries and any cancel events
  9589. */
  9590. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9591. var e_2, _a;
  9592. var queryId = query._queryIdentifier;
  9593. var removed = [];
  9594. var cancelEvents = [];
  9595. var hadCompleteView = syncPointHasCompleteView(syncPoint);
  9596. if (queryId === 'default') {
  9597. try {
  9598. // When you do ref.off(...), we search all views for the registration to remove.
  9599. for (var _b = tslib.__values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9600. var _d = tslib.__read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
  9601. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9602. if (viewIsEmpty(view)) {
  9603. syncPoint.views.delete(viewQueryId);
  9604. // We'll deal with complete views later.
  9605. if (!view.query._queryParams.loadsAllData()) {
  9606. removed.push(view.query);
  9607. }
  9608. }
  9609. }
  9610. }
  9611. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  9612. finally {
  9613. try {
  9614. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9615. }
  9616. finally { if (e_2) throw e_2.error; }
  9617. }
  9618. }
  9619. else {
  9620. // remove the callback from the specific view.
  9621. var view = syncPoint.views.get(queryId);
  9622. if (view) {
  9623. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9624. if (viewIsEmpty(view)) {
  9625. syncPoint.views.delete(queryId);
  9626. // We'll deal with complete views later.
  9627. if (!view.query._queryParams.loadsAllData()) {
  9628. removed.push(view.query);
  9629. }
  9630. }
  9631. }
  9632. }
  9633. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9634. // We removed our last complete view.
  9635. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9636. }
  9637. return { removed: removed, events: cancelEvents };
  9638. }
  9639. function syncPointGetQueryViews(syncPoint) {
  9640. var e_3, _a;
  9641. var result = [];
  9642. try {
  9643. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9644. var view = _c.value;
  9645. if (!view.query._queryParams.loadsAllData()) {
  9646. result.push(view);
  9647. }
  9648. }
  9649. }
  9650. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  9651. finally {
  9652. try {
  9653. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9654. }
  9655. finally { if (e_3) throw e_3.error; }
  9656. }
  9657. return result;
  9658. }
  9659. /**
  9660. * @param path - The path to the desired complete snapshot
  9661. * @returns A complete cache, if it exists
  9662. */
  9663. function syncPointGetCompleteServerCache(syncPoint, path) {
  9664. var e_4, _a;
  9665. var serverCache = null;
  9666. try {
  9667. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9668. var view = _c.value;
  9669. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9670. }
  9671. }
  9672. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  9673. finally {
  9674. try {
  9675. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9676. }
  9677. finally { if (e_4) throw e_4.error; }
  9678. }
  9679. return serverCache;
  9680. }
  9681. function syncPointViewForQuery(syncPoint, query) {
  9682. var params = query._queryParams;
  9683. if (params.loadsAllData()) {
  9684. return syncPointGetCompleteView(syncPoint);
  9685. }
  9686. else {
  9687. var queryId = query._queryIdentifier;
  9688. return syncPoint.views.get(queryId);
  9689. }
  9690. }
  9691. function syncPointViewExistsForQuery(syncPoint, query) {
  9692. return syncPointViewForQuery(syncPoint, query) != null;
  9693. }
  9694. function syncPointHasCompleteView(syncPoint) {
  9695. return syncPointGetCompleteView(syncPoint) != null;
  9696. }
  9697. function syncPointGetCompleteView(syncPoint) {
  9698. var e_5, _a;
  9699. try {
  9700. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9701. var view = _c.value;
  9702. if (view.query._queryParams.loadsAllData()) {
  9703. return view;
  9704. }
  9705. }
  9706. }
  9707. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  9708. finally {
  9709. try {
  9710. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9711. }
  9712. finally { if (e_5) throw e_5.error; }
  9713. }
  9714. return null;
  9715. }
  9716. /**
  9717. * @license
  9718. * Copyright 2017 Google LLC
  9719. *
  9720. * Licensed under the Apache License, Version 2.0 (the "License");
  9721. * you may not use this file except in compliance with the License.
  9722. * You may obtain a copy of the License at
  9723. *
  9724. * http://www.apache.org/licenses/LICENSE-2.0
  9725. *
  9726. * Unless required by applicable law or agreed to in writing, software
  9727. * distributed under the License is distributed on an "AS IS" BASIS,
  9728. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9729. * See the License for the specific language governing permissions and
  9730. * limitations under the License.
  9731. */
  9732. var referenceConstructor;
  9733. function syncTreeSetReferenceConstructor(val) {
  9734. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9735. referenceConstructor = val;
  9736. }
  9737. function syncTreeGetReferenceConstructor() {
  9738. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  9739. return referenceConstructor;
  9740. }
  9741. /**
  9742. * Static tracker for next query tag.
  9743. */
  9744. var syncTreeNextQueryTag_ = 1;
  9745. /**
  9746. * SyncTree is the central class for managing event callback registration, data caching, views
  9747. * (query processing), and event generation. There are typically two SyncTree instances for
  9748. * each Repo, one for the normal Firebase data, and one for the .info data.
  9749. *
  9750. * It has a number of responsibilities, including:
  9751. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9752. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9753. * (applyUserOverwrite(), applyUserMerge()).
  9754. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9755. * applyServerMerge()).
  9756. * - Generating user-facing events for server and user changes (all of the apply* methods
  9757. * return the set of events that need to be raised as a result).
  9758. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9759. * to the correct set of paths and queries to satisfy the current set of user event
  9760. * callbacks (listens are started/stopped using the provided listenProvider).
  9761. *
  9762. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9763. * events are returned to the caller rather than raised synchronously.
  9764. *
  9765. */
  9766. var SyncTree = /** @class */ (function () {
  9767. /**
  9768. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9769. * to server data.
  9770. */
  9771. function SyncTree(listenProvider_) {
  9772. this.listenProvider_ = listenProvider_;
  9773. /**
  9774. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9775. */
  9776. this.syncPointTree_ = new ImmutableTree(null);
  9777. /**
  9778. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9779. */
  9780. this.pendingWriteTree_ = newWriteTree();
  9781. this.tagToQueryMap = new Map();
  9782. this.queryToTagMap = new Map();
  9783. }
  9784. return SyncTree;
  9785. }());
  9786. /**
  9787. * Apply the data changes for a user-generated set() or transaction() call.
  9788. *
  9789. * @returns Events to raise.
  9790. */
  9791. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9792. // Record pending write.
  9793. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9794. if (!visible) {
  9795. return [];
  9796. }
  9797. else {
  9798. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9799. }
  9800. }
  9801. /**
  9802. * Apply the data from a user-generated update() call
  9803. *
  9804. * @returns Events to raise.
  9805. */
  9806. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9807. // Record pending merge.
  9808. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9809. var changeTree = ImmutableTree.fromObject(changedChildren);
  9810. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9811. }
  9812. /**
  9813. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9814. *
  9815. * @param revert - True if the given write failed and needs to be reverted
  9816. * @returns Events to raise.
  9817. */
  9818. function syncTreeAckUserWrite(syncTree, writeId, revert) {
  9819. if (revert === void 0) { revert = false; }
  9820. var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9821. var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9822. if (!needToReevaluate) {
  9823. return [];
  9824. }
  9825. else {
  9826. var affectedTree_1 = new ImmutableTree(null);
  9827. if (write.snap != null) {
  9828. // overwrite
  9829. affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
  9830. }
  9831. else {
  9832. each(write.children, function (pathString) {
  9833. affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
  9834. });
  9835. }
  9836. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
  9837. }
  9838. }
  9839. /**
  9840. * Apply new server data for the specified path..
  9841. *
  9842. * @returns Events to raise.
  9843. */
  9844. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9845. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9846. }
  9847. /**
  9848. * Apply new server data to be merged in at the specified path.
  9849. *
  9850. * @returns Events to raise.
  9851. */
  9852. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9853. var changeTree = ImmutableTree.fromObject(changedChildren);
  9854. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9855. }
  9856. /**
  9857. * Apply a listen complete for a query
  9858. *
  9859. * @returns Events to raise.
  9860. */
  9861. function syncTreeApplyListenComplete(syncTree, path) {
  9862. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9863. }
  9864. /**
  9865. * Apply a listen complete for a tagged query
  9866. *
  9867. * @returns Events to raise.
  9868. */
  9869. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9870. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9871. if (queryKey) {
  9872. var r = syncTreeParseQueryKey_(queryKey);
  9873. var queryPath = r.path, queryId = r.queryId;
  9874. var relativePath = newRelativePath(queryPath, path);
  9875. var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9876. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9877. }
  9878. else {
  9879. // We've already removed the query. No big deal, ignore the update
  9880. return [];
  9881. }
  9882. }
  9883. /**
  9884. * Remove event callback(s).
  9885. *
  9886. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9887. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9888. *
  9889. * @param eventRegistration - If null, all callbacks are removed.
  9890. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9891. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9892. * deduping needs to take place. This flag allows toggling of that behavior
  9893. * @returns Cancel events, if cancelError was provided.
  9894. */
  9895. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
  9896. if (skipListenerDedup === void 0) { skipListenerDedup = false; }
  9897. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9898. var path = query._path;
  9899. var maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9900. var cancelEvents = [];
  9901. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9902. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9903. // not loadsAllData().
  9904. if (maybeSyncPoint &&
  9905. (query._queryIdentifier === 'default' ||
  9906. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9907. var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9908. if (syncPointIsEmpty(maybeSyncPoint)) {
  9909. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9910. }
  9911. var removed = removedAndEvents.removed;
  9912. cancelEvents = removedAndEvents.events;
  9913. if (!skipListenerDedup) {
  9914. /**
  9915. * We may have just removed one of many listeners and can short-circuit this whole process
  9916. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9917. * properly set up.
  9918. */
  9919. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9920. // queryId === 'default'
  9921. var removingDefault = -1 !==
  9922. removed.findIndex(function (query) {
  9923. return query._queryParams.loadsAllData();
  9924. });
  9925. var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
  9926. return syncPointHasCompleteView(parentSyncPoint);
  9927. });
  9928. if (removingDefault && !covered) {
  9929. var subtree = syncTree.syncPointTree_.subtree(path);
  9930. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9931. // removal
  9932. if (!subtree.isEmpty()) {
  9933. // We need to fold over our subtree and collect the listeners to send
  9934. var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9935. // Ok, we've collected all the listens we need. Set them up.
  9936. for (var i = 0; i < newViews.length; ++i) {
  9937. var view = newViews[i], newQuery = view.query;
  9938. var listener = syncTreeCreateListenerForView_(syncTree, view);
  9939. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9940. }
  9941. }
  9942. // Otherwise there's nothing below us, so nothing we need to start listening on
  9943. }
  9944. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9945. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9946. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9947. if (!covered && removed.length > 0 && !cancelError) {
  9948. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9949. // default. Otherwise, we need to iterate through and cancel each individual query
  9950. if (removingDefault) {
  9951. // We don't tag default listeners
  9952. var defaultTag = null;
  9953. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9954. }
  9955. else {
  9956. removed.forEach(function (queryToRemove) {
  9957. var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9958. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9959. });
  9960. }
  9961. }
  9962. }
  9963. // Now, clear all of the tags we're tracking for the removed listens
  9964. syncTreeRemoveTags_(syncTree, removed);
  9965. }
  9966. return cancelEvents;
  9967. }
  9968. /**
  9969. * Apply new server data for the specified tagged query.
  9970. *
  9971. * @returns Events to raise.
  9972. */
  9973. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9974. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9975. if (queryKey != null) {
  9976. var r = syncTreeParseQueryKey_(queryKey);
  9977. var queryPath = r.path, queryId = r.queryId;
  9978. var relativePath = newRelativePath(queryPath, path);
  9979. var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9980. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9981. }
  9982. else {
  9983. // Query must have been removed already
  9984. return [];
  9985. }
  9986. }
  9987. /**
  9988. * Apply server data to be merged in for the specified tagged query.
  9989. *
  9990. * @returns Events to raise.
  9991. */
  9992. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9993. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9994. if (queryKey) {
  9995. var r = syncTreeParseQueryKey_(queryKey);
  9996. var queryPath = r.path, queryId = r.queryId;
  9997. var relativePath = newRelativePath(queryPath, path);
  9998. var changeTree = ImmutableTree.fromObject(changedChildren);
  9999. var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  10000. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  10001. }
  10002. else {
  10003. // We've already removed the query. No big deal, ignore the update
  10004. return [];
  10005. }
  10006. }
  10007. /**
  10008. * Add an event callback for the specified query.
  10009. *
  10010. * @returns Events to raise.
  10011. */
  10012. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
  10013. if (skipSetupListener === void 0) { skipSetupListener = false; }
  10014. var path = query._path;
  10015. var serverCache = null;
  10016. var foundAncestorDefaultView = false;
  10017. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10018. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10019. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10020. var relativePath = newRelativePath(pathToSyncPoint, path);
  10021. serverCache =
  10022. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10023. foundAncestorDefaultView =
  10024. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  10025. });
  10026. var syncPoint = syncTree.syncPointTree_.get(path);
  10027. if (!syncPoint) {
  10028. syncPoint = new SyncPoint();
  10029. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10030. }
  10031. else {
  10032. foundAncestorDefaultView =
  10033. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  10034. serverCache =
  10035. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10036. }
  10037. var serverCacheComplete;
  10038. if (serverCache != null) {
  10039. serverCacheComplete = true;
  10040. }
  10041. else {
  10042. serverCacheComplete = false;
  10043. serverCache = ChildrenNode.EMPTY_NODE;
  10044. var subtree = syncTree.syncPointTree_.subtree(path);
  10045. subtree.foreachChild(function (childName, childSyncPoint) {
  10046. var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  10047. if (completeCache) {
  10048. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  10049. }
  10050. });
  10051. }
  10052. var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  10053. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  10054. // We need to track a tag for this query
  10055. var queryKey = syncTreeMakeQueryKey_(query);
  10056. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  10057. var tag = syncTreeGetNextQueryTag_();
  10058. syncTree.queryToTagMap.set(queryKey, tag);
  10059. syncTree.tagToQueryMap.set(tag, queryKey);
  10060. }
  10061. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  10062. var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  10063. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  10064. var view = syncPointViewForQuery(syncPoint, query);
  10065. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  10066. }
  10067. return events;
  10068. }
  10069. /**
  10070. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  10071. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  10072. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  10073. * <incremented total> as the write is applied locally and then acknowledged at the server.
  10074. *
  10075. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  10076. *
  10077. * @param path - The path to the data we want
  10078. * @param writeIdsToExclude - A specific set to be excluded
  10079. */
  10080. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  10081. var includeHiddenSets = true;
  10082. var writeTree = syncTree.pendingWriteTree_;
  10083. var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
  10084. var relativePath = newRelativePath(pathSoFar, path);
  10085. var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  10086. if (serverCache) {
  10087. return serverCache;
  10088. }
  10089. });
  10090. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  10091. }
  10092. function syncTreeGetServerValue(syncTree, query) {
  10093. var path = query._path;
  10094. var serverCache = null;
  10095. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10096. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10097. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10098. var relativePath = newRelativePath(pathToSyncPoint, path);
  10099. serverCache =
  10100. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10101. });
  10102. var syncPoint = syncTree.syncPointTree_.get(path);
  10103. if (!syncPoint) {
  10104. syncPoint = new SyncPoint();
  10105. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10106. }
  10107. else {
  10108. serverCache =
  10109. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10110. }
  10111. var serverCacheComplete = serverCache != null;
  10112. var serverCacheNode = serverCacheComplete
  10113. ? new CacheNode(serverCache, true, false)
  10114. : null;
  10115. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  10116. var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  10117. return viewGetCompleteNode(view);
  10118. }
  10119. /**
  10120. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  10121. *
  10122. * NOTES:
  10123. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  10124. *
  10125. * - We call applyOperation() on each SyncPoint passing three things:
  10126. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  10127. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  10128. * 3. A snapshot Node with cached server data, if we have it.
  10129. *
  10130. * - We concatenate all of the events returned by each SyncPoint and return the result.
  10131. */
  10132. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  10133. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  10134. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  10135. }
  10136. /**
  10137. * Recursive helper for applyOperationToSyncPoints_
  10138. */
  10139. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  10140. if (pathIsEmpty(operation.path)) {
  10141. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  10142. }
  10143. else {
  10144. var syncPoint = syncPointTree.get(newEmptyPath());
  10145. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10146. if (serverCache == null && syncPoint != null) {
  10147. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10148. }
  10149. var events = [];
  10150. var childName = pathGetFront(operation.path);
  10151. var childOperation = operation.operationForChild(childName);
  10152. var childTree = syncPointTree.children.get(childName);
  10153. if (childTree && childOperation) {
  10154. var childServerCache = serverCache
  10155. ? serverCache.getImmediateChild(childName)
  10156. : null;
  10157. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10158. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10159. }
  10160. if (syncPoint) {
  10161. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10162. }
  10163. return events;
  10164. }
  10165. }
  10166. /**
  10167. * Recursive helper for applyOperationToSyncPoints_
  10168. */
  10169. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  10170. var syncPoint = syncPointTree.get(newEmptyPath());
  10171. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10172. if (serverCache == null && syncPoint != null) {
  10173. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10174. }
  10175. var events = [];
  10176. syncPointTree.children.inorderTraversal(function (childName, childTree) {
  10177. var childServerCache = serverCache
  10178. ? serverCache.getImmediateChild(childName)
  10179. : null;
  10180. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10181. var childOperation = operation.operationForChild(childName);
  10182. if (childOperation) {
  10183. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10184. }
  10185. });
  10186. if (syncPoint) {
  10187. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10188. }
  10189. return events;
  10190. }
  10191. function syncTreeCreateListenerForView_(syncTree, view) {
  10192. var query = view.query;
  10193. var tag = syncTreeTagForQuery(syncTree, query);
  10194. return {
  10195. hashFn: function () {
  10196. var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  10197. return cache.hash();
  10198. },
  10199. onComplete: function (status) {
  10200. if (status === 'ok') {
  10201. if (tag) {
  10202. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  10203. }
  10204. else {
  10205. return syncTreeApplyListenComplete(syncTree, query._path);
  10206. }
  10207. }
  10208. else {
  10209. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  10210. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  10211. var error = errorForServerCode(status, query);
  10212. return syncTreeRemoveEventRegistration(syncTree, query,
  10213. /*eventRegistration*/ null, error);
  10214. }
  10215. }
  10216. };
  10217. }
  10218. /**
  10219. * Return the tag associated with the given query.
  10220. */
  10221. function syncTreeTagForQuery(syncTree, query) {
  10222. var queryKey = syncTreeMakeQueryKey_(query);
  10223. return syncTree.queryToTagMap.get(queryKey);
  10224. }
  10225. /**
  10226. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  10227. */
  10228. function syncTreeMakeQueryKey_(query) {
  10229. return query._path.toString() + '$' + query._queryIdentifier;
  10230. }
  10231. /**
  10232. * Return the query associated with the given tag, if we have one
  10233. */
  10234. function syncTreeQueryKeyForTag_(syncTree, tag) {
  10235. return syncTree.tagToQueryMap.get(tag);
  10236. }
  10237. /**
  10238. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  10239. */
  10240. function syncTreeParseQueryKey_(queryKey) {
  10241. var splitIndex = queryKey.indexOf('$');
  10242. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  10243. return {
  10244. queryId: queryKey.substr(splitIndex + 1),
  10245. path: new Path(queryKey.substr(0, splitIndex))
  10246. };
  10247. }
  10248. /**
  10249. * A helper method to apply tagged operations
  10250. */
  10251. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  10252. var syncPoint = syncTree.syncPointTree_.get(queryPath);
  10253. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  10254. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  10255. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  10256. }
  10257. /**
  10258. * This collapses multiple unfiltered views into a single view, since we only need a single
  10259. * listener for them.
  10260. */
  10261. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  10262. return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10263. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  10264. var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  10265. return [completeView];
  10266. }
  10267. else {
  10268. // No complete view here, flatten any deeper listens into an array
  10269. var views_1 = [];
  10270. if (maybeChildSyncPoint) {
  10271. views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
  10272. }
  10273. each(childMap, function (_key, childViews) {
  10274. views_1 = views_1.concat(childViews);
  10275. });
  10276. return views_1;
  10277. }
  10278. });
  10279. }
  10280. /**
  10281. * Normalizes a query to a query we send the server for listening
  10282. *
  10283. * @returns The normalized query
  10284. */
  10285. function syncTreeQueryForListening_(query) {
  10286. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  10287. // We treat queries that load all data as default queries
  10288. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  10289. // from Query
  10290. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  10291. }
  10292. else {
  10293. return query;
  10294. }
  10295. }
  10296. function syncTreeRemoveTags_(syncTree, queries) {
  10297. for (var j = 0; j < queries.length; ++j) {
  10298. var removedQuery = queries[j];
  10299. if (!removedQuery._queryParams.loadsAllData()) {
  10300. // We should have a tag for this
  10301. var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  10302. var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  10303. syncTree.queryToTagMap.delete(removedQueryKey);
  10304. syncTree.tagToQueryMap.delete(removedQueryTag);
  10305. }
  10306. }
  10307. }
  10308. /**
  10309. * Static accessor for query tags.
  10310. */
  10311. function syncTreeGetNextQueryTag_() {
  10312. return syncTreeNextQueryTag_++;
  10313. }
  10314. /**
  10315. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  10316. *
  10317. * @returns This method can return events to support synchronous data sources
  10318. */
  10319. function syncTreeSetupListener_(syncTree, query, view) {
  10320. var path = query._path;
  10321. var tag = syncTreeTagForQuery(syncTree, query);
  10322. var listener = syncTreeCreateListenerForView_(syncTree, view);
  10323. var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10324. var subtree = syncTree.syncPointTree_.subtree(path);
  10325. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10326. // may need to shadow other listens as well.
  10327. if (tag) {
  10328. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10329. }
  10330. else {
  10331. // Shadow everything at or below this location, this is a default listener.
  10332. var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10333. if (!pathIsEmpty(relativePath) &&
  10334. maybeChildSyncPoint &&
  10335. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10336. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10337. }
  10338. else {
  10339. // No default listener here, flatten any deeper queries into an array
  10340. var queries_1 = [];
  10341. if (maybeChildSyncPoint) {
  10342. queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
  10343. }
  10344. each(childMap, function (_key, childQueries) {
  10345. queries_1 = queries_1.concat(childQueries);
  10346. });
  10347. return queries_1;
  10348. }
  10349. });
  10350. for (var i = 0; i < queriesToStop.length; ++i) {
  10351. var queryToStop = queriesToStop[i];
  10352. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10353. }
  10354. }
  10355. return events;
  10356. }
  10357. /**
  10358. * @license
  10359. * Copyright 2017 Google LLC
  10360. *
  10361. * Licensed under the Apache License, Version 2.0 (the "License");
  10362. * you may not use this file except in compliance with the License.
  10363. * You may obtain a copy of the License at
  10364. *
  10365. * http://www.apache.org/licenses/LICENSE-2.0
  10366. *
  10367. * Unless required by applicable law or agreed to in writing, software
  10368. * distributed under the License is distributed on an "AS IS" BASIS,
  10369. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10370. * See the License for the specific language governing permissions and
  10371. * limitations under the License.
  10372. */
  10373. var ExistingValueProvider = /** @class */ (function () {
  10374. function ExistingValueProvider(node_) {
  10375. this.node_ = node_;
  10376. }
  10377. ExistingValueProvider.prototype.getImmediateChild = function (childName) {
  10378. var child = this.node_.getImmediateChild(childName);
  10379. return new ExistingValueProvider(child);
  10380. };
  10381. ExistingValueProvider.prototype.node = function () {
  10382. return this.node_;
  10383. };
  10384. return ExistingValueProvider;
  10385. }());
  10386. var DeferredValueProvider = /** @class */ (function () {
  10387. function DeferredValueProvider(syncTree, path) {
  10388. this.syncTree_ = syncTree;
  10389. this.path_ = path;
  10390. }
  10391. DeferredValueProvider.prototype.getImmediateChild = function (childName) {
  10392. var childPath = pathChild(this.path_, childName);
  10393. return new DeferredValueProvider(this.syncTree_, childPath);
  10394. };
  10395. DeferredValueProvider.prototype.node = function () {
  10396. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10397. };
  10398. return DeferredValueProvider;
  10399. }());
  10400. /**
  10401. * Generate placeholders for deferred values.
  10402. */
  10403. var generateWithValues = function (values) {
  10404. values = values || {};
  10405. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10406. return values;
  10407. };
  10408. /**
  10409. * Value to use when firing local events. When writing server values, fire
  10410. * local events with an approximate value, otherwise return value as-is.
  10411. */
  10412. var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10413. if (!value || typeof value !== 'object') {
  10414. return value;
  10415. }
  10416. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10417. if (typeof value['.sv'] === 'string') {
  10418. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10419. }
  10420. else if (typeof value['.sv'] === 'object') {
  10421. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10422. }
  10423. else {
  10424. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10425. }
  10426. };
  10427. var resolveScalarDeferredValue = function (op, existing, serverValues) {
  10428. switch (op) {
  10429. case 'timestamp':
  10430. return serverValues['timestamp'];
  10431. default:
  10432. util.assert(false, 'Unexpected server value: ' + op);
  10433. }
  10434. };
  10435. var resolveComplexDeferredValue = function (op, existing, unused) {
  10436. if (!op.hasOwnProperty('increment')) {
  10437. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10438. }
  10439. var delta = op['increment'];
  10440. if (typeof delta !== 'number') {
  10441. util.assert(false, 'Unexpected increment value: ' + delta);
  10442. }
  10443. var existingNode = existing.node();
  10444. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10445. // Incrementing a non-number sets the value to the incremented amount
  10446. if (!existingNode.isLeafNode()) {
  10447. return delta;
  10448. }
  10449. var leaf = existingNode;
  10450. var existingVal = leaf.getValue();
  10451. if (typeof existingVal !== 'number') {
  10452. return delta;
  10453. }
  10454. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10455. return existingVal + delta;
  10456. };
  10457. /**
  10458. * Recursively replace all deferred values and priorities in the tree with the
  10459. * specified generated replacement values.
  10460. * @param path - path to which write is relative
  10461. * @param node - new data written at path
  10462. * @param syncTree - current data
  10463. */
  10464. var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10465. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10466. };
  10467. /**
  10468. * Recursively replace all deferred values and priorities in the node with the
  10469. * specified generated replacement values. If there are no server values in the node,
  10470. * it'll be returned as-is.
  10471. */
  10472. var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10473. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10474. };
  10475. function resolveDeferredValue(node, existingVal, serverValues) {
  10476. var rawPri = node.getPriority().val();
  10477. var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10478. var newNode;
  10479. if (node.isLeafNode()) {
  10480. var leafNode = node;
  10481. var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10482. if (value !== leafNode.getValue() ||
  10483. priority !== leafNode.getPriority().val()) {
  10484. return new LeafNode(value, nodeFromJSON(priority));
  10485. }
  10486. else {
  10487. return node;
  10488. }
  10489. }
  10490. else {
  10491. var childrenNode = node;
  10492. newNode = childrenNode;
  10493. if (priority !== childrenNode.getPriority().val()) {
  10494. newNode = newNode.updatePriority(new LeafNode(priority));
  10495. }
  10496. childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  10497. var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10498. if (newChildNode !== childNode) {
  10499. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10500. }
  10501. });
  10502. return newNode;
  10503. }
  10504. }
  10505. /**
  10506. * @license
  10507. * Copyright 2017 Google LLC
  10508. *
  10509. * Licensed under the Apache License, Version 2.0 (the "License");
  10510. * you may not use this file except in compliance with the License.
  10511. * You may obtain a copy of the License at
  10512. *
  10513. * http://www.apache.org/licenses/LICENSE-2.0
  10514. *
  10515. * Unless required by applicable law or agreed to in writing, software
  10516. * distributed under the License is distributed on an "AS IS" BASIS,
  10517. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10518. * See the License for the specific language governing permissions and
  10519. * limitations under the License.
  10520. */
  10521. /**
  10522. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10523. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10524. * children.
  10525. */
  10526. var Tree = /** @class */ (function () {
  10527. /**
  10528. * @param name - Optional name of the node.
  10529. * @param parent - Optional parent node.
  10530. * @param node - Optional node to wrap.
  10531. */
  10532. function Tree(name, parent, node) {
  10533. if (name === void 0) { name = ''; }
  10534. if (parent === void 0) { parent = null; }
  10535. if (node === void 0) { node = { children: {}, childCount: 0 }; }
  10536. this.name = name;
  10537. this.parent = parent;
  10538. this.node = node;
  10539. }
  10540. return Tree;
  10541. }());
  10542. /**
  10543. * Returns a sub-Tree for the given path.
  10544. *
  10545. * @param pathObj - Path to look up.
  10546. * @returns Tree for path.
  10547. */
  10548. function treeSubTree(tree, pathObj) {
  10549. // TODO: Require pathObj to be Path?
  10550. var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10551. var child = tree, next = pathGetFront(path);
  10552. while (next !== null) {
  10553. var childNode = util.safeGet(child.node.children, next) || {
  10554. children: {},
  10555. childCount: 0
  10556. };
  10557. child = new Tree(next, child, childNode);
  10558. path = pathPopFront(path);
  10559. next = pathGetFront(path);
  10560. }
  10561. return child;
  10562. }
  10563. /**
  10564. * Returns the data associated with this tree node.
  10565. *
  10566. * @returns The data or null if no data exists.
  10567. */
  10568. function treeGetValue(tree) {
  10569. return tree.node.value;
  10570. }
  10571. /**
  10572. * Sets data to this tree node.
  10573. *
  10574. * @param value - Value to set.
  10575. */
  10576. function treeSetValue(tree, value) {
  10577. tree.node.value = value;
  10578. treeUpdateParents(tree);
  10579. }
  10580. /**
  10581. * @returns Whether the tree has any children.
  10582. */
  10583. function treeHasChildren(tree) {
  10584. return tree.node.childCount > 0;
  10585. }
  10586. /**
  10587. * @returns Whethe rthe tree is empty (no value or children).
  10588. */
  10589. function treeIsEmpty(tree) {
  10590. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10591. }
  10592. /**
  10593. * Calls action for each child of this tree node.
  10594. *
  10595. * @param action - Action to be called for each child.
  10596. */
  10597. function treeForEachChild(tree, action) {
  10598. each(tree.node.children, function (child, childTree) {
  10599. action(new Tree(child, tree, childTree));
  10600. });
  10601. }
  10602. /**
  10603. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10604. *
  10605. * @param action - Action to be called for each child.
  10606. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10607. * false.
  10608. * @param childrenFirst - Whether to call action on children before calling it on
  10609. * parent.
  10610. */
  10611. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10612. if (includeSelf && !childrenFirst) {
  10613. action(tree);
  10614. }
  10615. treeForEachChild(tree, function (child) {
  10616. treeForEachDescendant(child, action, true, childrenFirst);
  10617. });
  10618. if (includeSelf && childrenFirst) {
  10619. action(tree);
  10620. }
  10621. }
  10622. /**
  10623. * Calls action on each ancestor node.
  10624. *
  10625. * @param action - Action to be called on each parent; return
  10626. * true to abort.
  10627. * @param includeSelf - Whether to call action on this node as well.
  10628. * @returns true if the action callback returned true.
  10629. */
  10630. function treeForEachAncestor(tree, action, includeSelf) {
  10631. var node = includeSelf ? tree : tree.parent;
  10632. while (node !== null) {
  10633. if (action(node)) {
  10634. return true;
  10635. }
  10636. node = node.parent;
  10637. }
  10638. return false;
  10639. }
  10640. /**
  10641. * @returns The path of this tree node, as a Path.
  10642. */
  10643. function treeGetPath(tree) {
  10644. return new Path(tree.parent === null
  10645. ? tree.name
  10646. : treeGetPath(tree.parent) + '/' + tree.name);
  10647. }
  10648. /**
  10649. * Adds or removes this child from its parent based on whether it's empty or not.
  10650. */
  10651. function treeUpdateParents(tree) {
  10652. if (tree.parent !== null) {
  10653. treeUpdateChild(tree.parent, tree.name, tree);
  10654. }
  10655. }
  10656. /**
  10657. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10658. *
  10659. * @param childName - The name of the child to update.
  10660. * @param child - The child to update.
  10661. */
  10662. function treeUpdateChild(tree, childName, child) {
  10663. var childEmpty = treeIsEmpty(child);
  10664. var childExists = util.contains(tree.node.children, childName);
  10665. if (childEmpty && childExists) {
  10666. delete tree.node.children[childName];
  10667. tree.node.childCount--;
  10668. treeUpdateParents(tree);
  10669. }
  10670. else if (!childEmpty && !childExists) {
  10671. tree.node.children[childName] = child.node;
  10672. tree.node.childCount++;
  10673. treeUpdateParents(tree);
  10674. }
  10675. }
  10676. /**
  10677. * @license
  10678. * Copyright 2017 Google LLC
  10679. *
  10680. * Licensed under the Apache License, Version 2.0 (the "License");
  10681. * you may not use this file except in compliance with the License.
  10682. * You may obtain a copy of the License at
  10683. *
  10684. * http://www.apache.org/licenses/LICENSE-2.0
  10685. *
  10686. * Unless required by applicable law or agreed to in writing, software
  10687. * distributed under the License is distributed on an "AS IS" BASIS,
  10688. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10689. * See the License for the specific language governing permissions and
  10690. * limitations under the License.
  10691. */
  10692. /**
  10693. * True for invalid Firebase keys
  10694. */
  10695. var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10696. /**
  10697. * True for invalid Firebase paths.
  10698. * Allows '/' in paths.
  10699. */
  10700. var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10701. /**
  10702. * Maximum number of characters to allow in leaf value
  10703. */
  10704. var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10705. var isValidKey = function (key) {
  10706. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10707. };
  10708. var isValidPathString = function (pathString) {
  10709. return (typeof pathString === 'string' &&
  10710. pathString.length !== 0 &&
  10711. !INVALID_PATH_REGEX_.test(pathString));
  10712. };
  10713. var isValidRootPathString = function (pathString) {
  10714. if (pathString) {
  10715. // Allow '/.info/' at the beginning.
  10716. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10717. }
  10718. return isValidPathString(pathString);
  10719. };
  10720. var isValidPriority = function (priority) {
  10721. return (priority === null ||
  10722. typeof priority === 'string' ||
  10723. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10724. (priority &&
  10725. typeof priority === 'object' &&
  10726. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10727. util.contains(priority, '.sv')));
  10728. };
  10729. /**
  10730. * Pre-validate a datum passed as an argument to Firebase function.
  10731. */
  10732. var validateFirebaseDataArg = function (fnName, value, path, optional) {
  10733. if (optional && value === undefined) {
  10734. return;
  10735. }
  10736. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  10737. };
  10738. /**
  10739. * Validate a data object client-side before sending to server.
  10740. */
  10741. var validateFirebaseData = function (errorPrefix, data, path_) {
  10742. var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10743. if (data === undefined) {
  10744. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10745. }
  10746. if (typeof data === 'function') {
  10747. throw new Error(errorPrefix +
  10748. 'contains a function ' +
  10749. validationPathToErrorString(path) +
  10750. ' with contents = ' +
  10751. data.toString());
  10752. }
  10753. if (isInvalidJSONNumber(data)) {
  10754. throw new Error(errorPrefix +
  10755. 'contains ' +
  10756. data.toString() +
  10757. ' ' +
  10758. validationPathToErrorString(path));
  10759. }
  10760. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10761. if (typeof data === 'string' &&
  10762. data.length > MAX_LEAF_SIZE_ / 3 &&
  10763. util.stringLength(data) > MAX_LEAF_SIZE_) {
  10764. throw new Error(errorPrefix +
  10765. 'contains a string greater than ' +
  10766. MAX_LEAF_SIZE_ +
  10767. ' utf8 bytes ' +
  10768. validationPathToErrorString(path) +
  10769. " ('" +
  10770. data.substring(0, 50) +
  10771. "...')");
  10772. }
  10773. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10774. // to save extra walking of large objects.
  10775. if (data && typeof data === 'object') {
  10776. var hasDotValue_1 = false;
  10777. var hasActualChild_1 = false;
  10778. each(data, function (key, value) {
  10779. if (key === '.value') {
  10780. hasDotValue_1 = true;
  10781. }
  10782. else if (key !== '.priority' && key !== '.sv') {
  10783. hasActualChild_1 = true;
  10784. if (!isValidKey(key)) {
  10785. throw new Error(errorPrefix +
  10786. ' contains an invalid key (' +
  10787. key +
  10788. ') ' +
  10789. validationPathToErrorString(path) +
  10790. '. Keys must be non-empty strings ' +
  10791. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10792. }
  10793. }
  10794. validationPathPush(path, key);
  10795. validateFirebaseData(errorPrefix, value, path);
  10796. validationPathPop(path);
  10797. });
  10798. if (hasDotValue_1 && hasActualChild_1) {
  10799. throw new Error(errorPrefix +
  10800. ' contains ".value" child ' +
  10801. validationPathToErrorString(path) +
  10802. ' in addition to actual children.');
  10803. }
  10804. }
  10805. };
  10806. /**
  10807. * Pre-validate paths passed in the firebase function.
  10808. */
  10809. var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10810. var i, curPath;
  10811. for (i = 0; i < mergePaths.length; i++) {
  10812. curPath = mergePaths[i];
  10813. var keys = pathSlice(curPath);
  10814. for (var j = 0; j < keys.length; j++) {
  10815. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10816. else if (!isValidKey(keys[j])) {
  10817. throw new Error(errorPrefix +
  10818. 'contains an invalid key (' +
  10819. keys[j] +
  10820. ') in path ' +
  10821. curPath.toString() +
  10822. '. Keys must be non-empty strings ' +
  10823. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10824. }
  10825. }
  10826. }
  10827. // Check that update keys are not descendants of each other.
  10828. // We rely on the property that sorting guarantees that ancestors come
  10829. // right before descendants.
  10830. mergePaths.sort(pathCompare);
  10831. var prevPath = null;
  10832. for (i = 0; i < mergePaths.length; i++) {
  10833. curPath = mergePaths[i];
  10834. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10835. throw new Error(errorPrefix +
  10836. 'contains a path ' +
  10837. prevPath.toString() +
  10838. ' that is ancestor of another path ' +
  10839. curPath.toString());
  10840. }
  10841. prevPath = curPath;
  10842. }
  10843. };
  10844. /**
  10845. * pre-validate an object passed as an argument to firebase function (
  10846. * must be an object - e.g. for firebase.update()).
  10847. */
  10848. var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10849. if (optional && data === undefined) {
  10850. return;
  10851. }
  10852. var errorPrefix = util.errorPrefix(fnName, 'values');
  10853. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10854. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  10855. }
  10856. var mergePaths = [];
  10857. each(data, function (key, value) {
  10858. var curPath = new Path(key);
  10859. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  10860. if (pathGetBack(curPath) === '.priority') {
  10861. if (!isValidPriority(value)) {
  10862. throw new Error(errorPrefix +
  10863. "contains an invalid value for '" +
  10864. curPath.toString() +
  10865. "', which must be a valid " +
  10866. 'Firebase priority (a string, finite number, server value, or null).');
  10867. }
  10868. }
  10869. mergePaths.push(curPath);
  10870. });
  10871. validateFirebaseMergePaths(errorPrefix, mergePaths);
  10872. };
  10873. var validatePriority = function (fnName, priority, optional) {
  10874. if (optional && priority === undefined) {
  10875. return;
  10876. }
  10877. if (isInvalidJSONNumber(priority)) {
  10878. throw new Error(util.errorPrefix(fnName, 'priority') +
  10879. 'is ' +
  10880. priority.toString() +
  10881. ', but must be a valid Firebase priority (a string, finite number, ' +
  10882. 'server value, or null).');
  10883. }
  10884. // Special case to allow importing data with a .sv.
  10885. if (!isValidPriority(priority)) {
  10886. throw new Error(util.errorPrefix(fnName, 'priority') +
  10887. 'must be a valid Firebase priority ' +
  10888. '(a string, finite number, server value, or null).');
  10889. }
  10890. };
  10891. var validateKey = function (fnName, argumentName, key, optional) {
  10892. if (optional && key === undefined) {
  10893. return;
  10894. }
  10895. if (!isValidKey(key)) {
  10896. throw new Error(util.errorPrefix(fnName, argumentName) +
  10897. 'was an invalid key = "' +
  10898. key +
  10899. '". Firebase keys must be non-empty strings and ' +
  10900. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10901. }
  10902. };
  10903. /**
  10904. * @internal
  10905. */
  10906. var validatePathString = function (fnName, argumentName, pathString, optional) {
  10907. if (optional && pathString === undefined) {
  10908. return;
  10909. }
  10910. if (!isValidPathString(pathString)) {
  10911. throw new Error(util.errorPrefix(fnName, argumentName) +
  10912. 'was an invalid path = "' +
  10913. pathString +
  10914. '". Paths must be non-empty strings and ' +
  10915. 'can\'t contain ".", "#", "$", "[", or "]"');
  10916. }
  10917. };
  10918. var validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10919. if (pathString) {
  10920. // Allow '/.info/' at the beginning.
  10921. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10922. }
  10923. validatePathString(fnName, argumentName, pathString, optional);
  10924. };
  10925. /**
  10926. * @internal
  10927. */
  10928. var validateWritablePath = function (fnName, path) {
  10929. if (pathGetFront(path) === '.info') {
  10930. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10931. }
  10932. };
  10933. var validateUrl = function (fnName, parsedUrl) {
  10934. // TODO = Validate server better.
  10935. var pathString = parsedUrl.path.toString();
  10936. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10937. parsedUrl.repoInfo.host.length === 0 ||
  10938. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10939. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10940. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10941. throw new Error(util.errorPrefix(fnName, 'url') +
  10942. 'must be a valid firebase URL and ' +
  10943. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10944. }
  10945. };
  10946. /**
  10947. * @license
  10948. * Copyright 2017 Google LLC
  10949. *
  10950. * Licensed under the Apache License, Version 2.0 (the "License");
  10951. * you may not use this file except in compliance with the License.
  10952. * You may obtain a copy of the License at
  10953. *
  10954. * http://www.apache.org/licenses/LICENSE-2.0
  10955. *
  10956. * Unless required by applicable law or agreed to in writing, software
  10957. * distributed under the License is distributed on an "AS IS" BASIS,
  10958. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10959. * See the License for the specific language governing permissions and
  10960. * limitations under the License.
  10961. */
  10962. /**
  10963. * The event queue serves a few purposes:
  10964. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10965. * events being queued.
  10966. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10967. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10968. * left off, ensuring that the events are still raised synchronously and in order.
  10969. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10970. * events are raised synchronously.
  10971. *
  10972. * NOTE: This can all go away if/when we move to async events.
  10973. *
  10974. */
  10975. var EventQueue = /** @class */ (function () {
  10976. function EventQueue() {
  10977. this.eventLists_ = [];
  10978. /**
  10979. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10980. */
  10981. this.recursionDepth_ = 0;
  10982. }
  10983. return EventQueue;
  10984. }());
  10985. /**
  10986. * @param eventDataList - The new events to queue.
  10987. */
  10988. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10989. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10990. var currList = null;
  10991. for (var i = 0; i < eventDataList.length; i++) {
  10992. var data = eventDataList[i];
  10993. var path = data.getPath();
  10994. if (currList !== null && !pathEquals(path, currList.path)) {
  10995. eventQueue.eventLists_.push(currList);
  10996. currList = null;
  10997. }
  10998. if (currList === null) {
  10999. currList = { events: [], path: path };
  11000. }
  11001. currList.events.push(data);
  11002. }
  11003. if (currList) {
  11004. eventQueue.eventLists_.push(currList);
  11005. }
  11006. }
  11007. /**
  11008. * Queues the specified events and synchronously raises all events (including previously queued ones)
  11009. * for the specified path.
  11010. *
  11011. * It is assumed that the new events are all for the specified path.
  11012. *
  11013. * @param path - The path to raise events for.
  11014. * @param eventDataList - The new events to raise.
  11015. */
  11016. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  11017. eventQueueQueueEvents(eventQueue, eventDataList);
  11018. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11019. return pathEquals(eventPath, path);
  11020. });
  11021. }
  11022. /**
  11023. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  11024. * locations related to the specified change path (i.e. all ancestors and descendants).
  11025. *
  11026. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  11027. *
  11028. * @param changedPath - The path to raise events for.
  11029. * @param eventDataList - The events to raise
  11030. */
  11031. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  11032. eventQueueQueueEvents(eventQueue, eventDataList);
  11033. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11034. return pathContains(eventPath, changedPath) ||
  11035. pathContains(changedPath, eventPath);
  11036. });
  11037. }
  11038. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  11039. eventQueue.recursionDepth_++;
  11040. var sentAll = true;
  11041. for (var i = 0; i < eventQueue.eventLists_.length; i++) {
  11042. var eventList = eventQueue.eventLists_[i];
  11043. if (eventList) {
  11044. var eventPath = eventList.path;
  11045. if (predicate(eventPath)) {
  11046. eventListRaise(eventQueue.eventLists_[i]);
  11047. eventQueue.eventLists_[i] = null;
  11048. }
  11049. else {
  11050. sentAll = false;
  11051. }
  11052. }
  11053. }
  11054. if (sentAll) {
  11055. eventQueue.eventLists_ = [];
  11056. }
  11057. eventQueue.recursionDepth_--;
  11058. }
  11059. /**
  11060. * Iterates through the list and raises each event
  11061. */
  11062. function eventListRaise(eventList) {
  11063. for (var i = 0; i < eventList.events.length; i++) {
  11064. var eventData = eventList.events[i];
  11065. if (eventData !== null) {
  11066. eventList.events[i] = null;
  11067. var eventFn = eventData.getEventRunner();
  11068. if (logger) {
  11069. log('event: ' + eventData.toString());
  11070. }
  11071. exceptionGuard(eventFn);
  11072. }
  11073. }
  11074. }
  11075. /**
  11076. * @license
  11077. * Copyright 2017 Google LLC
  11078. *
  11079. * Licensed under the Apache License, Version 2.0 (the "License");
  11080. * you may not use this file except in compliance with the License.
  11081. * You may obtain a copy of the License at
  11082. *
  11083. * http://www.apache.org/licenses/LICENSE-2.0
  11084. *
  11085. * Unless required by applicable law or agreed to in writing, software
  11086. * distributed under the License is distributed on an "AS IS" BASIS,
  11087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11088. * See the License for the specific language governing permissions and
  11089. * limitations under the License.
  11090. */
  11091. var INTERRUPT_REASON = 'repo_interrupt';
  11092. /**
  11093. * If a transaction does not succeed after 25 retries, we abort it. Among other
  11094. * things this ensure that if there's ever a bug causing a mismatch between
  11095. * client / server hashes for some data, we won't retry indefinitely.
  11096. */
  11097. var MAX_TRANSACTION_RETRIES = 25;
  11098. /**
  11099. * A connection to a single data repository.
  11100. */
  11101. var Repo = /** @class */ (function () {
  11102. function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  11103. this.repoInfo_ = repoInfo_;
  11104. this.forceRestClient_ = forceRestClient_;
  11105. this.authTokenProvider_ = authTokenProvider_;
  11106. this.appCheckProvider_ = appCheckProvider_;
  11107. this.dataUpdateCount = 0;
  11108. this.statsListener_ = null;
  11109. this.eventQueue_ = new EventQueue();
  11110. this.nextWriteId_ = 1;
  11111. this.interceptServerDataCallback_ = null;
  11112. /** A list of data pieces and paths to be set when this client disconnects. */
  11113. this.onDisconnect_ = newSparseSnapshotTree();
  11114. /** Stores queues of outstanding transactions for Firebase locations. */
  11115. this.transactionQueueTree_ = new Tree();
  11116. // TODO: This should be @private but it's used by test_access.js and internal.js
  11117. this.persistentConnection_ = null;
  11118. // This key is intentionally not updated if RepoInfo is later changed or replaced
  11119. this.key = this.repoInfo_.toURLString();
  11120. }
  11121. /**
  11122. * @returns The URL corresponding to the root of this Firebase.
  11123. */
  11124. Repo.prototype.toString = function () {
  11125. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  11126. };
  11127. return Repo;
  11128. }());
  11129. function repoStart(repo, appId, authOverride) {
  11130. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  11131. if (repo.forceRestClient_ || beingCrawled()) {
  11132. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
  11133. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11134. }, repo.authTokenProvider_, repo.appCheckProvider_);
  11135. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  11136. setTimeout(function () { return repoOnConnectStatus(repo, /* connectStatus= */ true); }, 0);
  11137. }
  11138. else {
  11139. // Validate authOverride
  11140. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  11141. if (typeof authOverride !== 'object') {
  11142. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  11143. }
  11144. try {
  11145. util.stringify(authOverride);
  11146. }
  11147. catch (e) {
  11148. throw new Error('Invalid authOverride provided: ' + e);
  11149. }
  11150. }
  11151. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
  11152. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11153. }, function (connectStatus) {
  11154. repoOnConnectStatus(repo, connectStatus);
  11155. }, function (updates) {
  11156. repoOnServerInfoUpdate(repo, updates);
  11157. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  11158. repo.server_ = repo.persistentConnection_;
  11159. }
  11160. repo.authTokenProvider_.addTokenChangeListener(function (token) {
  11161. repo.server_.refreshAuthToken(token);
  11162. });
  11163. repo.appCheckProvider_.addTokenChangeListener(function (result) {
  11164. repo.server_.refreshAppCheckToken(result.token);
  11165. });
  11166. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  11167. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  11168. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
  11169. // Used for .info.
  11170. repo.infoData_ = new SnapshotHolder();
  11171. repo.infoSyncTree_ = new SyncTree({
  11172. startListening: function (query, tag, currentHashFn, onComplete) {
  11173. var infoEvents = [];
  11174. var node = repo.infoData_.getNode(query._path);
  11175. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  11176. // on initial data...
  11177. if (!node.isEmpty()) {
  11178. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  11179. setTimeout(function () {
  11180. onComplete('ok');
  11181. }, 0);
  11182. }
  11183. return infoEvents;
  11184. },
  11185. stopListening: function () { }
  11186. });
  11187. repoUpdateInfo(repo, 'connected', false);
  11188. repo.serverSyncTree_ = new SyncTree({
  11189. startListening: function (query, tag, currentHashFn, onComplete) {
  11190. repo.server_.listen(query, currentHashFn, tag, function (status, data) {
  11191. var events = onComplete(status, data);
  11192. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11193. });
  11194. // No synchronous events for network-backed sync trees
  11195. return [];
  11196. },
  11197. stopListening: function (query, tag) {
  11198. repo.server_.unlisten(query, tag);
  11199. }
  11200. });
  11201. }
  11202. /**
  11203. * @returns The time in milliseconds, taking the server offset into account if we have one.
  11204. */
  11205. function repoServerTime(repo) {
  11206. var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  11207. var offset = offsetNode.val() || 0;
  11208. return new Date().getTime() + offset;
  11209. }
  11210. /**
  11211. * Generate ServerValues using some variables from the repo object.
  11212. */
  11213. function repoGenerateServerValues(repo) {
  11214. return generateWithValues({
  11215. timestamp: repoServerTime(repo)
  11216. });
  11217. }
  11218. /**
  11219. * Called by realtime when we get new messages from the server.
  11220. */
  11221. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  11222. // For testing.
  11223. repo.dataUpdateCount++;
  11224. var path = new Path(pathString);
  11225. data = repo.interceptServerDataCallback_
  11226. ? repo.interceptServerDataCallback_(pathString, data)
  11227. : data;
  11228. var events = [];
  11229. if (tag) {
  11230. if (isMerge) {
  11231. var taggedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11232. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  11233. }
  11234. else {
  11235. var taggedSnap = nodeFromJSON(data);
  11236. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  11237. }
  11238. }
  11239. else if (isMerge) {
  11240. var changedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11241. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  11242. }
  11243. else {
  11244. var snap = nodeFromJSON(data);
  11245. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  11246. }
  11247. var affectedPath = path;
  11248. if (events.length > 0) {
  11249. // Since we have a listener outstanding for each transaction, receiving any events
  11250. // is a proxy for some change having occurred.
  11251. affectedPath = repoRerunTransactions(repo, path);
  11252. }
  11253. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  11254. }
  11255. function repoOnConnectStatus(repo, connectStatus) {
  11256. repoUpdateInfo(repo, 'connected', connectStatus);
  11257. if (connectStatus === false) {
  11258. repoRunOnDisconnectEvents(repo);
  11259. }
  11260. }
  11261. function repoOnServerInfoUpdate(repo, updates) {
  11262. each(updates, function (key, value) {
  11263. repoUpdateInfo(repo, key, value);
  11264. });
  11265. }
  11266. function repoUpdateInfo(repo, pathString, value) {
  11267. var path = new Path('/.info/' + pathString);
  11268. var newNode = nodeFromJSON(value);
  11269. repo.infoData_.updateSnapshot(path, newNode);
  11270. var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  11271. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11272. }
  11273. function repoGetNextWriteId(repo) {
  11274. return repo.nextWriteId_++;
  11275. }
  11276. /**
  11277. * The purpose of `getValue` is to return the latest known value
  11278. * satisfying `query`.
  11279. *
  11280. * This method will first check for in-memory cached values
  11281. * belonging to active listeners. If they are found, such values
  11282. * are considered to be the most up-to-date.
  11283. *
  11284. * If the client is not connected, this method will wait until the
  11285. * repo has established a connection and then request the value for `query`.
  11286. * If the client is not able to retrieve the query result for another reason,
  11287. * it reports an error.
  11288. *
  11289. * @param query - The query to surface a value for.
  11290. */
  11291. function repoGetValue(repo, query, eventRegistration) {
  11292. // Only active queries are cached. There is no persisted cache.
  11293. var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  11294. if (cached != null) {
  11295. return Promise.resolve(cached);
  11296. }
  11297. return repo.server_.get(query).then(function (payload) {
  11298. var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  11299. /**
  11300. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  11301. * Add an event registration,
  11302. * Update data at the path,
  11303. * Raise any events,
  11304. * Cleanup the SyncTree
  11305. */
  11306. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  11307. var events;
  11308. if (query._queryParams.loadsAllData()) {
  11309. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  11310. }
  11311. else {
  11312. var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  11313. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  11314. }
  11315. /*
  11316. * We need to raise events in the scenario where `get()` is called at a parent path, and
  11317. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  11318. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  11319. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  11320. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  11321. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  11322. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  11323. * ensure the corresponding child events will get fired.
  11324. */
  11325. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11326. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  11327. return node;
  11328. }, function (err) {
  11329. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  11330. return Promise.reject(new Error(err));
  11331. });
  11332. }
  11333. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  11334. repoLog(repo, 'set', {
  11335. path: path.toString(),
  11336. value: newVal,
  11337. priority: newPriority
  11338. });
  11339. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11340. // (b) store unresolved paths on JSON parse
  11341. var serverValues = repoGenerateServerValues(repo);
  11342. var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11343. var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11344. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11345. var writeId = repoGetNextWriteId(repo);
  11346. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11347. eventQueueQueueEvents(repo.eventQueue_, events);
  11348. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {
  11349. var success = status === 'ok';
  11350. if (!success) {
  11351. warn('set at ' + path + ' failed: ' + status);
  11352. }
  11353. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11354. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11355. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11356. });
  11357. var affectedPath = repoAbortTransactions(repo, path);
  11358. repoRerunTransactions(repo, affectedPath);
  11359. // We queued the events above, so just flush the queue here
  11360. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11361. }
  11362. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11363. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11364. // Start with our existing data and merge each child into it.
  11365. var empty = true;
  11366. var serverValues = repoGenerateServerValues(repo);
  11367. var changedChildren = {};
  11368. each(childrenToMerge, function (changedKey, changedValue) {
  11369. empty = false;
  11370. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11371. });
  11372. if (!empty) {
  11373. var writeId_1 = repoGetNextWriteId(repo);
  11374. var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
  11375. eventQueueQueueEvents(repo.eventQueue_, events);
  11376. repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
  11377. var success = status === 'ok';
  11378. if (!success) {
  11379. warn('update at ' + path + ' failed: ' + status);
  11380. }
  11381. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
  11382. var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11383. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11384. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11385. });
  11386. each(childrenToMerge, function (changedPath) {
  11387. var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11388. repoRerunTransactions(repo, affectedPath);
  11389. });
  11390. // We queued the events above, so just flush the queue here
  11391. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11392. }
  11393. else {
  11394. log("update() called with empty data. Don't do anything.");
  11395. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11396. }
  11397. }
  11398. /**
  11399. * Applies all of the changes stored up in the onDisconnect_ tree.
  11400. */
  11401. function repoRunOnDisconnectEvents(repo) {
  11402. repoLog(repo, 'onDisconnectEvents');
  11403. var serverValues = repoGenerateServerValues(repo);
  11404. var resolvedOnDisconnectTree = newSparseSnapshotTree();
  11405. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
  11406. var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11407. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11408. });
  11409. var events = [];
  11410. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
  11411. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11412. var affectedPath = repoAbortTransactions(repo, path);
  11413. repoRerunTransactions(repo, affectedPath);
  11414. });
  11415. repo.onDisconnect_ = newSparseSnapshotTree();
  11416. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11417. }
  11418. function repoOnDisconnectCancel(repo, path, onComplete) {
  11419. repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
  11420. if (status === 'ok') {
  11421. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11422. }
  11423. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11424. });
  11425. }
  11426. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11427. var newNode = nodeFromJSON(value);
  11428. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11429. if (status === 'ok') {
  11430. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11431. }
  11432. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11433. });
  11434. }
  11435. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11436. var newNode = nodeFromJSON(value, priority);
  11437. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11438. if (status === 'ok') {
  11439. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11440. }
  11441. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11442. });
  11443. }
  11444. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11445. if (util.isEmpty(childrenToMerge)) {
  11446. log("onDisconnect().update() called with empty data. Don't do anything.");
  11447. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11448. return;
  11449. }
  11450. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
  11451. if (status === 'ok') {
  11452. each(childrenToMerge, function (childName, childNode) {
  11453. var newChildNode = nodeFromJSON(childNode);
  11454. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11455. });
  11456. }
  11457. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11458. });
  11459. }
  11460. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11461. var events;
  11462. if (pathGetFront(query._path) === '.info') {
  11463. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11464. }
  11465. else {
  11466. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11467. }
  11468. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11469. }
  11470. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11471. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11472. // a little bit by handling the return values anyways.
  11473. var events;
  11474. if (pathGetFront(query._path) === '.info') {
  11475. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11476. }
  11477. else {
  11478. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11479. }
  11480. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11481. }
  11482. function repoInterrupt(repo) {
  11483. if (repo.persistentConnection_) {
  11484. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11485. }
  11486. }
  11487. function repoResume(repo) {
  11488. if (repo.persistentConnection_) {
  11489. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11490. }
  11491. }
  11492. function repoLog(repo) {
  11493. var varArgs = [];
  11494. for (var _i = 1; _i < arguments.length; _i++) {
  11495. varArgs[_i - 1] = arguments[_i];
  11496. }
  11497. var prefix = '';
  11498. if (repo.persistentConnection_) {
  11499. prefix = repo.persistentConnection_.id + ':';
  11500. }
  11501. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  11502. }
  11503. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11504. if (callback) {
  11505. exceptionGuard(function () {
  11506. if (status === 'ok') {
  11507. callback(null);
  11508. }
  11509. else {
  11510. var code = (status || 'error').toUpperCase();
  11511. var message = code;
  11512. if (errorReason) {
  11513. message += ': ' + errorReason;
  11514. }
  11515. var error = new Error(message);
  11516. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11517. error.code = code;
  11518. callback(error);
  11519. }
  11520. });
  11521. }
  11522. }
  11523. /**
  11524. * Creates a new transaction, adds it to the transactions we're tracking, and
  11525. * sends it to the server if possible.
  11526. *
  11527. * @param path - Path at which to do transaction.
  11528. * @param transactionUpdate - Update callback.
  11529. * @param onComplete - Completion callback.
  11530. * @param unwatcher - Function that will be called when the transaction no longer
  11531. * need data updates for `path`.
  11532. * @param applyLocally - Whether or not to make intermediate results visible
  11533. */
  11534. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11535. repoLog(repo, 'transaction on ' + path);
  11536. // Initialize transaction.
  11537. var transaction = {
  11538. path: path,
  11539. update: transactionUpdate,
  11540. onComplete: onComplete,
  11541. // One of TransactionStatus enums.
  11542. status: null,
  11543. // Used when combining transactions at different locations to figure out
  11544. // which one goes first.
  11545. order: LUIDGenerator(),
  11546. // Whether to raise local events for this transaction.
  11547. applyLocally: applyLocally,
  11548. // Count of how many times we've retried the transaction.
  11549. retryCount: 0,
  11550. // Function to call to clean up our .on() listener.
  11551. unwatcher: unwatcher,
  11552. // Stores why a transaction was aborted.
  11553. abortReason: null,
  11554. currentWriteId: null,
  11555. currentInputSnapshot: null,
  11556. currentOutputSnapshotRaw: null,
  11557. currentOutputSnapshotResolved: null
  11558. };
  11559. // Run transaction initially.
  11560. var currentState = repoGetLatestState(repo, path, undefined);
  11561. transaction.currentInputSnapshot = currentState;
  11562. var newVal = transaction.update(currentState.val());
  11563. if (newVal === undefined) {
  11564. // Abort transaction.
  11565. transaction.unwatcher();
  11566. transaction.currentOutputSnapshotRaw = null;
  11567. transaction.currentOutputSnapshotResolved = null;
  11568. if (transaction.onComplete) {
  11569. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11570. }
  11571. }
  11572. else {
  11573. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11574. // Mark as run and add to our queue.
  11575. transaction.status = 0 /* TransactionStatus.RUN */;
  11576. var queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11577. var nodeQueue = treeGetValue(queueNode) || [];
  11578. nodeQueue.push(transaction);
  11579. treeSetValue(queueNode, nodeQueue);
  11580. // Update visibleData and raise events
  11581. // Note: We intentionally raise events after updating all of our
  11582. // transaction state, since the user could start new transactions from the
  11583. // event callbacks.
  11584. var priorityForNode = void 0;
  11585. if (typeof newVal === 'object' &&
  11586. newVal !== null &&
  11587. util.contains(newVal, '.priority')) {
  11588. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11589. priorityForNode = util.safeGet(newVal, '.priority');
  11590. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11591. 'Priority must be a valid string, finite number, server value, or null.');
  11592. }
  11593. else {
  11594. var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11595. ChildrenNode.EMPTY_NODE;
  11596. priorityForNode = currentNode.getPriority().val();
  11597. }
  11598. var serverValues = repoGenerateServerValues(repo);
  11599. var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11600. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11601. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11602. transaction.currentOutputSnapshotResolved = newNode;
  11603. transaction.currentWriteId = repoGetNextWriteId(repo);
  11604. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11605. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11606. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11607. }
  11608. }
  11609. /**
  11610. * @param excludeSets - A specific set to exclude
  11611. */
  11612. function repoGetLatestState(repo, path, excludeSets) {
  11613. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11614. ChildrenNode.EMPTY_NODE);
  11615. }
  11616. /**
  11617. * Sends any already-run transactions that aren't waiting for outstanding
  11618. * transactions to complete.
  11619. *
  11620. * Externally it's called with no arguments, but it calls itself recursively
  11621. * with a particular transactionQueueTree node to recurse through the tree.
  11622. *
  11623. * @param node - transactionQueueTree node to start at.
  11624. */
  11625. function repoSendReadyTransactions(repo, node) {
  11626. if (node === void 0) { node = repo.transactionQueueTree_; }
  11627. // Before recursing, make sure any completed transactions are removed.
  11628. if (!node) {
  11629. repoPruneCompletedTransactionsBelowNode(repo, node);
  11630. }
  11631. if (treeGetValue(node)) {
  11632. var queue = repoBuildTransactionQueue(repo, node);
  11633. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  11634. var allRun = queue.every(function (transaction) { return transaction.status === 0 /* TransactionStatus.RUN */; });
  11635. // If they're all run (and not sent), we can send them. Else, we must wait.
  11636. if (allRun) {
  11637. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11638. }
  11639. }
  11640. else if (treeHasChildren(node)) {
  11641. treeForEachChild(node, function (childNode) {
  11642. repoSendReadyTransactions(repo, childNode);
  11643. });
  11644. }
  11645. }
  11646. /**
  11647. * Given a list of run transactions, send them to the server and then handle
  11648. * the result (success or failure).
  11649. *
  11650. * @param path - The location of the queue.
  11651. * @param queue - Queue of transactions under the specified location.
  11652. */
  11653. function repoSendTransactionQueue(repo, path, queue) {
  11654. // Mark transactions as sent and increment retry count!
  11655. var setsToIgnore = queue.map(function (txn) {
  11656. return txn.currentWriteId;
  11657. });
  11658. var latestState = repoGetLatestState(repo, path, setsToIgnore);
  11659. var snapToSend = latestState;
  11660. var latestHash = latestState.hash();
  11661. for (var i = 0; i < queue.length; i++) {
  11662. var txn = queue[i];
  11663. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11664. txn.status = 1 /* TransactionStatus.SENT */;
  11665. txn.retryCount++;
  11666. var relativePath = newRelativePath(path, txn.path);
  11667. // If we've gotten to this point, the output snapshot must be defined.
  11668. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11669. }
  11670. var dataToSend = snapToSend.val(true);
  11671. var pathToSend = path;
  11672. // Send the put.
  11673. repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
  11674. repoLog(repo, 'transaction put response', {
  11675. path: pathToSend.toString(),
  11676. status: status
  11677. });
  11678. var events = [];
  11679. if (status === 'ok') {
  11680. // Queue up the callbacks and fire them after cleaning up all of our
  11681. // transaction state, since the callback could trigger more
  11682. // transactions or sets.
  11683. var callbacks = [];
  11684. var _loop_1 = function (i) {
  11685. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11686. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11687. if (queue[i].onComplete) {
  11688. // We never unset the output snapshot, and given that this
  11689. // transaction is complete, it should be set
  11690. callbacks.push(function () {
  11691. return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
  11692. });
  11693. }
  11694. queue[i].unwatcher();
  11695. };
  11696. for (var i = 0; i < queue.length; i++) {
  11697. _loop_1(i);
  11698. }
  11699. // Now remove the completed transactions.
  11700. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11701. // There may be pending transactions that we can now send.
  11702. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11703. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11704. // Finally, trigger onComplete callbacks.
  11705. for (var i = 0; i < callbacks.length; i++) {
  11706. exceptionGuard(callbacks[i]);
  11707. }
  11708. }
  11709. else {
  11710. // transactions are no longer sent. Update their status appropriately.
  11711. if (status === 'datastale') {
  11712. for (var i = 0; i < queue.length; i++) {
  11713. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11714. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11715. }
  11716. else {
  11717. queue[i].status = 0 /* TransactionStatus.RUN */;
  11718. }
  11719. }
  11720. }
  11721. else {
  11722. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11723. for (var i = 0; i < queue.length; i++) {
  11724. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11725. queue[i].abortReason = status;
  11726. }
  11727. }
  11728. repoRerunTransactions(repo, path);
  11729. }
  11730. }, latestHash);
  11731. }
  11732. /**
  11733. * Finds all transactions dependent on the data at changedPath and reruns them.
  11734. *
  11735. * Should be called any time cached data changes.
  11736. *
  11737. * Return the highest path that was affected by rerunning transactions. This
  11738. * is the path at which events need to be raised for.
  11739. *
  11740. * @param changedPath - The path in mergedData that changed.
  11741. * @returns The rootmost path that was affected by rerunning transactions.
  11742. */
  11743. function repoRerunTransactions(repo, changedPath) {
  11744. var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11745. var path = treeGetPath(rootMostTransactionNode);
  11746. var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11747. repoRerunTransactionQueue(repo, queue, path);
  11748. return path;
  11749. }
  11750. /**
  11751. * Does all the work of rerunning transactions (as well as cleans up aborted
  11752. * transactions and whatnot).
  11753. *
  11754. * @param queue - The queue of transactions to run.
  11755. * @param path - The path the queue is for.
  11756. */
  11757. function repoRerunTransactionQueue(repo, queue, path) {
  11758. if (queue.length === 0) {
  11759. return; // Nothing to do!
  11760. }
  11761. // Queue up the callbacks and fire them after cleaning up all of our
  11762. // transaction state, since the callback could trigger more transactions or
  11763. // sets.
  11764. var callbacks = [];
  11765. var events = [];
  11766. // Ignore all of the sets we're going to re-run.
  11767. var txnsToRerun = queue.filter(function (q) {
  11768. return q.status === 0 /* TransactionStatus.RUN */;
  11769. });
  11770. var setsToIgnore = txnsToRerun.map(function (q) {
  11771. return q.currentWriteId;
  11772. });
  11773. var _loop_2 = function (i) {
  11774. var transaction = queue[i];
  11775. var relativePath = newRelativePath(path, transaction.path);
  11776. var abortTransaction = false, abortReason;
  11777. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11778. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11779. abortTransaction = true;
  11780. abortReason = transaction.abortReason;
  11781. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11782. }
  11783. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11784. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11785. abortTransaction = true;
  11786. abortReason = 'maxretry';
  11787. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11788. }
  11789. else {
  11790. // This code reruns a transaction
  11791. var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11792. transaction.currentInputSnapshot = currentNode;
  11793. var newData = queue[i].update(currentNode.val());
  11794. if (newData !== undefined) {
  11795. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11796. var newDataNode = nodeFromJSON(newData);
  11797. var hasExplicitPriority = typeof newData === 'object' &&
  11798. newData != null &&
  11799. util.contains(newData, '.priority');
  11800. if (!hasExplicitPriority) {
  11801. // Keep the old priority if there wasn't a priority explicitly specified.
  11802. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11803. }
  11804. var oldWriteId = transaction.currentWriteId;
  11805. var serverValues = repoGenerateServerValues(repo);
  11806. var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11807. transaction.currentOutputSnapshotRaw = newDataNode;
  11808. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11809. transaction.currentWriteId = repoGetNextWriteId(repo);
  11810. // Mutates setsToIgnore in place
  11811. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11812. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11813. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11814. }
  11815. else {
  11816. abortTransaction = true;
  11817. abortReason = 'nodata';
  11818. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11819. }
  11820. }
  11821. }
  11822. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11823. events = [];
  11824. if (abortTransaction) {
  11825. // Abort.
  11826. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11827. // Removing a listener can trigger pruning which can muck with
  11828. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11829. // until we're done.
  11830. (function (unwatcher) {
  11831. setTimeout(unwatcher, Math.floor(0));
  11832. })(queue[i].unwatcher);
  11833. if (queue[i].onComplete) {
  11834. if (abortReason === 'nodata') {
  11835. callbacks.push(function () {
  11836. return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
  11837. });
  11838. }
  11839. else {
  11840. callbacks.push(function () {
  11841. return queue[i].onComplete(new Error(abortReason), false, null);
  11842. });
  11843. }
  11844. }
  11845. }
  11846. };
  11847. for (var i = 0; i < queue.length; i++) {
  11848. _loop_2(i);
  11849. }
  11850. // Clean up completed transactions.
  11851. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11852. // Now fire callbacks, now that we're in a good, known state.
  11853. for (var i = 0; i < callbacks.length; i++) {
  11854. exceptionGuard(callbacks[i]);
  11855. }
  11856. // Try to send the transaction result to the server.
  11857. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11858. }
  11859. /**
  11860. * Returns the rootmost ancestor node of the specified path that has a pending
  11861. * transaction on it, or just returns the node for the given path if there are
  11862. * no pending transactions on any ancestor.
  11863. *
  11864. * @param path - The location to start at.
  11865. * @returns The rootmost node with a transaction.
  11866. */
  11867. function repoGetAncestorTransactionNode(repo, path) {
  11868. var front;
  11869. // Start at the root and walk deeper into the tree towards path until we
  11870. // find a node with pending transactions.
  11871. var transactionNode = repo.transactionQueueTree_;
  11872. front = pathGetFront(path);
  11873. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11874. transactionNode = treeSubTree(transactionNode, front);
  11875. path = pathPopFront(path);
  11876. front = pathGetFront(path);
  11877. }
  11878. return transactionNode;
  11879. }
  11880. /**
  11881. * Builds the queue of all transactions at or below the specified
  11882. * transactionNode.
  11883. *
  11884. * @param transactionNode
  11885. * @returns The generated queue.
  11886. */
  11887. function repoBuildTransactionQueue(repo, transactionNode) {
  11888. // Walk any child transaction queues and aggregate them into a single queue.
  11889. var transactionQueue = [];
  11890. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11891. // Sort them by the order the transactions were created.
  11892. transactionQueue.sort(function (a, b) { return a.order - b.order; });
  11893. return transactionQueue;
  11894. }
  11895. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11896. var nodeQueue = treeGetValue(node);
  11897. if (nodeQueue) {
  11898. for (var i = 0; i < nodeQueue.length; i++) {
  11899. queue.push(nodeQueue[i]);
  11900. }
  11901. }
  11902. treeForEachChild(node, function (child) {
  11903. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11904. });
  11905. }
  11906. /**
  11907. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11908. */
  11909. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11910. var queue = treeGetValue(node);
  11911. if (queue) {
  11912. var to = 0;
  11913. for (var from = 0; from < queue.length; from++) {
  11914. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11915. queue[to] = queue[from];
  11916. to++;
  11917. }
  11918. }
  11919. queue.length = to;
  11920. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11921. }
  11922. treeForEachChild(node, function (childNode) {
  11923. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11924. });
  11925. }
  11926. /**
  11927. * Aborts all transactions on ancestors or descendants of the specified path.
  11928. * Called when doing a set() or update() since we consider them incompatible
  11929. * with transactions.
  11930. *
  11931. * @param path - Path for which we want to abort related transactions.
  11932. */
  11933. function repoAbortTransactions(repo, path) {
  11934. var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11935. var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11936. treeForEachAncestor(transactionNode, function (node) {
  11937. repoAbortTransactionsOnNode(repo, node);
  11938. });
  11939. repoAbortTransactionsOnNode(repo, transactionNode);
  11940. treeForEachDescendant(transactionNode, function (node) {
  11941. repoAbortTransactionsOnNode(repo, node);
  11942. });
  11943. return affectedPath;
  11944. }
  11945. /**
  11946. * Abort transactions stored in this transaction queue node.
  11947. *
  11948. * @param node - Node to abort transactions for.
  11949. */
  11950. function repoAbortTransactionsOnNode(repo, node) {
  11951. var queue = treeGetValue(node);
  11952. if (queue) {
  11953. // Queue up the callbacks and fire them after cleaning up all of our
  11954. // transaction state, since the callback could trigger more transactions
  11955. // or sets.
  11956. var callbacks = [];
  11957. // Go through queue. Any already-sent transactions must be marked for
  11958. // abort, while the unsent ones can be immediately aborted and removed.
  11959. var events = [];
  11960. var lastSent = -1;
  11961. for (var i = 0; i < queue.length; i++) {
  11962. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11963. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11964. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11965. lastSent = i;
  11966. // Mark transaction for abort when it comes back.
  11967. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11968. queue[i].abortReason = 'set';
  11969. }
  11970. else {
  11971. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11972. // We can abort it immediately.
  11973. queue[i].unwatcher();
  11974. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11975. if (queue[i].onComplete) {
  11976. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11977. }
  11978. }
  11979. }
  11980. if (lastSent === -1) {
  11981. // We're not waiting for any sent transactions. We can clear the queue.
  11982. treeSetValue(node, undefined);
  11983. }
  11984. else {
  11985. // Remove the transactions we aborted.
  11986. queue.length = lastSent + 1;
  11987. }
  11988. // Now fire the callbacks.
  11989. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11990. for (var i = 0; i < callbacks.length; i++) {
  11991. exceptionGuard(callbacks[i]);
  11992. }
  11993. }
  11994. }
  11995. /**
  11996. * @license
  11997. * Copyright 2017 Google LLC
  11998. *
  11999. * Licensed under the Apache License, Version 2.0 (the "License");
  12000. * you may not use this file except in compliance with the License.
  12001. * You may obtain a copy of the License at
  12002. *
  12003. * http://www.apache.org/licenses/LICENSE-2.0
  12004. *
  12005. * Unless required by applicable law or agreed to in writing, software
  12006. * distributed under the License is distributed on an "AS IS" BASIS,
  12007. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12008. * See the License for the specific language governing permissions and
  12009. * limitations under the License.
  12010. */
  12011. function decodePath(pathString) {
  12012. var pathStringDecoded = '';
  12013. var pieces = pathString.split('/');
  12014. for (var i = 0; i < pieces.length; i++) {
  12015. if (pieces[i].length > 0) {
  12016. var piece = pieces[i];
  12017. try {
  12018. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  12019. }
  12020. catch (e) { }
  12021. pathStringDecoded += '/' + piece;
  12022. }
  12023. }
  12024. return pathStringDecoded;
  12025. }
  12026. /**
  12027. * @returns key value hash
  12028. */
  12029. function decodeQuery(queryString) {
  12030. var e_1, _a;
  12031. var results = {};
  12032. if (queryString.charAt(0) === '?') {
  12033. queryString = queryString.substring(1);
  12034. }
  12035. try {
  12036. for (var _b = tslib.__values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
  12037. var segment = _c.value;
  12038. if (segment.length === 0) {
  12039. continue;
  12040. }
  12041. var kv = segment.split('=');
  12042. if (kv.length === 2) {
  12043. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  12044. }
  12045. else {
  12046. warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
  12047. }
  12048. }
  12049. }
  12050. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  12051. finally {
  12052. try {
  12053. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12054. }
  12055. finally { if (e_1) throw e_1.error; }
  12056. }
  12057. return results;
  12058. }
  12059. var parseRepoInfo = function (dataURL, nodeAdmin) {
  12060. var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  12061. if (parsedUrl.domain === 'firebase.com') {
  12062. fatal(parsedUrl.host +
  12063. ' is no longer supported. ' +
  12064. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  12065. }
  12066. // Catch common error of uninitialized namespace value.
  12067. if ((!namespace || namespace === 'undefined') &&
  12068. parsedUrl.domain !== 'localhost') {
  12069. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  12070. }
  12071. if (!parsedUrl.secure) {
  12072. warnIfPageIsSecure();
  12073. }
  12074. var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  12075. return {
  12076. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  12077. /*persistenceKey=*/ '',
  12078. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  12079. path: new Path(parsedUrl.pathString)
  12080. };
  12081. };
  12082. var parseDatabaseURL = function (dataURL) {
  12083. // Default to empty strings in the event of a malformed string.
  12084. var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  12085. // Always default to SSL, unless otherwise specified.
  12086. var secure = true, scheme = 'https', port = 443;
  12087. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  12088. if (typeof dataURL === 'string') {
  12089. // Parse scheme.
  12090. var colonInd = dataURL.indexOf('//');
  12091. if (colonInd >= 0) {
  12092. scheme = dataURL.substring(0, colonInd - 1);
  12093. dataURL = dataURL.substring(colonInd + 2);
  12094. }
  12095. // Parse host, path, and query string.
  12096. var slashInd = dataURL.indexOf('/');
  12097. if (slashInd === -1) {
  12098. slashInd = dataURL.length;
  12099. }
  12100. var questionMarkInd = dataURL.indexOf('?');
  12101. if (questionMarkInd === -1) {
  12102. questionMarkInd = dataURL.length;
  12103. }
  12104. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  12105. if (slashInd < questionMarkInd) {
  12106. // For pathString, questionMarkInd will always come after slashInd
  12107. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  12108. }
  12109. var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  12110. // If we have a port, use scheme for determining if it's secure.
  12111. colonInd = host.indexOf(':');
  12112. if (colonInd >= 0) {
  12113. secure = scheme === 'https' || scheme === 'wss';
  12114. port = parseInt(host.substring(colonInd + 1), 10);
  12115. }
  12116. else {
  12117. colonInd = host.length;
  12118. }
  12119. var hostWithoutPort = host.slice(0, colonInd);
  12120. if (hostWithoutPort.toLowerCase() === 'localhost') {
  12121. domain = 'localhost';
  12122. }
  12123. else if (hostWithoutPort.split('.').length <= 2) {
  12124. domain = hostWithoutPort;
  12125. }
  12126. else {
  12127. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  12128. var dotInd = host.indexOf('.');
  12129. subdomain = host.substring(0, dotInd).toLowerCase();
  12130. domain = host.substring(dotInd + 1);
  12131. // Normalize namespaces to lowercase to share storage / connection.
  12132. namespace = subdomain;
  12133. }
  12134. // Always treat the value of the `ns` as the namespace name if it is present.
  12135. if ('ns' in queryParams) {
  12136. namespace = queryParams['ns'];
  12137. }
  12138. }
  12139. return {
  12140. host: host,
  12141. port: port,
  12142. domain: domain,
  12143. subdomain: subdomain,
  12144. secure: secure,
  12145. scheme: scheme,
  12146. pathString: pathString,
  12147. namespace: namespace
  12148. };
  12149. };
  12150. /**
  12151. * @license
  12152. * Copyright 2017 Google LLC
  12153. *
  12154. * Licensed under the Apache License, Version 2.0 (the "License");
  12155. * you may not use this file except in compliance with the License.
  12156. * You may obtain a copy of the License at
  12157. *
  12158. * http://www.apache.org/licenses/LICENSE-2.0
  12159. *
  12160. * Unless required by applicable law or agreed to in writing, software
  12161. * distributed under the License is distributed on an "AS IS" BASIS,
  12162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12163. * See the License for the specific language governing permissions and
  12164. * limitations under the License.
  12165. */
  12166. // Modeled after base64 web-safe chars, but ordered by ASCII.
  12167. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  12168. /**
  12169. * Fancy ID generator that creates 20-character string identifiers with the
  12170. * following properties:
  12171. *
  12172. * 1. They're based on timestamp so that they sort *after* any existing ids.
  12173. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  12174. * collide with other clients' IDs.
  12175. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  12176. * that will sort properly).
  12177. * 4. They're monotonically increasing. Even if you generate more than one in
  12178. * the same timestamp, the latter ones will sort after the former ones. We do
  12179. * this by using the previous random bits but "incrementing" them by 1 (only
  12180. * in the case of a timestamp collision).
  12181. */
  12182. var nextPushId = (function () {
  12183. // Timestamp of last push, used to prevent local collisions if you push twice
  12184. // in one ms.
  12185. var lastPushTime = 0;
  12186. // We generate 72-bits of randomness which get turned into 12 characters and
  12187. // appended to the timestamp to prevent collisions with other clients. We
  12188. // store the last characters we generated because in the event of a collision,
  12189. // we'll use those same characters except "incremented" by one.
  12190. var lastRandChars = [];
  12191. return function (now) {
  12192. var duplicateTime = now === lastPushTime;
  12193. lastPushTime = now;
  12194. var i;
  12195. var timeStampChars = new Array(8);
  12196. for (i = 7; i >= 0; i--) {
  12197. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  12198. // NOTE: Can't use << here because javascript will convert to int and lose
  12199. // the upper bits.
  12200. now = Math.floor(now / 64);
  12201. }
  12202. util.assert(now === 0, 'Cannot push at time == 0');
  12203. var id = timeStampChars.join('');
  12204. if (!duplicateTime) {
  12205. for (i = 0; i < 12; i++) {
  12206. lastRandChars[i] = Math.floor(Math.random() * 64);
  12207. }
  12208. }
  12209. else {
  12210. // If the timestamp hasn't changed since last push, use the same random
  12211. // number, except incremented by 1.
  12212. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  12213. lastRandChars[i] = 0;
  12214. }
  12215. lastRandChars[i]++;
  12216. }
  12217. for (i = 0; i < 12; i++) {
  12218. id += PUSH_CHARS.charAt(lastRandChars[i]);
  12219. }
  12220. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  12221. return id;
  12222. };
  12223. })();
  12224. /**
  12225. * @license
  12226. * Copyright 2017 Google LLC
  12227. *
  12228. * Licensed under the Apache License, Version 2.0 (the "License");
  12229. * you may not use this file except in compliance with the License.
  12230. * You may obtain a copy of the License at
  12231. *
  12232. * http://www.apache.org/licenses/LICENSE-2.0
  12233. *
  12234. * Unless required by applicable law or agreed to in writing, software
  12235. * distributed under the License is distributed on an "AS IS" BASIS,
  12236. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12237. * See the License for the specific language governing permissions and
  12238. * limitations under the License.
  12239. */
  12240. /**
  12241. * Encapsulates the data needed to raise an event
  12242. */
  12243. var DataEvent = /** @class */ (function () {
  12244. /**
  12245. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  12246. * @param eventRegistration - The function to call to with the event data. User provided
  12247. * @param snapshot - The data backing the event
  12248. * @param prevName - Optional, the name of the previous child for child_* events.
  12249. */
  12250. function DataEvent(eventType, eventRegistration, snapshot, prevName) {
  12251. this.eventType = eventType;
  12252. this.eventRegistration = eventRegistration;
  12253. this.snapshot = snapshot;
  12254. this.prevName = prevName;
  12255. }
  12256. DataEvent.prototype.getPath = function () {
  12257. var ref = this.snapshot.ref;
  12258. if (this.eventType === 'value') {
  12259. return ref._path;
  12260. }
  12261. else {
  12262. return ref.parent._path;
  12263. }
  12264. };
  12265. DataEvent.prototype.getEventType = function () {
  12266. return this.eventType;
  12267. };
  12268. DataEvent.prototype.getEventRunner = function () {
  12269. return this.eventRegistration.getEventRunner(this);
  12270. };
  12271. DataEvent.prototype.toString = function () {
  12272. return (this.getPath().toString() +
  12273. ':' +
  12274. this.eventType +
  12275. ':' +
  12276. util.stringify(this.snapshot.exportVal()));
  12277. };
  12278. return DataEvent;
  12279. }());
  12280. var CancelEvent = /** @class */ (function () {
  12281. function CancelEvent(eventRegistration, error, path) {
  12282. this.eventRegistration = eventRegistration;
  12283. this.error = error;
  12284. this.path = path;
  12285. }
  12286. CancelEvent.prototype.getPath = function () {
  12287. return this.path;
  12288. };
  12289. CancelEvent.prototype.getEventType = function () {
  12290. return 'cancel';
  12291. };
  12292. CancelEvent.prototype.getEventRunner = function () {
  12293. return this.eventRegistration.getEventRunner(this);
  12294. };
  12295. CancelEvent.prototype.toString = function () {
  12296. return this.path.toString() + ':cancel';
  12297. };
  12298. return CancelEvent;
  12299. }());
  12300. /**
  12301. * @license
  12302. * Copyright 2017 Google LLC
  12303. *
  12304. * Licensed under the Apache License, Version 2.0 (the "License");
  12305. * you may not use this file except in compliance with the License.
  12306. * You may obtain a copy of the License at
  12307. *
  12308. * http://www.apache.org/licenses/LICENSE-2.0
  12309. *
  12310. * Unless required by applicable law or agreed to in writing, software
  12311. * distributed under the License is distributed on an "AS IS" BASIS,
  12312. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12313. * See the License for the specific language governing permissions and
  12314. * limitations under the License.
  12315. */
  12316. /**
  12317. * A wrapper class that converts events from the database@exp SDK to the legacy
  12318. * Database SDK. Events are not converted directly as event registration relies
  12319. * on reference comparison of the original user callback (see `matches()`) and
  12320. * relies on equality of the legacy SDK's `context` object.
  12321. */
  12322. var CallbackContext = /** @class */ (function () {
  12323. function CallbackContext(snapshotCallback, cancelCallback) {
  12324. this.snapshotCallback = snapshotCallback;
  12325. this.cancelCallback = cancelCallback;
  12326. }
  12327. CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
  12328. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  12329. };
  12330. CallbackContext.prototype.onCancel = function (error) {
  12331. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  12332. return this.cancelCallback.call(null, error);
  12333. };
  12334. Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
  12335. get: function () {
  12336. return !!this.cancelCallback;
  12337. },
  12338. enumerable: false,
  12339. configurable: true
  12340. });
  12341. CallbackContext.prototype.matches = function (other) {
  12342. return (this.snapshotCallback === other.snapshotCallback ||
  12343. (this.snapshotCallback.userCallback !== undefined &&
  12344. this.snapshotCallback.userCallback ===
  12345. other.snapshotCallback.userCallback &&
  12346. this.snapshotCallback.context === other.snapshotCallback.context));
  12347. };
  12348. return CallbackContext;
  12349. }());
  12350. /**
  12351. * @license
  12352. * Copyright 2021 Google LLC
  12353. *
  12354. * Licensed under the Apache License, Version 2.0 (the "License");
  12355. * you may not use this file except in compliance with the License.
  12356. * You may obtain a copy of the License at
  12357. *
  12358. * http://www.apache.org/licenses/LICENSE-2.0
  12359. *
  12360. * Unless required by applicable law or agreed to in writing, software
  12361. * distributed under the License is distributed on an "AS IS" BASIS,
  12362. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12363. * See the License for the specific language governing permissions and
  12364. * limitations under the License.
  12365. */
  12366. /**
  12367. * The `onDisconnect` class allows you to write or clear data when your client
  12368. * disconnects from the Database server. These updates occur whether your
  12369. * client disconnects cleanly or not, so you can rely on them to clean up data
  12370. * even if a connection is dropped or a client crashes.
  12371. *
  12372. * The `onDisconnect` class is most commonly used to manage presence in
  12373. * applications where it is useful to detect how many clients are connected and
  12374. * when other clients disconnect. See
  12375. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12376. * for more information.
  12377. *
  12378. * To avoid problems when a connection is dropped before the requests can be
  12379. * transferred to the Database server, these functions should be called before
  12380. * writing any data.
  12381. *
  12382. * Note that `onDisconnect` operations are only triggered once. If you want an
  12383. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12384. * the `onDisconnect` operations each time you reconnect.
  12385. */
  12386. var OnDisconnect = /** @class */ (function () {
  12387. /** @hideconstructor */
  12388. function OnDisconnect(_repo, _path) {
  12389. this._repo = _repo;
  12390. this._path = _path;
  12391. }
  12392. /**
  12393. * Cancels all previously queued `onDisconnect()` set or update events for this
  12394. * location and all children.
  12395. *
  12396. * If a write has been queued for this location via a `set()` or `update()` at a
  12397. * parent location, the write at this location will be canceled, though writes
  12398. * to sibling locations will still occur.
  12399. *
  12400. * @returns Resolves when synchronization to the server is complete.
  12401. */
  12402. OnDisconnect.prototype.cancel = function () {
  12403. var deferred = new util.Deferred();
  12404. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
  12405. return deferred.promise;
  12406. };
  12407. /**
  12408. * Ensures the data at this location is deleted when the client is disconnected
  12409. * (due to closing the browser, navigating to a new page, or network issues).
  12410. *
  12411. * @returns Resolves when synchronization to the server is complete.
  12412. */
  12413. OnDisconnect.prototype.remove = function () {
  12414. validateWritablePath('OnDisconnect.remove', this._path);
  12415. var deferred = new util.Deferred();
  12416. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
  12417. return deferred.promise;
  12418. };
  12419. /**
  12420. * Ensures the data at this location is set to the specified value when the
  12421. * client is disconnected (due to closing the browser, navigating to a new page,
  12422. * or network issues).
  12423. *
  12424. * `set()` is especially useful for implementing "presence" systems, where a
  12425. * value should be changed or cleared when a user disconnects so that they
  12426. * appear "offline" to other users. See
  12427. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12428. * for more information.
  12429. *
  12430. * Note that `onDisconnect` operations are only triggered once. If you want an
  12431. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12432. * the `onDisconnect` operations each time.
  12433. *
  12434. * @param value - The value to be written to this location on disconnect (can
  12435. * be an object, array, string, number, boolean, or null).
  12436. * @returns Resolves when synchronization to the Database is complete.
  12437. */
  12438. OnDisconnect.prototype.set = function (value) {
  12439. validateWritablePath('OnDisconnect.set', this._path);
  12440. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12441. var deferred = new util.Deferred();
  12442. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
  12443. return deferred.promise;
  12444. };
  12445. /**
  12446. * Ensures the data at this location is set to the specified value and priority
  12447. * when the client is disconnected (due to closing the browser, navigating to a
  12448. * new page, or network issues).
  12449. *
  12450. * @param value - The value to be written to this location on disconnect (can
  12451. * be an object, array, string, number, boolean, or null).
  12452. * @param priority - The priority to be written (string, number, or null).
  12453. * @returns Resolves when synchronization to the Database is complete.
  12454. */
  12455. OnDisconnect.prototype.setWithPriority = function (value, priority) {
  12456. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12457. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12458. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12459. var deferred = new util.Deferred();
  12460. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
  12461. return deferred.promise;
  12462. };
  12463. /**
  12464. * Writes multiple values at this location when the client is disconnected (due
  12465. * to closing the browser, navigating to a new page, or network issues).
  12466. *
  12467. * The `values` argument contains multiple property-value pairs that will be
  12468. * written to the Database together. Each child property can either be a simple
  12469. * property (for example, "name") or a relative path (for example, "name/first")
  12470. * from the current location to the data to update.
  12471. *
  12472. * As opposed to the `set()` method, `update()` can be use to selectively update
  12473. * only the referenced properties at the current location (instead of replacing
  12474. * all the child properties at the current location).
  12475. *
  12476. * @param values - Object containing multiple values.
  12477. * @returns Resolves when synchronization to the Database is complete.
  12478. */
  12479. OnDisconnect.prototype.update = function (values) {
  12480. validateWritablePath('OnDisconnect.update', this._path);
  12481. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12482. var deferred = new util.Deferred();
  12483. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
  12484. return deferred.promise;
  12485. };
  12486. return OnDisconnect;
  12487. }());
  12488. /**
  12489. * @license
  12490. * Copyright 2020 Google LLC
  12491. *
  12492. * Licensed under the Apache License, Version 2.0 (the "License");
  12493. * you may not use this file except in compliance with the License.
  12494. * You may obtain a copy of the License at
  12495. *
  12496. * http://www.apache.org/licenses/LICENSE-2.0
  12497. *
  12498. * Unless required by applicable law or agreed to in writing, software
  12499. * distributed under the License is distributed on an "AS IS" BASIS,
  12500. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12501. * See the License for the specific language governing permissions and
  12502. * limitations under the License.
  12503. */
  12504. /**
  12505. * @internal
  12506. */
  12507. var QueryImpl = /** @class */ (function () {
  12508. /**
  12509. * @hideconstructor
  12510. */
  12511. function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
  12512. this._repo = _repo;
  12513. this._path = _path;
  12514. this._queryParams = _queryParams;
  12515. this._orderByCalled = _orderByCalled;
  12516. }
  12517. Object.defineProperty(QueryImpl.prototype, "key", {
  12518. get: function () {
  12519. if (pathIsEmpty(this._path)) {
  12520. return null;
  12521. }
  12522. else {
  12523. return pathGetBack(this._path);
  12524. }
  12525. },
  12526. enumerable: false,
  12527. configurable: true
  12528. });
  12529. Object.defineProperty(QueryImpl.prototype, "ref", {
  12530. get: function () {
  12531. return new ReferenceImpl(this._repo, this._path);
  12532. },
  12533. enumerable: false,
  12534. configurable: true
  12535. });
  12536. Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
  12537. get: function () {
  12538. var obj = queryParamsGetQueryObject(this._queryParams);
  12539. var id = ObjectToUniqueKey(obj);
  12540. return id === '{}' ? 'default' : id;
  12541. },
  12542. enumerable: false,
  12543. configurable: true
  12544. });
  12545. Object.defineProperty(QueryImpl.prototype, "_queryObject", {
  12546. /**
  12547. * An object representation of the query parameters used by this Query.
  12548. */
  12549. get: function () {
  12550. return queryParamsGetQueryObject(this._queryParams);
  12551. },
  12552. enumerable: false,
  12553. configurable: true
  12554. });
  12555. QueryImpl.prototype.isEqual = function (other) {
  12556. other = util.getModularInstance(other);
  12557. if (!(other instanceof QueryImpl)) {
  12558. return false;
  12559. }
  12560. var sameRepo = this._repo === other._repo;
  12561. var samePath = pathEquals(this._path, other._path);
  12562. var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12563. return sameRepo && samePath && sameQueryIdentifier;
  12564. };
  12565. QueryImpl.prototype.toJSON = function () {
  12566. return this.toString();
  12567. };
  12568. QueryImpl.prototype.toString = function () {
  12569. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12570. };
  12571. return QueryImpl;
  12572. }());
  12573. /**
  12574. * Validates that no other order by call has been made
  12575. */
  12576. function validateNoPreviousOrderByCall(query, fnName) {
  12577. if (query._orderByCalled === true) {
  12578. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12579. }
  12580. }
  12581. /**
  12582. * Validates start/end values for queries.
  12583. */
  12584. function validateQueryEndpoints(params) {
  12585. var startNode = null;
  12586. var endNode = null;
  12587. if (params.hasStart()) {
  12588. startNode = params.getIndexStartValue();
  12589. }
  12590. if (params.hasEnd()) {
  12591. endNode = params.getIndexEndValue();
  12592. }
  12593. if (params.getIndex() === KEY_INDEX) {
  12594. var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12595. 'startAt(), endAt(), or equalTo().';
  12596. var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12597. 'endAt(), endBefore(), or equalTo() must be a string.';
  12598. if (params.hasStart()) {
  12599. var startName = params.getIndexStartName();
  12600. if (startName !== MIN_NAME) {
  12601. throw new Error(tooManyArgsError);
  12602. }
  12603. else if (typeof startNode !== 'string') {
  12604. throw new Error(wrongArgTypeError);
  12605. }
  12606. }
  12607. if (params.hasEnd()) {
  12608. var endName = params.getIndexEndName();
  12609. if (endName !== MAX_NAME) {
  12610. throw new Error(tooManyArgsError);
  12611. }
  12612. else if (typeof endNode !== 'string') {
  12613. throw new Error(wrongArgTypeError);
  12614. }
  12615. }
  12616. }
  12617. else if (params.getIndex() === PRIORITY_INDEX) {
  12618. if ((startNode != null && !isValidPriority(startNode)) ||
  12619. (endNode != null && !isValidPriority(endNode))) {
  12620. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12621. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12622. '(null, a number, or a string).');
  12623. }
  12624. }
  12625. else {
  12626. util.assert(params.getIndex() instanceof PathIndex ||
  12627. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12628. if ((startNode != null && typeof startNode === 'object') ||
  12629. (endNode != null && typeof endNode === 'object')) {
  12630. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12631. 'equalTo() cannot be an object.');
  12632. }
  12633. }
  12634. }
  12635. /**
  12636. * Validates that limit* has been called with the correct combination of parameters
  12637. */
  12638. function validateLimit(params) {
  12639. if (params.hasStart() &&
  12640. params.hasEnd() &&
  12641. params.hasLimit() &&
  12642. !params.hasAnchoredLimit()) {
  12643. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12644. 'limitToFirst() or limitToLast() instead.');
  12645. }
  12646. }
  12647. /**
  12648. * @internal
  12649. */
  12650. var ReferenceImpl = /** @class */ (function (_super) {
  12651. tslib.__extends(ReferenceImpl, _super);
  12652. /** @hideconstructor */
  12653. function ReferenceImpl(repo, path) {
  12654. return _super.call(this, repo, path, new QueryParams(), false) || this;
  12655. }
  12656. Object.defineProperty(ReferenceImpl.prototype, "parent", {
  12657. get: function () {
  12658. var parentPath = pathParent(this._path);
  12659. return parentPath === null
  12660. ? null
  12661. : new ReferenceImpl(this._repo, parentPath);
  12662. },
  12663. enumerable: false,
  12664. configurable: true
  12665. });
  12666. Object.defineProperty(ReferenceImpl.prototype, "root", {
  12667. get: function () {
  12668. var ref = this;
  12669. while (ref.parent !== null) {
  12670. ref = ref.parent;
  12671. }
  12672. return ref;
  12673. },
  12674. enumerable: false,
  12675. configurable: true
  12676. });
  12677. return ReferenceImpl;
  12678. }(QueryImpl));
  12679. /**
  12680. * A `DataSnapshot` contains data from a Database location.
  12681. *
  12682. * Any time you read data from the Database, you receive the data as a
  12683. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12684. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12685. * JavaScript object by calling the `val()` method. Alternatively, you can
  12686. * traverse into the snapshot by calling `child()` to return child snapshots
  12687. * (which you could then call `val()` on).
  12688. *
  12689. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12690. * a Database location. It cannot be modified and will never change (to modify
  12691. * data, you always call the `set()` method on a `Reference` directly).
  12692. */
  12693. var DataSnapshot = /** @class */ (function () {
  12694. /**
  12695. * @param _node - A SnapshotNode to wrap.
  12696. * @param ref - The location this snapshot came from.
  12697. * @param _index - The iteration order for this snapshot
  12698. * @hideconstructor
  12699. */
  12700. function DataSnapshot(_node,
  12701. /**
  12702. * The location of this DataSnapshot.
  12703. */
  12704. ref, _index) {
  12705. this._node = _node;
  12706. this.ref = ref;
  12707. this._index = _index;
  12708. }
  12709. Object.defineProperty(DataSnapshot.prototype, "priority", {
  12710. /**
  12711. * Gets the priority value of the data in this `DataSnapshot`.
  12712. *
  12713. * Applications need not use priority but can order collections by
  12714. * ordinary properties (see
  12715. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12716. * ).
  12717. */
  12718. get: function () {
  12719. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12720. return this._node.getPriority().val();
  12721. },
  12722. enumerable: false,
  12723. configurable: true
  12724. });
  12725. Object.defineProperty(DataSnapshot.prototype, "key", {
  12726. /**
  12727. * The key (last part of the path) of the location of this `DataSnapshot`.
  12728. *
  12729. * The last token in a Database location is considered its key. For example,
  12730. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12731. * `DataSnapshot` will return the key for the location that generated it.
  12732. * However, accessing the key on the root URL of a Database will return
  12733. * `null`.
  12734. */
  12735. get: function () {
  12736. return this.ref.key;
  12737. },
  12738. enumerable: false,
  12739. configurable: true
  12740. });
  12741. Object.defineProperty(DataSnapshot.prototype, "size", {
  12742. /** Returns the number of child properties of this `DataSnapshot`. */
  12743. get: function () {
  12744. return this._node.numChildren();
  12745. },
  12746. enumerable: false,
  12747. configurable: true
  12748. });
  12749. /**
  12750. * Gets another `DataSnapshot` for the location at the specified relative path.
  12751. *
  12752. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12753. * another `DataSnapshot` for the location at the specified relative path. The
  12754. * relative path can either be a simple child name (for example, "ada") or a
  12755. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12756. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12757. * whose value is `null`) is returned.
  12758. *
  12759. * @param path - A relative path to the location of child data.
  12760. */
  12761. DataSnapshot.prototype.child = function (path) {
  12762. var childPath = new Path(path);
  12763. var childRef = child(this.ref, path);
  12764. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12765. };
  12766. /**
  12767. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12768. * efficient than using `snapshot.val() !== null`.
  12769. */
  12770. DataSnapshot.prototype.exists = function () {
  12771. return !this._node.isEmpty();
  12772. };
  12773. /**
  12774. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12775. *
  12776. * The `exportVal()` method is similar to `val()`, except priority information
  12777. * is included (if available), making it suitable for backing up your data.
  12778. *
  12779. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12780. * Array, string, number, boolean, or `null`).
  12781. */
  12782. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12783. DataSnapshot.prototype.exportVal = function () {
  12784. return this._node.val(true);
  12785. };
  12786. /**
  12787. * Enumerates the top-level children in the `DataSnapshot`.
  12788. *
  12789. * Because of the way JavaScript objects work, the ordering of data in the
  12790. * JavaScript object returned by `val()` is not guaranteed to match the
  12791. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12792. * where `forEach()` comes in handy. It guarantees the children of a
  12793. * `DataSnapshot` will be iterated in their query order.
  12794. *
  12795. * If no explicit `orderBy*()` method is used, results are returned
  12796. * ordered by key (unless priorities are used, in which case, results are
  12797. * returned by priority).
  12798. *
  12799. * @param action - A function that will be called for each child DataSnapshot.
  12800. * The callback can return true to cancel further enumeration.
  12801. * @returns true if enumeration was canceled due to your callback returning
  12802. * true.
  12803. */
  12804. DataSnapshot.prototype.forEach = function (action) {
  12805. var _this = this;
  12806. if (this._node.isLeafNode()) {
  12807. return false;
  12808. }
  12809. var childrenNode = this._node;
  12810. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12811. return !!childrenNode.forEachChild(this._index, function (key, node) {
  12812. return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
  12813. });
  12814. };
  12815. /**
  12816. * Returns true if the specified child path has (non-null) data.
  12817. *
  12818. * @param path - A relative path to the location of a potential child.
  12819. * @returns `true` if data exists at the specified child path; else
  12820. * `false`.
  12821. */
  12822. DataSnapshot.prototype.hasChild = function (path) {
  12823. var childPath = new Path(path);
  12824. return !this._node.getChild(childPath).isEmpty();
  12825. };
  12826. /**
  12827. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12828. * properties.
  12829. *
  12830. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12831. * children. If it does, you can enumerate them using `forEach()`. If it
  12832. * doesn't, then either this snapshot contains a primitive value (which can be
  12833. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12834. * `null`).
  12835. *
  12836. * @returns true if this snapshot has any children; else false.
  12837. */
  12838. DataSnapshot.prototype.hasChildren = function () {
  12839. if (this._node.isLeafNode()) {
  12840. return false;
  12841. }
  12842. else {
  12843. return !this._node.isEmpty();
  12844. }
  12845. };
  12846. /**
  12847. * Returns a JSON-serializable representation of this object.
  12848. */
  12849. DataSnapshot.prototype.toJSON = function () {
  12850. return this.exportVal();
  12851. };
  12852. /**
  12853. * Extracts a JavaScript value from a `DataSnapshot`.
  12854. *
  12855. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12856. * scalar type (string, number, or boolean), an array, or an object. It may
  12857. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12858. * data).
  12859. *
  12860. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12861. * Array, string, number, boolean, or `null`).
  12862. */
  12863. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12864. DataSnapshot.prototype.val = function () {
  12865. return this._node.val();
  12866. };
  12867. return DataSnapshot;
  12868. }());
  12869. /**
  12870. *
  12871. * Returns a `Reference` representing the location in the Database
  12872. * corresponding to the provided path. If no path is provided, the `Reference`
  12873. * will point to the root of the Database.
  12874. *
  12875. * @param db - The database instance to obtain a reference for.
  12876. * @param path - Optional path representing the location the returned
  12877. * `Reference` will point. If not provided, the returned `Reference` will
  12878. * point to the root of the Database.
  12879. * @returns If a path is provided, a `Reference`
  12880. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12881. * root of the Database.
  12882. */
  12883. function ref(db, path) {
  12884. db = util.getModularInstance(db);
  12885. db._checkNotDeleted('ref');
  12886. return path !== undefined ? child(db._root, path) : db._root;
  12887. }
  12888. /**
  12889. * Returns a `Reference` representing the location in the Database
  12890. * corresponding to the provided Firebase URL.
  12891. *
  12892. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12893. * has a different domain than the current `Database` instance.
  12894. *
  12895. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12896. * and are not applied to the returned `Reference`.
  12897. *
  12898. * @param db - The database instance to obtain a reference for.
  12899. * @param url - The Firebase URL at which the returned `Reference` will
  12900. * point.
  12901. * @returns A `Reference` pointing to the provided
  12902. * Firebase URL.
  12903. */
  12904. function refFromURL(db, url) {
  12905. db = util.getModularInstance(db);
  12906. db._checkNotDeleted('refFromURL');
  12907. var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12908. validateUrl('refFromURL', parsedURL);
  12909. var repoInfo = parsedURL.repoInfo;
  12910. if (!db._repo.repoInfo_.isCustomHost() &&
  12911. repoInfo.host !== db._repo.repoInfo_.host) {
  12912. fatal('refFromURL' +
  12913. ': Host name does not match the current database: ' +
  12914. '(found ' +
  12915. repoInfo.host +
  12916. ' but expected ' +
  12917. db._repo.repoInfo_.host +
  12918. ')');
  12919. }
  12920. return ref(db, parsedURL.path.toString());
  12921. }
  12922. /**
  12923. * Gets a `Reference` for the location at the specified relative path.
  12924. *
  12925. * The relative path can either be a simple child name (for example, "ada") or
  12926. * a deeper slash-separated path (for example, "ada/name/first").
  12927. *
  12928. * @param parent - The parent location.
  12929. * @param path - A relative path from this location to the desired child
  12930. * location.
  12931. * @returns The specified child location.
  12932. */
  12933. function child(parent, path) {
  12934. parent = util.getModularInstance(parent);
  12935. if (pathGetFront(parent._path) === null) {
  12936. validateRootPathString('child', 'path', path, false);
  12937. }
  12938. else {
  12939. validatePathString('child', 'path', path, false);
  12940. }
  12941. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12942. }
  12943. /**
  12944. * Returns an `OnDisconnect` object - see
  12945. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12946. * for more information on how to use it.
  12947. *
  12948. * @param ref - The reference to add OnDisconnect triggers for.
  12949. */
  12950. function onDisconnect(ref) {
  12951. ref = util.getModularInstance(ref);
  12952. return new OnDisconnect(ref._repo, ref._path);
  12953. }
  12954. /**
  12955. * Generates a new child location using a unique key and returns its
  12956. * `Reference`.
  12957. *
  12958. * This is the most common pattern for adding data to a collection of items.
  12959. *
  12960. * If you provide a value to `push()`, the value is written to the
  12961. * generated location. If you don't pass a value, nothing is written to the
  12962. * database and the child remains empty (but you can use the `Reference`
  12963. * elsewhere).
  12964. *
  12965. * The unique keys generated by `push()` are ordered by the current time, so the
  12966. * resulting list of items is chronologically sorted. The keys are also
  12967. * designed to be unguessable (they contain 72 random bits of entropy).
  12968. *
  12969. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12970. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12971. *
  12972. * @param parent - The parent location.
  12973. * @param value - Optional value to be written at the generated location.
  12974. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12975. * but can be used immediately as the `Reference` to the child location.
  12976. */
  12977. function push(parent, value) {
  12978. parent = util.getModularInstance(parent);
  12979. validateWritablePath('push', parent._path);
  12980. validateFirebaseDataArg('push', value, parent._path, true);
  12981. var now = repoServerTime(parent._repo);
  12982. var name = nextPushId(now);
  12983. // push() returns a ThennableReference whose promise is fulfilled with a
  12984. // regular Reference. We use child() to create handles to two different
  12985. // references. The first is turned into a ThennableReference below by adding
  12986. // then() and catch() methods and is used as the return value of push(). The
  12987. // second remains a regular Reference and is used as the fulfilled value of
  12988. // the first ThennableReference.
  12989. var thennablePushRef = child(parent, name);
  12990. var pushRef = child(parent, name);
  12991. var promise;
  12992. if (value != null) {
  12993. promise = set(pushRef, value).then(function () { return pushRef; });
  12994. }
  12995. else {
  12996. promise = Promise.resolve(pushRef);
  12997. }
  12998. thennablePushRef.then = promise.then.bind(promise);
  12999. thennablePushRef.catch = promise.then.bind(promise, undefined);
  13000. return thennablePushRef;
  13001. }
  13002. /**
  13003. * Removes the data at this Database location.
  13004. *
  13005. * Any data at child locations will also be deleted.
  13006. *
  13007. * The effect of the remove will be visible immediately and the corresponding
  13008. * event 'value' will be triggered. Synchronization of the remove to the
  13009. * Firebase servers will also be started, and the returned Promise will resolve
  13010. * when complete. If provided, the onComplete callback will be called
  13011. * asynchronously after synchronization has finished.
  13012. *
  13013. * @param ref - The location to remove.
  13014. * @returns Resolves when remove on server is complete.
  13015. */
  13016. function remove(ref) {
  13017. validateWritablePath('remove', ref._path);
  13018. return set(ref, null);
  13019. }
  13020. /**
  13021. * Writes data to this Database location.
  13022. *
  13023. * This will overwrite any data at this location and all child locations.
  13024. *
  13025. * The effect of the write will be visible immediately, and the corresponding
  13026. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  13027. * the data to the Firebase servers will also be started, and the returned
  13028. * Promise will resolve when complete. If provided, the `onComplete` callback
  13029. * will be called asynchronously after synchronization has finished.
  13030. *
  13031. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  13032. * all data at this location and all child locations will be deleted.
  13033. *
  13034. * `set()` will remove any priority stored at this location, so if priority is
  13035. * meant to be preserved, you need to use `setWithPriority()` instead.
  13036. *
  13037. * Note that modifying data with `set()` will cancel any pending transactions
  13038. * at that location, so extreme care should be taken if mixing `set()` and
  13039. * `transaction()` to modify the same data.
  13040. *
  13041. * A single `set()` will generate a single "value" event at the location where
  13042. * the `set()` was performed.
  13043. *
  13044. * @param ref - The location to write to.
  13045. * @param value - The value to be written (string, number, boolean, object,
  13046. * array, or null).
  13047. * @returns Resolves when write to server is complete.
  13048. */
  13049. function set(ref, value) {
  13050. ref = util.getModularInstance(ref);
  13051. validateWritablePath('set', ref._path);
  13052. validateFirebaseDataArg('set', value, ref._path, false);
  13053. var deferred = new util.Deferred();
  13054. repoSetWithPriority(ref._repo, ref._path, value,
  13055. /*priority=*/ null, deferred.wrapCallback(function () { }));
  13056. return deferred.promise;
  13057. }
  13058. /**
  13059. * Sets a priority for the data at this Database location.
  13060. *
  13061. * Applications need not use priority but can order collections by
  13062. * ordinary properties (see
  13063. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13064. * ).
  13065. *
  13066. * @param ref - The location to write to.
  13067. * @param priority - The priority to be written (string, number, or null).
  13068. * @returns Resolves when write to server is complete.
  13069. */
  13070. function setPriority(ref, priority) {
  13071. ref = util.getModularInstance(ref);
  13072. validateWritablePath('setPriority', ref._path);
  13073. validatePriority('setPriority', priority, false);
  13074. var deferred = new util.Deferred();
  13075. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
  13076. return deferred.promise;
  13077. }
  13078. /**
  13079. * Writes data the Database location. Like `set()` but also specifies the
  13080. * priority for that data.
  13081. *
  13082. * Applications need not use priority but can order collections by
  13083. * ordinary properties (see
  13084. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13085. * ).
  13086. *
  13087. * @param ref - The location to write to.
  13088. * @param value - The value to be written (string, number, boolean, object,
  13089. * array, or null).
  13090. * @param priority - The priority to be written (string, number, or null).
  13091. * @returns Resolves when write to server is complete.
  13092. */
  13093. function setWithPriority(ref, value, priority) {
  13094. validateWritablePath('setWithPriority', ref._path);
  13095. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  13096. validatePriority('setWithPriority', priority, false);
  13097. if (ref.key === '.length' || ref.key === '.keys') {
  13098. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  13099. }
  13100. var deferred = new util.Deferred();
  13101. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
  13102. return deferred.promise;
  13103. }
  13104. /**
  13105. * Writes multiple values to the Database at once.
  13106. *
  13107. * The `values` argument contains multiple property-value pairs that will be
  13108. * written to the Database together. Each child property can either be a simple
  13109. * property (for example, "name") or a relative path (for example,
  13110. * "name/first") from the current location to the data to update.
  13111. *
  13112. * As opposed to the `set()` method, `update()` can be use to selectively update
  13113. * only the referenced properties at the current location (instead of replacing
  13114. * all the child properties at the current location).
  13115. *
  13116. * The effect of the write will be visible immediately, and the corresponding
  13117. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  13118. * the data to the Firebase servers will also be started, and the returned
  13119. * Promise will resolve when complete. If provided, the `onComplete` callback
  13120. * will be called asynchronously after synchronization has finished.
  13121. *
  13122. * A single `update()` will generate a single "value" event at the location
  13123. * where the `update()` was performed, regardless of how many children were
  13124. * modified.
  13125. *
  13126. * Note that modifying data with `update()` will cancel any pending
  13127. * transactions at that location, so extreme care should be taken if mixing
  13128. * `update()` and `transaction()` to modify the same data.
  13129. *
  13130. * Passing `null` to `update()` will remove the data at this location.
  13131. *
  13132. * See
  13133. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  13134. *
  13135. * @param ref - The location to write to.
  13136. * @param values - Object containing multiple values.
  13137. * @returns Resolves when update on server is complete.
  13138. */
  13139. function update(ref, values) {
  13140. validateFirebaseMergeDataArg('update', values, ref._path, false);
  13141. var deferred = new util.Deferred();
  13142. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
  13143. return deferred.promise;
  13144. }
  13145. /**
  13146. * Gets the most up-to-date result for this query.
  13147. *
  13148. * @param query - The query to run.
  13149. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  13150. * available, or rejects if the client is unable to return a value (e.g., if the
  13151. * server is unreachable and there is nothing cached).
  13152. */
  13153. function get(query) {
  13154. query = util.getModularInstance(query);
  13155. var callbackContext = new CallbackContext(function () { });
  13156. var container = new ValueEventRegistration(callbackContext);
  13157. return repoGetValue(query._repo, query, container).then(function (node) {
  13158. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  13159. });
  13160. }
  13161. /**
  13162. * Represents registration for 'value' events.
  13163. */
  13164. var ValueEventRegistration = /** @class */ (function () {
  13165. function ValueEventRegistration(callbackContext) {
  13166. this.callbackContext = callbackContext;
  13167. }
  13168. ValueEventRegistration.prototype.respondsTo = function (eventType) {
  13169. return eventType === 'value';
  13170. };
  13171. ValueEventRegistration.prototype.createEvent = function (change, query) {
  13172. var index = query._queryParams.getIndex();
  13173. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  13174. };
  13175. ValueEventRegistration.prototype.getEventRunner = function (eventData) {
  13176. var _this = this;
  13177. if (eventData.getEventType() === 'cancel') {
  13178. return function () {
  13179. return _this.callbackContext.onCancel(eventData.error);
  13180. };
  13181. }
  13182. else {
  13183. return function () {
  13184. return _this.callbackContext.onValue(eventData.snapshot, null);
  13185. };
  13186. }
  13187. };
  13188. ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
  13189. if (this.callbackContext.hasCancelCallback) {
  13190. return new CancelEvent(this, error, path);
  13191. }
  13192. else {
  13193. return null;
  13194. }
  13195. };
  13196. ValueEventRegistration.prototype.matches = function (other) {
  13197. if (!(other instanceof ValueEventRegistration)) {
  13198. return false;
  13199. }
  13200. else if (!other.callbackContext || !this.callbackContext) {
  13201. // If no callback specified, we consider it to match any callback.
  13202. return true;
  13203. }
  13204. else {
  13205. return other.callbackContext.matches(this.callbackContext);
  13206. }
  13207. };
  13208. ValueEventRegistration.prototype.hasAnyCallback = function () {
  13209. return this.callbackContext !== null;
  13210. };
  13211. return ValueEventRegistration;
  13212. }());
  13213. /**
  13214. * Represents the registration of a child_x event.
  13215. */
  13216. var ChildEventRegistration = /** @class */ (function () {
  13217. function ChildEventRegistration(eventType, callbackContext) {
  13218. this.eventType = eventType;
  13219. this.callbackContext = callbackContext;
  13220. }
  13221. ChildEventRegistration.prototype.respondsTo = function (eventType) {
  13222. var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  13223. eventToCheck =
  13224. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  13225. return this.eventType === eventToCheck;
  13226. };
  13227. ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
  13228. if (this.callbackContext.hasCancelCallback) {
  13229. return new CancelEvent(this, error, path);
  13230. }
  13231. else {
  13232. return null;
  13233. }
  13234. };
  13235. ChildEventRegistration.prototype.createEvent = function (change, query) {
  13236. util.assert(change.childName != null, 'Child events should have a childName.');
  13237. var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  13238. var index = query._queryParams.getIndex();
  13239. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  13240. };
  13241. ChildEventRegistration.prototype.getEventRunner = function (eventData) {
  13242. var _this = this;
  13243. if (eventData.getEventType() === 'cancel') {
  13244. return function () {
  13245. return _this.callbackContext.onCancel(eventData.error);
  13246. };
  13247. }
  13248. else {
  13249. return function () {
  13250. return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  13251. };
  13252. }
  13253. };
  13254. ChildEventRegistration.prototype.matches = function (other) {
  13255. if (other instanceof ChildEventRegistration) {
  13256. return (this.eventType === other.eventType &&
  13257. (!this.callbackContext ||
  13258. !other.callbackContext ||
  13259. this.callbackContext.matches(other.callbackContext)));
  13260. }
  13261. return false;
  13262. };
  13263. ChildEventRegistration.prototype.hasAnyCallback = function () {
  13264. return !!this.callbackContext;
  13265. };
  13266. return ChildEventRegistration;
  13267. }());
  13268. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  13269. var cancelCallback;
  13270. if (typeof cancelCallbackOrListenOptions === 'object') {
  13271. cancelCallback = undefined;
  13272. options = cancelCallbackOrListenOptions;
  13273. }
  13274. if (typeof cancelCallbackOrListenOptions === 'function') {
  13275. cancelCallback = cancelCallbackOrListenOptions;
  13276. }
  13277. if (options && options.onlyOnce) {
  13278. var userCallback_1 = callback;
  13279. var onceCallback = function (dataSnapshot, previousChildName) {
  13280. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13281. userCallback_1(dataSnapshot, previousChildName);
  13282. };
  13283. onceCallback.userCallback = callback.userCallback;
  13284. onceCallback.context = callback.context;
  13285. callback = onceCallback;
  13286. }
  13287. var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  13288. var container = eventType === 'value'
  13289. ? new ValueEventRegistration(callbackContext)
  13290. : new ChildEventRegistration(eventType, callbackContext);
  13291. repoAddEventCallbackForQuery(query._repo, query, container);
  13292. return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
  13293. }
  13294. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  13295. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  13296. }
  13297. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  13298. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  13299. }
  13300. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  13301. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  13302. }
  13303. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  13304. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  13305. }
  13306. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  13307. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  13308. }
  13309. /**
  13310. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  13311. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  13312. * the respective `on*` callbacks.
  13313. *
  13314. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  13315. * will not automatically remove listeners registered on child nodes, `off()`
  13316. * must also be called on any child listeners to remove the callback.
  13317. *
  13318. * If a callback is not specified, all callbacks for the specified eventType
  13319. * will be removed. Similarly, if no eventType is specified, all callbacks
  13320. * for the `Reference` will be removed.
  13321. *
  13322. * Individual listeners can also be removed by invoking their unsubscribe
  13323. * callbacks.
  13324. *
  13325. * @param query - The query that the listener was registered with.
  13326. * @param eventType - One of the following strings: "value", "child_added",
  13327. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  13328. * for the `Reference` will be removed.
  13329. * @param callback - The callback function that was passed to `on()` or
  13330. * `undefined` to remove all callbacks.
  13331. */
  13332. function off(query, eventType, callback) {
  13333. var container = null;
  13334. var expCallback = callback ? new CallbackContext(callback) : null;
  13335. if (eventType === 'value') {
  13336. container = new ValueEventRegistration(expCallback);
  13337. }
  13338. else if (eventType) {
  13339. container = new ChildEventRegistration(eventType, expCallback);
  13340. }
  13341. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13342. }
  13343. /**
  13344. * A `QueryConstraint` is used to narrow the set of documents returned by a
  13345. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  13346. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  13347. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  13348. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  13349. * {@link orderByValue} or {@link equalTo} and
  13350. * can then be passed to {@link query} to create a new query instance that
  13351. * also contains this `QueryConstraint`.
  13352. */
  13353. var QueryConstraint = /** @class */ (function () {
  13354. function QueryConstraint() {
  13355. }
  13356. return QueryConstraint;
  13357. }());
  13358. var QueryEndAtConstraint = /** @class */ (function (_super) {
  13359. tslib.__extends(QueryEndAtConstraint, _super);
  13360. function QueryEndAtConstraint(_value, _key) {
  13361. var _this = _super.call(this) || this;
  13362. _this._value = _value;
  13363. _this._key = _key;
  13364. return _this;
  13365. }
  13366. QueryEndAtConstraint.prototype._apply = function (query) {
  13367. validateFirebaseDataArg('endAt', this._value, query._path, true);
  13368. var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  13369. validateLimit(newParams);
  13370. validateQueryEndpoints(newParams);
  13371. if (query._queryParams.hasEnd()) {
  13372. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  13373. 'endBefore or equalTo).');
  13374. }
  13375. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13376. };
  13377. return QueryEndAtConstraint;
  13378. }(QueryConstraint));
  13379. /**
  13380. * Creates a `QueryConstraint` with the specified ending point.
  13381. *
  13382. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13383. * allows you to choose arbitrary starting and ending points for your queries.
  13384. *
  13385. * The ending point is inclusive, so children with exactly the specified value
  13386. * will be included in the query. The optional key argument can be used to
  13387. * further limit the range of the query. If it is specified, then children that
  13388. * have exactly the specified value must also have a key name less than or equal
  13389. * to the specified key.
  13390. *
  13391. * You can read more about `endAt()` in
  13392. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13393. *
  13394. * @param value - The value to end at. The argument type depends on which
  13395. * `orderBy*()` function was used in this query. Specify a value that matches
  13396. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13397. * value must be a string.
  13398. * @param key - The child key to end at, among the children with the previously
  13399. * specified priority. This argument is only allowed if ordering by child,
  13400. * value, or priority.
  13401. */
  13402. function endAt(value, key) {
  13403. validateKey('endAt', 'key', key, true);
  13404. return new QueryEndAtConstraint(value, key);
  13405. }
  13406. var QueryEndBeforeConstraint = /** @class */ (function (_super) {
  13407. tslib.__extends(QueryEndBeforeConstraint, _super);
  13408. function QueryEndBeforeConstraint(_value, _key) {
  13409. var _this = _super.call(this) || this;
  13410. _this._value = _value;
  13411. _this._key = _key;
  13412. return _this;
  13413. }
  13414. QueryEndBeforeConstraint.prototype._apply = function (query) {
  13415. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  13416. var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  13417. validateLimit(newParams);
  13418. validateQueryEndpoints(newParams);
  13419. if (query._queryParams.hasEnd()) {
  13420. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  13421. 'endBefore or equalTo).');
  13422. }
  13423. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13424. };
  13425. return QueryEndBeforeConstraint;
  13426. }(QueryConstraint));
  13427. /**
  13428. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  13429. *
  13430. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13431. * allows you to choose arbitrary starting and ending points for your queries.
  13432. *
  13433. * The ending point is exclusive. If only a value is provided, children
  13434. * with a value less than the specified value will be included in the query.
  13435. * If a key is specified, then children must have a value less than or equal
  13436. * to the specified value and a key name less than the specified key.
  13437. *
  13438. * @param value - The value to end before. The argument type depends on which
  13439. * `orderBy*()` function was used in this query. Specify a value that matches
  13440. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13441. * value must be a string.
  13442. * @param key - The child key to end before, among the children with the
  13443. * previously specified priority. This argument is only allowed if ordering by
  13444. * child, value, or priority.
  13445. */
  13446. function endBefore(value, key) {
  13447. validateKey('endBefore', 'key', key, true);
  13448. return new QueryEndBeforeConstraint(value, key);
  13449. }
  13450. var QueryStartAtConstraint = /** @class */ (function (_super) {
  13451. tslib.__extends(QueryStartAtConstraint, _super);
  13452. function QueryStartAtConstraint(_value, _key) {
  13453. var _this = _super.call(this) || this;
  13454. _this._value = _value;
  13455. _this._key = _key;
  13456. return _this;
  13457. }
  13458. QueryStartAtConstraint.prototype._apply = function (query) {
  13459. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13460. var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13461. validateLimit(newParams);
  13462. validateQueryEndpoints(newParams);
  13463. if (query._queryParams.hasStart()) {
  13464. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13465. 'startBefore or equalTo).');
  13466. }
  13467. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13468. };
  13469. return QueryStartAtConstraint;
  13470. }(QueryConstraint));
  13471. /**
  13472. * Creates a `QueryConstraint` with the specified starting point.
  13473. *
  13474. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13475. * allows you to choose arbitrary starting and ending points for your queries.
  13476. *
  13477. * The starting point is inclusive, so children with exactly the specified value
  13478. * will be included in the query. The optional key argument can be used to
  13479. * further limit the range of the query. If it is specified, then children that
  13480. * have exactly the specified value must also have a key name greater than or
  13481. * equal to the specified key.
  13482. *
  13483. * You can read more about `startAt()` in
  13484. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13485. *
  13486. * @param value - The value to start at. The argument type depends on which
  13487. * `orderBy*()` function was used in this query. Specify a value that matches
  13488. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13489. * value must be a string.
  13490. * @param key - The child key to start at. This argument is only allowed if
  13491. * ordering by child, value, or priority.
  13492. */
  13493. function startAt(value, key) {
  13494. if (value === void 0) { value = null; }
  13495. validateKey('startAt', 'key', key, true);
  13496. return new QueryStartAtConstraint(value, key);
  13497. }
  13498. var QueryStartAfterConstraint = /** @class */ (function (_super) {
  13499. tslib.__extends(QueryStartAfterConstraint, _super);
  13500. function QueryStartAfterConstraint(_value, _key) {
  13501. var _this = _super.call(this) || this;
  13502. _this._value = _value;
  13503. _this._key = _key;
  13504. return _this;
  13505. }
  13506. QueryStartAfterConstraint.prototype._apply = function (query) {
  13507. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13508. var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13509. validateLimit(newParams);
  13510. validateQueryEndpoints(newParams);
  13511. if (query._queryParams.hasStart()) {
  13512. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13513. 'startAfter, or equalTo).');
  13514. }
  13515. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13516. };
  13517. return QueryStartAfterConstraint;
  13518. }(QueryConstraint));
  13519. /**
  13520. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13521. *
  13522. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13523. * allows you to choose arbitrary starting and ending points for your queries.
  13524. *
  13525. * The starting point is exclusive. If only a value is provided, children
  13526. * with a value greater than the specified value will be included in the query.
  13527. * If a key is specified, then children must have a value greater than or equal
  13528. * to the specified value and a a key name greater than the specified key.
  13529. *
  13530. * @param value - The value to start after. The argument type depends on which
  13531. * `orderBy*()` function was used in this query. Specify a value that matches
  13532. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13533. * value must be a string.
  13534. * @param key - The child key to start after. This argument is only allowed if
  13535. * ordering by child, value, or priority.
  13536. */
  13537. function startAfter(value, key) {
  13538. validateKey('startAfter', 'key', key, true);
  13539. return new QueryStartAfterConstraint(value, key);
  13540. }
  13541. var QueryLimitToFirstConstraint = /** @class */ (function (_super) {
  13542. tslib.__extends(QueryLimitToFirstConstraint, _super);
  13543. function QueryLimitToFirstConstraint(_limit) {
  13544. var _this = _super.call(this) || this;
  13545. _this._limit = _limit;
  13546. return _this;
  13547. }
  13548. QueryLimitToFirstConstraint.prototype._apply = function (query) {
  13549. if (query._queryParams.hasLimit()) {
  13550. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13551. 'or limitToLast).');
  13552. }
  13553. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13554. };
  13555. return QueryLimitToFirstConstraint;
  13556. }(QueryConstraint));
  13557. /**
  13558. * Creates a new `QueryConstraint` that if limited to the first specific number
  13559. * of children.
  13560. *
  13561. * The `limitToFirst()` method is used to set a maximum number of children to be
  13562. * synced for a given callback. If we set a limit of 100, we will initially only
  13563. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13564. * stored in our Database, a `child_added` event will fire for each message.
  13565. * However, if we have over 100 messages, we will only receive a `child_added`
  13566. * event for the first 100 ordered messages. As items change, we will receive
  13567. * `child_removed` events for each item that drops out of the active list so
  13568. * that the total number stays at 100.
  13569. *
  13570. * You can read more about `limitToFirst()` in
  13571. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13572. *
  13573. * @param limit - The maximum number of nodes to include in this query.
  13574. */
  13575. function limitToFirst(limit) {
  13576. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13577. throw new Error('limitToFirst: First argument must be a positive integer.');
  13578. }
  13579. return new QueryLimitToFirstConstraint(limit);
  13580. }
  13581. var QueryLimitToLastConstraint = /** @class */ (function (_super) {
  13582. tslib.__extends(QueryLimitToLastConstraint, _super);
  13583. function QueryLimitToLastConstraint(_limit) {
  13584. var _this = _super.call(this) || this;
  13585. _this._limit = _limit;
  13586. return _this;
  13587. }
  13588. QueryLimitToLastConstraint.prototype._apply = function (query) {
  13589. if (query._queryParams.hasLimit()) {
  13590. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13591. 'or limitToLast).');
  13592. }
  13593. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13594. };
  13595. return QueryLimitToLastConstraint;
  13596. }(QueryConstraint));
  13597. /**
  13598. * Creates a new `QueryConstraint` that is limited to return only the last
  13599. * specified number of children.
  13600. *
  13601. * The `limitToLast()` method is used to set a maximum number of children to be
  13602. * synced for a given callback. If we set a limit of 100, we will initially only
  13603. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13604. * stored in our Database, a `child_added` event will fire for each message.
  13605. * However, if we have over 100 messages, we will only receive a `child_added`
  13606. * event for the last 100 ordered messages. As items change, we will receive
  13607. * `child_removed` events for each item that drops out of the active list so
  13608. * that the total number stays at 100.
  13609. *
  13610. * You can read more about `limitToLast()` in
  13611. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13612. *
  13613. * @param limit - The maximum number of nodes to include in this query.
  13614. */
  13615. function limitToLast(limit) {
  13616. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13617. throw new Error('limitToLast: First argument must be a positive integer.');
  13618. }
  13619. return new QueryLimitToLastConstraint(limit);
  13620. }
  13621. var QueryOrderByChildConstraint = /** @class */ (function (_super) {
  13622. tslib.__extends(QueryOrderByChildConstraint, _super);
  13623. function QueryOrderByChildConstraint(_path) {
  13624. var _this = _super.call(this) || this;
  13625. _this._path = _path;
  13626. return _this;
  13627. }
  13628. QueryOrderByChildConstraint.prototype._apply = function (query) {
  13629. validateNoPreviousOrderByCall(query, 'orderByChild');
  13630. var parsedPath = new Path(this._path);
  13631. if (pathIsEmpty(parsedPath)) {
  13632. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13633. }
  13634. var index = new PathIndex(parsedPath);
  13635. var newParams = queryParamsOrderBy(query._queryParams, index);
  13636. validateQueryEndpoints(newParams);
  13637. return new QueryImpl(query._repo, query._path, newParams,
  13638. /*orderByCalled=*/ true);
  13639. };
  13640. return QueryOrderByChildConstraint;
  13641. }(QueryConstraint));
  13642. /**
  13643. * Creates a new `QueryConstraint` that orders by the specified child key.
  13644. *
  13645. * Queries can only order by one key at a time. Calling `orderByChild()`
  13646. * multiple times on the same query is an error.
  13647. *
  13648. * Firebase queries allow you to order your data by any child key on the fly.
  13649. * However, if you know in advance what your indexes will be, you can define
  13650. * them via the .indexOn rule in your Security Rules for better performance. See
  13651. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13652. * rule for more information.
  13653. *
  13654. * You can read more about `orderByChild()` in
  13655. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13656. *
  13657. * @param path - The path to order by.
  13658. */
  13659. function orderByChild(path) {
  13660. if (path === '$key') {
  13661. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13662. }
  13663. else if (path === '$priority') {
  13664. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13665. }
  13666. else if (path === '$value') {
  13667. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13668. }
  13669. validatePathString('orderByChild', 'path', path, false);
  13670. return new QueryOrderByChildConstraint(path);
  13671. }
  13672. var QueryOrderByKeyConstraint = /** @class */ (function (_super) {
  13673. tslib.__extends(QueryOrderByKeyConstraint, _super);
  13674. function QueryOrderByKeyConstraint() {
  13675. return _super !== null && _super.apply(this, arguments) || this;
  13676. }
  13677. QueryOrderByKeyConstraint.prototype._apply = function (query) {
  13678. validateNoPreviousOrderByCall(query, 'orderByKey');
  13679. var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13680. validateQueryEndpoints(newParams);
  13681. return new QueryImpl(query._repo, query._path, newParams,
  13682. /*orderByCalled=*/ true);
  13683. };
  13684. return QueryOrderByKeyConstraint;
  13685. }(QueryConstraint));
  13686. /**
  13687. * Creates a new `QueryConstraint` that orders by the key.
  13688. *
  13689. * Sorts the results of a query by their (ascending) key values.
  13690. *
  13691. * You can read more about `orderByKey()` in
  13692. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13693. */
  13694. function orderByKey() {
  13695. return new QueryOrderByKeyConstraint();
  13696. }
  13697. var QueryOrderByPriorityConstraint = /** @class */ (function (_super) {
  13698. tslib.__extends(QueryOrderByPriorityConstraint, _super);
  13699. function QueryOrderByPriorityConstraint() {
  13700. return _super !== null && _super.apply(this, arguments) || this;
  13701. }
  13702. QueryOrderByPriorityConstraint.prototype._apply = function (query) {
  13703. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13704. var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13705. validateQueryEndpoints(newParams);
  13706. return new QueryImpl(query._repo, query._path, newParams,
  13707. /*orderByCalled=*/ true);
  13708. };
  13709. return QueryOrderByPriorityConstraint;
  13710. }(QueryConstraint));
  13711. /**
  13712. * Creates a new `QueryConstraint` that orders by priority.
  13713. *
  13714. * Applications need not use priority but can order collections by
  13715. * ordinary properties (see
  13716. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13717. * for alternatives to priority.
  13718. */
  13719. function orderByPriority() {
  13720. return new QueryOrderByPriorityConstraint();
  13721. }
  13722. var QueryOrderByValueConstraint = /** @class */ (function (_super) {
  13723. tslib.__extends(QueryOrderByValueConstraint, _super);
  13724. function QueryOrderByValueConstraint() {
  13725. return _super !== null && _super.apply(this, arguments) || this;
  13726. }
  13727. QueryOrderByValueConstraint.prototype._apply = function (query) {
  13728. validateNoPreviousOrderByCall(query, 'orderByValue');
  13729. var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13730. validateQueryEndpoints(newParams);
  13731. return new QueryImpl(query._repo, query._path, newParams,
  13732. /*orderByCalled=*/ true);
  13733. };
  13734. return QueryOrderByValueConstraint;
  13735. }(QueryConstraint));
  13736. /**
  13737. * Creates a new `QueryConstraint` that orders by value.
  13738. *
  13739. * If the children of a query are all scalar values (string, number, or
  13740. * boolean), you can order the results by their (ascending) values.
  13741. *
  13742. * You can read more about `orderByValue()` in
  13743. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13744. */
  13745. function orderByValue() {
  13746. return new QueryOrderByValueConstraint();
  13747. }
  13748. var QueryEqualToValueConstraint = /** @class */ (function (_super) {
  13749. tslib.__extends(QueryEqualToValueConstraint, _super);
  13750. function QueryEqualToValueConstraint(_value, _key) {
  13751. var _this = _super.call(this) || this;
  13752. _this._value = _value;
  13753. _this._key = _key;
  13754. return _this;
  13755. }
  13756. QueryEqualToValueConstraint.prototype._apply = function (query) {
  13757. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13758. if (query._queryParams.hasStart()) {
  13759. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13760. 'equalTo).');
  13761. }
  13762. if (query._queryParams.hasEnd()) {
  13763. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13764. 'equalTo).');
  13765. }
  13766. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13767. };
  13768. return QueryEqualToValueConstraint;
  13769. }(QueryConstraint));
  13770. /**
  13771. * Creates a `QueryConstraint` that includes children that match the specified
  13772. * value.
  13773. *
  13774. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13775. * allows you to choose arbitrary starting and ending points for your queries.
  13776. *
  13777. * The optional key argument can be used to further limit the range of the
  13778. * query. If it is specified, then children that have exactly the specified
  13779. * value must also have exactly the specified key as their key name. This can be
  13780. * used to filter result sets with many matches for the same value.
  13781. *
  13782. * You can read more about `equalTo()` in
  13783. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13784. *
  13785. * @param value - The value to match for. The argument type depends on which
  13786. * `orderBy*()` function was used in this query. Specify a value that matches
  13787. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13788. * value must be a string.
  13789. * @param key - The child key to start at, among the children with the
  13790. * previously specified priority. This argument is only allowed if ordering by
  13791. * child, value, or priority.
  13792. */
  13793. function equalTo(value, key) {
  13794. validateKey('equalTo', 'key', key, true);
  13795. return new QueryEqualToValueConstraint(value, key);
  13796. }
  13797. /**
  13798. * Creates a new immutable instance of `Query` that is extended to also include
  13799. * additional query constraints.
  13800. *
  13801. * @param query - The Query instance to use as a base for the new constraints.
  13802. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13803. * @throws if any of the provided query constraints cannot be combined with the
  13804. * existing or new constraints.
  13805. */
  13806. function query(query) {
  13807. var e_1, _a;
  13808. var queryConstraints = [];
  13809. for (var _i = 1; _i < arguments.length; _i++) {
  13810. queryConstraints[_i - 1] = arguments[_i];
  13811. }
  13812. var queryImpl = util.getModularInstance(query);
  13813. try {
  13814. for (var queryConstraints_1 = tslib.__values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
  13815. var constraint = queryConstraints_1_1.value;
  13816. queryImpl = constraint._apply(queryImpl);
  13817. }
  13818. }
  13819. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13820. finally {
  13821. try {
  13822. if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
  13823. }
  13824. finally { if (e_1) throw e_1.error; }
  13825. }
  13826. return queryImpl;
  13827. }
  13828. /**
  13829. * Define reference constructor in various modules
  13830. *
  13831. * We are doing this here to avoid several circular
  13832. * dependency issues
  13833. */
  13834. syncPointSetReferenceConstructor(ReferenceImpl);
  13835. syncTreeSetReferenceConstructor(ReferenceImpl);
  13836. /**
  13837. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13838. * modifying this definition, consult the definition in:
  13839. *
  13840. * https://github.com/firebase/firebase-admin-node
  13841. *
  13842. * and make sure the two are consistent.
  13843. */
  13844. var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13845. /**
  13846. * Creates and caches `Repo` instances.
  13847. */
  13848. var repos = {};
  13849. /**
  13850. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13851. */
  13852. var useRestClient = false;
  13853. /**
  13854. * Update an existing `Repo` in place to point to a new host/port.
  13855. */
  13856. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13857. repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
  13858. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13859. /*isUsingEmulator=*/ true);
  13860. if (tokenProvider) {
  13861. repo.authTokenProvider_ = tokenProvider;
  13862. }
  13863. }
  13864. /**
  13865. * This function should only ever be called to CREATE a new database instance.
  13866. * @internal
  13867. */
  13868. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13869. var dbUrl = url || app.options.databaseURL;
  13870. if (dbUrl === undefined) {
  13871. if (!app.options.projectId) {
  13872. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13873. ' a Project ID when calling firebase.initializeApp().');
  13874. }
  13875. log('Using default host for project ', app.options.projectId);
  13876. dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
  13877. }
  13878. var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13879. var repoInfo = parsedUrl.repoInfo;
  13880. var isEmulator;
  13881. var dbEmulatorHost = undefined;
  13882. if (typeof process !== 'undefined' && process.env) {
  13883. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13884. }
  13885. if (dbEmulatorHost) {
  13886. isEmulator = true;
  13887. dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
  13888. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13889. repoInfo = parsedUrl.repoInfo;
  13890. }
  13891. else {
  13892. isEmulator = !parsedUrl.repoInfo.secure;
  13893. }
  13894. var authTokenProvider = nodeAdmin && isEmulator
  13895. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13896. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13897. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13898. if (!pathIsEmpty(parsedUrl.path)) {
  13899. fatal('Database URL must point to the root of a Firebase Database ' +
  13900. '(not including a child path).');
  13901. }
  13902. var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13903. return new Database(repo, app);
  13904. }
  13905. /**
  13906. * Remove the repo and make sure it is disconnected.
  13907. *
  13908. */
  13909. function repoManagerDeleteRepo(repo, appName) {
  13910. var appRepos = repos[appName];
  13911. // This should never happen...
  13912. if (!appRepos || appRepos[repo.key] !== repo) {
  13913. fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
  13914. }
  13915. repoInterrupt(repo);
  13916. delete appRepos[repo.key];
  13917. }
  13918. /**
  13919. * Ensures a repo doesn't already exist and then creates one using the
  13920. * provided app.
  13921. *
  13922. * @param repoInfo - The metadata about the Repo
  13923. * @returns The Repo object for the specified server / repoName.
  13924. */
  13925. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13926. var appRepos = repos[app.name];
  13927. if (!appRepos) {
  13928. appRepos = {};
  13929. repos[app.name] = appRepos;
  13930. }
  13931. var repo = appRepos[repoInfo.toURLString()];
  13932. if (repo) {
  13933. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13934. }
  13935. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13936. appRepos[repoInfo.toURLString()] = repo;
  13937. return repo;
  13938. }
  13939. /**
  13940. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13941. */
  13942. function repoManagerForceRestClient(forceRestClient) {
  13943. useRestClient = forceRestClient;
  13944. }
  13945. /**
  13946. * Class representing a Firebase Realtime Database.
  13947. */
  13948. var Database = /** @class */ (function () {
  13949. /** @hideconstructor */
  13950. function Database(_repoInternal,
  13951. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13952. app) {
  13953. this._repoInternal = _repoInternal;
  13954. this.app = app;
  13955. /** Represents a `Database` instance. */
  13956. this['type'] = 'database';
  13957. /** Track if the instance has been used (root or repo accessed) */
  13958. this._instanceStarted = false;
  13959. }
  13960. Object.defineProperty(Database.prototype, "_repo", {
  13961. get: function () {
  13962. if (!this._instanceStarted) {
  13963. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13964. this._instanceStarted = true;
  13965. }
  13966. return this._repoInternal;
  13967. },
  13968. enumerable: false,
  13969. configurable: true
  13970. });
  13971. Object.defineProperty(Database.prototype, "_root", {
  13972. get: function () {
  13973. if (!this._rootInternal) {
  13974. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13975. }
  13976. return this._rootInternal;
  13977. },
  13978. enumerable: false,
  13979. configurable: true
  13980. });
  13981. Database.prototype._delete = function () {
  13982. if (this._rootInternal !== null) {
  13983. repoManagerDeleteRepo(this._repo, this.app.name);
  13984. this._repoInternal = null;
  13985. this._rootInternal = null;
  13986. }
  13987. return Promise.resolve();
  13988. };
  13989. Database.prototype._checkNotDeleted = function (apiName) {
  13990. if (this._rootInternal === null) {
  13991. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13992. }
  13993. };
  13994. return Database;
  13995. }());
  13996. function checkTransportInit() {
  13997. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13998. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13999. }
  14000. }
  14001. /**
  14002. * Force the use of websockets instead of longPolling.
  14003. */
  14004. function forceWebSockets() {
  14005. checkTransportInit();
  14006. BrowserPollConnection.forceDisallow();
  14007. }
  14008. /**
  14009. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  14010. */
  14011. function forceLongPolling() {
  14012. checkTransportInit();
  14013. WebSocketConnection.forceDisallow();
  14014. BrowserPollConnection.forceAllow();
  14015. }
  14016. /**
  14017. * Returns the instance of the Realtime Database SDK that is associated
  14018. * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
  14019. * with default settings if no instance exists or if the existing instance uses
  14020. * a custom database URL.
  14021. *
  14022. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  14023. * Database instance is associated with.
  14024. * @param url - The URL of the Realtime Database instance to connect to. If not
  14025. * provided, the SDK connects to the default instance of the Firebase App.
  14026. * @returns The `Database` instance of the provided app.
  14027. */
  14028. function getDatabase(app$1, url) {
  14029. if (app$1 === void 0) { app$1 = app.getApp(); }
  14030. var db = app._getProvider(app$1, 'database').getImmediate({
  14031. identifier: url
  14032. });
  14033. if (!db._instanceStarted) {
  14034. var emulator = util.getDefaultEmulatorHostnameAndPort('database');
  14035. if (emulator) {
  14036. connectDatabaseEmulator.apply(void 0, tslib.__spreadArray([db], tslib.__read(emulator), false));
  14037. }
  14038. }
  14039. return db;
  14040. }
  14041. /**
  14042. * Modify the provided instance to communicate with the Realtime Database
  14043. * emulator.
  14044. *
  14045. * <p>Note: This method must be called before performing any other operation.
  14046. *
  14047. * @param db - The instance to modify.
  14048. * @param host - The emulator host (ex: localhost)
  14049. * @param port - The emulator port (ex: 8080)
  14050. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  14051. */
  14052. function connectDatabaseEmulator(db, host, port, options) {
  14053. if (options === void 0) { options = {}; }
  14054. db = util.getModularInstance(db);
  14055. db._checkNotDeleted('useEmulator');
  14056. if (db._instanceStarted) {
  14057. fatal('Cannot call useEmulator() after instance has already been initialized.');
  14058. }
  14059. var repo = db._repoInternal;
  14060. var tokenProvider = undefined;
  14061. if (repo.repoInfo_.nodeAdmin) {
  14062. if (options.mockUserToken) {
  14063. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  14064. }
  14065. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  14066. }
  14067. else if (options.mockUserToken) {
  14068. var token = typeof options.mockUserToken === 'string'
  14069. ? options.mockUserToken
  14070. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  14071. tokenProvider = new EmulatorTokenProvider(token);
  14072. }
  14073. // Modify the repo to apply emulator settings
  14074. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  14075. }
  14076. /**
  14077. * Disconnects from the server (all Database operations will be completed
  14078. * offline).
  14079. *
  14080. * The client automatically maintains a persistent connection to the Database
  14081. * server, which will remain active indefinitely and reconnect when
  14082. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  14083. * to control the client connection in cases where a persistent connection is
  14084. * undesirable.
  14085. *
  14086. * While offline, the client will no longer receive data updates from the
  14087. * Database. However, all Database operations performed locally will continue to
  14088. * immediately fire events, allowing your application to continue behaving
  14089. * normally. Additionally, each operation performed locally will automatically
  14090. * be queued and retried upon reconnection to the Database server.
  14091. *
  14092. * To reconnect to the Database and begin receiving remote events, see
  14093. * `goOnline()`.
  14094. *
  14095. * @param db - The instance to disconnect.
  14096. */
  14097. function goOffline(db) {
  14098. db = util.getModularInstance(db);
  14099. db._checkNotDeleted('goOffline');
  14100. repoInterrupt(db._repo);
  14101. }
  14102. /**
  14103. * Reconnects to the server and synchronizes the offline Database state
  14104. * with the server state.
  14105. *
  14106. * This method should be used after disabling the active connection with
  14107. * `goOffline()`. Once reconnected, the client will transmit the proper data
  14108. * and fire the appropriate events so that your client "catches up"
  14109. * automatically.
  14110. *
  14111. * @param db - The instance to reconnect.
  14112. */
  14113. function goOnline(db) {
  14114. db = util.getModularInstance(db);
  14115. db._checkNotDeleted('goOnline');
  14116. repoResume(db._repo);
  14117. }
  14118. function enableLogging(logger, persistent) {
  14119. enableLogging$1(logger, persistent);
  14120. }
  14121. /**
  14122. * @license
  14123. * Copyright 2021 Google LLC
  14124. *
  14125. * Licensed under the Apache License, Version 2.0 (the "License");
  14126. * you may not use this file except in compliance with the License.
  14127. * You may obtain a copy of the License at
  14128. *
  14129. * http://www.apache.org/licenses/LICENSE-2.0
  14130. *
  14131. * Unless required by applicable law or agreed to in writing, software
  14132. * distributed under the License is distributed on an "AS IS" BASIS,
  14133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14134. * See the License for the specific language governing permissions and
  14135. * limitations under the License.
  14136. */
  14137. function registerDatabase(variant) {
  14138. setSDKVersion(app.SDK_VERSION);
  14139. app._registerComponent(new component.Component('database', function (container, _a) {
  14140. var url = _a.instanceIdentifier;
  14141. var app = container.getProvider('app').getImmediate();
  14142. var authProvider = container.getProvider('auth-internal');
  14143. var appCheckProvider = container.getProvider('app-check-internal');
  14144. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  14145. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  14146. app.registerVersion(name, version, variant);
  14147. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  14148. app.registerVersion(name, version, 'cjs5');
  14149. }
  14150. /**
  14151. * @license
  14152. * Copyright 2020 Google LLC
  14153. *
  14154. * Licensed under the Apache License, Version 2.0 (the "License");
  14155. * you may not use this file except in compliance with the License.
  14156. * You may obtain a copy of the License at
  14157. *
  14158. * http://www.apache.org/licenses/LICENSE-2.0
  14159. *
  14160. * Unless required by applicable law or agreed to in writing, software
  14161. * distributed under the License is distributed on an "AS IS" BASIS,
  14162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14163. * See the License for the specific language governing permissions and
  14164. * limitations under the License.
  14165. */
  14166. var SERVER_TIMESTAMP = {
  14167. '.sv': 'timestamp'
  14168. };
  14169. /**
  14170. * Returns a placeholder value for auto-populating the current timestamp (time
  14171. * since the Unix epoch, in milliseconds) as determined by the Firebase
  14172. * servers.
  14173. */
  14174. function serverTimestamp() {
  14175. return SERVER_TIMESTAMP;
  14176. }
  14177. /**
  14178. * Returns a placeholder value that can be used to atomically increment the
  14179. * current database value by the provided delta.
  14180. *
  14181. * @param delta - the amount to modify the current value atomically.
  14182. * @returns A placeholder value for modifying data atomically server-side.
  14183. */
  14184. function increment(delta) {
  14185. return {
  14186. '.sv': {
  14187. 'increment': delta
  14188. }
  14189. };
  14190. }
  14191. /**
  14192. * @license
  14193. * Copyright 2020 Google LLC
  14194. *
  14195. * Licensed under the Apache License, Version 2.0 (the "License");
  14196. * you may not use this file except in compliance with the License.
  14197. * You may obtain a copy of the License at
  14198. *
  14199. * http://www.apache.org/licenses/LICENSE-2.0
  14200. *
  14201. * Unless required by applicable law or agreed to in writing, software
  14202. * distributed under the License is distributed on an "AS IS" BASIS,
  14203. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14204. * See the License for the specific language governing permissions and
  14205. * limitations under the License.
  14206. */
  14207. /**
  14208. * A type for the resolve value of {@link runTransaction}.
  14209. */
  14210. var TransactionResult = /** @class */ (function () {
  14211. /** @hideconstructor */
  14212. function TransactionResult(
  14213. /** Whether the transaction was successfully committed. */
  14214. committed,
  14215. /** The resulting data snapshot. */
  14216. snapshot) {
  14217. this.committed = committed;
  14218. this.snapshot = snapshot;
  14219. }
  14220. /** Returns a JSON-serializable representation of this object. */
  14221. TransactionResult.prototype.toJSON = function () {
  14222. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  14223. };
  14224. return TransactionResult;
  14225. }());
  14226. /**
  14227. * Atomically modifies the data at this location.
  14228. *
  14229. * Atomically modify the data at this location. Unlike a normal `set()`, which
  14230. * just overwrites the data regardless of its previous value, `runTransaction()` is
  14231. * used to modify the existing value to a new value, ensuring there are no
  14232. * conflicts with other clients writing to the same location at the same time.
  14233. *
  14234. * To accomplish this, you pass `runTransaction()` an update function which is
  14235. * used to transform the current value into a new value. If another client
  14236. * writes to the location before your new value is successfully written, your
  14237. * update function will be called again with the new current value, and the
  14238. * write will be retried. This will happen repeatedly until your write succeeds
  14239. * without conflict or you abort the transaction by not returning a value from
  14240. * your update function.
  14241. *
  14242. * Note: Modifying data with `set()` will cancel any pending transactions at
  14243. * that location, so extreme care should be taken if mixing `set()` and
  14244. * `runTransaction()` to update the same data.
  14245. *
  14246. * Note: When using transactions with Security and Firebase Rules in place, be
  14247. * aware that a client needs `.read` access in addition to `.write` access in
  14248. * order to perform a transaction. This is because the client-side nature of
  14249. * transactions requires the client to read the data in order to transactionally
  14250. * update it.
  14251. *
  14252. * @param ref - The location to atomically modify.
  14253. * @param transactionUpdate - A developer-supplied function which will be passed
  14254. * the current data stored at this location (as a JavaScript object). The
  14255. * function should return the new value it would like written (as a JavaScript
  14256. * object). If `undefined` is returned (i.e. you return with no arguments) the
  14257. * transaction will be aborted and the data at this location will not be
  14258. * modified.
  14259. * @param options - An options object to configure transactions.
  14260. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  14261. * callback to handle success and failure.
  14262. */
  14263. function runTransaction(ref,
  14264. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14265. transactionUpdate, options) {
  14266. var _a;
  14267. ref = util.getModularInstance(ref);
  14268. validateWritablePath('Reference.transaction', ref._path);
  14269. if (ref.key === '.length' || ref.key === '.keys') {
  14270. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  14271. }
  14272. var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  14273. var deferred = new util.Deferred();
  14274. var promiseComplete = function (error, committed, node) {
  14275. var dataSnapshot = null;
  14276. if (error) {
  14277. deferred.reject(error);
  14278. }
  14279. else {
  14280. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  14281. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  14282. }
  14283. };
  14284. // Add a watch to make sure we get server updates.
  14285. var unwatcher = onValue(ref, function () { });
  14286. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  14287. return deferred.promise;
  14288. }
  14289. /**
  14290. * @license
  14291. * Copyright 2017 Google LLC
  14292. *
  14293. * Licensed under the Apache License, Version 2.0 (the "License");
  14294. * you may not use this file except in compliance with the License.
  14295. * You may obtain a copy of the License at
  14296. *
  14297. * http://www.apache.org/licenses/LICENSE-2.0
  14298. *
  14299. * Unless required by applicable law or agreed to in writing, software
  14300. * distributed under the License is distributed on an "AS IS" BASIS,
  14301. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14302. * See the License for the specific language governing permissions and
  14303. * limitations under the License.
  14304. */
  14305. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14306. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  14307. this.sendRequest('q', { p: pathString }, onComplete);
  14308. };
  14309. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14310. PersistentConnection.prototype.echo = function (data, onEcho) {
  14311. this.sendRequest('echo', { d: data }, onEcho);
  14312. };
  14313. /**
  14314. * @internal
  14315. */
  14316. var hijackHash = function (newHash) {
  14317. var oldPut = PersistentConnection.prototype.put;
  14318. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  14319. if (hash !== undefined) {
  14320. hash = newHash();
  14321. }
  14322. oldPut.call(this, pathString, data, onComplete, hash);
  14323. };
  14324. return function () {
  14325. PersistentConnection.prototype.put = oldPut;
  14326. };
  14327. };
  14328. /**
  14329. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  14330. * @internal
  14331. */
  14332. var forceRestClient = function (forceRestClient) {
  14333. repoManagerForceRestClient(forceRestClient);
  14334. };
  14335. /**
  14336. * @license
  14337. * Copyright 2021 Google LLC
  14338. *
  14339. * Licensed under the Apache License, Version 2.0 (the "License");
  14340. * you may not use this file except in compliance with the License.
  14341. * You may obtain a copy of the License at
  14342. *
  14343. * http://www.apache.org/licenses/LICENSE-2.0
  14344. *
  14345. * Unless required by applicable law or agreed to in writing, software
  14346. * distributed under the License is distributed on an "AS IS" BASIS,
  14347. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14348. * See the License for the specific language governing permissions and
  14349. * limitations under the License.
  14350. */
  14351. setWebSocketImpl(Websocket__default["default"].Client);
  14352. registerDatabase('node');
  14353. exports.DataSnapshot = DataSnapshot;
  14354. exports.Database = Database;
  14355. exports.OnDisconnect = OnDisconnect;
  14356. exports.QueryConstraint = QueryConstraint;
  14357. exports.TransactionResult = TransactionResult;
  14358. exports._QueryImpl = QueryImpl;
  14359. exports._QueryParams = QueryParams;
  14360. exports._ReferenceImpl = ReferenceImpl;
  14361. exports._TEST_ACCESS_forceRestClient = forceRestClient;
  14362. exports._TEST_ACCESS_hijackHash = hijackHash;
  14363. exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  14364. exports._setSDKVersion = setSDKVersion;
  14365. exports._validatePathString = validatePathString;
  14366. exports._validateWritablePath = validateWritablePath;
  14367. exports.child = child;
  14368. exports.connectDatabaseEmulator = connectDatabaseEmulator;
  14369. exports.enableLogging = enableLogging;
  14370. exports.endAt = endAt;
  14371. exports.endBefore = endBefore;
  14372. exports.equalTo = equalTo;
  14373. exports.forceLongPolling = forceLongPolling;
  14374. exports.forceWebSockets = forceWebSockets;
  14375. exports.get = get;
  14376. exports.getDatabase = getDatabase;
  14377. exports.goOffline = goOffline;
  14378. exports.goOnline = goOnline;
  14379. exports.increment = increment;
  14380. exports.limitToFirst = limitToFirst;
  14381. exports.limitToLast = limitToLast;
  14382. exports.off = off;
  14383. exports.onChildAdded = onChildAdded;
  14384. exports.onChildChanged = onChildChanged;
  14385. exports.onChildMoved = onChildMoved;
  14386. exports.onChildRemoved = onChildRemoved;
  14387. exports.onDisconnect = onDisconnect;
  14388. exports.onValue = onValue;
  14389. exports.orderByChild = orderByChild;
  14390. exports.orderByKey = orderByKey;
  14391. exports.orderByPriority = orderByPriority;
  14392. exports.orderByValue = orderByValue;
  14393. exports.push = push;
  14394. exports.query = query;
  14395. exports.ref = ref;
  14396. exports.refFromURL = refFromURL;
  14397. exports.remove = remove;
  14398. exports.runTransaction = runTransaction;
  14399. exports.serverTimestamp = serverTimestamp;
  14400. exports.set = set;
  14401. exports.setPriority = setPriority;
  14402. exports.setWithPriority = setWithPriority;
  14403. exports.startAfter = startAfter;
  14404. exports.startAt = startAt;
  14405. exports.update = update;
  14406. //# sourceMappingURL=index.node.cjs.js.map