index.esm2017.js 548 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943
  1. import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';
  2. import { Component } from '@firebase/component';
  3. import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';
  4. import { Logger, LogLevel } from '@firebase/logger';
  5. const name = "@firebase/database";
  6. const version = "0.14.4";
  7. /**
  8. * @license
  9. * Copyright 2019 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /** The semver (www.semver.org) version of the SDK. */
  24. let SDK_VERSION = '';
  25. /**
  26. * SDK_VERSION should be set before any database instance is created
  27. * @internal
  28. */
  29. function setSDKVersion(version) {
  30. SDK_VERSION = version;
  31. }
  32. /**
  33. * @license
  34. * Copyright 2017 Google LLC
  35. *
  36. * Licensed under the Apache License, Version 2.0 (the "License");
  37. * you may not use this file except in compliance with the License.
  38. * You may obtain a copy of the License at
  39. *
  40. * http://www.apache.org/licenses/LICENSE-2.0
  41. *
  42. * Unless required by applicable law or agreed to in writing, software
  43. * distributed under the License is distributed on an "AS IS" BASIS,
  44. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  45. * See the License for the specific language governing permissions and
  46. * limitations under the License.
  47. */
  48. /**
  49. * Wraps a DOM Storage object and:
  50. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  51. * - prefixes names with "firebase:" to avoid collisions with app data.
  52. *
  53. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  54. * and one for localStorage.
  55. *
  56. */
  57. class DOMStorageWrapper {
  58. /**
  59. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  60. */
  61. constructor(domStorage_) {
  62. this.domStorage_ = domStorage_;
  63. // Use a prefix to avoid collisions with other stuff saved by the app.
  64. this.prefix_ = 'firebase:';
  65. }
  66. /**
  67. * @param key - The key to save the value under
  68. * @param value - The value being stored, or null to remove the key.
  69. */
  70. set(key, value) {
  71. if (value == null) {
  72. this.domStorage_.removeItem(this.prefixedName_(key));
  73. }
  74. else {
  75. this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
  76. }
  77. }
  78. /**
  79. * @returns The value that was stored under this key, or null
  80. */
  81. get(key) {
  82. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  83. if (storedVal == null) {
  84. return null;
  85. }
  86. else {
  87. return jsonEval(storedVal);
  88. }
  89. }
  90. remove(key) {
  91. this.domStorage_.removeItem(this.prefixedName_(key));
  92. }
  93. prefixedName_(name) {
  94. return this.prefix_ + name;
  95. }
  96. toString() {
  97. return this.domStorage_.toString();
  98. }
  99. }
  100. /**
  101. * @license
  102. * Copyright 2017 Google LLC
  103. *
  104. * Licensed under the Apache License, Version 2.0 (the "License");
  105. * you may not use this file except in compliance with the License.
  106. * You may obtain a copy of the License at
  107. *
  108. * http://www.apache.org/licenses/LICENSE-2.0
  109. *
  110. * Unless required by applicable law or agreed to in writing, software
  111. * distributed under the License is distributed on an "AS IS" BASIS,
  112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  113. * See the License for the specific language governing permissions and
  114. * limitations under the License.
  115. */
  116. /**
  117. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  118. * (TODO: create interface for both to implement).
  119. */
  120. class MemoryStorage {
  121. constructor() {
  122. this.cache_ = {};
  123. this.isInMemoryStorage = true;
  124. }
  125. set(key, value) {
  126. if (value == null) {
  127. delete this.cache_[key];
  128. }
  129. else {
  130. this.cache_[key] = value;
  131. }
  132. }
  133. get(key) {
  134. if (contains(this.cache_, key)) {
  135. return this.cache_[key];
  136. }
  137. return null;
  138. }
  139. remove(key) {
  140. delete this.cache_[key];
  141. }
  142. }
  143. /**
  144. * @license
  145. * Copyright 2017 Google LLC
  146. *
  147. * Licensed under the Apache License, Version 2.0 (the "License");
  148. * you may not use this file except in compliance with the License.
  149. * You may obtain a copy of the License at
  150. *
  151. * http://www.apache.org/licenses/LICENSE-2.0
  152. *
  153. * Unless required by applicable law or agreed to in writing, software
  154. * distributed under the License is distributed on an "AS IS" BASIS,
  155. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  156. * See the License for the specific language governing permissions and
  157. * limitations under the License.
  158. */
  159. /**
  160. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  161. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  162. * to reflect this type
  163. *
  164. * @param domStorageName - Name of the underlying storage object
  165. * (e.g. 'localStorage' or 'sessionStorage').
  166. * @returns Turning off type information until a common interface is defined.
  167. */
  168. const createStoragefor = function (domStorageName) {
  169. try {
  170. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  171. // so it must be inside the try/catch.
  172. if (typeof window !== 'undefined' &&
  173. typeof window[domStorageName] !== 'undefined') {
  174. // Need to test cache. Just because it's here doesn't mean it works
  175. const domStorage = window[domStorageName];
  176. domStorage.setItem('firebase:sentinel', 'cache');
  177. domStorage.removeItem('firebase:sentinel');
  178. return new DOMStorageWrapper(domStorage);
  179. }
  180. }
  181. catch (e) { }
  182. // Failed to create wrapper. Just return in-memory storage.
  183. // TODO: log?
  184. return new MemoryStorage();
  185. };
  186. /** A storage object that lasts across sessions */
  187. const PersistentStorage = createStoragefor('localStorage');
  188. /** A storage object that only lasts one session */
  189. const SessionStorage = createStoragefor('sessionStorage');
  190. /**
  191. * @license
  192. * Copyright 2017 Google LLC
  193. *
  194. * Licensed under the Apache License, Version 2.0 (the "License");
  195. * you may not use this file except in compliance with the License.
  196. * You may obtain a copy of the License at
  197. *
  198. * http://www.apache.org/licenses/LICENSE-2.0
  199. *
  200. * Unless required by applicable law or agreed to in writing, software
  201. * distributed under the License is distributed on an "AS IS" BASIS,
  202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  203. * See the License for the specific language governing permissions and
  204. * limitations under the License.
  205. */
  206. const logClient = new Logger('@firebase/database');
  207. /**
  208. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  209. */
  210. const LUIDGenerator = (function () {
  211. let id = 1;
  212. return function () {
  213. return id++;
  214. };
  215. })();
  216. /**
  217. * Sha1 hash of the input string
  218. * @param str - The string to hash
  219. * @returns {!string} The resulting hash
  220. */
  221. const sha1 = function (str) {
  222. const utf8Bytes = stringToByteArray(str);
  223. const sha1 = new Sha1();
  224. sha1.update(utf8Bytes);
  225. const sha1Bytes = sha1.digest();
  226. return base64.encodeByteArray(sha1Bytes);
  227. };
  228. const buildLogMessage_ = function (...varArgs) {
  229. let message = '';
  230. for (let i = 0; i < varArgs.length; i++) {
  231. const arg = varArgs[i];
  232. if (Array.isArray(arg) ||
  233. (arg &&
  234. typeof arg === 'object' &&
  235. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  236. typeof arg.length === 'number')) {
  237. message += buildLogMessage_.apply(null, arg);
  238. }
  239. else if (typeof arg === 'object') {
  240. message += stringify(arg);
  241. }
  242. else {
  243. message += arg;
  244. }
  245. message += ' ';
  246. }
  247. return message;
  248. };
  249. /**
  250. * Use this for all debug messages in Firebase.
  251. */
  252. let logger = null;
  253. /**
  254. * Flag to check for log availability on first log message
  255. */
  256. let firstLog_ = true;
  257. /**
  258. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  259. * @param logger_ - A flag to turn on logging, or a custom logger
  260. * @param persistent - Whether or not to persist logging settings across refreshes
  261. */
  262. const enableLogging$1 = function (logger_, persistent) {
  263. assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  264. if (logger_ === true) {
  265. logClient.logLevel = LogLevel.VERBOSE;
  266. logger = logClient.log.bind(logClient);
  267. if (persistent) {
  268. SessionStorage.set('logging_enabled', true);
  269. }
  270. }
  271. else if (typeof logger_ === 'function') {
  272. logger = logger_;
  273. }
  274. else {
  275. logger = null;
  276. SessionStorage.remove('logging_enabled');
  277. }
  278. };
  279. const log = function (...varArgs) {
  280. if (firstLog_ === true) {
  281. firstLog_ = false;
  282. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  283. enableLogging$1(true);
  284. }
  285. }
  286. if (logger) {
  287. const message = buildLogMessage_.apply(null, varArgs);
  288. logger(message);
  289. }
  290. };
  291. const logWrapper = function (prefix) {
  292. return function (...varArgs) {
  293. log(prefix, ...varArgs);
  294. };
  295. };
  296. const error = function (...varArgs) {
  297. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  298. logClient.error(message);
  299. };
  300. const fatal = function (...varArgs) {
  301. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  302. logClient.error(message);
  303. throw new Error(message);
  304. };
  305. const warn = function (...varArgs) {
  306. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  307. logClient.warn(message);
  308. };
  309. /**
  310. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  311. * does not use https.
  312. */
  313. const warnIfPageIsSecure = function () {
  314. // Be very careful accessing browser globals. Who knows what may or may not exist.
  315. if (typeof window !== 'undefined' &&
  316. window.location &&
  317. window.location.protocol &&
  318. window.location.protocol.indexOf('https:') !== -1) {
  319. warn('Insecure Firebase access from a secure page. ' +
  320. 'Please use https in calls to new Firebase().');
  321. }
  322. };
  323. /**
  324. * Returns true if data is NaN, or +/- Infinity.
  325. */
  326. const isInvalidJSONNumber = function (data) {
  327. return (typeof data === 'number' &&
  328. (data !== data || // NaN
  329. data === Number.POSITIVE_INFINITY ||
  330. data === Number.NEGATIVE_INFINITY));
  331. };
  332. const executeWhenDOMReady = function (fn) {
  333. if (isNodeSdk() || document.readyState === 'complete') {
  334. fn();
  335. }
  336. else {
  337. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  338. // fire before onload), but fall back to onload.
  339. let called = false;
  340. const wrappedFn = function () {
  341. if (!document.body) {
  342. setTimeout(wrappedFn, Math.floor(10));
  343. return;
  344. }
  345. if (!called) {
  346. called = true;
  347. fn();
  348. }
  349. };
  350. if (document.addEventListener) {
  351. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  352. // fallback to onload.
  353. window.addEventListener('load', wrappedFn, false);
  354. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  355. }
  356. else if (document.attachEvent) {
  357. // IE.
  358. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  359. document.attachEvent('onreadystatechange', () => {
  360. if (document.readyState === 'complete') {
  361. wrappedFn();
  362. }
  363. });
  364. // fallback to onload.
  365. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  366. window.attachEvent('onload', wrappedFn);
  367. // jQuery has an extra hack for IE that we could employ (based on
  368. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  369. // I'm hoping we don't need it.
  370. }
  371. }
  372. };
  373. /**
  374. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  375. */
  376. const MIN_NAME = '[MIN_NAME]';
  377. /**
  378. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  379. */
  380. const MAX_NAME = '[MAX_NAME]';
  381. /**
  382. * Compares valid Firebase key names, plus min and max name
  383. */
  384. const nameCompare = function (a, b) {
  385. if (a === b) {
  386. return 0;
  387. }
  388. else if (a === MIN_NAME || b === MAX_NAME) {
  389. return -1;
  390. }
  391. else if (b === MIN_NAME || a === MAX_NAME) {
  392. return 1;
  393. }
  394. else {
  395. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  396. if (aAsInt !== null) {
  397. if (bAsInt !== null) {
  398. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  399. }
  400. else {
  401. return -1;
  402. }
  403. }
  404. else if (bAsInt !== null) {
  405. return 1;
  406. }
  407. else {
  408. return a < b ? -1 : 1;
  409. }
  410. }
  411. };
  412. /**
  413. * @returns {!number} comparison result.
  414. */
  415. const stringCompare = function (a, b) {
  416. if (a === b) {
  417. return 0;
  418. }
  419. else if (a < b) {
  420. return -1;
  421. }
  422. else {
  423. return 1;
  424. }
  425. };
  426. const requireKey = function (key, obj) {
  427. if (obj && key in obj) {
  428. return obj[key];
  429. }
  430. else {
  431. throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
  432. }
  433. };
  434. const ObjectToUniqueKey = function (obj) {
  435. if (typeof obj !== 'object' || obj === null) {
  436. return stringify(obj);
  437. }
  438. const keys = [];
  439. // eslint-disable-next-line guard-for-in
  440. for (const k in obj) {
  441. keys.push(k);
  442. }
  443. // Export as json, but with the keys sorted.
  444. keys.sort();
  445. let key = '{';
  446. for (let i = 0; i < keys.length; i++) {
  447. if (i !== 0) {
  448. key += ',';
  449. }
  450. key += stringify(keys[i]);
  451. key += ':';
  452. key += ObjectToUniqueKey(obj[keys[i]]);
  453. }
  454. key += '}';
  455. return key;
  456. };
  457. /**
  458. * Splits a string into a number of smaller segments of maximum size
  459. * @param str - The string
  460. * @param segsize - The maximum number of chars in the string.
  461. * @returns The string, split into appropriately-sized chunks
  462. */
  463. const splitStringBySize = function (str, segsize) {
  464. const len = str.length;
  465. if (len <= segsize) {
  466. return [str];
  467. }
  468. const dataSegs = [];
  469. for (let c = 0; c < len; c += segsize) {
  470. if (c + segsize > len) {
  471. dataSegs.push(str.substring(c, len));
  472. }
  473. else {
  474. dataSegs.push(str.substring(c, c + segsize));
  475. }
  476. }
  477. return dataSegs;
  478. };
  479. /**
  480. * Apply a function to each (key, value) pair in an object or
  481. * apply a function to each (index, value) pair in an array
  482. * @param obj - The object or array to iterate over
  483. * @param fn - The function to apply
  484. */
  485. function each(obj, fn) {
  486. for (const key in obj) {
  487. if (obj.hasOwnProperty(key)) {
  488. fn(key, obj[key]);
  489. }
  490. }
  491. }
  492. /**
  493. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  494. * I made one modification at the end and removed the NaN / Infinity
  495. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  496. * @param v - A double
  497. *
  498. */
  499. const doubleToIEEE754String = function (v) {
  500. assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  501. const ebits = 11, fbits = 52;
  502. const bias = (1 << (ebits - 1)) - 1;
  503. let s, e, f, ln, i;
  504. // Compute sign, exponent, fraction
  505. // Skip NaN / Infinity handling --MJL.
  506. if (v === 0) {
  507. e = 0;
  508. f = 0;
  509. s = 1 / v === -Infinity ? 1 : 0;
  510. }
  511. else {
  512. s = v < 0;
  513. v = Math.abs(v);
  514. if (v >= Math.pow(2, 1 - bias)) {
  515. // Normalized
  516. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  517. e = ln + bias;
  518. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  519. }
  520. else {
  521. // Denormalized
  522. e = 0;
  523. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  524. }
  525. }
  526. // Pack sign, exponent, fraction
  527. const bits = [];
  528. for (i = fbits; i; i -= 1) {
  529. bits.push(f % 2 ? 1 : 0);
  530. f = Math.floor(f / 2);
  531. }
  532. for (i = ebits; i; i -= 1) {
  533. bits.push(e % 2 ? 1 : 0);
  534. e = Math.floor(e / 2);
  535. }
  536. bits.push(s ? 1 : 0);
  537. bits.reverse();
  538. const str = bits.join('');
  539. // Return the data as a hex string. --MJL
  540. let hexByteString = '';
  541. for (i = 0; i < 64; i += 8) {
  542. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  543. if (hexByte.length === 1) {
  544. hexByte = '0' + hexByte;
  545. }
  546. hexByteString = hexByteString + hexByte;
  547. }
  548. return hexByteString.toLowerCase();
  549. };
  550. /**
  551. * Used to detect if we're in a Chrome content script (which executes in an
  552. * isolated environment where long-polling doesn't work).
  553. */
  554. const isChromeExtensionContentScript = function () {
  555. return !!(typeof window === 'object' &&
  556. window['chrome'] &&
  557. window['chrome']['extension'] &&
  558. !/^chrome/.test(window.location.href));
  559. };
  560. /**
  561. * Used to detect if we're in a Windows 8 Store app.
  562. */
  563. const isWindowsStoreApp = function () {
  564. // Check for the presence of a couple WinRT globals
  565. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  566. };
  567. /**
  568. * Converts a server error code to a Javascript Error
  569. */
  570. function errorForServerCode(code, query) {
  571. let reason = 'Unknown Error';
  572. if (code === 'too_big') {
  573. reason =
  574. 'The data requested exceeds the maximum size ' +
  575. 'that can be accessed with a single request.';
  576. }
  577. else if (code === 'permission_denied') {
  578. reason = "Client doesn't have permission to access the desired data.";
  579. }
  580. else if (code === 'unavailable') {
  581. reason = 'The service is unavailable';
  582. }
  583. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  584. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  585. error.code = code.toUpperCase();
  586. return error;
  587. }
  588. /**
  589. * Used to test for integer-looking strings
  590. */
  591. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  592. /**
  593. * For use in keys, the minimum possible 32-bit integer.
  594. */
  595. const INTEGER_32_MIN = -2147483648;
  596. /**
  597. * For use in kyes, the maximum possible 32-bit integer.
  598. */
  599. const INTEGER_32_MAX = 2147483647;
  600. /**
  601. * If the string contains a 32-bit integer, return it. Else return null.
  602. */
  603. const tryParseInt = function (str) {
  604. if (INTEGER_REGEXP_.test(str)) {
  605. const intVal = Number(str);
  606. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  607. return intVal;
  608. }
  609. }
  610. return null;
  611. };
  612. /**
  613. * Helper to run some code but catch any exceptions and re-throw them later.
  614. * Useful for preventing user callbacks from breaking internal code.
  615. *
  616. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  617. * convenient (we don't have to try to figure out when is a safe point to
  618. * re-throw it), and the behavior seems reasonable:
  619. *
  620. * * If you aren't pausing on exceptions, you get an error in the console with
  621. * the correct stack trace.
  622. * * If you're pausing on all exceptions, the debugger will pause on your
  623. * exception and then again when we rethrow it.
  624. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  625. * on us re-throwing it.
  626. *
  627. * @param fn - The code to guard.
  628. */
  629. const exceptionGuard = function (fn) {
  630. try {
  631. fn();
  632. }
  633. catch (e) {
  634. // Re-throw exception when it's safe.
  635. setTimeout(() => {
  636. // It used to be that "throw e" would result in a good console error with
  637. // relevant context, but as of Chrome 39, you just get the firebase.js
  638. // file/line number where we re-throw it, which is useless. So we log
  639. // e.stack explicitly.
  640. const stack = e.stack || '';
  641. warn('Exception was thrown by user callback.', stack);
  642. throw e;
  643. }, Math.floor(0));
  644. }
  645. };
  646. /**
  647. * @returns {boolean} true if we think we're currently being crawled.
  648. */
  649. const beingCrawled = function () {
  650. const userAgent = (typeof window === 'object' &&
  651. window['navigator'] &&
  652. window['navigator']['userAgent']) ||
  653. '';
  654. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  655. // believe to support JavaScript/AJAX rendering.
  656. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  657. // would have seen the page" is flaky if we don't treat it as a crawler.
  658. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  659. };
  660. /**
  661. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  662. *
  663. * It is removed with clearTimeout() as normal.
  664. *
  665. * @param fn - Function to run.
  666. * @param time - Milliseconds to wait before running.
  667. * @returns The setTimeout() return value.
  668. */
  669. const setTimeoutNonBlocking = function (fn, time) {
  670. const timeout = setTimeout(fn, time);
  671. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  672. if (typeof timeout === 'number' &&
  673. // @ts-ignore Is only defined in Deno environments.
  674. typeof Deno !== 'undefined' &&
  675. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  676. Deno['unrefTimer']) {
  677. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  678. Deno.unrefTimer(timeout);
  679. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  680. }
  681. else if (typeof timeout === 'object' && timeout['unref']) {
  682. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  683. timeout['unref']();
  684. }
  685. return timeout;
  686. };
  687. /**
  688. * @license
  689. * Copyright 2021 Google LLC
  690. *
  691. * Licensed under the Apache License, Version 2.0 (the "License");
  692. * you may not use this file except in compliance with the License.
  693. * You may obtain a copy of the License at
  694. *
  695. * http://www.apache.org/licenses/LICENSE-2.0
  696. *
  697. * Unless required by applicable law or agreed to in writing, software
  698. * distributed under the License is distributed on an "AS IS" BASIS,
  699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  700. * See the License for the specific language governing permissions and
  701. * limitations under the License.
  702. */
  703. /**
  704. * Abstraction around AppCheck's token fetching capabilities.
  705. */
  706. class AppCheckTokenProvider {
  707. constructor(appName_, appCheckProvider) {
  708. this.appName_ = appName_;
  709. this.appCheckProvider = appCheckProvider;
  710. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  711. if (!this.appCheck) {
  712. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  713. }
  714. }
  715. getToken(forceRefresh) {
  716. if (!this.appCheck) {
  717. return new Promise((resolve, reject) => {
  718. // Support delayed initialization of FirebaseAppCheck. This allows our
  719. // customers to initialize the RTDB SDK before initializing Firebase
  720. // AppCheck and ensures that all requests are authenticated if a token
  721. // becomes available before the timoeout below expires.
  722. setTimeout(() => {
  723. if (this.appCheck) {
  724. this.getToken(forceRefresh).then(resolve, reject);
  725. }
  726. else {
  727. resolve(null);
  728. }
  729. }, 0);
  730. });
  731. }
  732. return this.appCheck.getToken(forceRefresh);
  733. }
  734. addTokenChangeListener(listener) {
  735. var _a;
  736. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  737. }
  738. notifyForInvalidToken() {
  739. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  740. 'are invalid. This usually indicates your app was not initialized correctly.');
  741. }
  742. }
  743. /**
  744. * @license
  745. * Copyright 2017 Google LLC
  746. *
  747. * Licensed under the Apache License, Version 2.0 (the "License");
  748. * you may not use this file except in compliance with the License.
  749. * You may obtain a copy of the License at
  750. *
  751. * http://www.apache.org/licenses/LICENSE-2.0
  752. *
  753. * Unless required by applicable law or agreed to in writing, software
  754. * distributed under the License is distributed on an "AS IS" BASIS,
  755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  756. * See the License for the specific language governing permissions and
  757. * limitations under the License.
  758. */
  759. /**
  760. * Abstraction around FirebaseApp's token fetching capabilities.
  761. */
  762. class FirebaseAuthTokenProvider {
  763. constructor(appName_, firebaseOptions_, authProvider_) {
  764. this.appName_ = appName_;
  765. this.firebaseOptions_ = firebaseOptions_;
  766. this.authProvider_ = authProvider_;
  767. this.auth_ = null;
  768. this.auth_ = authProvider_.getImmediate({ optional: true });
  769. if (!this.auth_) {
  770. authProvider_.onInit(auth => (this.auth_ = auth));
  771. }
  772. }
  773. getToken(forceRefresh) {
  774. if (!this.auth_) {
  775. return new Promise((resolve, reject) => {
  776. // Support delayed initialization of FirebaseAuth. This allows our
  777. // customers to initialize the RTDB SDK before initializing Firebase
  778. // Auth and ensures that all requests are authenticated if a token
  779. // becomes available before the timoeout below expires.
  780. setTimeout(() => {
  781. if (this.auth_) {
  782. this.getToken(forceRefresh).then(resolve, reject);
  783. }
  784. else {
  785. resolve(null);
  786. }
  787. }, 0);
  788. });
  789. }
  790. return this.auth_.getToken(forceRefresh).catch(error => {
  791. // TODO: Need to figure out all the cases this is raised and whether
  792. // this makes sense.
  793. if (error && error.code === 'auth/token-not-initialized') {
  794. log('Got auth/token-not-initialized error. Treating as null token.');
  795. return null;
  796. }
  797. else {
  798. return Promise.reject(error);
  799. }
  800. });
  801. }
  802. addTokenChangeListener(listener) {
  803. // TODO: We might want to wrap the listener and call it with no args to
  804. // avoid a leaky abstraction, but that makes removing the listener harder.
  805. if (this.auth_) {
  806. this.auth_.addAuthTokenListener(listener);
  807. }
  808. else {
  809. this.authProvider_
  810. .get()
  811. .then(auth => auth.addAuthTokenListener(listener));
  812. }
  813. }
  814. removeTokenChangeListener(listener) {
  815. this.authProvider_
  816. .get()
  817. .then(auth => auth.removeAuthTokenListener(listener));
  818. }
  819. notifyForInvalidToken() {
  820. let errorMessage = 'Provided authentication credentials for the app named "' +
  821. this.appName_ +
  822. '" are invalid. This usually indicates your app was not ' +
  823. 'initialized correctly. ';
  824. if ('credential' in this.firebaseOptions_) {
  825. errorMessage +=
  826. 'Make sure the "credential" property provided to initializeApp() ' +
  827. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  828. 'project.';
  829. }
  830. else if ('serviceAccount' in this.firebaseOptions_) {
  831. errorMessage +=
  832. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  833. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  834. 'project.';
  835. }
  836. else {
  837. errorMessage +=
  838. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  839. 'initializeApp() match the values provided for your app at ' +
  840. 'https://console.firebase.google.com/.';
  841. }
  842. warn(errorMessage);
  843. }
  844. }
  845. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  846. class EmulatorTokenProvider {
  847. constructor(accessToken) {
  848. this.accessToken = accessToken;
  849. }
  850. getToken(forceRefresh) {
  851. return Promise.resolve({
  852. accessToken: this.accessToken
  853. });
  854. }
  855. addTokenChangeListener(listener) {
  856. // Invoke the listener immediately to match the behavior in Firebase Auth
  857. // (see packages/auth/src/auth.js#L1807)
  858. listener(this.accessToken);
  859. }
  860. removeTokenChangeListener(listener) { }
  861. notifyForInvalidToken() { }
  862. }
  863. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  864. EmulatorTokenProvider.OWNER = 'owner';
  865. /**
  866. * @license
  867. * Copyright 2017 Google LLC
  868. *
  869. * Licensed under the Apache License, Version 2.0 (the "License");
  870. * you may not use this file except in compliance with the License.
  871. * You may obtain a copy of the License at
  872. *
  873. * http://www.apache.org/licenses/LICENSE-2.0
  874. *
  875. * Unless required by applicable law or agreed to in writing, software
  876. * distributed under the License is distributed on an "AS IS" BASIS,
  877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  878. * See the License for the specific language governing permissions and
  879. * limitations under the License.
  880. */
  881. const PROTOCOL_VERSION = '5';
  882. const VERSION_PARAM = 'v';
  883. const TRANSPORT_SESSION_PARAM = 's';
  884. const REFERER_PARAM = 'r';
  885. const FORGE_REF = 'f';
  886. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  887. // firebase.corp.google.com
  888. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  889. const LAST_SESSION_PARAM = 'ls';
  890. const APPLICATION_ID_PARAM = 'p';
  891. const APP_CHECK_TOKEN_PARAM = 'ac';
  892. const WEBSOCKET = 'websocket';
  893. const LONG_POLLING = 'long_polling';
  894. /**
  895. * @license
  896. * Copyright 2017 Google LLC
  897. *
  898. * Licensed under the Apache License, Version 2.0 (the "License");
  899. * you may not use this file except in compliance with the License.
  900. * You may obtain a copy of the License at
  901. *
  902. * http://www.apache.org/licenses/LICENSE-2.0
  903. *
  904. * Unless required by applicable law or agreed to in writing, software
  905. * distributed under the License is distributed on an "AS IS" BASIS,
  906. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  907. * See the License for the specific language governing permissions and
  908. * limitations under the License.
  909. */
  910. /**
  911. * A class that holds metadata about a Repo object
  912. */
  913. class RepoInfo {
  914. /**
  915. * @param host - Hostname portion of the url for the repo
  916. * @param secure - Whether or not this repo is accessed over ssl
  917. * @param namespace - The namespace represented by the repo
  918. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  919. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  920. * @param persistenceKey - Override the default session persistence storage key
  921. */
  922. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {
  923. this.secure = secure;
  924. this.namespace = namespace;
  925. this.webSocketOnly = webSocketOnly;
  926. this.nodeAdmin = nodeAdmin;
  927. this.persistenceKey = persistenceKey;
  928. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  929. this.isUsingEmulator = isUsingEmulator;
  930. this._host = host.toLowerCase();
  931. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  932. this.internalHost =
  933. PersistentStorage.get('host:' + host) || this._host;
  934. }
  935. isCacheableHost() {
  936. return this.internalHost.substr(0, 2) === 's-';
  937. }
  938. isCustomHost() {
  939. return (this._domain !== 'firebaseio.com' &&
  940. this._domain !== 'firebaseio-demo.com');
  941. }
  942. get host() {
  943. return this._host;
  944. }
  945. set host(newHost) {
  946. if (newHost !== this.internalHost) {
  947. this.internalHost = newHost;
  948. if (this.isCacheableHost()) {
  949. PersistentStorage.set('host:' + this._host, this.internalHost);
  950. }
  951. }
  952. }
  953. toString() {
  954. let str = this.toURLString();
  955. if (this.persistenceKey) {
  956. str += '<' + this.persistenceKey + '>';
  957. }
  958. return str;
  959. }
  960. toURLString() {
  961. const protocol = this.secure ? 'https://' : 'http://';
  962. const query = this.includeNamespaceInQueryParams
  963. ? `?ns=${this.namespace}`
  964. : '';
  965. return `${protocol}${this.host}/${query}`;
  966. }
  967. }
  968. function repoInfoNeedsQueryParam(repoInfo) {
  969. return (repoInfo.host !== repoInfo.internalHost ||
  970. repoInfo.isCustomHost() ||
  971. repoInfo.includeNamespaceInQueryParams);
  972. }
  973. /**
  974. * Returns the websocket URL for this repo
  975. * @param repoInfo - RepoInfo object
  976. * @param type - of connection
  977. * @param params - list
  978. * @returns The URL for this repo
  979. */
  980. function repoInfoConnectionURL(repoInfo, type, params) {
  981. assert(typeof type === 'string', 'typeof type must == string');
  982. assert(typeof params === 'object', 'typeof params must == object');
  983. let connURL;
  984. if (type === WEBSOCKET) {
  985. connURL =
  986. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  987. }
  988. else if (type === LONG_POLLING) {
  989. connURL =
  990. (repoInfo.secure ? 'https://' : 'http://') +
  991. repoInfo.internalHost +
  992. '/.lp?';
  993. }
  994. else {
  995. throw new Error('Unknown connection type: ' + type);
  996. }
  997. if (repoInfoNeedsQueryParam(repoInfo)) {
  998. params['ns'] = repoInfo.namespace;
  999. }
  1000. const pairs = [];
  1001. each(params, (key, value) => {
  1002. pairs.push(key + '=' + value);
  1003. });
  1004. return connURL + pairs.join('&');
  1005. }
  1006. /**
  1007. * @license
  1008. * Copyright 2017 Google LLC
  1009. *
  1010. * Licensed under the Apache License, Version 2.0 (the "License");
  1011. * you may not use this file except in compliance with the License.
  1012. * You may obtain a copy of the License at
  1013. *
  1014. * http://www.apache.org/licenses/LICENSE-2.0
  1015. *
  1016. * Unless required by applicable law or agreed to in writing, software
  1017. * distributed under the License is distributed on an "AS IS" BASIS,
  1018. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1019. * See the License for the specific language governing permissions and
  1020. * limitations under the License.
  1021. */
  1022. /**
  1023. * Tracks a collection of stats.
  1024. */
  1025. class StatsCollection {
  1026. constructor() {
  1027. this.counters_ = {};
  1028. }
  1029. incrementCounter(name, amount = 1) {
  1030. if (!contains(this.counters_, name)) {
  1031. this.counters_[name] = 0;
  1032. }
  1033. this.counters_[name] += amount;
  1034. }
  1035. get() {
  1036. return deepCopy(this.counters_);
  1037. }
  1038. }
  1039. /**
  1040. * @license
  1041. * Copyright 2017 Google LLC
  1042. *
  1043. * Licensed under the Apache License, Version 2.0 (the "License");
  1044. * you may not use this file except in compliance with the License.
  1045. * You may obtain a copy of the License at
  1046. *
  1047. * http://www.apache.org/licenses/LICENSE-2.0
  1048. *
  1049. * Unless required by applicable law or agreed to in writing, software
  1050. * distributed under the License is distributed on an "AS IS" BASIS,
  1051. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1052. * See the License for the specific language governing permissions and
  1053. * limitations under the License.
  1054. */
  1055. const collections = {};
  1056. const reporters = {};
  1057. function statsManagerGetCollection(repoInfo) {
  1058. const hashString = repoInfo.toString();
  1059. if (!collections[hashString]) {
  1060. collections[hashString] = new StatsCollection();
  1061. }
  1062. return collections[hashString];
  1063. }
  1064. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  1065. const hashString = repoInfo.toString();
  1066. if (!reporters[hashString]) {
  1067. reporters[hashString] = creatorFunction();
  1068. }
  1069. return reporters[hashString];
  1070. }
  1071. /**
  1072. * @license
  1073. * Copyright 2017 Google LLC
  1074. *
  1075. * Licensed under the Apache License, Version 2.0 (the "License");
  1076. * you may not use this file except in compliance with the License.
  1077. * You may obtain a copy of the License at
  1078. *
  1079. * http://www.apache.org/licenses/LICENSE-2.0
  1080. *
  1081. * Unless required by applicable law or agreed to in writing, software
  1082. * distributed under the License is distributed on an "AS IS" BASIS,
  1083. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1084. * See the License for the specific language governing permissions and
  1085. * limitations under the License.
  1086. */
  1087. /**
  1088. * This class ensures the packets from the server arrive in order
  1089. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1090. */
  1091. class PacketReceiver {
  1092. /**
  1093. * @param onMessage_
  1094. */
  1095. constructor(onMessage_) {
  1096. this.onMessage_ = onMessage_;
  1097. this.pendingResponses = [];
  1098. this.currentResponseNum = 0;
  1099. this.closeAfterResponse = -1;
  1100. this.onClose = null;
  1101. }
  1102. closeAfter(responseNum, callback) {
  1103. this.closeAfterResponse = responseNum;
  1104. this.onClose = callback;
  1105. if (this.closeAfterResponse < this.currentResponseNum) {
  1106. this.onClose();
  1107. this.onClose = null;
  1108. }
  1109. }
  1110. /**
  1111. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1112. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1113. * browsers will respond in the same order as the requests we sent
  1114. */
  1115. handleResponse(requestNum, data) {
  1116. this.pendingResponses[requestNum] = data;
  1117. while (this.pendingResponses[this.currentResponseNum]) {
  1118. const toProcess = this.pendingResponses[this.currentResponseNum];
  1119. delete this.pendingResponses[this.currentResponseNum];
  1120. for (let i = 0; i < toProcess.length; ++i) {
  1121. if (toProcess[i]) {
  1122. exceptionGuard(() => {
  1123. this.onMessage_(toProcess[i]);
  1124. });
  1125. }
  1126. }
  1127. if (this.currentResponseNum === this.closeAfterResponse) {
  1128. if (this.onClose) {
  1129. this.onClose();
  1130. this.onClose = null;
  1131. }
  1132. break;
  1133. }
  1134. this.currentResponseNum++;
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * @license
  1140. * Copyright 2017 Google LLC
  1141. *
  1142. * Licensed under the Apache License, Version 2.0 (the "License");
  1143. * you may not use this file except in compliance with the License.
  1144. * You may obtain a copy of the License at
  1145. *
  1146. * http://www.apache.org/licenses/LICENSE-2.0
  1147. *
  1148. * Unless required by applicable law or agreed to in writing, software
  1149. * distributed under the License is distributed on an "AS IS" BASIS,
  1150. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1151. * See the License for the specific language governing permissions and
  1152. * limitations under the License.
  1153. */
  1154. // URL query parameters associated with longpolling
  1155. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1156. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1157. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1158. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1159. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1160. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1161. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1162. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1163. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1164. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1165. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1166. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1167. //Data size constants.
  1168. //TODO: Perf: the maximum length actually differs from browser to browser.
  1169. // We should check what browser we're on and set accordingly.
  1170. const MAX_URL_DATA_SIZE = 1870;
  1171. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1172. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1173. /**
  1174. * Keepalive period
  1175. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1176. * length of 30 seconds that we can't exceed.
  1177. */
  1178. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1179. /**
  1180. * How long to wait before aborting a long-polling connection attempt.
  1181. */
  1182. const LP_CONNECT_TIMEOUT = 30000;
  1183. /**
  1184. * This class manages a single long-polling connection.
  1185. */
  1186. class BrowserPollConnection {
  1187. /**
  1188. * @param connId An identifier for this connection, used for logging
  1189. * @param repoInfo The info for the endpoint to send data to.
  1190. * @param applicationId The Firebase App ID for this project.
  1191. * @param appCheckToken The AppCheck token for this client.
  1192. * @param authToken The AuthToken to use for this connection.
  1193. * @param transportSessionId Optional transportSessionid if we are
  1194. * reconnecting for an existing transport session
  1195. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1196. * already created a connection previously
  1197. */
  1198. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1199. this.connId = connId;
  1200. this.repoInfo = repoInfo;
  1201. this.applicationId = applicationId;
  1202. this.appCheckToken = appCheckToken;
  1203. this.authToken = authToken;
  1204. this.transportSessionId = transportSessionId;
  1205. this.lastSessionId = lastSessionId;
  1206. this.bytesSent = 0;
  1207. this.bytesReceived = 0;
  1208. this.everConnected_ = false;
  1209. this.log_ = logWrapper(connId);
  1210. this.stats_ = statsManagerGetCollection(repoInfo);
  1211. this.urlFn = (params) => {
  1212. // Always add the token if we have one.
  1213. if (this.appCheckToken) {
  1214. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1215. }
  1216. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1217. };
  1218. }
  1219. /**
  1220. * @param onMessage - Callback when messages arrive
  1221. * @param onDisconnect - Callback with connection lost.
  1222. */
  1223. open(onMessage, onDisconnect) {
  1224. this.curSegmentNum = 0;
  1225. this.onDisconnect_ = onDisconnect;
  1226. this.myPacketOrderer = new PacketReceiver(onMessage);
  1227. this.isClosed_ = false;
  1228. this.connectTimeoutTimer_ = setTimeout(() => {
  1229. this.log_('Timed out trying to connect.');
  1230. // Make sure we clear the host cache
  1231. this.onClosed_();
  1232. this.connectTimeoutTimer_ = null;
  1233. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1234. }, Math.floor(LP_CONNECT_TIMEOUT));
  1235. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1236. executeWhenDOMReady(() => {
  1237. if (this.isClosed_) {
  1238. return;
  1239. }
  1240. //Set up a callback that gets triggered once a connection is set up.
  1241. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1242. const [command, arg1, arg2, arg3, arg4] = args;
  1243. this.incrementIncomingBytes_(args);
  1244. if (!this.scriptTagHolder) {
  1245. return; // we closed the connection.
  1246. }
  1247. if (this.connectTimeoutTimer_) {
  1248. clearTimeout(this.connectTimeoutTimer_);
  1249. this.connectTimeoutTimer_ = null;
  1250. }
  1251. this.everConnected_ = true;
  1252. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1253. this.id = arg1;
  1254. this.password = arg2;
  1255. }
  1256. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1257. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1258. if (arg1) {
  1259. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1260. // through our already open polls), so don't send any more.
  1261. this.scriptTagHolder.sendNewPolls = false;
  1262. // arg1 in this case is the last response number sent by the server. We should try to receive
  1263. // all of the responses up to this one before closing
  1264. this.myPacketOrderer.closeAfter(arg1, () => {
  1265. this.onClosed_();
  1266. });
  1267. }
  1268. else {
  1269. this.onClosed_();
  1270. }
  1271. }
  1272. else {
  1273. throw new Error('Unrecognized command received: ' + command);
  1274. }
  1275. }, (...args) => {
  1276. const [pN, data] = args;
  1277. this.incrementIncomingBytes_(args);
  1278. this.myPacketOrderer.handleResponse(pN, data);
  1279. }, () => {
  1280. this.onClosed_();
  1281. }, this.urlFn);
  1282. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1283. //from cache.
  1284. const urlParams = {};
  1285. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1286. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1287. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1288. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1289. this.scriptTagHolder.uniqueCallbackIdentifier;
  1290. }
  1291. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1292. if (this.transportSessionId) {
  1293. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1294. }
  1295. if (this.lastSessionId) {
  1296. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1297. }
  1298. if (this.applicationId) {
  1299. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1300. }
  1301. if (this.appCheckToken) {
  1302. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1303. }
  1304. if (typeof location !== 'undefined' &&
  1305. location.hostname &&
  1306. FORGE_DOMAIN_RE.test(location.hostname)) {
  1307. urlParams[REFERER_PARAM] = FORGE_REF;
  1308. }
  1309. const connectURL = this.urlFn(urlParams);
  1310. this.log_('Connecting via long-poll to ' + connectURL);
  1311. this.scriptTagHolder.addTag(connectURL, () => {
  1312. /* do nothing */
  1313. });
  1314. });
  1315. }
  1316. /**
  1317. * Call this when a handshake has completed successfully and we want to consider the connection established
  1318. */
  1319. start() {
  1320. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1321. this.addDisconnectPingFrame(this.id, this.password);
  1322. }
  1323. /**
  1324. * Forces long polling to be considered as a potential transport
  1325. */
  1326. static forceAllow() {
  1327. BrowserPollConnection.forceAllow_ = true;
  1328. }
  1329. /**
  1330. * Forces longpolling to not be considered as a potential transport
  1331. */
  1332. static forceDisallow() {
  1333. BrowserPollConnection.forceDisallow_ = true;
  1334. }
  1335. // Static method, use string literal so it can be accessed in a generic way
  1336. static isAvailable() {
  1337. if (isNodeSdk()) {
  1338. return false;
  1339. }
  1340. else if (BrowserPollConnection.forceAllow_) {
  1341. return true;
  1342. }
  1343. else {
  1344. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1345. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1346. return (!BrowserPollConnection.forceDisallow_ &&
  1347. typeof document !== 'undefined' &&
  1348. document.createElement != null &&
  1349. !isChromeExtensionContentScript() &&
  1350. !isWindowsStoreApp());
  1351. }
  1352. }
  1353. /**
  1354. * No-op for polling
  1355. */
  1356. markConnectionHealthy() { }
  1357. /**
  1358. * Stops polling and cleans up the iframe
  1359. */
  1360. shutdown_() {
  1361. this.isClosed_ = true;
  1362. if (this.scriptTagHolder) {
  1363. this.scriptTagHolder.close();
  1364. this.scriptTagHolder = null;
  1365. }
  1366. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1367. if (this.myDisconnFrame) {
  1368. document.body.removeChild(this.myDisconnFrame);
  1369. this.myDisconnFrame = null;
  1370. }
  1371. if (this.connectTimeoutTimer_) {
  1372. clearTimeout(this.connectTimeoutTimer_);
  1373. this.connectTimeoutTimer_ = null;
  1374. }
  1375. }
  1376. /**
  1377. * Triggered when this transport is closed
  1378. */
  1379. onClosed_() {
  1380. if (!this.isClosed_) {
  1381. this.log_('Longpoll is closing itself');
  1382. this.shutdown_();
  1383. if (this.onDisconnect_) {
  1384. this.onDisconnect_(this.everConnected_);
  1385. this.onDisconnect_ = null;
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1391. * that we've left.
  1392. */
  1393. close() {
  1394. if (!this.isClosed_) {
  1395. this.log_('Longpoll is being closed.');
  1396. this.shutdown_();
  1397. }
  1398. }
  1399. /**
  1400. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1401. * broken into chunks (since URLs have a small maximum length).
  1402. * @param data - The JSON data to transmit.
  1403. */
  1404. send(data) {
  1405. const dataStr = stringify(data);
  1406. this.bytesSent += dataStr.length;
  1407. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1408. //first, lets get the base64-encoded data
  1409. const base64data = base64Encode(dataStr);
  1410. //We can only fit a certain amount in each URL, so we need to split this request
  1411. //up into multiple pieces if it doesn't fit in one request.
  1412. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1413. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1414. //of segments so that we can reassemble the packet on the server.
  1415. for (let i = 0; i < dataSegs.length; i++) {
  1416. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1417. this.curSegmentNum++;
  1418. }
  1419. }
  1420. /**
  1421. * This is how we notify the server that we're leaving.
  1422. * We aren't able to send requests with DHTML on a window close event, but we can
  1423. * trigger XHR requests in some browsers (everything but Opera basically).
  1424. */
  1425. addDisconnectPingFrame(id, pw) {
  1426. if (isNodeSdk()) {
  1427. return;
  1428. }
  1429. this.myDisconnFrame = document.createElement('iframe');
  1430. const urlParams = {};
  1431. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1432. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1433. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1434. this.myDisconnFrame.src = this.urlFn(urlParams);
  1435. this.myDisconnFrame.style.display = 'none';
  1436. document.body.appendChild(this.myDisconnFrame);
  1437. }
  1438. /**
  1439. * Used to track the bytes received by this client
  1440. */
  1441. incrementIncomingBytes_(args) {
  1442. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1443. const bytesReceived = stringify(args).length;
  1444. this.bytesReceived += bytesReceived;
  1445. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1446. }
  1447. }
  1448. /*********************************************************************************************
  1449. * A wrapper around an iframe that is used as a long-polling script holder.
  1450. *********************************************************************************************/
  1451. class FirebaseIFrameScriptHolder {
  1452. /**
  1453. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1454. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1455. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1456. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1457. */
  1458. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1459. this.onDisconnect = onDisconnect;
  1460. this.urlFn = urlFn;
  1461. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1462. //problems in some browsers.
  1463. this.outstandingRequests = new Set();
  1464. //A queue of the pending segments waiting for transmission to the server.
  1465. this.pendingSegs = [];
  1466. //A serial number. We use this for two things:
  1467. // 1) A way to ensure the browser doesn't cache responses to polls
  1468. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1469. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1470. // JSONP code in the order it was added to the iframe.
  1471. this.currentSerial = Math.floor(Math.random() * 100000000);
  1472. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1473. // incoming data from the server that we're waiting for).
  1474. this.sendNewPolls = true;
  1475. if (!isNodeSdk()) {
  1476. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1477. //iframes where we put the long-polling script tags. We have two callbacks:
  1478. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1479. // 2) Message Callback - Triggered when new data arrives.
  1480. this.uniqueCallbackIdentifier = LUIDGenerator();
  1481. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1482. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1483. onMessageCB;
  1484. //Create an iframe for us to add script tags to.
  1485. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1486. // Set the iframe's contents.
  1487. let script = '';
  1488. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1489. // for ie9, but ie8 needs to do it again in the document itself.
  1490. if (this.myIFrame.src &&
  1491. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1492. const currentDomain = document.domain;
  1493. script = '<script>document.domain="' + currentDomain + '";</script>';
  1494. }
  1495. const iframeContents = '<html><body>' + script + '</body></html>';
  1496. try {
  1497. this.myIFrame.doc.open();
  1498. this.myIFrame.doc.write(iframeContents);
  1499. this.myIFrame.doc.close();
  1500. }
  1501. catch (e) {
  1502. log('frame writing exception');
  1503. if (e.stack) {
  1504. log(e.stack);
  1505. }
  1506. log(e);
  1507. }
  1508. }
  1509. else {
  1510. this.commandCB = commandCB;
  1511. this.onMessageCB = onMessageCB;
  1512. }
  1513. }
  1514. /**
  1515. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1516. * actually use.
  1517. */
  1518. static createIFrame_() {
  1519. const iframe = document.createElement('iframe');
  1520. iframe.style.display = 'none';
  1521. // This is necessary in order to initialize the document inside the iframe
  1522. if (document.body) {
  1523. document.body.appendChild(iframe);
  1524. try {
  1525. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1526. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1527. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1528. const a = iframe.contentWindow.document;
  1529. if (!a) {
  1530. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1531. log('No IE domain setting required');
  1532. }
  1533. }
  1534. catch (e) {
  1535. const domain = document.domain;
  1536. iframe.src =
  1537. "javascript:void((function(){document.open();document.domain='" +
  1538. domain +
  1539. "';document.close();})())";
  1540. }
  1541. }
  1542. else {
  1543. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1544. // never gets hit.
  1545. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1546. }
  1547. // Get the document of the iframe in a browser-specific way.
  1548. if (iframe.contentDocument) {
  1549. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1550. }
  1551. else if (iframe.contentWindow) {
  1552. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1553. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1554. }
  1555. else if (iframe.document) {
  1556. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1557. iframe.doc = iframe.document; //others?
  1558. }
  1559. return iframe;
  1560. }
  1561. /**
  1562. * Cancel all outstanding queries and remove the frame.
  1563. */
  1564. close() {
  1565. //Mark this iframe as dead, so no new requests are sent.
  1566. this.alive = false;
  1567. if (this.myIFrame) {
  1568. //We have to actually remove all of the html inside this iframe before removing it from the
  1569. //window, or IE will continue loading and executing the script tags we've already added, which
  1570. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1571. this.myIFrame.doc.body.textContent = '';
  1572. setTimeout(() => {
  1573. if (this.myIFrame !== null) {
  1574. document.body.removeChild(this.myIFrame);
  1575. this.myIFrame = null;
  1576. }
  1577. }, Math.floor(0));
  1578. }
  1579. // Protect from being called recursively.
  1580. const onDisconnect = this.onDisconnect;
  1581. if (onDisconnect) {
  1582. this.onDisconnect = null;
  1583. onDisconnect();
  1584. }
  1585. }
  1586. /**
  1587. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1588. * @param id - The ID of this connection
  1589. * @param pw - The password for this connection
  1590. */
  1591. startLongPoll(id, pw) {
  1592. this.myID = id;
  1593. this.myPW = pw;
  1594. this.alive = true;
  1595. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1596. while (this.newRequest_()) { }
  1597. }
  1598. /**
  1599. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1600. * too many outstanding requests and we are still alive.
  1601. *
  1602. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1603. * needed.
  1604. */
  1605. newRequest_() {
  1606. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1607. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1608. // close the old request.
  1609. if (this.alive &&
  1610. this.sendNewPolls &&
  1611. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1612. //construct our url
  1613. this.currentSerial++;
  1614. const urlParams = {};
  1615. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1616. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1617. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1618. let theURL = this.urlFn(urlParams);
  1619. //Now add as much data as we can.
  1620. let curDataString = '';
  1621. let i = 0;
  1622. while (this.pendingSegs.length > 0) {
  1623. //first, lets see if the next segment will fit.
  1624. const nextSeg = this.pendingSegs[0];
  1625. if (nextSeg.d.length +
  1626. SEG_HEADER_SIZE +
  1627. curDataString.length <=
  1628. MAX_URL_DATA_SIZE) {
  1629. //great, the segment will fit. Lets append it.
  1630. const theSeg = this.pendingSegs.shift();
  1631. curDataString =
  1632. curDataString +
  1633. '&' +
  1634. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1635. i +
  1636. '=' +
  1637. theSeg.seg +
  1638. '&' +
  1639. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1640. i +
  1641. '=' +
  1642. theSeg.ts +
  1643. '&' +
  1644. FIREBASE_LONGPOLL_DATA_PARAM +
  1645. i +
  1646. '=' +
  1647. theSeg.d;
  1648. i++;
  1649. }
  1650. else {
  1651. break;
  1652. }
  1653. }
  1654. theURL = theURL + curDataString;
  1655. this.addLongPollTag_(theURL, this.currentSerial);
  1656. return true;
  1657. }
  1658. else {
  1659. return false;
  1660. }
  1661. }
  1662. /**
  1663. * Queue a packet for transmission to the server.
  1664. * @param segnum - A sequential id for this packet segment used for reassembly
  1665. * @param totalsegs - The total number of segments in this packet
  1666. * @param data - The data for this segment.
  1667. */
  1668. enqueueSegment(segnum, totalsegs, data) {
  1669. //add this to the queue of segments to send.
  1670. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  1671. //send the data immediately if there isn't already data being transmitted, unless
  1672. //startLongPoll hasn't been called yet.
  1673. if (this.alive) {
  1674. this.newRequest_();
  1675. }
  1676. }
  1677. /**
  1678. * Add a script tag for a regular long-poll request.
  1679. * @param url - The URL of the script tag.
  1680. * @param serial - The serial number of the request.
  1681. */
  1682. addLongPollTag_(url, serial) {
  1683. //remember that we sent this request.
  1684. this.outstandingRequests.add(serial);
  1685. const doNewRequest = () => {
  1686. this.outstandingRequests.delete(serial);
  1687. this.newRequest_();
  1688. };
  1689. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  1690. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  1691. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  1692. const readyStateCB = () => {
  1693. // Request completed. Cancel the keepalive.
  1694. clearTimeout(keepaliveTimeout);
  1695. // Trigger a new request so we can continue receiving data.
  1696. doNewRequest();
  1697. };
  1698. this.addTag(url, readyStateCB);
  1699. }
  1700. /**
  1701. * Add an arbitrary script tag to the iframe.
  1702. * @param url - The URL for the script tag source.
  1703. * @param loadCB - A callback to be triggered once the script has loaded.
  1704. */
  1705. addTag(url, loadCB) {
  1706. if (isNodeSdk()) {
  1707. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1708. this.doNodeLongPoll(url, loadCB);
  1709. }
  1710. else {
  1711. setTimeout(() => {
  1712. try {
  1713. // if we're already closed, don't add this poll
  1714. if (!this.sendNewPolls) {
  1715. return;
  1716. }
  1717. const newScript = this.myIFrame.doc.createElement('script');
  1718. newScript.type = 'text/javascript';
  1719. newScript.async = true;
  1720. newScript.src = url;
  1721. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1722. newScript.onload = newScript.onreadystatechange =
  1723. function () {
  1724. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1725. const rstate = newScript.readyState;
  1726. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  1727. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1728. newScript.onload = newScript.onreadystatechange = null;
  1729. if (newScript.parentNode) {
  1730. newScript.parentNode.removeChild(newScript);
  1731. }
  1732. loadCB();
  1733. }
  1734. };
  1735. newScript.onerror = () => {
  1736. log('Long-poll script failed to load: ' + url);
  1737. this.sendNewPolls = false;
  1738. this.close();
  1739. };
  1740. this.myIFrame.doc.body.appendChild(newScript);
  1741. }
  1742. catch (e) {
  1743. // TODO: we should make this error visible somehow
  1744. }
  1745. }, Math.floor(1));
  1746. }
  1747. }
  1748. }
  1749. /**
  1750. * @license
  1751. * Copyright 2017 Google LLC
  1752. *
  1753. * Licensed under the Apache License, Version 2.0 (the "License");
  1754. * you may not use this file except in compliance with the License.
  1755. * You may obtain a copy of the License at
  1756. *
  1757. * http://www.apache.org/licenses/LICENSE-2.0
  1758. *
  1759. * Unless required by applicable law or agreed to in writing, software
  1760. * distributed under the License is distributed on an "AS IS" BASIS,
  1761. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1762. * See the License for the specific language governing permissions and
  1763. * limitations under the License.
  1764. */
  1765. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  1766. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  1767. let WebSocketImpl = null;
  1768. if (typeof MozWebSocket !== 'undefined') {
  1769. WebSocketImpl = MozWebSocket;
  1770. }
  1771. else if (typeof WebSocket !== 'undefined') {
  1772. WebSocketImpl = WebSocket;
  1773. }
  1774. /**
  1775. * Create a new websocket connection with the given callbacks.
  1776. */
  1777. class WebSocketConnection {
  1778. /**
  1779. * @param connId identifier for this transport
  1780. * @param repoInfo The info for the websocket endpoint.
  1781. * @param applicationId The Firebase App ID for this project.
  1782. * @param appCheckToken The App Check Token for this client.
  1783. * @param authToken The Auth Token for this client.
  1784. * @param transportSessionId Optional transportSessionId if this is connecting
  1785. * to an existing transport session
  1786. * @param lastSessionId Optional lastSessionId if there was a previous
  1787. * connection
  1788. */
  1789. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1790. this.connId = connId;
  1791. this.applicationId = applicationId;
  1792. this.appCheckToken = appCheckToken;
  1793. this.authToken = authToken;
  1794. this.keepaliveTimer = null;
  1795. this.frames = null;
  1796. this.totalFrames = 0;
  1797. this.bytesSent = 0;
  1798. this.bytesReceived = 0;
  1799. this.log_ = logWrapper(this.connId);
  1800. this.stats_ = statsManagerGetCollection(repoInfo);
  1801. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  1802. this.nodeAdmin = repoInfo.nodeAdmin;
  1803. }
  1804. /**
  1805. * @param repoInfo - The info for the websocket endpoint.
  1806. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  1807. * session
  1808. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  1809. * @returns connection url
  1810. */
  1811. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  1812. const urlParams = {};
  1813. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1814. if (!isNodeSdk() &&
  1815. typeof location !== 'undefined' &&
  1816. location.hostname &&
  1817. FORGE_DOMAIN_RE.test(location.hostname)) {
  1818. urlParams[REFERER_PARAM] = FORGE_REF;
  1819. }
  1820. if (transportSessionId) {
  1821. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1822. }
  1823. if (lastSessionId) {
  1824. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1825. }
  1826. if (appCheckToken) {
  1827. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1828. }
  1829. if (applicationId) {
  1830. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1831. }
  1832. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1833. }
  1834. /**
  1835. * @param onMessage - Callback when messages arrive
  1836. * @param onDisconnect - Callback with connection lost.
  1837. */
  1838. open(onMessage, onDisconnect) {
  1839. this.onDisconnect = onDisconnect;
  1840. this.onMessage = onMessage;
  1841. this.log_('Websocket connecting to ' + this.connURL);
  1842. this.everConnected_ = false;
  1843. // Assume failure until proven otherwise.
  1844. PersistentStorage.set('previous_websocket_failure', true);
  1845. try {
  1846. let options;
  1847. if (isNodeSdk()) {
  1848. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1849. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1850. options = {
  1851. headers: {
  1852. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  1853. 'X-Firebase-GMPID': this.applicationId || ''
  1854. }
  1855. };
  1856. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1857. // Note that we send the credentials here even if they aren't admin credentials, which is
  1858. // not a problem.
  1859. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1860. // through the websocket connection once it is established.
  1861. if (this.authToken) {
  1862. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1863. }
  1864. if (this.appCheckToken) {
  1865. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1866. }
  1867. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1868. const env = process['env'];
  1869. const proxy = this.connURL.indexOf('wss://') === 0
  1870. ? env['HTTPS_PROXY'] || env['https_proxy']
  1871. : env['HTTP_PROXY'] || env['http_proxy'];
  1872. if (proxy) {
  1873. options['proxy'] = { origin: proxy };
  1874. }
  1875. }
  1876. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1877. }
  1878. catch (e) {
  1879. this.log_('Error instantiating WebSocket.');
  1880. const error = e.message || e.data;
  1881. if (error) {
  1882. this.log_(error);
  1883. }
  1884. this.onClosed_();
  1885. return;
  1886. }
  1887. this.mySock.onopen = () => {
  1888. this.log_('Websocket connected.');
  1889. this.everConnected_ = true;
  1890. };
  1891. this.mySock.onclose = () => {
  1892. this.log_('Websocket connection was disconnected.');
  1893. this.mySock = null;
  1894. this.onClosed_();
  1895. };
  1896. this.mySock.onmessage = m => {
  1897. this.handleIncomingFrame(m);
  1898. };
  1899. this.mySock.onerror = e => {
  1900. this.log_('WebSocket error. Closing connection.');
  1901. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1902. const error = e.message || e.data;
  1903. if (error) {
  1904. this.log_(error);
  1905. }
  1906. this.onClosed_();
  1907. };
  1908. }
  1909. /**
  1910. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1911. */
  1912. start() { }
  1913. static forceDisallow() {
  1914. WebSocketConnection.forceDisallow_ = true;
  1915. }
  1916. static isAvailable() {
  1917. let isOldAndroid = false;
  1918. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1919. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1920. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1921. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1922. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1923. isOldAndroid = true;
  1924. }
  1925. }
  1926. }
  1927. return (!isOldAndroid &&
  1928. WebSocketImpl !== null &&
  1929. !WebSocketConnection.forceDisallow_);
  1930. }
  1931. /**
  1932. * Returns true if we previously failed to connect with this transport.
  1933. */
  1934. static previouslyFailed() {
  1935. // If our persistent storage is actually only in-memory storage,
  1936. // we default to assuming that it previously failed to be safe.
  1937. return (PersistentStorage.isInMemoryStorage ||
  1938. PersistentStorage.get('previous_websocket_failure') === true);
  1939. }
  1940. markConnectionHealthy() {
  1941. PersistentStorage.remove('previous_websocket_failure');
  1942. }
  1943. appendFrame_(data) {
  1944. this.frames.push(data);
  1945. if (this.frames.length === this.totalFrames) {
  1946. const fullMess = this.frames.join('');
  1947. this.frames = null;
  1948. const jsonMess = jsonEval(fullMess);
  1949. //handle the message
  1950. this.onMessage(jsonMess);
  1951. }
  1952. }
  1953. /**
  1954. * @param frameCount - The number of frames we are expecting from the server
  1955. */
  1956. handleNewFrameCount_(frameCount) {
  1957. this.totalFrames = frameCount;
  1958. this.frames = [];
  1959. }
  1960. /**
  1961. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1962. * @returns Any remaining data to be process, or null if there is none
  1963. */
  1964. extractFrameCount_(data) {
  1965. assert(this.frames === null, 'We already have a frame buffer');
  1966. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1967. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1968. if (data.length <= 6) {
  1969. const frameCount = Number(data);
  1970. if (!isNaN(frameCount)) {
  1971. this.handleNewFrameCount_(frameCount);
  1972. return null;
  1973. }
  1974. }
  1975. this.handleNewFrameCount_(1);
  1976. return data;
  1977. }
  1978. /**
  1979. * Process a websocket frame that has arrived from the server.
  1980. * @param mess - The frame data
  1981. */
  1982. handleIncomingFrame(mess) {
  1983. if (this.mySock === null) {
  1984. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1985. }
  1986. const data = mess['data'];
  1987. this.bytesReceived += data.length;
  1988. this.stats_.incrementCounter('bytes_received', data.length);
  1989. this.resetKeepAlive();
  1990. if (this.frames !== null) {
  1991. // we're buffering
  1992. this.appendFrame_(data);
  1993. }
  1994. else {
  1995. // try to parse out a frame count, otherwise, assume 1 and process it
  1996. const remainingData = this.extractFrameCount_(data);
  1997. if (remainingData !== null) {
  1998. this.appendFrame_(remainingData);
  1999. }
  2000. }
  2001. }
  2002. /**
  2003. * Send a message to the server
  2004. * @param data - The JSON object to transmit
  2005. */
  2006. send(data) {
  2007. this.resetKeepAlive();
  2008. const dataStr = stringify(data);
  2009. this.bytesSent += dataStr.length;
  2010. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  2011. //We can only fit a certain amount in each websocket frame, so we need to split this request
  2012. //up into multiple pieces if it doesn't fit in one request.
  2013. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  2014. //Send the length header
  2015. if (dataSegs.length > 1) {
  2016. this.sendString_(String(dataSegs.length));
  2017. }
  2018. //Send the actual data in segments.
  2019. for (let i = 0; i < dataSegs.length; i++) {
  2020. this.sendString_(dataSegs[i]);
  2021. }
  2022. }
  2023. shutdown_() {
  2024. this.isClosed_ = true;
  2025. if (this.keepaliveTimer) {
  2026. clearInterval(this.keepaliveTimer);
  2027. this.keepaliveTimer = null;
  2028. }
  2029. if (this.mySock) {
  2030. this.mySock.close();
  2031. this.mySock = null;
  2032. }
  2033. }
  2034. onClosed_() {
  2035. if (!this.isClosed_) {
  2036. this.log_('WebSocket is closing itself');
  2037. this.shutdown_();
  2038. // since this is an internal close, trigger the close listener
  2039. if (this.onDisconnect) {
  2040. this.onDisconnect(this.everConnected_);
  2041. this.onDisconnect = null;
  2042. }
  2043. }
  2044. }
  2045. /**
  2046. * External-facing close handler.
  2047. * Close the websocket and kill the connection.
  2048. */
  2049. close() {
  2050. if (!this.isClosed_) {
  2051. this.log_('WebSocket is being closed');
  2052. this.shutdown_();
  2053. }
  2054. }
  2055. /**
  2056. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  2057. * the last activity.
  2058. */
  2059. resetKeepAlive() {
  2060. clearInterval(this.keepaliveTimer);
  2061. this.keepaliveTimer = setInterval(() => {
  2062. //If there has been no websocket activity for a while, send a no-op
  2063. if (this.mySock) {
  2064. this.sendString_('0');
  2065. }
  2066. this.resetKeepAlive();
  2067. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2068. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  2069. }
  2070. /**
  2071. * Send a string over the websocket.
  2072. *
  2073. * @param str - String to send.
  2074. */
  2075. sendString_(str) {
  2076. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  2077. // calls for some unknown reason. We treat these as an error and disconnect.
  2078. // See https://app.asana.com/0/58926111402292/68021340250410
  2079. try {
  2080. this.mySock.send(str);
  2081. }
  2082. catch (e) {
  2083. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  2084. setTimeout(this.onClosed_.bind(this), 0);
  2085. }
  2086. }
  2087. }
  2088. /**
  2089. * Number of response before we consider the connection "healthy."
  2090. */
  2091. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  2092. /**
  2093. * Time to wait for the connection te become healthy before giving up.
  2094. */
  2095. WebSocketConnection.healthyTimeout = 30000;
  2096. /**
  2097. * @license
  2098. * Copyright 2017 Google LLC
  2099. *
  2100. * Licensed under the Apache License, Version 2.0 (the "License");
  2101. * you may not use this file except in compliance with the License.
  2102. * You may obtain a copy of the License at
  2103. *
  2104. * http://www.apache.org/licenses/LICENSE-2.0
  2105. *
  2106. * Unless required by applicable law or agreed to in writing, software
  2107. * distributed under the License is distributed on an "AS IS" BASIS,
  2108. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2109. * See the License for the specific language governing permissions and
  2110. * limitations under the License.
  2111. */
  2112. /**
  2113. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2114. * lifecycle.
  2115. *
  2116. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2117. * they are available.
  2118. */
  2119. class TransportManager {
  2120. /**
  2121. * @param repoInfo - Metadata around the namespace we're connecting to
  2122. */
  2123. constructor(repoInfo) {
  2124. this.initTransports_(repoInfo);
  2125. }
  2126. static get ALL_TRANSPORTS() {
  2127. return [BrowserPollConnection, WebSocketConnection];
  2128. }
  2129. /**
  2130. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2131. * TransportManager has already set up transports_
  2132. */
  2133. static get IS_TRANSPORT_INITIALIZED() {
  2134. return this.globalTransportInitialized_;
  2135. }
  2136. initTransports_(repoInfo) {
  2137. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2138. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2139. if (repoInfo.webSocketOnly) {
  2140. if (!isWebSocketsAvailable) {
  2141. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2142. }
  2143. isSkipPollConnection = true;
  2144. }
  2145. if (isSkipPollConnection) {
  2146. this.transports_ = [WebSocketConnection];
  2147. }
  2148. else {
  2149. const transports = (this.transports_ = []);
  2150. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2151. if (transport && transport['isAvailable']()) {
  2152. transports.push(transport);
  2153. }
  2154. }
  2155. TransportManager.globalTransportInitialized_ = true;
  2156. }
  2157. }
  2158. /**
  2159. * @returns The constructor for the initial transport to use
  2160. */
  2161. initialTransport() {
  2162. if (this.transports_.length > 0) {
  2163. return this.transports_[0];
  2164. }
  2165. else {
  2166. throw new Error('No transports available');
  2167. }
  2168. }
  2169. /**
  2170. * @returns The constructor for the next transport, or null
  2171. */
  2172. upgradeTransport() {
  2173. if (this.transports_.length > 1) {
  2174. return this.transports_[1];
  2175. }
  2176. else {
  2177. return null;
  2178. }
  2179. }
  2180. }
  2181. // Keeps track of whether the TransportManager has already chosen a transport to use
  2182. TransportManager.globalTransportInitialized_ = false;
  2183. /**
  2184. * @license
  2185. * Copyright 2017 Google LLC
  2186. *
  2187. * Licensed under the Apache License, Version 2.0 (the "License");
  2188. * you may not use this file except in compliance with the License.
  2189. * You may obtain a copy of the License at
  2190. *
  2191. * http://www.apache.org/licenses/LICENSE-2.0
  2192. *
  2193. * Unless required by applicable law or agreed to in writing, software
  2194. * distributed under the License is distributed on an "AS IS" BASIS,
  2195. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2196. * See the License for the specific language governing permissions and
  2197. * limitations under the License.
  2198. */
  2199. // Abort upgrade attempt if it takes longer than 60s.
  2200. const UPGRADE_TIMEOUT = 60000;
  2201. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2202. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2203. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2204. // 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)
  2205. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2206. // but we've sent/received enough bytes, we don't cancel the connection.
  2207. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2208. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2209. const MESSAGE_TYPE = 't';
  2210. const MESSAGE_DATA = 'd';
  2211. const CONTROL_SHUTDOWN = 's';
  2212. const CONTROL_RESET = 'r';
  2213. const CONTROL_ERROR = 'e';
  2214. const CONTROL_PONG = 'o';
  2215. const SWITCH_ACK = 'a';
  2216. const END_TRANSMISSION = 'n';
  2217. const PING = 'p';
  2218. const SERVER_HELLO = 'h';
  2219. /**
  2220. * Creates a new real-time connection to the server using whichever method works
  2221. * best in the current browser.
  2222. */
  2223. class Connection {
  2224. /**
  2225. * @param id - an id for this connection
  2226. * @param repoInfo_ - the info for the endpoint to connect to
  2227. * @param applicationId_ - the Firebase App ID for this project
  2228. * @param appCheckToken_ - The App Check Token for this device.
  2229. * @param authToken_ - The auth token for this session.
  2230. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2231. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2232. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2233. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2234. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2235. */
  2236. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2237. this.id = id;
  2238. this.repoInfo_ = repoInfo_;
  2239. this.applicationId_ = applicationId_;
  2240. this.appCheckToken_ = appCheckToken_;
  2241. this.authToken_ = authToken_;
  2242. this.onMessage_ = onMessage_;
  2243. this.onReady_ = onReady_;
  2244. this.onDisconnect_ = onDisconnect_;
  2245. this.onKill_ = onKill_;
  2246. this.lastSessionId = lastSessionId;
  2247. this.connectionCount = 0;
  2248. this.pendingDataMessages = [];
  2249. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2250. this.log_ = logWrapper('c:' + this.id + ':');
  2251. this.transportManager_ = new TransportManager(repoInfo_);
  2252. this.log_('Connection created');
  2253. this.start_();
  2254. }
  2255. /**
  2256. * Starts a connection attempt
  2257. */
  2258. start_() {
  2259. const conn = this.transportManager_.initialTransport();
  2260. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2261. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2262. // can consider the transport healthy.
  2263. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2264. const onMessageReceived = this.connReceiver_(this.conn_);
  2265. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2266. this.tx_ = this.conn_;
  2267. this.rx_ = this.conn_;
  2268. this.secondaryConn_ = null;
  2269. this.isHealthy_ = false;
  2270. /*
  2271. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2272. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2273. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2274. * still have the context of your originating frame.
  2275. */
  2276. setTimeout(() => {
  2277. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2278. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2279. }, Math.floor(0));
  2280. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2281. if (healthyTimeoutMS > 0) {
  2282. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2283. this.healthyTimeout_ = null;
  2284. if (!this.isHealthy_) {
  2285. if (this.conn_ &&
  2286. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2287. this.log_('Connection exceeded healthy timeout but has received ' +
  2288. this.conn_.bytesReceived +
  2289. ' bytes. Marking connection healthy.');
  2290. this.isHealthy_ = true;
  2291. this.conn_.markConnectionHealthy();
  2292. }
  2293. else if (this.conn_ &&
  2294. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2295. this.log_('Connection exceeded healthy timeout but has sent ' +
  2296. this.conn_.bytesSent +
  2297. ' bytes. Leaving connection alive.');
  2298. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2299. // the server.
  2300. }
  2301. else {
  2302. this.log_('Closing unhealthy connection after timeout.');
  2303. this.close();
  2304. }
  2305. }
  2306. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2307. }, Math.floor(healthyTimeoutMS));
  2308. }
  2309. }
  2310. nextTransportId_() {
  2311. return 'c:' + this.id + ':' + this.connectionCount++;
  2312. }
  2313. disconnReceiver_(conn) {
  2314. return everConnected => {
  2315. if (conn === this.conn_) {
  2316. this.onConnectionLost_(everConnected);
  2317. }
  2318. else if (conn === this.secondaryConn_) {
  2319. this.log_('Secondary connection lost.');
  2320. this.onSecondaryConnectionLost_();
  2321. }
  2322. else {
  2323. this.log_('closing an old connection');
  2324. }
  2325. };
  2326. }
  2327. connReceiver_(conn) {
  2328. return (message) => {
  2329. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2330. if (conn === this.rx_) {
  2331. this.onPrimaryMessageReceived_(message);
  2332. }
  2333. else if (conn === this.secondaryConn_) {
  2334. this.onSecondaryMessageReceived_(message);
  2335. }
  2336. else {
  2337. this.log_('message on old connection');
  2338. }
  2339. }
  2340. };
  2341. }
  2342. /**
  2343. * @param dataMsg - An arbitrary data message to be sent to the server
  2344. */
  2345. sendRequest(dataMsg) {
  2346. // wrap in a data message envelope and send it on
  2347. const msg = { t: 'd', d: dataMsg };
  2348. this.sendData_(msg);
  2349. }
  2350. tryCleanupConnection() {
  2351. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2352. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2353. this.conn_ = this.secondaryConn_;
  2354. this.secondaryConn_ = null;
  2355. // the server will shutdown the old connection
  2356. }
  2357. }
  2358. onSecondaryControl_(controlData) {
  2359. if (MESSAGE_TYPE in controlData) {
  2360. const cmd = controlData[MESSAGE_TYPE];
  2361. if (cmd === SWITCH_ACK) {
  2362. this.upgradeIfSecondaryHealthy_();
  2363. }
  2364. else if (cmd === CONTROL_RESET) {
  2365. // Most likely the session wasn't valid. Abandon the switch attempt
  2366. this.log_('Got a reset on secondary, closing it');
  2367. this.secondaryConn_.close();
  2368. // If we were already using this connection for something, than we need to fully close
  2369. if (this.tx_ === this.secondaryConn_ ||
  2370. this.rx_ === this.secondaryConn_) {
  2371. this.close();
  2372. }
  2373. }
  2374. else if (cmd === CONTROL_PONG) {
  2375. this.log_('got pong on secondary.');
  2376. this.secondaryResponsesRequired_--;
  2377. this.upgradeIfSecondaryHealthy_();
  2378. }
  2379. }
  2380. }
  2381. onSecondaryMessageReceived_(parsedData) {
  2382. const layer = requireKey('t', parsedData);
  2383. const data = requireKey('d', parsedData);
  2384. if (layer === 'c') {
  2385. this.onSecondaryControl_(data);
  2386. }
  2387. else if (layer === 'd') {
  2388. // got a data message, but we're still second connection. Need to buffer it up
  2389. this.pendingDataMessages.push(data);
  2390. }
  2391. else {
  2392. throw new Error('Unknown protocol layer: ' + layer);
  2393. }
  2394. }
  2395. upgradeIfSecondaryHealthy_() {
  2396. if (this.secondaryResponsesRequired_ <= 0) {
  2397. this.log_('Secondary connection is healthy.');
  2398. this.isHealthy_ = true;
  2399. this.secondaryConn_.markConnectionHealthy();
  2400. this.proceedWithUpgrade_();
  2401. }
  2402. else {
  2403. // Send a ping to make sure the connection is healthy.
  2404. this.log_('sending ping on secondary.');
  2405. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2406. }
  2407. }
  2408. proceedWithUpgrade_() {
  2409. // tell this connection to consider itself open
  2410. this.secondaryConn_.start();
  2411. // send ack
  2412. this.log_('sending client ack on secondary');
  2413. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2414. // send end packet on primary transport, switch to sending on this one
  2415. // can receive on this one, buffer responses until end received on primary transport
  2416. this.log_('Ending transmission on primary');
  2417. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2418. this.tx_ = this.secondaryConn_;
  2419. this.tryCleanupConnection();
  2420. }
  2421. onPrimaryMessageReceived_(parsedData) {
  2422. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2423. const layer = requireKey('t', parsedData);
  2424. const data = requireKey('d', parsedData);
  2425. if (layer === 'c') {
  2426. this.onControl_(data);
  2427. }
  2428. else if (layer === 'd') {
  2429. this.onDataMessage_(data);
  2430. }
  2431. }
  2432. onDataMessage_(message) {
  2433. this.onPrimaryResponse_();
  2434. // We don't do anything with data messages, just kick them up a level
  2435. this.onMessage_(message);
  2436. }
  2437. onPrimaryResponse_() {
  2438. if (!this.isHealthy_) {
  2439. this.primaryResponsesRequired_--;
  2440. if (this.primaryResponsesRequired_ <= 0) {
  2441. this.log_('Primary connection is healthy.');
  2442. this.isHealthy_ = true;
  2443. this.conn_.markConnectionHealthy();
  2444. }
  2445. }
  2446. }
  2447. onControl_(controlData) {
  2448. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2449. if (MESSAGE_DATA in controlData) {
  2450. const payload = controlData[MESSAGE_DATA];
  2451. if (cmd === SERVER_HELLO) {
  2452. const handshakePayload = Object.assign({}, payload);
  2453. if (this.repoInfo_.isUsingEmulator) {
  2454. // 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.
  2455. handshakePayload.h = this.repoInfo_.host;
  2456. }
  2457. this.onHandshake_(handshakePayload);
  2458. }
  2459. else if (cmd === END_TRANSMISSION) {
  2460. this.log_('recvd end transmission on primary');
  2461. this.rx_ = this.secondaryConn_;
  2462. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2463. this.onDataMessage_(this.pendingDataMessages[i]);
  2464. }
  2465. this.pendingDataMessages = [];
  2466. this.tryCleanupConnection();
  2467. }
  2468. else if (cmd === CONTROL_SHUTDOWN) {
  2469. // This was previously the 'onKill' callback passed to the lower-level connection
  2470. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2471. this.onConnectionShutdown_(payload);
  2472. }
  2473. else if (cmd === CONTROL_RESET) {
  2474. // payload in this case is the host we should contact
  2475. this.onReset_(payload);
  2476. }
  2477. else if (cmd === CONTROL_ERROR) {
  2478. error('Server Error: ' + payload);
  2479. }
  2480. else if (cmd === CONTROL_PONG) {
  2481. this.log_('got pong on primary.');
  2482. this.onPrimaryResponse_();
  2483. this.sendPingOnPrimaryIfNecessary_();
  2484. }
  2485. else {
  2486. error('Unknown control packet command: ' + cmd);
  2487. }
  2488. }
  2489. }
  2490. /**
  2491. * @param handshake - The handshake data returned from the server
  2492. */
  2493. onHandshake_(handshake) {
  2494. const timestamp = handshake.ts;
  2495. const version = handshake.v;
  2496. const host = handshake.h;
  2497. this.sessionId = handshake.s;
  2498. this.repoInfo_.host = host;
  2499. // if we've already closed the connection, then don't bother trying to progress further
  2500. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2501. this.conn_.start();
  2502. this.onConnectionEstablished_(this.conn_, timestamp);
  2503. if (PROTOCOL_VERSION !== version) {
  2504. warn('Protocol version mismatch detected');
  2505. }
  2506. // TODO: do we want to upgrade? when? maybe a delay?
  2507. this.tryStartUpgrade_();
  2508. }
  2509. }
  2510. tryStartUpgrade_() {
  2511. const conn = this.transportManager_.upgradeTransport();
  2512. if (conn) {
  2513. this.startUpgrade_(conn);
  2514. }
  2515. }
  2516. startUpgrade_(conn) {
  2517. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2518. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2519. // can consider the transport healthy.
  2520. this.secondaryResponsesRequired_ =
  2521. conn['responsesRequiredToBeHealthy'] || 0;
  2522. const onMessage = this.connReceiver_(this.secondaryConn_);
  2523. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2524. this.secondaryConn_.open(onMessage, onDisconnect);
  2525. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2526. setTimeoutNonBlocking(() => {
  2527. if (this.secondaryConn_) {
  2528. this.log_('Timed out trying to upgrade.');
  2529. this.secondaryConn_.close();
  2530. }
  2531. }, Math.floor(UPGRADE_TIMEOUT));
  2532. }
  2533. onReset_(host) {
  2534. this.log_('Reset packet received. New host: ' + host);
  2535. this.repoInfo_.host = host;
  2536. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2537. // We don't currently support resets after the connection has already been established
  2538. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2539. this.close();
  2540. }
  2541. else {
  2542. // Close whatever connections we have open and start again.
  2543. this.closeConnections_();
  2544. this.start_();
  2545. }
  2546. }
  2547. onConnectionEstablished_(conn, timestamp) {
  2548. this.log_('Realtime connection established.');
  2549. this.conn_ = conn;
  2550. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2551. if (this.onReady_) {
  2552. this.onReady_(timestamp, this.sessionId);
  2553. this.onReady_ = null;
  2554. }
  2555. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2556. // send some pings.
  2557. if (this.primaryResponsesRequired_ === 0) {
  2558. this.log_('Primary connection is healthy.');
  2559. this.isHealthy_ = true;
  2560. }
  2561. else {
  2562. setTimeoutNonBlocking(() => {
  2563. this.sendPingOnPrimaryIfNecessary_();
  2564. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2565. }
  2566. }
  2567. sendPingOnPrimaryIfNecessary_() {
  2568. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2569. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2570. this.log_('sending ping on primary.');
  2571. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2572. }
  2573. }
  2574. onSecondaryConnectionLost_() {
  2575. const conn = this.secondaryConn_;
  2576. this.secondaryConn_ = null;
  2577. if (this.tx_ === conn || this.rx_ === conn) {
  2578. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2579. this.close();
  2580. }
  2581. }
  2582. /**
  2583. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2584. * we should flush the host cache
  2585. */
  2586. onConnectionLost_(everConnected) {
  2587. this.conn_ = null;
  2588. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2589. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2590. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2591. this.log_('Realtime connection failed.');
  2592. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2593. if (this.repoInfo_.isCacheableHost()) {
  2594. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2595. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2596. this.repoInfo_.internalHost = this.repoInfo_.host;
  2597. }
  2598. }
  2599. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2600. this.log_('Realtime connection lost.');
  2601. }
  2602. this.close();
  2603. }
  2604. onConnectionShutdown_(reason) {
  2605. this.log_('Connection shutdown command received. Shutting down...');
  2606. if (this.onKill_) {
  2607. this.onKill_(reason);
  2608. this.onKill_ = null;
  2609. }
  2610. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2611. // so clear the callback.
  2612. this.onDisconnect_ = null;
  2613. this.close();
  2614. }
  2615. sendData_(data) {
  2616. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2617. throw 'Connection is not connected';
  2618. }
  2619. else {
  2620. this.tx_.send(data);
  2621. }
  2622. }
  2623. /**
  2624. * Cleans up this connection, calling the appropriate callbacks
  2625. */
  2626. close() {
  2627. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2628. this.log_('Closing realtime connection.');
  2629. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2630. this.closeConnections_();
  2631. if (this.onDisconnect_) {
  2632. this.onDisconnect_();
  2633. this.onDisconnect_ = null;
  2634. }
  2635. }
  2636. }
  2637. closeConnections_() {
  2638. this.log_('Shutting down all connections');
  2639. if (this.conn_) {
  2640. this.conn_.close();
  2641. this.conn_ = null;
  2642. }
  2643. if (this.secondaryConn_) {
  2644. this.secondaryConn_.close();
  2645. this.secondaryConn_ = null;
  2646. }
  2647. if (this.healthyTimeout_) {
  2648. clearTimeout(this.healthyTimeout_);
  2649. this.healthyTimeout_ = null;
  2650. }
  2651. }
  2652. }
  2653. /**
  2654. * @license
  2655. * Copyright 2017 Google LLC
  2656. *
  2657. * Licensed under the Apache License, Version 2.0 (the "License");
  2658. * you may not use this file except in compliance with the License.
  2659. * You may obtain a copy of the License at
  2660. *
  2661. * http://www.apache.org/licenses/LICENSE-2.0
  2662. *
  2663. * Unless required by applicable law or agreed to in writing, software
  2664. * distributed under the License is distributed on an "AS IS" BASIS,
  2665. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2666. * See the License for the specific language governing permissions and
  2667. * limitations under the License.
  2668. */
  2669. /**
  2670. * Interface defining the set of actions that can be performed against the Firebase server
  2671. * (basically corresponds to our wire protocol).
  2672. *
  2673. * @interface
  2674. */
  2675. class ServerActions {
  2676. put(pathString, data, onComplete, hash) { }
  2677. merge(pathString, data, onComplete, hash) { }
  2678. /**
  2679. * Refreshes the auth token for the current connection.
  2680. * @param token - The authentication token
  2681. */
  2682. refreshAuthToken(token) { }
  2683. /**
  2684. * Refreshes the app check token for the current connection.
  2685. * @param token The app check token
  2686. */
  2687. refreshAppCheckToken(token) { }
  2688. onDisconnectPut(pathString, data, onComplete) { }
  2689. onDisconnectMerge(pathString, data, onComplete) { }
  2690. onDisconnectCancel(pathString, onComplete) { }
  2691. reportStats(stats) { }
  2692. }
  2693. /**
  2694. * @license
  2695. * Copyright 2017 Google LLC
  2696. *
  2697. * Licensed under the Apache License, Version 2.0 (the "License");
  2698. * you may not use this file except in compliance with the License.
  2699. * You may obtain a copy of the License at
  2700. *
  2701. * http://www.apache.org/licenses/LICENSE-2.0
  2702. *
  2703. * Unless required by applicable law or agreed to in writing, software
  2704. * distributed under the License is distributed on an "AS IS" BASIS,
  2705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2706. * See the License for the specific language governing permissions and
  2707. * limitations under the License.
  2708. */
  2709. /**
  2710. * Base class to be used if you want to emit events. Call the constructor with
  2711. * the set of allowed event names.
  2712. */
  2713. class EventEmitter {
  2714. constructor(allowedEvents_) {
  2715. this.allowedEvents_ = allowedEvents_;
  2716. this.listeners_ = {};
  2717. assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2718. }
  2719. /**
  2720. * To be called by derived classes to trigger events.
  2721. */
  2722. trigger(eventType, ...varArgs) {
  2723. if (Array.isArray(this.listeners_[eventType])) {
  2724. // Clone the list, since callbacks could add/remove listeners.
  2725. const listeners = [...this.listeners_[eventType]];
  2726. for (let i = 0; i < listeners.length; i++) {
  2727. listeners[i].callback.apply(listeners[i].context, varArgs);
  2728. }
  2729. }
  2730. }
  2731. on(eventType, callback, context) {
  2732. this.validateEventType_(eventType);
  2733. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2734. this.listeners_[eventType].push({ callback, context });
  2735. const eventData = this.getInitialEvent(eventType);
  2736. if (eventData) {
  2737. callback.apply(context, eventData);
  2738. }
  2739. }
  2740. off(eventType, callback, context) {
  2741. this.validateEventType_(eventType);
  2742. const listeners = this.listeners_[eventType] || [];
  2743. for (let i = 0; i < listeners.length; i++) {
  2744. if (listeners[i].callback === callback &&
  2745. (!context || context === listeners[i].context)) {
  2746. listeners.splice(i, 1);
  2747. return;
  2748. }
  2749. }
  2750. }
  2751. validateEventType_(eventType) {
  2752. assert(this.allowedEvents_.find(et => {
  2753. return et === eventType;
  2754. }), 'Unknown event: ' + eventType);
  2755. }
  2756. }
  2757. /**
  2758. * @license
  2759. * Copyright 2017 Google LLC
  2760. *
  2761. * Licensed under the Apache License, Version 2.0 (the "License");
  2762. * you may not use this file except in compliance with the License.
  2763. * You may obtain a copy of the License at
  2764. *
  2765. * http://www.apache.org/licenses/LICENSE-2.0
  2766. *
  2767. * Unless required by applicable law or agreed to in writing, software
  2768. * distributed under the License is distributed on an "AS IS" BASIS,
  2769. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2770. * See the License for the specific language governing permissions and
  2771. * limitations under the License.
  2772. */
  2773. /**
  2774. * Monitors online state (as reported by window.online/offline events).
  2775. *
  2776. * The expectation is that this could have many false positives (thinks we are online
  2777. * when we're not), but no false negatives. So we can safely use it to determine when
  2778. * we definitely cannot reach the internet.
  2779. */
  2780. class OnlineMonitor extends EventEmitter {
  2781. constructor() {
  2782. super(['online']);
  2783. this.online_ = true;
  2784. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2785. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2786. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2787. // for Cordova.
  2788. if (typeof window !== 'undefined' &&
  2789. typeof window.addEventListener !== 'undefined' &&
  2790. !isMobileCordova()) {
  2791. window.addEventListener('online', () => {
  2792. if (!this.online_) {
  2793. this.online_ = true;
  2794. this.trigger('online', true);
  2795. }
  2796. }, false);
  2797. window.addEventListener('offline', () => {
  2798. if (this.online_) {
  2799. this.online_ = false;
  2800. this.trigger('online', false);
  2801. }
  2802. }, false);
  2803. }
  2804. }
  2805. static getInstance() {
  2806. return new OnlineMonitor();
  2807. }
  2808. getInitialEvent(eventType) {
  2809. assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2810. return [this.online_];
  2811. }
  2812. currentlyOnline() {
  2813. return this.online_;
  2814. }
  2815. }
  2816. /**
  2817. * @license
  2818. * Copyright 2017 Google LLC
  2819. *
  2820. * Licensed under the Apache License, Version 2.0 (the "License");
  2821. * you may not use this file except in compliance with the License.
  2822. * You may obtain a copy of the License at
  2823. *
  2824. * http://www.apache.org/licenses/LICENSE-2.0
  2825. *
  2826. * Unless required by applicable law or agreed to in writing, software
  2827. * distributed under the License is distributed on an "AS IS" BASIS,
  2828. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2829. * See the License for the specific language governing permissions and
  2830. * limitations under the License.
  2831. */
  2832. /** Maximum key depth. */
  2833. const MAX_PATH_DEPTH = 32;
  2834. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2835. const MAX_PATH_LENGTH_BYTES = 768;
  2836. /**
  2837. * An immutable object representing a parsed path. It's immutable so that you
  2838. * can pass them around to other functions without worrying about them changing
  2839. * it.
  2840. */
  2841. class Path {
  2842. /**
  2843. * @param pathOrString - Path string to parse, or another path, or the raw
  2844. * tokens array
  2845. */
  2846. constructor(pathOrString, pieceNum) {
  2847. if (pieceNum === void 0) {
  2848. this.pieces_ = pathOrString.split('/');
  2849. // Remove empty pieces.
  2850. let copyTo = 0;
  2851. for (let i = 0; i < this.pieces_.length; i++) {
  2852. if (this.pieces_[i].length > 0) {
  2853. this.pieces_[copyTo] = this.pieces_[i];
  2854. copyTo++;
  2855. }
  2856. }
  2857. this.pieces_.length = copyTo;
  2858. this.pieceNum_ = 0;
  2859. }
  2860. else {
  2861. this.pieces_ = pathOrString;
  2862. this.pieceNum_ = pieceNum;
  2863. }
  2864. }
  2865. toString() {
  2866. let pathString = '';
  2867. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2868. if (this.pieces_[i] !== '') {
  2869. pathString += '/' + this.pieces_[i];
  2870. }
  2871. }
  2872. return pathString || '/';
  2873. }
  2874. }
  2875. function newEmptyPath() {
  2876. return new Path('');
  2877. }
  2878. function pathGetFront(path) {
  2879. if (path.pieceNum_ >= path.pieces_.length) {
  2880. return null;
  2881. }
  2882. return path.pieces_[path.pieceNum_];
  2883. }
  2884. /**
  2885. * @returns The number of segments in this path
  2886. */
  2887. function pathGetLength(path) {
  2888. return path.pieces_.length - path.pieceNum_;
  2889. }
  2890. function pathPopFront(path) {
  2891. let pieceNum = path.pieceNum_;
  2892. if (pieceNum < path.pieces_.length) {
  2893. pieceNum++;
  2894. }
  2895. return new Path(path.pieces_, pieceNum);
  2896. }
  2897. function pathGetBack(path) {
  2898. if (path.pieceNum_ < path.pieces_.length) {
  2899. return path.pieces_[path.pieces_.length - 1];
  2900. }
  2901. return null;
  2902. }
  2903. function pathToUrlEncodedString(path) {
  2904. let pathString = '';
  2905. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2906. if (path.pieces_[i] !== '') {
  2907. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2908. }
  2909. }
  2910. return pathString || '/';
  2911. }
  2912. /**
  2913. * Shallow copy of the parts of the path.
  2914. *
  2915. */
  2916. function pathSlice(path, begin = 0) {
  2917. return path.pieces_.slice(path.pieceNum_ + begin);
  2918. }
  2919. function pathParent(path) {
  2920. if (path.pieceNum_ >= path.pieces_.length) {
  2921. return null;
  2922. }
  2923. const pieces = [];
  2924. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2925. pieces.push(path.pieces_[i]);
  2926. }
  2927. return new Path(pieces, 0);
  2928. }
  2929. function pathChild(path, childPathObj) {
  2930. const pieces = [];
  2931. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2932. pieces.push(path.pieces_[i]);
  2933. }
  2934. if (childPathObj instanceof Path) {
  2935. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2936. pieces.push(childPathObj.pieces_[i]);
  2937. }
  2938. }
  2939. else {
  2940. const childPieces = childPathObj.split('/');
  2941. for (let i = 0; i < childPieces.length; i++) {
  2942. if (childPieces[i].length > 0) {
  2943. pieces.push(childPieces[i]);
  2944. }
  2945. }
  2946. }
  2947. return new Path(pieces, 0);
  2948. }
  2949. /**
  2950. * @returns True if there are no segments in this path
  2951. */
  2952. function pathIsEmpty(path) {
  2953. return path.pieceNum_ >= path.pieces_.length;
  2954. }
  2955. /**
  2956. * @returns The path from outerPath to innerPath
  2957. */
  2958. function newRelativePath(outerPath, innerPath) {
  2959. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2960. if (outer === null) {
  2961. return innerPath;
  2962. }
  2963. else if (outer === inner) {
  2964. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2965. }
  2966. else {
  2967. throw new Error('INTERNAL ERROR: innerPath (' +
  2968. innerPath +
  2969. ') is not within ' +
  2970. 'outerPath (' +
  2971. outerPath +
  2972. ')');
  2973. }
  2974. }
  2975. /**
  2976. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2977. */
  2978. function pathCompare(left, right) {
  2979. const leftKeys = pathSlice(left, 0);
  2980. const rightKeys = pathSlice(right, 0);
  2981. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2982. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2983. if (cmp !== 0) {
  2984. return cmp;
  2985. }
  2986. }
  2987. if (leftKeys.length === rightKeys.length) {
  2988. return 0;
  2989. }
  2990. return leftKeys.length < rightKeys.length ? -1 : 1;
  2991. }
  2992. /**
  2993. * @returns true if paths are the same.
  2994. */
  2995. function pathEquals(path, other) {
  2996. if (pathGetLength(path) !== pathGetLength(other)) {
  2997. return false;
  2998. }
  2999. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3000. if (path.pieces_[i] !== other.pieces_[j]) {
  3001. return false;
  3002. }
  3003. }
  3004. return true;
  3005. }
  3006. /**
  3007. * @returns True if this path is a parent of (or the same as) other
  3008. */
  3009. function pathContains(path, other) {
  3010. let i = path.pieceNum_;
  3011. let j = other.pieceNum_;
  3012. if (pathGetLength(path) > pathGetLength(other)) {
  3013. return false;
  3014. }
  3015. while (i < path.pieces_.length) {
  3016. if (path.pieces_[i] !== other.pieces_[j]) {
  3017. return false;
  3018. }
  3019. ++i;
  3020. ++j;
  3021. }
  3022. return true;
  3023. }
  3024. /**
  3025. * Dynamic (mutable) path used to count path lengths.
  3026. *
  3027. * This class is used to efficiently check paths for valid
  3028. * length (in UTF8 bytes) and depth (used in path validation).
  3029. *
  3030. * Throws Error exception if path is ever invalid.
  3031. *
  3032. * The definition of a path always begins with '/'.
  3033. */
  3034. class ValidationPath {
  3035. /**
  3036. * @param path - Initial Path.
  3037. * @param errorPrefix_ - Prefix for any error messages.
  3038. */
  3039. constructor(path, errorPrefix_) {
  3040. this.errorPrefix_ = errorPrefix_;
  3041. this.parts_ = pathSlice(path, 0);
  3042. /** Initialize to number of '/' chars needed in path. */
  3043. this.byteLength_ = Math.max(1, this.parts_.length);
  3044. for (let i = 0; i < this.parts_.length; i++) {
  3045. this.byteLength_ += stringLength(this.parts_[i]);
  3046. }
  3047. validationPathCheckValid(this);
  3048. }
  3049. }
  3050. function validationPathPush(validationPath, child) {
  3051. // Count the needed '/'
  3052. if (validationPath.parts_.length > 0) {
  3053. validationPath.byteLength_ += 1;
  3054. }
  3055. validationPath.parts_.push(child);
  3056. validationPath.byteLength_ += stringLength(child);
  3057. validationPathCheckValid(validationPath);
  3058. }
  3059. function validationPathPop(validationPath) {
  3060. const last = validationPath.parts_.pop();
  3061. validationPath.byteLength_ -= stringLength(last);
  3062. // Un-count the previous '/'
  3063. if (validationPath.parts_.length > 0) {
  3064. validationPath.byteLength_ -= 1;
  3065. }
  3066. }
  3067. function validationPathCheckValid(validationPath) {
  3068. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3069. throw new Error(validationPath.errorPrefix_ +
  3070. 'has a key path longer than ' +
  3071. MAX_PATH_LENGTH_BYTES +
  3072. ' bytes (' +
  3073. validationPath.byteLength_ +
  3074. ').');
  3075. }
  3076. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3077. throw new Error(validationPath.errorPrefix_ +
  3078. 'path specified exceeds the maximum depth that can be written (' +
  3079. MAX_PATH_DEPTH +
  3080. ') or object contains a cycle ' +
  3081. validationPathToErrorString(validationPath));
  3082. }
  3083. }
  3084. /**
  3085. * String for use in error messages - uses '.' notation for path.
  3086. */
  3087. function validationPathToErrorString(validationPath) {
  3088. if (validationPath.parts_.length === 0) {
  3089. return '';
  3090. }
  3091. return "in property '" + validationPath.parts_.join('.') + "'";
  3092. }
  3093. /**
  3094. * @license
  3095. * Copyright 2017 Google LLC
  3096. *
  3097. * Licensed under the Apache License, Version 2.0 (the "License");
  3098. * you may not use this file except in compliance with the License.
  3099. * You may obtain a copy of the License at
  3100. *
  3101. * http://www.apache.org/licenses/LICENSE-2.0
  3102. *
  3103. * Unless required by applicable law or agreed to in writing, software
  3104. * distributed under the License is distributed on an "AS IS" BASIS,
  3105. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3106. * See the License for the specific language governing permissions and
  3107. * limitations under the License.
  3108. */
  3109. class VisibilityMonitor extends EventEmitter {
  3110. constructor() {
  3111. super(['visible']);
  3112. let hidden;
  3113. let visibilityChange;
  3114. if (typeof document !== 'undefined' &&
  3115. typeof document.addEventListener !== 'undefined') {
  3116. if (typeof document['hidden'] !== 'undefined') {
  3117. // Opera 12.10 and Firefox 18 and later support
  3118. visibilityChange = 'visibilitychange';
  3119. hidden = 'hidden';
  3120. }
  3121. else if (typeof document['mozHidden'] !== 'undefined') {
  3122. visibilityChange = 'mozvisibilitychange';
  3123. hidden = 'mozHidden';
  3124. }
  3125. else if (typeof document['msHidden'] !== 'undefined') {
  3126. visibilityChange = 'msvisibilitychange';
  3127. hidden = 'msHidden';
  3128. }
  3129. else if (typeof document['webkitHidden'] !== 'undefined') {
  3130. visibilityChange = 'webkitvisibilitychange';
  3131. hidden = 'webkitHidden';
  3132. }
  3133. }
  3134. // Initially, we always assume we are visible. This ensures that in browsers
  3135. // without page visibility support or in cases where we are never visible
  3136. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3137. // reconnects
  3138. this.visible_ = true;
  3139. if (visibilityChange) {
  3140. document.addEventListener(visibilityChange, () => {
  3141. const visible = !document[hidden];
  3142. if (visible !== this.visible_) {
  3143. this.visible_ = visible;
  3144. this.trigger('visible', visible);
  3145. }
  3146. }, false);
  3147. }
  3148. }
  3149. static getInstance() {
  3150. return new VisibilityMonitor();
  3151. }
  3152. getInitialEvent(eventType) {
  3153. assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3154. return [this.visible_];
  3155. }
  3156. }
  3157. /**
  3158. * @license
  3159. * Copyright 2017 Google LLC
  3160. *
  3161. * Licensed under the Apache License, Version 2.0 (the "License");
  3162. * you may not use this file except in compliance with the License.
  3163. * You may obtain a copy of the License at
  3164. *
  3165. * http://www.apache.org/licenses/LICENSE-2.0
  3166. *
  3167. * Unless required by applicable law or agreed to in writing, software
  3168. * distributed under the License is distributed on an "AS IS" BASIS,
  3169. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3170. * See the License for the specific language governing permissions and
  3171. * limitations under the License.
  3172. */
  3173. const RECONNECT_MIN_DELAY = 1000;
  3174. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3175. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3176. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3177. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3178. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3179. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3180. const INVALID_TOKEN_THRESHOLD = 3;
  3181. /**
  3182. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3183. *
  3184. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3185. * in quotes to make sure the closure compiler does not minify them.
  3186. */
  3187. class PersistentConnection extends ServerActions {
  3188. /**
  3189. * @param repoInfo_ - Data about the namespace we are connecting to
  3190. * @param applicationId_ - The Firebase App ID for this project
  3191. * @param onDataUpdate_ - A callback for new data from the server
  3192. */
  3193. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3194. super();
  3195. this.repoInfo_ = repoInfo_;
  3196. this.applicationId_ = applicationId_;
  3197. this.onDataUpdate_ = onDataUpdate_;
  3198. this.onConnectStatus_ = onConnectStatus_;
  3199. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3200. this.authTokenProvider_ = authTokenProvider_;
  3201. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3202. this.authOverride_ = authOverride_;
  3203. // Used for diagnostic logging.
  3204. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3205. this.log_ = logWrapper('p:' + this.id + ':');
  3206. this.interruptReasons_ = {};
  3207. this.listens = new Map();
  3208. this.outstandingPuts_ = [];
  3209. this.outstandingGets_ = [];
  3210. this.outstandingPutCount_ = 0;
  3211. this.outstandingGetCount_ = 0;
  3212. this.onDisconnectRequestQueue_ = [];
  3213. this.connected_ = false;
  3214. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3215. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3216. this.securityDebugCallback_ = null;
  3217. this.lastSessionId = null;
  3218. this.establishConnectionTimer_ = null;
  3219. this.visible_ = false;
  3220. // Before we get connected, we keep a queue of pending messages to send.
  3221. this.requestCBHash_ = {};
  3222. this.requestNumber_ = 0;
  3223. this.realtime_ = null;
  3224. this.authToken_ = null;
  3225. this.appCheckToken_ = null;
  3226. this.forceTokenRefresh_ = false;
  3227. this.invalidAuthTokenCount_ = 0;
  3228. this.invalidAppCheckTokenCount_ = 0;
  3229. this.firstConnection_ = true;
  3230. this.lastConnectionAttemptTime_ = null;
  3231. this.lastConnectionEstablishedTime_ = null;
  3232. if (authOverride_ && !isNodeSdk()) {
  3233. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3234. }
  3235. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3236. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3237. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3238. }
  3239. }
  3240. sendRequest(action, body, onResponse) {
  3241. const curReqNum = ++this.requestNumber_;
  3242. const msg = { r: curReqNum, a: action, b: body };
  3243. this.log_(stringify(msg));
  3244. assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3245. this.realtime_.sendRequest(msg);
  3246. if (onResponse) {
  3247. this.requestCBHash_[curReqNum] = onResponse;
  3248. }
  3249. }
  3250. get(query) {
  3251. this.initConnection_();
  3252. const deferred = new Deferred();
  3253. const request = {
  3254. p: query._path.toString(),
  3255. q: query._queryObject
  3256. };
  3257. const outstandingGet = {
  3258. action: 'g',
  3259. request,
  3260. onComplete: (message) => {
  3261. const payload = message['d'];
  3262. if (message['s'] === 'ok') {
  3263. deferred.resolve(payload);
  3264. }
  3265. else {
  3266. deferred.reject(payload);
  3267. }
  3268. }
  3269. };
  3270. this.outstandingGets_.push(outstandingGet);
  3271. this.outstandingGetCount_++;
  3272. const index = this.outstandingGets_.length - 1;
  3273. if (this.connected_) {
  3274. this.sendGet_(index);
  3275. }
  3276. return deferred.promise;
  3277. }
  3278. listen(query, currentHashFn, tag, onComplete) {
  3279. this.initConnection_();
  3280. const queryId = query._queryIdentifier;
  3281. const pathString = query._path.toString();
  3282. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3283. if (!this.listens.has(pathString)) {
  3284. this.listens.set(pathString, new Map());
  3285. }
  3286. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3287. assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3288. const listenSpec = {
  3289. onComplete,
  3290. hashFn: currentHashFn,
  3291. query,
  3292. tag
  3293. };
  3294. this.listens.get(pathString).set(queryId, listenSpec);
  3295. if (this.connected_) {
  3296. this.sendListen_(listenSpec);
  3297. }
  3298. }
  3299. sendGet_(index) {
  3300. const get = this.outstandingGets_[index];
  3301. this.sendRequest('g', get.request, (message) => {
  3302. delete this.outstandingGets_[index];
  3303. this.outstandingGetCount_--;
  3304. if (this.outstandingGetCount_ === 0) {
  3305. this.outstandingGets_ = [];
  3306. }
  3307. if (get.onComplete) {
  3308. get.onComplete(message);
  3309. }
  3310. });
  3311. }
  3312. sendListen_(listenSpec) {
  3313. const query = listenSpec.query;
  3314. const pathString = query._path.toString();
  3315. const queryId = query._queryIdentifier;
  3316. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3317. const req = { /*path*/ p: pathString };
  3318. const action = 'q';
  3319. // Only bother to send query if it's non-default.
  3320. if (listenSpec.tag) {
  3321. req['q'] = query._queryObject;
  3322. req['t'] = listenSpec.tag;
  3323. }
  3324. req[ /*hash*/'h'] = listenSpec.hashFn();
  3325. this.sendRequest(action, req, (message) => {
  3326. const payload = message[ /*data*/'d'];
  3327. const status = message[ /*status*/'s'];
  3328. // print warnings in any case...
  3329. PersistentConnection.warnOnListenWarnings_(payload, query);
  3330. const currentListenSpec = this.listens.get(pathString) &&
  3331. this.listens.get(pathString).get(queryId);
  3332. // only trigger actions if the listen hasn't been removed and readded
  3333. if (currentListenSpec === listenSpec) {
  3334. this.log_('listen response', message);
  3335. if (status !== 'ok') {
  3336. this.removeListen_(pathString, queryId);
  3337. }
  3338. if (listenSpec.onComplete) {
  3339. listenSpec.onComplete(status, payload);
  3340. }
  3341. }
  3342. });
  3343. }
  3344. static warnOnListenWarnings_(payload, query) {
  3345. if (payload && typeof payload === 'object' && contains(payload, 'w')) {
  3346. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3347. const warnings = safeGet(payload, 'w');
  3348. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3349. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3350. const indexPath = query._path.toString();
  3351. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3352. `filtered on the client. Consider adding ${indexSpec} at ` +
  3353. `${indexPath} to your security rules for better performance.`);
  3354. }
  3355. }
  3356. }
  3357. refreshAuthToken(token) {
  3358. this.authToken_ = token;
  3359. this.log_('Auth token refreshed');
  3360. if (this.authToken_) {
  3361. this.tryAuth();
  3362. }
  3363. else {
  3364. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3365. //the credential so we dont become authenticated next time we connect.
  3366. if (this.connected_) {
  3367. this.sendRequest('unauth', {}, () => { });
  3368. }
  3369. }
  3370. this.reduceReconnectDelayIfAdminCredential_(token);
  3371. }
  3372. reduceReconnectDelayIfAdminCredential_(credential) {
  3373. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3374. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3375. const isFirebaseSecret = credential && credential.length === 40;
  3376. if (isFirebaseSecret || isAdmin(credential)) {
  3377. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3378. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3379. }
  3380. }
  3381. refreshAppCheckToken(token) {
  3382. this.appCheckToken_ = token;
  3383. this.log_('App check token refreshed');
  3384. if (this.appCheckToken_) {
  3385. this.tryAppCheck();
  3386. }
  3387. else {
  3388. //If we're connected we want to let the server know to unauthenticate us.
  3389. //If we're not connected, simply delete the credential so we dont become
  3390. // authenticated next time we connect.
  3391. if (this.connected_) {
  3392. this.sendRequest('unappeck', {}, () => { });
  3393. }
  3394. }
  3395. }
  3396. /**
  3397. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3398. * a auth revoked (the connection is closed).
  3399. */
  3400. tryAuth() {
  3401. if (this.connected_ && this.authToken_) {
  3402. const token = this.authToken_;
  3403. const authMethod = isValidFormat(token) ? 'auth' : 'gauth';
  3404. const requestData = { cred: token };
  3405. if (this.authOverride_ === null) {
  3406. requestData['noauth'] = true;
  3407. }
  3408. else if (typeof this.authOverride_ === 'object') {
  3409. requestData['authvar'] = this.authOverride_;
  3410. }
  3411. this.sendRequest(authMethod, requestData, (res) => {
  3412. const status = res[ /*status*/'s'];
  3413. const data = res[ /*data*/'d'] || 'error';
  3414. if (this.authToken_ === token) {
  3415. if (status === 'ok') {
  3416. this.invalidAuthTokenCount_ = 0;
  3417. }
  3418. else {
  3419. // Triggers reconnect and force refresh for auth token
  3420. this.onAuthRevoked_(status, data);
  3421. }
  3422. }
  3423. });
  3424. }
  3425. }
  3426. /**
  3427. * Attempts to authenticate with the given token. If the authentication
  3428. * attempt fails, it's triggered like the token was revoked (the connection is
  3429. * closed).
  3430. */
  3431. tryAppCheck() {
  3432. if (this.connected_ && this.appCheckToken_) {
  3433. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3434. const status = res[ /*status*/'s'];
  3435. const data = res[ /*data*/'d'] || 'error';
  3436. if (status === 'ok') {
  3437. this.invalidAppCheckTokenCount_ = 0;
  3438. }
  3439. else {
  3440. this.onAppCheckRevoked_(status, data);
  3441. }
  3442. });
  3443. }
  3444. }
  3445. /**
  3446. * @inheritDoc
  3447. */
  3448. unlisten(query, tag) {
  3449. const pathString = query._path.toString();
  3450. const queryId = query._queryIdentifier;
  3451. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3452. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3453. const listen = this.removeListen_(pathString, queryId);
  3454. if (listen && this.connected_) {
  3455. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3456. }
  3457. }
  3458. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3459. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3460. const req = { /*path*/ p: pathString };
  3461. const action = 'n';
  3462. // Only bother sending queryId if it's non-default.
  3463. if (tag) {
  3464. req['q'] = queryObj;
  3465. req['t'] = tag;
  3466. }
  3467. this.sendRequest(action, req);
  3468. }
  3469. onDisconnectPut(pathString, data, onComplete) {
  3470. this.initConnection_();
  3471. if (this.connected_) {
  3472. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3473. }
  3474. else {
  3475. this.onDisconnectRequestQueue_.push({
  3476. pathString,
  3477. action: 'o',
  3478. data,
  3479. onComplete
  3480. });
  3481. }
  3482. }
  3483. onDisconnectMerge(pathString, data, onComplete) {
  3484. this.initConnection_();
  3485. if (this.connected_) {
  3486. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3487. }
  3488. else {
  3489. this.onDisconnectRequestQueue_.push({
  3490. pathString,
  3491. action: 'om',
  3492. data,
  3493. onComplete
  3494. });
  3495. }
  3496. }
  3497. onDisconnectCancel(pathString, onComplete) {
  3498. this.initConnection_();
  3499. if (this.connected_) {
  3500. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3501. }
  3502. else {
  3503. this.onDisconnectRequestQueue_.push({
  3504. pathString,
  3505. action: 'oc',
  3506. data: null,
  3507. onComplete
  3508. });
  3509. }
  3510. }
  3511. sendOnDisconnect_(action, pathString, data, onComplete) {
  3512. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3513. this.log_('onDisconnect ' + action, request);
  3514. this.sendRequest(action, request, (response) => {
  3515. if (onComplete) {
  3516. setTimeout(() => {
  3517. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3518. }, Math.floor(0));
  3519. }
  3520. });
  3521. }
  3522. put(pathString, data, onComplete, hash) {
  3523. this.putInternal('p', pathString, data, onComplete, hash);
  3524. }
  3525. merge(pathString, data, onComplete, hash) {
  3526. this.putInternal('m', pathString, data, onComplete, hash);
  3527. }
  3528. putInternal(action, pathString, data, onComplete, hash) {
  3529. this.initConnection_();
  3530. const request = {
  3531. /*path*/ p: pathString,
  3532. /*data*/ d: data
  3533. };
  3534. if (hash !== undefined) {
  3535. request[ /*hash*/'h'] = hash;
  3536. }
  3537. // TODO: Only keep track of the most recent put for a given path?
  3538. this.outstandingPuts_.push({
  3539. action,
  3540. request,
  3541. onComplete
  3542. });
  3543. this.outstandingPutCount_++;
  3544. const index = this.outstandingPuts_.length - 1;
  3545. if (this.connected_) {
  3546. this.sendPut_(index);
  3547. }
  3548. else {
  3549. this.log_('Buffering put: ' + pathString);
  3550. }
  3551. }
  3552. sendPut_(index) {
  3553. const action = this.outstandingPuts_[index].action;
  3554. const request = this.outstandingPuts_[index].request;
  3555. const onComplete = this.outstandingPuts_[index].onComplete;
  3556. this.outstandingPuts_[index].queued = this.connected_;
  3557. this.sendRequest(action, request, (message) => {
  3558. this.log_(action + ' response', message);
  3559. delete this.outstandingPuts_[index];
  3560. this.outstandingPutCount_--;
  3561. // Clean up array occasionally.
  3562. if (this.outstandingPutCount_ === 0) {
  3563. this.outstandingPuts_ = [];
  3564. }
  3565. if (onComplete) {
  3566. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3567. }
  3568. });
  3569. }
  3570. reportStats(stats) {
  3571. // If we're not connected, we just drop the stats.
  3572. if (this.connected_) {
  3573. const request = { /*counters*/ c: stats };
  3574. this.log_('reportStats', request);
  3575. this.sendRequest(/*stats*/ 's', request, result => {
  3576. const status = result[ /*status*/'s'];
  3577. if (status !== 'ok') {
  3578. const errorReason = result[ /* data */'d'];
  3579. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3580. }
  3581. });
  3582. }
  3583. }
  3584. onDataMessage_(message) {
  3585. if ('r' in message) {
  3586. // this is a response
  3587. this.log_('from server: ' + stringify(message));
  3588. const reqNum = message['r'];
  3589. const onResponse = this.requestCBHash_[reqNum];
  3590. if (onResponse) {
  3591. delete this.requestCBHash_[reqNum];
  3592. onResponse(message[ /*body*/'b']);
  3593. }
  3594. }
  3595. else if ('error' in message) {
  3596. throw 'A server-side error has occurred: ' + message['error'];
  3597. }
  3598. else if ('a' in message) {
  3599. // a and b are action and body, respectively
  3600. this.onDataPush_(message['a'], message['b']);
  3601. }
  3602. }
  3603. onDataPush_(action, body) {
  3604. this.log_('handleServerMessage', action, body);
  3605. if (action === 'd') {
  3606. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3607. /*isMerge*/ false, body['t']);
  3608. }
  3609. else if (action === 'm') {
  3610. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3611. /*isMerge=*/ true, body['t']);
  3612. }
  3613. else if (action === 'c') {
  3614. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3615. }
  3616. else if (action === 'ac') {
  3617. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3618. }
  3619. else if (action === 'apc') {
  3620. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3621. }
  3622. else if (action === 'sd') {
  3623. this.onSecurityDebugPacket_(body);
  3624. }
  3625. else {
  3626. error('Unrecognized action received from server: ' +
  3627. stringify(action) +
  3628. '\nAre you using the latest client?');
  3629. }
  3630. }
  3631. onReady_(timestamp, sessionId) {
  3632. this.log_('connection ready');
  3633. this.connected_ = true;
  3634. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3635. this.handleTimestamp_(timestamp);
  3636. this.lastSessionId = sessionId;
  3637. if (this.firstConnection_) {
  3638. this.sendConnectStats_();
  3639. }
  3640. this.restoreState_();
  3641. this.firstConnection_ = false;
  3642. this.onConnectStatus_(true);
  3643. }
  3644. scheduleConnect_(timeout) {
  3645. assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3646. if (this.establishConnectionTimer_) {
  3647. clearTimeout(this.establishConnectionTimer_);
  3648. }
  3649. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3650. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3651. this.establishConnectionTimer_ = setTimeout(() => {
  3652. this.establishConnectionTimer_ = null;
  3653. this.establishConnection_();
  3654. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3655. }, Math.floor(timeout));
  3656. }
  3657. initConnection_() {
  3658. if (!this.realtime_ && this.firstConnection_) {
  3659. this.scheduleConnect_(0);
  3660. }
  3661. }
  3662. onVisible_(visible) {
  3663. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3664. if (visible &&
  3665. !this.visible_ &&
  3666. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3667. this.log_('Window became visible. Reducing delay.');
  3668. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3669. if (!this.realtime_) {
  3670. this.scheduleConnect_(0);
  3671. }
  3672. }
  3673. this.visible_ = visible;
  3674. }
  3675. onOnline_(online) {
  3676. if (online) {
  3677. this.log_('Browser went online.');
  3678. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3679. if (!this.realtime_) {
  3680. this.scheduleConnect_(0);
  3681. }
  3682. }
  3683. else {
  3684. this.log_('Browser went offline. Killing connection.');
  3685. if (this.realtime_) {
  3686. this.realtime_.close();
  3687. }
  3688. }
  3689. }
  3690. onRealtimeDisconnect_() {
  3691. this.log_('data client disconnected');
  3692. this.connected_ = false;
  3693. this.realtime_ = null;
  3694. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3695. this.cancelSentTransactions_();
  3696. // Clear out the pending requests.
  3697. this.requestCBHash_ = {};
  3698. if (this.shouldReconnect_()) {
  3699. if (!this.visible_) {
  3700. this.log_("Window isn't visible. Delaying reconnect.");
  3701. this.reconnectDelay_ = this.maxReconnectDelay_;
  3702. this.lastConnectionAttemptTime_ = new Date().getTime();
  3703. }
  3704. else if (this.lastConnectionEstablishedTime_) {
  3705. // If we've been connected long enough, reset reconnect delay to minimum.
  3706. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3707. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3708. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3709. }
  3710. this.lastConnectionEstablishedTime_ = null;
  3711. }
  3712. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3713. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3714. reconnectDelay = Math.random() * reconnectDelay;
  3715. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3716. this.scheduleConnect_(reconnectDelay);
  3717. // Adjust reconnect delay for next time.
  3718. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3719. }
  3720. this.onConnectStatus_(false);
  3721. }
  3722. async establishConnection_() {
  3723. if (this.shouldReconnect_()) {
  3724. this.log_('Making a connection attempt');
  3725. this.lastConnectionAttemptTime_ = new Date().getTime();
  3726. this.lastConnectionEstablishedTime_ = null;
  3727. const onDataMessage = this.onDataMessage_.bind(this);
  3728. const onReady = this.onReady_.bind(this);
  3729. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3730. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3731. const lastSessionId = this.lastSessionId;
  3732. let canceled = false;
  3733. let connection = null;
  3734. const closeFn = function () {
  3735. if (connection) {
  3736. connection.close();
  3737. }
  3738. else {
  3739. canceled = true;
  3740. onDisconnect();
  3741. }
  3742. };
  3743. const sendRequestFn = function (msg) {
  3744. assert(connection, "sendRequest call when we're not connected not allowed.");
  3745. connection.sendRequest(msg);
  3746. };
  3747. this.realtime_ = {
  3748. close: closeFn,
  3749. sendRequest: sendRequestFn
  3750. };
  3751. const forceRefresh = this.forceTokenRefresh_;
  3752. this.forceTokenRefresh_ = false;
  3753. try {
  3754. // First fetch auth and app check token, and establish connection after
  3755. // fetching the token was successful
  3756. const [authToken, appCheckToken] = await Promise.all([
  3757. this.authTokenProvider_.getToken(forceRefresh),
  3758. this.appCheckTokenProvider_.getToken(forceRefresh)
  3759. ]);
  3760. if (!canceled) {
  3761. log('getToken() completed. Creating connection.');
  3762. this.authToken_ = authToken && authToken.accessToken;
  3763. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3764. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3765. /* onKill= */ reason => {
  3766. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3767. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3768. }, lastSessionId);
  3769. }
  3770. else {
  3771. log('getToken() completed but was canceled');
  3772. }
  3773. }
  3774. catch (error) {
  3775. this.log_('Failed to get token: ' + error);
  3776. if (!canceled) {
  3777. if (this.repoInfo_.nodeAdmin) {
  3778. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3779. // But getToken() may also just have temporarily failed, so we still want to
  3780. // continue retrying.
  3781. warn(error);
  3782. }
  3783. closeFn();
  3784. }
  3785. }
  3786. }
  3787. }
  3788. interrupt(reason) {
  3789. log('Interrupting connection for reason: ' + reason);
  3790. this.interruptReasons_[reason] = true;
  3791. if (this.realtime_) {
  3792. this.realtime_.close();
  3793. }
  3794. else {
  3795. if (this.establishConnectionTimer_) {
  3796. clearTimeout(this.establishConnectionTimer_);
  3797. this.establishConnectionTimer_ = null;
  3798. }
  3799. if (this.connected_) {
  3800. this.onRealtimeDisconnect_();
  3801. }
  3802. }
  3803. }
  3804. resume(reason) {
  3805. log('Resuming connection for reason: ' + reason);
  3806. delete this.interruptReasons_[reason];
  3807. if (isEmpty(this.interruptReasons_)) {
  3808. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3809. if (!this.realtime_) {
  3810. this.scheduleConnect_(0);
  3811. }
  3812. }
  3813. }
  3814. handleTimestamp_(timestamp) {
  3815. const delta = timestamp - new Date().getTime();
  3816. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3817. }
  3818. cancelSentTransactions_() {
  3819. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3820. const put = this.outstandingPuts_[i];
  3821. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3822. if (put.onComplete) {
  3823. put.onComplete('disconnect');
  3824. }
  3825. delete this.outstandingPuts_[i];
  3826. this.outstandingPutCount_--;
  3827. }
  3828. }
  3829. // Clean up array occasionally.
  3830. if (this.outstandingPutCount_ === 0) {
  3831. this.outstandingPuts_ = [];
  3832. }
  3833. }
  3834. onListenRevoked_(pathString, query) {
  3835. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3836. let queryId;
  3837. if (!query) {
  3838. queryId = 'default';
  3839. }
  3840. else {
  3841. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3842. }
  3843. const listen = this.removeListen_(pathString, queryId);
  3844. if (listen && listen.onComplete) {
  3845. listen.onComplete('permission_denied');
  3846. }
  3847. }
  3848. removeListen_(pathString, queryId) {
  3849. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3850. let listen;
  3851. if (this.listens.has(normalizedPathString)) {
  3852. const map = this.listens.get(normalizedPathString);
  3853. listen = map.get(queryId);
  3854. map.delete(queryId);
  3855. if (map.size === 0) {
  3856. this.listens.delete(normalizedPathString);
  3857. }
  3858. }
  3859. else {
  3860. // all listens for this path has already been removed
  3861. listen = undefined;
  3862. }
  3863. return listen;
  3864. }
  3865. onAuthRevoked_(statusCode, explanation) {
  3866. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3867. this.authToken_ = null;
  3868. this.forceTokenRefresh_ = true;
  3869. this.realtime_.close();
  3870. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3871. // We'll wait a couple times before logging the warning / increasing the
  3872. // retry period since oauth tokens will report as "invalid" if they're
  3873. // just expired. Plus there may be transient issues that resolve themselves.
  3874. this.invalidAuthTokenCount_++;
  3875. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3876. // Set a long reconnect delay because recovery is unlikely
  3877. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3878. // Notify the auth token provider that the token is invalid, which will log
  3879. // a warning
  3880. this.authTokenProvider_.notifyForInvalidToken();
  3881. }
  3882. }
  3883. }
  3884. onAppCheckRevoked_(statusCode, explanation) {
  3885. log('App check token revoked: ' + statusCode + '/' + explanation);
  3886. this.appCheckToken_ = null;
  3887. this.forceTokenRefresh_ = true;
  3888. // Note: We don't close the connection as the developer may not have
  3889. // enforcement enabled. The backend closes connections with enforcements.
  3890. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3891. // We'll wait a couple times before logging the warning / increasing the
  3892. // retry period since oauth tokens will report as "invalid" if they're
  3893. // just expired. Plus there may be transient issues that resolve themselves.
  3894. this.invalidAppCheckTokenCount_++;
  3895. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3896. this.appCheckTokenProvider_.notifyForInvalidToken();
  3897. }
  3898. }
  3899. }
  3900. onSecurityDebugPacket_(body) {
  3901. if (this.securityDebugCallback_) {
  3902. this.securityDebugCallback_(body);
  3903. }
  3904. else {
  3905. if ('msg' in body) {
  3906. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3907. }
  3908. }
  3909. }
  3910. restoreState_() {
  3911. //Re-authenticate ourselves if we have a credential stored.
  3912. this.tryAuth();
  3913. this.tryAppCheck();
  3914. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3915. // make sure to send listens before puts.
  3916. for (const queries of this.listens.values()) {
  3917. for (const listenSpec of queries.values()) {
  3918. this.sendListen_(listenSpec);
  3919. }
  3920. }
  3921. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3922. if (this.outstandingPuts_[i]) {
  3923. this.sendPut_(i);
  3924. }
  3925. }
  3926. while (this.onDisconnectRequestQueue_.length) {
  3927. const request = this.onDisconnectRequestQueue_.shift();
  3928. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3929. }
  3930. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3931. if (this.outstandingGets_[i]) {
  3932. this.sendGet_(i);
  3933. }
  3934. }
  3935. }
  3936. /**
  3937. * Sends client stats for first connection
  3938. */
  3939. sendConnectStats_() {
  3940. const stats = {};
  3941. let clientName = 'js';
  3942. if (isNodeSdk()) {
  3943. if (this.repoInfo_.nodeAdmin) {
  3944. clientName = 'admin_node';
  3945. }
  3946. else {
  3947. clientName = 'node';
  3948. }
  3949. }
  3950. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3951. if (isMobileCordova()) {
  3952. stats['framework.cordova'] = 1;
  3953. }
  3954. else if (isReactNative()) {
  3955. stats['framework.reactnative'] = 1;
  3956. }
  3957. this.reportStats(stats);
  3958. }
  3959. shouldReconnect_() {
  3960. const online = OnlineMonitor.getInstance().currentlyOnline();
  3961. return isEmpty(this.interruptReasons_) && online;
  3962. }
  3963. }
  3964. PersistentConnection.nextPersistentConnectionId_ = 0;
  3965. /**
  3966. * Counter for number of connections created. Mainly used for tagging in the logs
  3967. */
  3968. PersistentConnection.nextConnectionId_ = 0;
  3969. /**
  3970. * @license
  3971. * Copyright 2017 Google LLC
  3972. *
  3973. * Licensed under the Apache License, Version 2.0 (the "License");
  3974. * you may not use this file except in compliance with the License.
  3975. * You may obtain a copy of the License at
  3976. *
  3977. * http://www.apache.org/licenses/LICENSE-2.0
  3978. *
  3979. * Unless required by applicable law or agreed to in writing, software
  3980. * distributed under the License is distributed on an "AS IS" BASIS,
  3981. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3982. * See the License for the specific language governing permissions and
  3983. * limitations under the License.
  3984. */
  3985. class NamedNode {
  3986. constructor(name, node) {
  3987. this.name = name;
  3988. this.node = node;
  3989. }
  3990. static Wrap(name, node) {
  3991. return new NamedNode(name, node);
  3992. }
  3993. }
  3994. /**
  3995. * @license
  3996. * Copyright 2017 Google LLC
  3997. *
  3998. * Licensed under the Apache License, Version 2.0 (the "License");
  3999. * you may not use this file except in compliance with the License.
  4000. * You may obtain a copy of the License at
  4001. *
  4002. * http://www.apache.org/licenses/LICENSE-2.0
  4003. *
  4004. * Unless required by applicable law or agreed to in writing, software
  4005. * distributed under the License is distributed on an "AS IS" BASIS,
  4006. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4007. * See the License for the specific language governing permissions and
  4008. * limitations under the License.
  4009. */
  4010. class Index {
  4011. /**
  4012. * @returns A standalone comparison function for
  4013. * this index
  4014. */
  4015. getCompare() {
  4016. return this.compare.bind(this);
  4017. }
  4018. /**
  4019. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4020. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4021. *
  4022. *
  4023. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4024. */
  4025. indexedValueChanged(oldNode, newNode) {
  4026. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4027. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4028. return this.compare(oldWrapped, newWrapped) !== 0;
  4029. }
  4030. /**
  4031. * @returns a node wrapper that will sort equal to or less than
  4032. * any other node wrapper, using this index
  4033. */
  4034. minPost() {
  4035. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4036. return NamedNode.MIN;
  4037. }
  4038. }
  4039. /**
  4040. * @license
  4041. * Copyright 2017 Google LLC
  4042. *
  4043. * Licensed under the Apache License, Version 2.0 (the "License");
  4044. * you may not use this file except in compliance with the License.
  4045. * You may obtain a copy of the License at
  4046. *
  4047. * http://www.apache.org/licenses/LICENSE-2.0
  4048. *
  4049. * Unless required by applicable law or agreed to in writing, software
  4050. * distributed under the License is distributed on an "AS IS" BASIS,
  4051. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4052. * See the License for the specific language governing permissions and
  4053. * limitations under the License.
  4054. */
  4055. let __EMPTY_NODE;
  4056. class KeyIndex extends Index {
  4057. static get __EMPTY_NODE() {
  4058. return __EMPTY_NODE;
  4059. }
  4060. static set __EMPTY_NODE(val) {
  4061. __EMPTY_NODE = val;
  4062. }
  4063. compare(a, b) {
  4064. return nameCompare(a.name, b.name);
  4065. }
  4066. isDefinedOn(node) {
  4067. // We could probably return true here (since every node has a key), but it's never called
  4068. // so just leaving unimplemented for now.
  4069. throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4070. }
  4071. indexedValueChanged(oldNode, newNode) {
  4072. return false; // The key for a node never changes.
  4073. }
  4074. minPost() {
  4075. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4076. return NamedNode.MIN;
  4077. }
  4078. maxPost() {
  4079. // TODO: This should really be created once and cached in a static property, but
  4080. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4081. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4082. }
  4083. makePost(indexValue, name) {
  4084. assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4085. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4086. return new NamedNode(indexValue, __EMPTY_NODE);
  4087. }
  4088. /**
  4089. * @returns String representation for inclusion in a query spec
  4090. */
  4091. toString() {
  4092. return '.key';
  4093. }
  4094. }
  4095. const KEY_INDEX = new KeyIndex();
  4096. /**
  4097. * @license
  4098. * Copyright 2017 Google LLC
  4099. *
  4100. * Licensed under the Apache License, Version 2.0 (the "License");
  4101. * you may not use this file except in compliance with the License.
  4102. * You may obtain a copy of the License at
  4103. *
  4104. * http://www.apache.org/licenses/LICENSE-2.0
  4105. *
  4106. * Unless required by applicable law or agreed to in writing, software
  4107. * distributed under the License is distributed on an "AS IS" BASIS,
  4108. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4109. * See the License for the specific language governing permissions and
  4110. * limitations under the License.
  4111. */
  4112. /**
  4113. * An iterator over an LLRBNode.
  4114. */
  4115. class SortedMapIterator {
  4116. /**
  4117. * @param node - Node to iterate.
  4118. * @param isReverse_ - Whether or not to iterate in reverse
  4119. */
  4120. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4121. this.isReverse_ = isReverse_;
  4122. this.resultGenerator_ = resultGenerator_;
  4123. this.nodeStack_ = [];
  4124. let cmp = 1;
  4125. while (!node.isEmpty()) {
  4126. node = node;
  4127. cmp = startKey ? comparator(node.key, startKey) : 1;
  4128. // flip the comparison if we're going in reverse
  4129. if (isReverse_) {
  4130. cmp *= -1;
  4131. }
  4132. if (cmp < 0) {
  4133. // This node is less than our start key. ignore it
  4134. if (this.isReverse_) {
  4135. node = node.left;
  4136. }
  4137. else {
  4138. node = node.right;
  4139. }
  4140. }
  4141. else if (cmp === 0) {
  4142. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4143. this.nodeStack_.push(node);
  4144. break;
  4145. }
  4146. else {
  4147. // This node is greater than our start key, add it to the stack and move to the next one
  4148. this.nodeStack_.push(node);
  4149. if (this.isReverse_) {
  4150. node = node.right;
  4151. }
  4152. else {
  4153. node = node.left;
  4154. }
  4155. }
  4156. }
  4157. }
  4158. getNext() {
  4159. if (this.nodeStack_.length === 0) {
  4160. return null;
  4161. }
  4162. let node = this.nodeStack_.pop();
  4163. let result;
  4164. if (this.resultGenerator_) {
  4165. result = this.resultGenerator_(node.key, node.value);
  4166. }
  4167. else {
  4168. result = { key: node.key, value: node.value };
  4169. }
  4170. if (this.isReverse_) {
  4171. node = node.left;
  4172. while (!node.isEmpty()) {
  4173. this.nodeStack_.push(node);
  4174. node = node.right;
  4175. }
  4176. }
  4177. else {
  4178. node = node.right;
  4179. while (!node.isEmpty()) {
  4180. this.nodeStack_.push(node);
  4181. node = node.left;
  4182. }
  4183. }
  4184. return result;
  4185. }
  4186. hasNext() {
  4187. return this.nodeStack_.length > 0;
  4188. }
  4189. peek() {
  4190. if (this.nodeStack_.length === 0) {
  4191. return null;
  4192. }
  4193. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4194. if (this.resultGenerator_) {
  4195. return this.resultGenerator_(node.key, node.value);
  4196. }
  4197. else {
  4198. return { key: node.key, value: node.value };
  4199. }
  4200. }
  4201. }
  4202. /**
  4203. * Represents a node in a Left-leaning Red-Black tree.
  4204. */
  4205. class LLRBNode {
  4206. /**
  4207. * @param key - Key associated with this node.
  4208. * @param value - Value associated with this node.
  4209. * @param color - Whether this node is red.
  4210. * @param left - Left child.
  4211. * @param right - Right child.
  4212. */
  4213. constructor(key, value, color, left, right) {
  4214. this.key = key;
  4215. this.value = value;
  4216. this.color = color != null ? color : LLRBNode.RED;
  4217. this.left =
  4218. left != null ? left : SortedMap.EMPTY_NODE;
  4219. this.right =
  4220. right != null ? right : SortedMap.EMPTY_NODE;
  4221. }
  4222. /**
  4223. * Returns a copy of the current node, optionally replacing pieces of it.
  4224. *
  4225. * @param key - New key for the node, or null.
  4226. * @param value - New value for the node, or null.
  4227. * @param color - New color for the node, or null.
  4228. * @param left - New left child for the node, or null.
  4229. * @param right - New right child for the node, or null.
  4230. * @returns The node copy.
  4231. */
  4232. copy(key, value, color, left, right) {
  4233. 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);
  4234. }
  4235. /**
  4236. * @returns The total number of nodes in the tree.
  4237. */
  4238. count() {
  4239. return this.left.count() + 1 + this.right.count();
  4240. }
  4241. /**
  4242. * @returns True if the tree is empty.
  4243. */
  4244. isEmpty() {
  4245. return false;
  4246. }
  4247. /**
  4248. * Traverses the tree in key order and calls the specified action function
  4249. * for each node.
  4250. *
  4251. * @param action - Callback function to be called for each
  4252. * node. If it returns true, traversal is aborted.
  4253. * @returns The first truthy value returned by action, or the last falsey
  4254. * value returned by action
  4255. */
  4256. inorderTraversal(action) {
  4257. return (this.left.inorderTraversal(action) ||
  4258. !!action(this.key, this.value) ||
  4259. this.right.inorderTraversal(action));
  4260. }
  4261. /**
  4262. * Traverses the tree in reverse key order and calls the specified action function
  4263. * for each node.
  4264. *
  4265. * @param action - Callback function to be called for each
  4266. * node. If it returns true, traversal is aborted.
  4267. * @returns True if traversal was aborted.
  4268. */
  4269. reverseTraversal(action) {
  4270. return (this.right.reverseTraversal(action) ||
  4271. action(this.key, this.value) ||
  4272. this.left.reverseTraversal(action));
  4273. }
  4274. /**
  4275. * @returns The minimum node in the tree.
  4276. */
  4277. min_() {
  4278. if (this.left.isEmpty()) {
  4279. return this;
  4280. }
  4281. else {
  4282. return this.left.min_();
  4283. }
  4284. }
  4285. /**
  4286. * @returns The maximum key in the tree.
  4287. */
  4288. minKey() {
  4289. return this.min_().key;
  4290. }
  4291. /**
  4292. * @returns The maximum key in the tree.
  4293. */
  4294. maxKey() {
  4295. if (this.right.isEmpty()) {
  4296. return this.key;
  4297. }
  4298. else {
  4299. return this.right.maxKey();
  4300. }
  4301. }
  4302. /**
  4303. * @param key - Key to insert.
  4304. * @param value - Value to insert.
  4305. * @param comparator - Comparator.
  4306. * @returns New tree, with the key/value added.
  4307. */
  4308. insert(key, value, comparator) {
  4309. let n = this;
  4310. const cmp = comparator(key, n.key);
  4311. if (cmp < 0) {
  4312. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4313. }
  4314. else if (cmp === 0) {
  4315. n = n.copy(null, value, null, null, null);
  4316. }
  4317. else {
  4318. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4319. }
  4320. return n.fixUp_();
  4321. }
  4322. /**
  4323. * @returns New tree, with the minimum key removed.
  4324. */
  4325. removeMin_() {
  4326. if (this.left.isEmpty()) {
  4327. return SortedMap.EMPTY_NODE;
  4328. }
  4329. let n = this;
  4330. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4331. n = n.moveRedLeft_();
  4332. }
  4333. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4334. return n.fixUp_();
  4335. }
  4336. /**
  4337. * @param key - The key of the item to remove.
  4338. * @param comparator - Comparator.
  4339. * @returns New tree, with the specified item removed.
  4340. */
  4341. remove(key, comparator) {
  4342. let n, smallest;
  4343. n = this;
  4344. if (comparator(key, n.key) < 0) {
  4345. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4346. n = n.moveRedLeft_();
  4347. }
  4348. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4349. }
  4350. else {
  4351. if (n.left.isRed_()) {
  4352. n = n.rotateRight_();
  4353. }
  4354. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4355. n = n.moveRedRight_();
  4356. }
  4357. if (comparator(key, n.key) === 0) {
  4358. if (n.right.isEmpty()) {
  4359. return SortedMap.EMPTY_NODE;
  4360. }
  4361. else {
  4362. smallest = n.right.min_();
  4363. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4364. }
  4365. }
  4366. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4367. }
  4368. return n.fixUp_();
  4369. }
  4370. /**
  4371. * @returns Whether this is a RED node.
  4372. */
  4373. isRed_() {
  4374. return this.color;
  4375. }
  4376. /**
  4377. * @returns New tree after performing any needed rotations.
  4378. */
  4379. fixUp_() {
  4380. let n = this;
  4381. if (n.right.isRed_() && !n.left.isRed_()) {
  4382. n = n.rotateLeft_();
  4383. }
  4384. if (n.left.isRed_() && n.left.left.isRed_()) {
  4385. n = n.rotateRight_();
  4386. }
  4387. if (n.left.isRed_() && n.right.isRed_()) {
  4388. n = n.colorFlip_();
  4389. }
  4390. return n;
  4391. }
  4392. /**
  4393. * @returns New tree, after moveRedLeft.
  4394. */
  4395. moveRedLeft_() {
  4396. let n = this.colorFlip_();
  4397. if (n.right.left.isRed_()) {
  4398. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4399. n = n.rotateLeft_();
  4400. n = n.colorFlip_();
  4401. }
  4402. return n;
  4403. }
  4404. /**
  4405. * @returns New tree, after moveRedRight.
  4406. */
  4407. moveRedRight_() {
  4408. let n = this.colorFlip_();
  4409. if (n.left.left.isRed_()) {
  4410. n = n.rotateRight_();
  4411. n = n.colorFlip_();
  4412. }
  4413. return n;
  4414. }
  4415. /**
  4416. * @returns New tree, after rotateLeft.
  4417. */
  4418. rotateLeft_() {
  4419. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4420. return this.right.copy(null, null, this.color, nl, null);
  4421. }
  4422. /**
  4423. * @returns New tree, after rotateRight.
  4424. */
  4425. rotateRight_() {
  4426. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4427. return this.left.copy(null, null, this.color, null, nr);
  4428. }
  4429. /**
  4430. * @returns Newt ree, after colorFlip.
  4431. */
  4432. colorFlip_() {
  4433. const left = this.left.copy(null, null, !this.left.color, null, null);
  4434. const right = this.right.copy(null, null, !this.right.color, null, null);
  4435. return this.copy(null, null, !this.color, left, right);
  4436. }
  4437. /**
  4438. * For testing.
  4439. *
  4440. * @returns True if all is well.
  4441. */
  4442. checkMaxDepth_() {
  4443. const blackDepth = this.check_();
  4444. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4445. }
  4446. check_() {
  4447. if (this.isRed_() && this.left.isRed_()) {
  4448. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4449. }
  4450. if (this.right.isRed_()) {
  4451. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4452. }
  4453. const blackDepth = this.left.check_();
  4454. if (blackDepth !== this.right.check_()) {
  4455. throw new Error('Black depths differ');
  4456. }
  4457. else {
  4458. return blackDepth + (this.isRed_() ? 0 : 1);
  4459. }
  4460. }
  4461. }
  4462. LLRBNode.RED = true;
  4463. LLRBNode.BLACK = false;
  4464. /**
  4465. * Represents an empty node (a leaf node in the Red-Black Tree).
  4466. */
  4467. class LLRBEmptyNode {
  4468. /**
  4469. * Returns a copy of the current node.
  4470. *
  4471. * @returns The node copy.
  4472. */
  4473. copy(key, value, color, left, right) {
  4474. return this;
  4475. }
  4476. /**
  4477. * Returns a copy of the tree, with the specified key/value added.
  4478. *
  4479. * @param key - Key to be added.
  4480. * @param value - Value to be added.
  4481. * @param comparator - Comparator.
  4482. * @returns New tree, with item added.
  4483. */
  4484. insert(key, value, comparator) {
  4485. return new LLRBNode(key, value, null);
  4486. }
  4487. /**
  4488. * Returns a copy of the tree, with the specified key removed.
  4489. *
  4490. * @param key - The key to remove.
  4491. * @param comparator - Comparator.
  4492. * @returns New tree, with item removed.
  4493. */
  4494. remove(key, comparator) {
  4495. return this;
  4496. }
  4497. /**
  4498. * @returns The total number of nodes in the tree.
  4499. */
  4500. count() {
  4501. return 0;
  4502. }
  4503. /**
  4504. * @returns True if the tree is empty.
  4505. */
  4506. isEmpty() {
  4507. return true;
  4508. }
  4509. /**
  4510. * Traverses the tree in key order and calls the specified action function
  4511. * for each node.
  4512. *
  4513. * @param action - Callback function to be called for each
  4514. * node. If it returns true, traversal is aborted.
  4515. * @returns True if traversal was aborted.
  4516. */
  4517. inorderTraversal(action) {
  4518. return false;
  4519. }
  4520. /**
  4521. * Traverses the tree in reverse key order and calls the specified action function
  4522. * for each node.
  4523. *
  4524. * @param action - Callback function to be called for each
  4525. * node. If it returns true, traversal is aborted.
  4526. * @returns True if traversal was aborted.
  4527. */
  4528. reverseTraversal(action) {
  4529. return false;
  4530. }
  4531. minKey() {
  4532. return null;
  4533. }
  4534. maxKey() {
  4535. return null;
  4536. }
  4537. check_() {
  4538. return 0;
  4539. }
  4540. /**
  4541. * @returns Whether this node is red.
  4542. */
  4543. isRed_() {
  4544. return false;
  4545. }
  4546. }
  4547. /**
  4548. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4549. * tree.
  4550. */
  4551. class SortedMap {
  4552. /**
  4553. * @param comparator_ - Key comparator.
  4554. * @param root_ - Optional root node for the map.
  4555. */
  4556. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4557. this.comparator_ = comparator_;
  4558. this.root_ = root_;
  4559. }
  4560. /**
  4561. * Returns a copy of the map, with the specified key/value added or replaced.
  4562. * (TODO: We should perhaps rename this method to 'put')
  4563. *
  4564. * @param key - Key to be added.
  4565. * @param value - Value to be added.
  4566. * @returns New map, with item added.
  4567. */
  4568. insert(key, value) {
  4569. return new SortedMap(this.comparator_, this.root_
  4570. .insert(key, value, this.comparator_)
  4571. .copy(null, null, LLRBNode.BLACK, null, null));
  4572. }
  4573. /**
  4574. * Returns a copy of the map, with the specified key removed.
  4575. *
  4576. * @param key - The key to remove.
  4577. * @returns New map, with item removed.
  4578. */
  4579. remove(key) {
  4580. return new SortedMap(this.comparator_, this.root_
  4581. .remove(key, this.comparator_)
  4582. .copy(null, null, LLRBNode.BLACK, null, null));
  4583. }
  4584. /**
  4585. * Returns the value of the node with the given key, or null.
  4586. *
  4587. * @param key - The key to look up.
  4588. * @returns The value of the node with the given key, or null if the
  4589. * key doesn't exist.
  4590. */
  4591. get(key) {
  4592. let cmp;
  4593. let node = this.root_;
  4594. while (!node.isEmpty()) {
  4595. cmp = this.comparator_(key, node.key);
  4596. if (cmp === 0) {
  4597. return node.value;
  4598. }
  4599. else if (cmp < 0) {
  4600. node = node.left;
  4601. }
  4602. else if (cmp > 0) {
  4603. node = node.right;
  4604. }
  4605. }
  4606. return null;
  4607. }
  4608. /**
  4609. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4610. * @param key - The key to find the predecessor of
  4611. * @returns The predecessor key.
  4612. */
  4613. getPredecessorKey(key) {
  4614. let cmp, node = this.root_, rightParent = null;
  4615. while (!node.isEmpty()) {
  4616. cmp = this.comparator_(key, node.key);
  4617. if (cmp === 0) {
  4618. if (!node.left.isEmpty()) {
  4619. node = node.left;
  4620. while (!node.right.isEmpty()) {
  4621. node = node.right;
  4622. }
  4623. return node.key;
  4624. }
  4625. else if (rightParent) {
  4626. return rightParent.key;
  4627. }
  4628. else {
  4629. return null; // first item.
  4630. }
  4631. }
  4632. else if (cmp < 0) {
  4633. node = node.left;
  4634. }
  4635. else if (cmp > 0) {
  4636. rightParent = node;
  4637. node = node.right;
  4638. }
  4639. }
  4640. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4641. }
  4642. /**
  4643. * @returns True if the map is empty.
  4644. */
  4645. isEmpty() {
  4646. return this.root_.isEmpty();
  4647. }
  4648. /**
  4649. * @returns The total number of nodes in the map.
  4650. */
  4651. count() {
  4652. return this.root_.count();
  4653. }
  4654. /**
  4655. * @returns The minimum key in the map.
  4656. */
  4657. minKey() {
  4658. return this.root_.minKey();
  4659. }
  4660. /**
  4661. * @returns The maximum key in the map.
  4662. */
  4663. maxKey() {
  4664. return this.root_.maxKey();
  4665. }
  4666. /**
  4667. * Traverses the map in key order and calls the specified action function
  4668. * for each key/value pair.
  4669. *
  4670. * @param action - Callback function to be called
  4671. * for each key/value pair. If action returns true, traversal is aborted.
  4672. * @returns The first truthy value returned by action, or the last falsey
  4673. * value returned by action
  4674. */
  4675. inorderTraversal(action) {
  4676. return this.root_.inorderTraversal(action);
  4677. }
  4678. /**
  4679. * Traverses the map in reverse key order and calls the specified action function
  4680. * for each key/value pair.
  4681. *
  4682. * @param action - Callback function to be called
  4683. * for each key/value pair. If action returns true, traversal is aborted.
  4684. * @returns True if the traversal was aborted.
  4685. */
  4686. reverseTraversal(action) {
  4687. return this.root_.reverseTraversal(action);
  4688. }
  4689. /**
  4690. * Returns an iterator over the SortedMap.
  4691. * @returns The iterator.
  4692. */
  4693. getIterator(resultGenerator) {
  4694. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4695. }
  4696. getIteratorFrom(key, resultGenerator) {
  4697. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4698. }
  4699. getReverseIteratorFrom(key, resultGenerator) {
  4700. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4701. }
  4702. getReverseIterator(resultGenerator) {
  4703. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4704. }
  4705. }
  4706. /**
  4707. * Always use the same empty node, to reduce memory.
  4708. */
  4709. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4710. /**
  4711. * @license
  4712. * Copyright 2017 Google LLC
  4713. *
  4714. * Licensed under the Apache License, Version 2.0 (the "License");
  4715. * you may not use this file except in compliance with the License.
  4716. * You may obtain a copy of the License at
  4717. *
  4718. * http://www.apache.org/licenses/LICENSE-2.0
  4719. *
  4720. * Unless required by applicable law or agreed to in writing, software
  4721. * distributed under the License is distributed on an "AS IS" BASIS,
  4722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4723. * See the License for the specific language governing permissions and
  4724. * limitations under the License.
  4725. */
  4726. function NAME_ONLY_COMPARATOR(left, right) {
  4727. return nameCompare(left.name, right.name);
  4728. }
  4729. function NAME_COMPARATOR(left, right) {
  4730. return nameCompare(left, right);
  4731. }
  4732. /**
  4733. * @license
  4734. * Copyright 2017 Google LLC
  4735. *
  4736. * Licensed under the Apache License, Version 2.0 (the "License");
  4737. * you may not use this file except in compliance with the License.
  4738. * You may obtain a copy of the License at
  4739. *
  4740. * http://www.apache.org/licenses/LICENSE-2.0
  4741. *
  4742. * Unless required by applicable law or agreed to in writing, software
  4743. * distributed under the License is distributed on an "AS IS" BASIS,
  4744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4745. * See the License for the specific language governing permissions and
  4746. * limitations under the License.
  4747. */
  4748. let MAX_NODE$2;
  4749. function setMaxNode$1(val) {
  4750. MAX_NODE$2 = val;
  4751. }
  4752. const priorityHashText = function (priority) {
  4753. if (typeof priority === 'number') {
  4754. return 'number:' + doubleToIEEE754String(priority);
  4755. }
  4756. else {
  4757. return 'string:' + priority;
  4758. }
  4759. };
  4760. /**
  4761. * Validates that a priority snapshot Node is valid.
  4762. */
  4763. const validatePriorityNode = function (priorityNode) {
  4764. if (priorityNode.isLeafNode()) {
  4765. const val = priorityNode.val();
  4766. assert(typeof val === 'string' ||
  4767. typeof val === 'number' ||
  4768. (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
  4769. }
  4770. else {
  4771. assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4772. }
  4773. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4774. assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4775. };
  4776. /**
  4777. * @license
  4778. * Copyright 2017 Google LLC
  4779. *
  4780. * Licensed under the Apache License, Version 2.0 (the "License");
  4781. * you may not use this file except in compliance with the License.
  4782. * You may obtain a copy of the License at
  4783. *
  4784. * http://www.apache.org/licenses/LICENSE-2.0
  4785. *
  4786. * Unless required by applicable law or agreed to in writing, software
  4787. * distributed under the License is distributed on an "AS IS" BASIS,
  4788. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4789. * See the License for the specific language governing permissions and
  4790. * limitations under the License.
  4791. */
  4792. let __childrenNodeConstructor;
  4793. /**
  4794. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4795. * implements Node and stores the value of the node (a string,
  4796. * number, or boolean) accessible via getValue().
  4797. */
  4798. class LeafNode {
  4799. /**
  4800. * @param value_ - The value to store in this leaf node. The object type is
  4801. * possible in the event of a deferred value
  4802. * @param priorityNode_ - The priority of this node.
  4803. */
  4804. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4805. this.value_ = value_;
  4806. this.priorityNode_ = priorityNode_;
  4807. this.lazyHash_ = null;
  4808. assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4809. validatePriorityNode(this.priorityNode_);
  4810. }
  4811. static set __childrenNodeConstructor(val) {
  4812. __childrenNodeConstructor = val;
  4813. }
  4814. static get __childrenNodeConstructor() {
  4815. return __childrenNodeConstructor;
  4816. }
  4817. /** @inheritDoc */
  4818. isLeafNode() {
  4819. return true;
  4820. }
  4821. /** @inheritDoc */
  4822. getPriority() {
  4823. return this.priorityNode_;
  4824. }
  4825. /** @inheritDoc */
  4826. updatePriority(newPriorityNode) {
  4827. return new LeafNode(this.value_, newPriorityNode);
  4828. }
  4829. /** @inheritDoc */
  4830. getImmediateChild(childName) {
  4831. // Hack to treat priority as a regular child
  4832. if (childName === '.priority') {
  4833. return this.priorityNode_;
  4834. }
  4835. else {
  4836. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4837. }
  4838. }
  4839. /** @inheritDoc */
  4840. getChild(path) {
  4841. if (pathIsEmpty(path)) {
  4842. return this;
  4843. }
  4844. else if (pathGetFront(path) === '.priority') {
  4845. return this.priorityNode_;
  4846. }
  4847. else {
  4848. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4849. }
  4850. }
  4851. hasChild() {
  4852. return false;
  4853. }
  4854. /** @inheritDoc */
  4855. getPredecessorChildName(childName, childNode) {
  4856. return null;
  4857. }
  4858. /** @inheritDoc */
  4859. updateImmediateChild(childName, newChildNode) {
  4860. if (childName === '.priority') {
  4861. return this.updatePriority(newChildNode);
  4862. }
  4863. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4864. return this;
  4865. }
  4866. else {
  4867. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4868. }
  4869. }
  4870. /** @inheritDoc */
  4871. updateChild(path, newChildNode) {
  4872. const front = pathGetFront(path);
  4873. if (front === null) {
  4874. return newChildNode;
  4875. }
  4876. else if (newChildNode.isEmpty() && front !== '.priority') {
  4877. return this;
  4878. }
  4879. else {
  4880. assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4881. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4882. }
  4883. }
  4884. /** @inheritDoc */
  4885. isEmpty() {
  4886. return false;
  4887. }
  4888. /** @inheritDoc */
  4889. numChildren() {
  4890. return 0;
  4891. }
  4892. /** @inheritDoc */
  4893. forEachChild(index, action) {
  4894. return false;
  4895. }
  4896. val(exportFormat) {
  4897. if (exportFormat && !this.getPriority().isEmpty()) {
  4898. return {
  4899. '.value': this.getValue(),
  4900. '.priority': this.getPriority().val()
  4901. };
  4902. }
  4903. else {
  4904. return this.getValue();
  4905. }
  4906. }
  4907. /** @inheritDoc */
  4908. hash() {
  4909. if (this.lazyHash_ === null) {
  4910. let toHash = '';
  4911. if (!this.priorityNode_.isEmpty()) {
  4912. toHash +=
  4913. 'priority:' +
  4914. priorityHashText(this.priorityNode_.val()) +
  4915. ':';
  4916. }
  4917. const type = typeof this.value_;
  4918. toHash += type + ':';
  4919. if (type === 'number') {
  4920. toHash += doubleToIEEE754String(this.value_);
  4921. }
  4922. else {
  4923. toHash += this.value_;
  4924. }
  4925. this.lazyHash_ = sha1(toHash);
  4926. }
  4927. return this.lazyHash_;
  4928. }
  4929. /**
  4930. * Returns the value of the leaf node.
  4931. * @returns The value of the node.
  4932. */
  4933. getValue() {
  4934. return this.value_;
  4935. }
  4936. compareTo(other) {
  4937. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4938. return 1;
  4939. }
  4940. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4941. return -1;
  4942. }
  4943. else {
  4944. assert(other.isLeafNode(), 'Unknown node type');
  4945. return this.compareToLeafNode_(other);
  4946. }
  4947. }
  4948. /**
  4949. * Comparison specifically for two leaf nodes
  4950. */
  4951. compareToLeafNode_(otherLeaf) {
  4952. const otherLeafType = typeof otherLeaf.value_;
  4953. const thisLeafType = typeof this.value_;
  4954. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4955. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4956. assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4957. assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4958. if (otherIndex === thisIndex) {
  4959. // Same type, compare values
  4960. if (thisLeafType === 'object') {
  4961. // Deferred value nodes are all equal, but we should also never get to this point...
  4962. return 0;
  4963. }
  4964. else {
  4965. // Note that this works because true > false, all others are number or string comparisons
  4966. if (this.value_ < otherLeaf.value_) {
  4967. return -1;
  4968. }
  4969. else if (this.value_ === otherLeaf.value_) {
  4970. return 0;
  4971. }
  4972. else {
  4973. return 1;
  4974. }
  4975. }
  4976. }
  4977. else {
  4978. return thisIndex - otherIndex;
  4979. }
  4980. }
  4981. withIndex() {
  4982. return this;
  4983. }
  4984. isIndexed() {
  4985. return true;
  4986. }
  4987. equals(other) {
  4988. if (other === this) {
  4989. return true;
  4990. }
  4991. else if (other.isLeafNode()) {
  4992. const otherLeaf = other;
  4993. return (this.value_ === otherLeaf.value_ &&
  4994. this.priorityNode_.equals(otherLeaf.priorityNode_));
  4995. }
  4996. else {
  4997. return false;
  4998. }
  4999. }
  5000. }
  5001. /**
  5002. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5003. * the same type, the comparison falls back to their value
  5004. */
  5005. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5006. /**
  5007. * @license
  5008. * Copyright 2017 Google LLC
  5009. *
  5010. * Licensed under the Apache License, Version 2.0 (the "License");
  5011. * you may not use this file except in compliance with the License.
  5012. * You may obtain a copy of the License at
  5013. *
  5014. * http://www.apache.org/licenses/LICENSE-2.0
  5015. *
  5016. * Unless required by applicable law or agreed to in writing, software
  5017. * distributed under the License is distributed on an "AS IS" BASIS,
  5018. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5019. * See the License for the specific language governing permissions and
  5020. * limitations under the License.
  5021. */
  5022. let nodeFromJSON$1;
  5023. let MAX_NODE$1;
  5024. function setNodeFromJSON(val) {
  5025. nodeFromJSON$1 = val;
  5026. }
  5027. function setMaxNode(val) {
  5028. MAX_NODE$1 = val;
  5029. }
  5030. class PriorityIndex extends Index {
  5031. compare(a, b) {
  5032. const aPriority = a.node.getPriority();
  5033. const bPriority = b.node.getPriority();
  5034. const indexCmp = aPriority.compareTo(bPriority);
  5035. if (indexCmp === 0) {
  5036. return nameCompare(a.name, b.name);
  5037. }
  5038. else {
  5039. return indexCmp;
  5040. }
  5041. }
  5042. isDefinedOn(node) {
  5043. return !node.getPriority().isEmpty();
  5044. }
  5045. indexedValueChanged(oldNode, newNode) {
  5046. return !oldNode.getPriority().equals(newNode.getPriority());
  5047. }
  5048. minPost() {
  5049. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5050. return NamedNode.MIN;
  5051. }
  5052. maxPost() {
  5053. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5054. }
  5055. makePost(indexValue, name) {
  5056. const priorityNode = nodeFromJSON$1(indexValue);
  5057. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5058. }
  5059. /**
  5060. * @returns String representation for inclusion in a query spec
  5061. */
  5062. toString() {
  5063. return '.priority';
  5064. }
  5065. }
  5066. const PRIORITY_INDEX = new PriorityIndex();
  5067. /**
  5068. * @license
  5069. * Copyright 2017 Google LLC
  5070. *
  5071. * Licensed under the Apache License, Version 2.0 (the "License");
  5072. * you may not use this file except in compliance with the License.
  5073. * You may obtain a copy of the License at
  5074. *
  5075. * http://www.apache.org/licenses/LICENSE-2.0
  5076. *
  5077. * Unless required by applicable law or agreed to in writing, software
  5078. * distributed under the License is distributed on an "AS IS" BASIS,
  5079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5080. * See the License for the specific language governing permissions and
  5081. * limitations under the License.
  5082. */
  5083. const LOG_2 = Math.log(2);
  5084. class Base12Num {
  5085. constructor(length) {
  5086. const logBase2 = (num) =>
  5087. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5088. parseInt((Math.log(num) / LOG_2), 10);
  5089. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5090. this.count = logBase2(length + 1);
  5091. this.current_ = this.count - 1;
  5092. const mask = bitMask(this.count);
  5093. this.bits_ = (length + 1) & mask;
  5094. }
  5095. nextBitIsOne() {
  5096. //noinspection JSBitwiseOperatorUsage
  5097. const result = !(this.bits_ & (0x1 << this.current_));
  5098. this.current_--;
  5099. return result;
  5100. }
  5101. }
  5102. /**
  5103. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5104. * function
  5105. *
  5106. * Uses the algorithm described in the paper linked here:
  5107. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5108. *
  5109. * @param childList - Unsorted list of children
  5110. * @param cmp - The comparison method to be used
  5111. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5112. * type is not NamedNode
  5113. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5114. */
  5115. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5116. childList.sort(cmp);
  5117. const buildBalancedTree = function (low, high) {
  5118. const length = high - low;
  5119. let namedNode;
  5120. let key;
  5121. if (length === 0) {
  5122. return null;
  5123. }
  5124. else if (length === 1) {
  5125. namedNode = childList[low];
  5126. key = keyFn ? keyFn(namedNode) : namedNode;
  5127. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5128. }
  5129. else {
  5130. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5131. const middle = parseInt((length / 2), 10) + low;
  5132. const left = buildBalancedTree(low, middle);
  5133. const right = buildBalancedTree(middle + 1, high);
  5134. namedNode = childList[middle];
  5135. key = keyFn ? keyFn(namedNode) : namedNode;
  5136. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5137. }
  5138. };
  5139. const buildFrom12Array = function (base12) {
  5140. let node = null;
  5141. let root = null;
  5142. let index = childList.length;
  5143. const buildPennant = function (chunkSize, color) {
  5144. const low = index - chunkSize;
  5145. const high = index;
  5146. index -= chunkSize;
  5147. const childTree = buildBalancedTree(low + 1, high);
  5148. const namedNode = childList[low];
  5149. const key = keyFn ? keyFn(namedNode) : namedNode;
  5150. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5151. };
  5152. const attachPennant = function (pennant) {
  5153. if (node) {
  5154. node.left = pennant;
  5155. node = pennant;
  5156. }
  5157. else {
  5158. root = pennant;
  5159. node = pennant;
  5160. }
  5161. };
  5162. for (let i = 0; i < base12.count; ++i) {
  5163. const isOne = base12.nextBitIsOne();
  5164. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5165. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5166. if (isOne) {
  5167. buildPennant(chunkSize, LLRBNode.BLACK);
  5168. }
  5169. else {
  5170. // current == 2
  5171. buildPennant(chunkSize, LLRBNode.BLACK);
  5172. buildPennant(chunkSize, LLRBNode.RED);
  5173. }
  5174. }
  5175. return root;
  5176. };
  5177. const base12 = new Base12Num(childList.length);
  5178. const root = buildFrom12Array(base12);
  5179. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5180. return new SortedMap(mapSortFn || cmp, root);
  5181. };
  5182. /**
  5183. * @license
  5184. * Copyright 2017 Google LLC
  5185. *
  5186. * Licensed under the Apache License, Version 2.0 (the "License");
  5187. * you may not use this file except in compliance with the License.
  5188. * You may obtain a copy of the License at
  5189. *
  5190. * http://www.apache.org/licenses/LICENSE-2.0
  5191. *
  5192. * Unless required by applicable law or agreed to in writing, software
  5193. * distributed under the License is distributed on an "AS IS" BASIS,
  5194. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5195. * See the License for the specific language governing permissions and
  5196. * limitations under the License.
  5197. */
  5198. let _defaultIndexMap;
  5199. const fallbackObject = {};
  5200. class IndexMap {
  5201. constructor(indexes_, indexSet_) {
  5202. this.indexes_ = indexes_;
  5203. this.indexSet_ = indexSet_;
  5204. }
  5205. /**
  5206. * The default IndexMap for nodes without a priority
  5207. */
  5208. static get Default() {
  5209. assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5210. _defaultIndexMap =
  5211. _defaultIndexMap ||
  5212. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5213. return _defaultIndexMap;
  5214. }
  5215. get(indexKey) {
  5216. const sortedMap = safeGet(this.indexes_, indexKey);
  5217. if (!sortedMap) {
  5218. throw new Error('No index defined for ' + indexKey);
  5219. }
  5220. if (sortedMap instanceof SortedMap) {
  5221. return sortedMap;
  5222. }
  5223. else {
  5224. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5225. // regular child map
  5226. return null;
  5227. }
  5228. }
  5229. hasIndex(indexDefinition) {
  5230. return contains(this.indexSet_, indexDefinition.toString());
  5231. }
  5232. addIndex(indexDefinition, existingChildren) {
  5233. assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5234. const childList = [];
  5235. let sawIndexedValue = false;
  5236. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5237. let next = iter.getNext();
  5238. while (next) {
  5239. sawIndexedValue =
  5240. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5241. childList.push(next);
  5242. next = iter.getNext();
  5243. }
  5244. let newIndex;
  5245. if (sawIndexedValue) {
  5246. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5247. }
  5248. else {
  5249. newIndex = fallbackObject;
  5250. }
  5251. const indexName = indexDefinition.toString();
  5252. const newIndexSet = Object.assign({}, this.indexSet_);
  5253. newIndexSet[indexName] = indexDefinition;
  5254. const newIndexes = Object.assign({}, this.indexes_);
  5255. newIndexes[indexName] = newIndex;
  5256. return new IndexMap(newIndexes, newIndexSet);
  5257. }
  5258. /**
  5259. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5260. */
  5261. addToIndexes(namedNode, existingChildren) {
  5262. const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
  5263. const index = safeGet(this.indexSet_, indexName);
  5264. assert(index, 'Missing index implementation for ' + indexName);
  5265. if (indexedChildren === fallbackObject) {
  5266. // Check to see if we need to index everything
  5267. if (index.isDefinedOn(namedNode.node)) {
  5268. // We need to build this index
  5269. const childList = [];
  5270. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5271. let next = iter.getNext();
  5272. while (next) {
  5273. if (next.name !== namedNode.name) {
  5274. childList.push(next);
  5275. }
  5276. next = iter.getNext();
  5277. }
  5278. childList.push(namedNode);
  5279. return buildChildSet(childList, index.getCompare());
  5280. }
  5281. else {
  5282. // No change, this remains a fallback
  5283. return fallbackObject;
  5284. }
  5285. }
  5286. else {
  5287. const existingSnap = existingChildren.get(namedNode.name);
  5288. let newChildren = indexedChildren;
  5289. if (existingSnap) {
  5290. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5291. }
  5292. return newChildren.insert(namedNode, namedNode.node);
  5293. }
  5294. });
  5295. return new IndexMap(newIndexes, this.indexSet_);
  5296. }
  5297. /**
  5298. * Create a new IndexMap instance with the given value removed
  5299. */
  5300. removeFromIndexes(namedNode, existingChildren) {
  5301. const newIndexes = map(this.indexes_, (indexedChildren) => {
  5302. if (indexedChildren === fallbackObject) {
  5303. // This is the fallback. Just return it, nothing to do in this case
  5304. return indexedChildren;
  5305. }
  5306. else {
  5307. const existingSnap = existingChildren.get(namedNode.name);
  5308. if (existingSnap) {
  5309. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5310. }
  5311. else {
  5312. // No record of this child
  5313. return indexedChildren;
  5314. }
  5315. }
  5316. });
  5317. return new IndexMap(newIndexes, this.indexSet_);
  5318. }
  5319. }
  5320. /**
  5321. * @license
  5322. * Copyright 2017 Google LLC
  5323. *
  5324. * Licensed under the Apache License, Version 2.0 (the "License");
  5325. * you may not use this file except in compliance with the License.
  5326. * You may obtain a copy of the License at
  5327. *
  5328. * http://www.apache.org/licenses/LICENSE-2.0
  5329. *
  5330. * Unless required by applicable law or agreed to in writing, software
  5331. * distributed under the License is distributed on an "AS IS" BASIS,
  5332. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5333. * See the License for the specific language governing permissions and
  5334. * limitations under the License.
  5335. */
  5336. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5337. let EMPTY_NODE;
  5338. /**
  5339. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5340. * (i.e. nodes with children). It implements Node and stores the
  5341. * list of children in the children property, sorted by child name.
  5342. */
  5343. class ChildrenNode {
  5344. /**
  5345. * @param children_ - List of children of this node..
  5346. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5347. */
  5348. constructor(children_, priorityNode_, indexMap_) {
  5349. this.children_ = children_;
  5350. this.priorityNode_ = priorityNode_;
  5351. this.indexMap_ = indexMap_;
  5352. this.lazyHash_ = null;
  5353. /**
  5354. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5355. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5356. * class instead of an empty ChildrenNode.
  5357. */
  5358. if (this.priorityNode_) {
  5359. validatePriorityNode(this.priorityNode_);
  5360. }
  5361. if (this.children_.isEmpty()) {
  5362. assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5363. }
  5364. }
  5365. static get EMPTY_NODE() {
  5366. return (EMPTY_NODE ||
  5367. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5368. }
  5369. /** @inheritDoc */
  5370. isLeafNode() {
  5371. return false;
  5372. }
  5373. /** @inheritDoc */
  5374. getPriority() {
  5375. return this.priorityNode_ || EMPTY_NODE;
  5376. }
  5377. /** @inheritDoc */
  5378. updatePriority(newPriorityNode) {
  5379. if (this.children_.isEmpty()) {
  5380. // Don't allow priorities on empty nodes
  5381. return this;
  5382. }
  5383. else {
  5384. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5385. }
  5386. }
  5387. /** @inheritDoc */
  5388. getImmediateChild(childName) {
  5389. // Hack to treat priority as a regular child
  5390. if (childName === '.priority') {
  5391. return this.getPriority();
  5392. }
  5393. else {
  5394. const child = this.children_.get(childName);
  5395. return child === null ? EMPTY_NODE : child;
  5396. }
  5397. }
  5398. /** @inheritDoc */
  5399. getChild(path) {
  5400. const front = pathGetFront(path);
  5401. if (front === null) {
  5402. return this;
  5403. }
  5404. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5405. }
  5406. /** @inheritDoc */
  5407. hasChild(childName) {
  5408. return this.children_.get(childName) !== null;
  5409. }
  5410. /** @inheritDoc */
  5411. updateImmediateChild(childName, newChildNode) {
  5412. assert(newChildNode, 'We should always be passing snapshot nodes');
  5413. if (childName === '.priority') {
  5414. return this.updatePriority(newChildNode);
  5415. }
  5416. else {
  5417. const namedNode = new NamedNode(childName, newChildNode);
  5418. let newChildren, newIndexMap;
  5419. if (newChildNode.isEmpty()) {
  5420. newChildren = this.children_.remove(childName);
  5421. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5422. }
  5423. else {
  5424. newChildren = this.children_.insert(childName, newChildNode);
  5425. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5426. }
  5427. const newPriority = newChildren.isEmpty()
  5428. ? EMPTY_NODE
  5429. : this.priorityNode_;
  5430. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5431. }
  5432. }
  5433. /** @inheritDoc */
  5434. updateChild(path, newChildNode) {
  5435. const front = pathGetFront(path);
  5436. if (front === null) {
  5437. return newChildNode;
  5438. }
  5439. else {
  5440. assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5441. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5442. return this.updateImmediateChild(front, newImmediateChild);
  5443. }
  5444. }
  5445. /** @inheritDoc */
  5446. isEmpty() {
  5447. return this.children_.isEmpty();
  5448. }
  5449. /** @inheritDoc */
  5450. numChildren() {
  5451. return this.children_.count();
  5452. }
  5453. /** @inheritDoc */
  5454. val(exportFormat) {
  5455. if (this.isEmpty()) {
  5456. return null;
  5457. }
  5458. const obj = {};
  5459. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5460. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5461. obj[key] = childNode.val(exportFormat);
  5462. numKeys++;
  5463. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5464. maxKey = Math.max(maxKey, Number(key));
  5465. }
  5466. else {
  5467. allIntegerKeys = false;
  5468. }
  5469. });
  5470. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5471. // convert to array.
  5472. const array = [];
  5473. // eslint-disable-next-line guard-for-in
  5474. for (const key in obj) {
  5475. array[key] = obj[key];
  5476. }
  5477. return array;
  5478. }
  5479. else {
  5480. if (exportFormat && !this.getPriority().isEmpty()) {
  5481. obj['.priority'] = this.getPriority().val();
  5482. }
  5483. return obj;
  5484. }
  5485. }
  5486. /** @inheritDoc */
  5487. hash() {
  5488. if (this.lazyHash_ === null) {
  5489. let toHash = '';
  5490. if (!this.getPriority().isEmpty()) {
  5491. toHash +=
  5492. 'priority:' +
  5493. priorityHashText(this.getPriority().val()) +
  5494. ':';
  5495. }
  5496. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5497. const childHash = childNode.hash();
  5498. if (childHash !== '') {
  5499. toHash += ':' + key + ':' + childHash;
  5500. }
  5501. });
  5502. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5503. }
  5504. return this.lazyHash_;
  5505. }
  5506. /** @inheritDoc */
  5507. getPredecessorChildName(childName, childNode, index) {
  5508. const idx = this.resolveIndex_(index);
  5509. if (idx) {
  5510. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5511. return predecessor ? predecessor.name : null;
  5512. }
  5513. else {
  5514. return this.children_.getPredecessorKey(childName);
  5515. }
  5516. }
  5517. getFirstChildName(indexDefinition) {
  5518. const idx = this.resolveIndex_(indexDefinition);
  5519. if (idx) {
  5520. const minKey = idx.minKey();
  5521. return minKey && minKey.name;
  5522. }
  5523. else {
  5524. return this.children_.minKey();
  5525. }
  5526. }
  5527. getFirstChild(indexDefinition) {
  5528. const minKey = this.getFirstChildName(indexDefinition);
  5529. if (minKey) {
  5530. return new NamedNode(minKey, this.children_.get(minKey));
  5531. }
  5532. else {
  5533. return null;
  5534. }
  5535. }
  5536. /**
  5537. * Given an index, return the key name of the largest value we have, according to that index
  5538. */
  5539. getLastChildName(indexDefinition) {
  5540. const idx = this.resolveIndex_(indexDefinition);
  5541. if (idx) {
  5542. const maxKey = idx.maxKey();
  5543. return maxKey && maxKey.name;
  5544. }
  5545. else {
  5546. return this.children_.maxKey();
  5547. }
  5548. }
  5549. getLastChild(indexDefinition) {
  5550. const maxKey = this.getLastChildName(indexDefinition);
  5551. if (maxKey) {
  5552. return new NamedNode(maxKey, this.children_.get(maxKey));
  5553. }
  5554. else {
  5555. return null;
  5556. }
  5557. }
  5558. forEachChild(index, action) {
  5559. const idx = this.resolveIndex_(index);
  5560. if (idx) {
  5561. return idx.inorderTraversal(wrappedNode => {
  5562. return action(wrappedNode.name, wrappedNode.node);
  5563. });
  5564. }
  5565. else {
  5566. return this.children_.inorderTraversal(action);
  5567. }
  5568. }
  5569. getIterator(indexDefinition) {
  5570. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5571. }
  5572. getIteratorFrom(startPost, indexDefinition) {
  5573. const idx = this.resolveIndex_(indexDefinition);
  5574. if (idx) {
  5575. return idx.getIteratorFrom(startPost, key => key);
  5576. }
  5577. else {
  5578. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5579. let next = iterator.peek();
  5580. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5581. iterator.getNext();
  5582. next = iterator.peek();
  5583. }
  5584. return iterator;
  5585. }
  5586. }
  5587. getReverseIterator(indexDefinition) {
  5588. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5589. }
  5590. getReverseIteratorFrom(endPost, indexDefinition) {
  5591. const idx = this.resolveIndex_(indexDefinition);
  5592. if (idx) {
  5593. return idx.getReverseIteratorFrom(endPost, key => {
  5594. return key;
  5595. });
  5596. }
  5597. else {
  5598. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5599. let next = iterator.peek();
  5600. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5601. iterator.getNext();
  5602. next = iterator.peek();
  5603. }
  5604. return iterator;
  5605. }
  5606. }
  5607. compareTo(other) {
  5608. if (this.isEmpty()) {
  5609. if (other.isEmpty()) {
  5610. return 0;
  5611. }
  5612. else {
  5613. return -1;
  5614. }
  5615. }
  5616. else if (other.isLeafNode() || other.isEmpty()) {
  5617. return 1;
  5618. }
  5619. else if (other === MAX_NODE) {
  5620. return -1;
  5621. }
  5622. else {
  5623. // Must be another node with children.
  5624. return 0;
  5625. }
  5626. }
  5627. withIndex(indexDefinition) {
  5628. if (indexDefinition === KEY_INDEX ||
  5629. this.indexMap_.hasIndex(indexDefinition)) {
  5630. return this;
  5631. }
  5632. else {
  5633. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5634. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5635. }
  5636. }
  5637. isIndexed(index) {
  5638. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5639. }
  5640. equals(other) {
  5641. if (other === this) {
  5642. return true;
  5643. }
  5644. else if (other.isLeafNode()) {
  5645. return false;
  5646. }
  5647. else {
  5648. const otherChildrenNode = other;
  5649. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5650. return false;
  5651. }
  5652. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5653. const thisIter = this.getIterator(PRIORITY_INDEX);
  5654. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5655. let thisCurrent = thisIter.getNext();
  5656. let otherCurrent = otherIter.getNext();
  5657. while (thisCurrent && otherCurrent) {
  5658. if (thisCurrent.name !== otherCurrent.name ||
  5659. !thisCurrent.node.equals(otherCurrent.node)) {
  5660. return false;
  5661. }
  5662. thisCurrent = thisIter.getNext();
  5663. otherCurrent = otherIter.getNext();
  5664. }
  5665. return thisCurrent === null && otherCurrent === null;
  5666. }
  5667. else {
  5668. return false;
  5669. }
  5670. }
  5671. }
  5672. /**
  5673. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5674. * instead.
  5675. *
  5676. */
  5677. resolveIndex_(indexDefinition) {
  5678. if (indexDefinition === KEY_INDEX) {
  5679. return null;
  5680. }
  5681. else {
  5682. return this.indexMap_.get(indexDefinition.toString());
  5683. }
  5684. }
  5685. }
  5686. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5687. class MaxNode extends ChildrenNode {
  5688. constructor() {
  5689. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5690. }
  5691. compareTo(other) {
  5692. if (other === this) {
  5693. return 0;
  5694. }
  5695. else {
  5696. return 1;
  5697. }
  5698. }
  5699. equals(other) {
  5700. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5701. return other === this;
  5702. }
  5703. getPriority() {
  5704. return this;
  5705. }
  5706. getImmediateChild(childName) {
  5707. return ChildrenNode.EMPTY_NODE;
  5708. }
  5709. isEmpty() {
  5710. return false;
  5711. }
  5712. }
  5713. /**
  5714. * Marker that will sort higher than any other snapshot.
  5715. */
  5716. const MAX_NODE = new MaxNode();
  5717. Object.defineProperties(NamedNode, {
  5718. MIN: {
  5719. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5720. },
  5721. MAX: {
  5722. value: new NamedNode(MAX_NAME, MAX_NODE)
  5723. }
  5724. });
  5725. /**
  5726. * Reference Extensions
  5727. */
  5728. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5729. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5730. setMaxNode$1(MAX_NODE);
  5731. setMaxNode(MAX_NODE);
  5732. /**
  5733. * @license
  5734. * Copyright 2017 Google LLC
  5735. *
  5736. * Licensed under the Apache License, Version 2.0 (the "License");
  5737. * you may not use this file except in compliance with the License.
  5738. * You may obtain a copy of the License at
  5739. *
  5740. * http://www.apache.org/licenses/LICENSE-2.0
  5741. *
  5742. * Unless required by applicable law or agreed to in writing, software
  5743. * distributed under the License is distributed on an "AS IS" BASIS,
  5744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5745. * See the License for the specific language governing permissions and
  5746. * limitations under the License.
  5747. */
  5748. const USE_HINZE = true;
  5749. /**
  5750. * Constructs a snapshot node representing the passed JSON and returns it.
  5751. * @param json - JSON to create a node for.
  5752. * @param priority - Optional priority to use. This will be ignored if the
  5753. * passed JSON contains a .priority property.
  5754. */
  5755. function nodeFromJSON(json, priority = null) {
  5756. if (json === null) {
  5757. return ChildrenNode.EMPTY_NODE;
  5758. }
  5759. if (typeof json === 'object' && '.priority' in json) {
  5760. priority = json['.priority'];
  5761. }
  5762. assert(priority === null ||
  5763. typeof priority === 'string' ||
  5764. typeof priority === 'number' ||
  5765. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5766. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5767. json = json['.value'];
  5768. }
  5769. // Valid leaf nodes include non-objects or server-value wrapper objects
  5770. if (typeof json !== 'object' || '.sv' in json) {
  5771. const jsonLeaf = json;
  5772. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5773. }
  5774. if (!(json instanceof Array) && USE_HINZE) {
  5775. const children = [];
  5776. let childrenHavePriority = false;
  5777. const hinzeJsonObj = json;
  5778. each(hinzeJsonObj, (key, child) => {
  5779. if (key.substring(0, 1) !== '.') {
  5780. // Ignore metadata nodes
  5781. const childNode = nodeFromJSON(child);
  5782. if (!childNode.isEmpty()) {
  5783. childrenHavePriority =
  5784. childrenHavePriority || !childNode.getPriority().isEmpty();
  5785. children.push(new NamedNode(key, childNode));
  5786. }
  5787. }
  5788. });
  5789. if (children.length === 0) {
  5790. return ChildrenNode.EMPTY_NODE;
  5791. }
  5792. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5793. if (childrenHavePriority) {
  5794. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5795. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5796. }
  5797. else {
  5798. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5799. }
  5800. }
  5801. else {
  5802. let node = ChildrenNode.EMPTY_NODE;
  5803. each(json, (key, childData) => {
  5804. if (contains(json, key)) {
  5805. if (key.substring(0, 1) !== '.') {
  5806. // ignore metadata nodes.
  5807. const childNode = nodeFromJSON(childData);
  5808. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5809. node = node.updateImmediateChild(key, childNode);
  5810. }
  5811. }
  5812. }
  5813. });
  5814. return node.updatePriority(nodeFromJSON(priority));
  5815. }
  5816. }
  5817. setNodeFromJSON(nodeFromJSON);
  5818. /**
  5819. * @license
  5820. * Copyright 2017 Google LLC
  5821. *
  5822. * Licensed under the Apache License, Version 2.0 (the "License");
  5823. * you may not use this file except in compliance with the License.
  5824. * You may obtain a copy of the License at
  5825. *
  5826. * http://www.apache.org/licenses/LICENSE-2.0
  5827. *
  5828. * Unless required by applicable law or agreed to in writing, software
  5829. * distributed under the License is distributed on an "AS IS" BASIS,
  5830. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5831. * See the License for the specific language governing permissions and
  5832. * limitations under the License.
  5833. */
  5834. class PathIndex extends Index {
  5835. constructor(indexPath_) {
  5836. super();
  5837. this.indexPath_ = indexPath_;
  5838. assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5839. }
  5840. extractChild(snap) {
  5841. return snap.getChild(this.indexPath_);
  5842. }
  5843. isDefinedOn(node) {
  5844. return !node.getChild(this.indexPath_).isEmpty();
  5845. }
  5846. compare(a, b) {
  5847. const aChild = this.extractChild(a.node);
  5848. const bChild = this.extractChild(b.node);
  5849. const indexCmp = aChild.compareTo(bChild);
  5850. if (indexCmp === 0) {
  5851. return nameCompare(a.name, b.name);
  5852. }
  5853. else {
  5854. return indexCmp;
  5855. }
  5856. }
  5857. makePost(indexValue, name) {
  5858. const valueNode = nodeFromJSON(indexValue);
  5859. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5860. return new NamedNode(name, node);
  5861. }
  5862. maxPost() {
  5863. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5864. return new NamedNode(MAX_NAME, node);
  5865. }
  5866. toString() {
  5867. return pathSlice(this.indexPath_, 0).join('/');
  5868. }
  5869. }
  5870. /**
  5871. * @license
  5872. * Copyright 2017 Google LLC
  5873. *
  5874. * Licensed under the Apache License, Version 2.0 (the "License");
  5875. * you may not use this file except in compliance with the License.
  5876. * You may obtain a copy of the License at
  5877. *
  5878. * http://www.apache.org/licenses/LICENSE-2.0
  5879. *
  5880. * Unless required by applicable law or agreed to in writing, software
  5881. * distributed under the License is distributed on an "AS IS" BASIS,
  5882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5883. * See the License for the specific language governing permissions and
  5884. * limitations under the License.
  5885. */
  5886. class ValueIndex extends Index {
  5887. compare(a, b) {
  5888. const indexCmp = a.node.compareTo(b.node);
  5889. if (indexCmp === 0) {
  5890. return nameCompare(a.name, b.name);
  5891. }
  5892. else {
  5893. return indexCmp;
  5894. }
  5895. }
  5896. isDefinedOn(node) {
  5897. return true;
  5898. }
  5899. indexedValueChanged(oldNode, newNode) {
  5900. return !oldNode.equals(newNode);
  5901. }
  5902. minPost() {
  5903. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5904. return NamedNode.MIN;
  5905. }
  5906. maxPost() {
  5907. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5908. return NamedNode.MAX;
  5909. }
  5910. makePost(indexValue, name) {
  5911. const valueNode = nodeFromJSON(indexValue);
  5912. return new NamedNode(name, valueNode);
  5913. }
  5914. /**
  5915. * @returns String representation for inclusion in a query spec
  5916. */
  5917. toString() {
  5918. return '.value';
  5919. }
  5920. }
  5921. const VALUE_INDEX = new ValueIndex();
  5922. /**
  5923. * @license
  5924. * Copyright 2017 Google LLC
  5925. *
  5926. * Licensed under the Apache License, Version 2.0 (the "License");
  5927. * you may not use this file except in compliance with the License.
  5928. * You may obtain a copy of the License at
  5929. *
  5930. * http://www.apache.org/licenses/LICENSE-2.0
  5931. *
  5932. * Unless required by applicable law or agreed to in writing, software
  5933. * distributed under the License is distributed on an "AS IS" BASIS,
  5934. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5935. * See the License for the specific language governing permissions and
  5936. * limitations under the License.
  5937. */
  5938. function changeValue(snapshotNode) {
  5939. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5940. }
  5941. function changeChildAdded(childName, snapshotNode) {
  5942. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5943. }
  5944. function changeChildRemoved(childName, snapshotNode) {
  5945. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5946. }
  5947. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5948. return {
  5949. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5950. snapshotNode,
  5951. childName,
  5952. oldSnap
  5953. };
  5954. }
  5955. function changeChildMoved(childName, snapshotNode) {
  5956. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5957. }
  5958. /**
  5959. * @license
  5960. * Copyright 2017 Google LLC
  5961. *
  5962. * Licensed under the Apache License, Version 2.0 (the "License");
  5963. * you may not use this file except in compliance with the License.
  5964. * You may obtain a copy of the License at
  5965. *
  5966. * http://www.apache.org/licenses/LICENSE-2.0
  5967. *
  5968. * Unless required by applicable law or agreed to in writing, software
  5969. * distributed under the License is distributed on an "AS IS" BASIS,
  5970. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5971. * See the License for the specific language governing permissions and
  5972. * limitations under the License.
  5973. */
  5974. /**
  5975. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5976. */
  5977. class IndexedFilter {
  5978. constructor(index_) {
  5979. this.index_ = index_;
  5980. }
  5981. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5982. assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5983. const oldChild = snap.getImmediateChild(key);
  5984. // Check if anything actually changed.
  5985. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5986. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5987. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5988. // to avoid treating these cases as "nothing changed."
  5989. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5990. // Nothing changed.
  5991. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  5992. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  5993. return snap;
  5994. }
  5995. }
  5996. if (optChangeAccumulator != null) {
  5997. if (newChild.isEmpty()) {
  5998. if (snap.hasChild(key)) {
  5999. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6000. }
  6001. else {
  6002. assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6003. }
  6004. }
  6005. else if (oldChild.isEmpty()) {
  6006. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6007. }
  6008. else {
  6009. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6010. }
  6011. }
  6012. if (snap.isLeafNode() && newChild.isEmpty()) {
  6013. return snap;
  6014. }
  6015. else {
  6016. // Make sure the node is indexed
  6017. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6018. }
  6019. }
  6020. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6021. if (optChangeAccumulator != null) {
  6022. if (!oldSnap.isLeafNode()) {
  6023. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6024. if (!newSnap.hasChild(key)) {
  6025. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6026. }
  6027. });
  6028. }
  6029. if (!newSnap.isLeafNode()) {
  6030. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6031. if (oldSnap.hasChild(key)) {
  6032. const oldChild = oldSnap.getImmediateChild(key);
  6033. if (!oldChild.equals(childNode)) {
  6034. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6035. }
  6036. }
  6037. else {
  6038. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6039. }
  6040. });
  6041. }
  6042. }
  6043. return newSnap.withIndex(this.index_);
  6044. }
  6045. updatePriority(oldSnap, newPriority) {
  6046. if (oldSnap.isEmpty()) {
  6047. return ChildrenNode.EMPTY_NODE;
  6048. }
  6049. else {
  6050. return oldSnap.updatePriority(newPriority);
  6051. }
  6052. }
  6053. filtersNodes() {
  6054. return false;
  6055. }
  6056. getIndexedFilter() {
  6057. return this;
  6058. }
  6059. getIndex() {
  6060. return this.index_;
  6061. }
  6062. }
  6063. /**
  6064. * @license
  6065. * Copyright 2017 Google LLC
  6066. *
  6067. * Licensed under the Apache License, Version 2.0 (the "License");
  6068. * you may not use this file except in compliance with the License.
  6069. * You may obtain a copy of the License at
  6070. *
  6071. * http://www.apache.org/licenses/LICENSE-2.0
  6072. *
  6073. * Unless required by applicable law or agreed to in writing, software
  6074. * distributed under the License is distributed on an "AS IS" BASIS,
  6075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6076. * See the License for the specific language governing permissions and
  6077. * limitations under the License.
  6078. */
  6079. /**
  6080. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6081. */
  6082. class RangedFilter {
  6083. constructor(params) {
  6084. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6085. this.index_ = params.getIndex();
  6086. this.startPost_ = RangedFilter.getStartPost_(params);
  6087. this.endPost_ = RangedFilter.getEndPost_(params);
  6088. this.startIsInclusive_ = !params.startAfterSet_;
  6089. this.endIsInclusive_ = !params.endBeforeSet_;
  6090. }
  6091. getStartPost() {
  6092. return this.startPost_;
  6093. }
  6094. getEndPost() {
  6095. return this.endPost_;
  6096. }
  6097. matches(node) {
  6098. const isWithinStart = this.startIsInclusive_
  6099. ? this.index_.compare(this.getStartPost(), node) <= 0
  6100. : this.index_.compare(this.getStartPost(), node) < 0;
  6101. const isWithinEnd = this.endIsInclusive_
  6102. ? this.index_.compare(node, this.getEndPost()) <= 0
  6103. : this.index_.compare(node, this.getEndPost()) < 0;
  6104. return isWithinStart && isWithinEnd;
  6105. }
  6106. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6107. if (!this.matches(new NamedNode(key, newChild))) {
  6108. newChild = ChildrenNode.EMPTY_NODE;
  6109. }
  6110. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6111. }
  6112. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6113. if (newSnap.isLeafNode()) {
  6114. // Make sure we have a children node with the correct index, not a leaf node;
  6115. newSnap = ChildrenNode.EMPTY_NODE;
  6116. }
  6117. let filtered = newSnap.withIndex(this.index_);
  6118. // Don't support priorities on queries
  6119. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6120. const self = this;
  6121. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6122. if (!self.matches(new NamedNode(key, childNode))) {
  6123. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6124. }
  6125. });
  6126. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6127. }
  6128. updatePriority(oldSnap, newPriority) {
  6129. // Don't support priorities on queries
  6130. return oldSnap;
  6131. }
  6132. filtersNodes() {
  6133. return true;
  6134. }
  6135. getIndexedFilter() {
  6136. return this.indexedFilter_;
  6137. }
  6138. getIndex() {
  6139. return this.index_;
  6140. }
  6141. static getStartPost_(params) {
  6142. if (params.hasStart()) {
  6143. const startName = params.getIndexStartName();
  6144. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6145. }
  6146. else {
  6147. return params.getIndex().minPost();
  6148. }
  6149. }
  6150. static getEndPost_(params) {
  6151. if (params.hasEnd()) {
  6152. const endName = params.getIndexEndName();
  6153. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6154. }
  6155. else {
  6156. return params.getIndex().maxPost();
  6157. }
  6158. }
  6159. }
  6160. /**
  6161. * @license
  6162. * Copyright 2017 Google LLC
  6163. *
  6164. * Licensed under the Apache License, Version 2.0 (the "License");
  6165. * you may not use this file except in compliance with the License.
  6166. * You may obtain a copy of the License at
  6167. *
  6168. * http://www.apache.org/licenses/LICENSE-2.0
  6169. *
  6170. * Unless required by applicable law or agreed to in writing, software
  6171. * distributed under the License is distributed on an "AS IS" BASIS,
  6172. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6173. * See the License for the specific language governing permissions and
  6174. * limitations under the License.
  6175. */
  6176. /**
  6177. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6178. */
  6179. class LimitedFilter {
  6180. constructor(params) {
  6181. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6182. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6183. this.withinStartPost = (node) => {
  6184. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6185. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6186. };
  6187. this.withinEndPost = (node) => {
  6188. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6189. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6190. };
  6191. this.rangedFilter_ = new RangedFilter(params);
  6192. this.index_ = params.getIndex();
  6193. this.limit_ = params.getLimit();
  6194. this.reverse_ = !params.isViewFromLeft();
  6195. this.startIsInclusive_ = !params.startAfterSet_;
  6196. this.endIsInclusive_ = !params.endBeforeSet_;
  6197. }
  6198. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6199. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6200. newChild = ChildrenNode.EMPTY_NODE;
  6201. }
  6202. if (snap.getImmediateChild(key).equals(newChild)) {
  6203. // No change
  6204. return snap;
  6205. }
  6206. else if (snap.numChildren() < this.limit_) {
  6207. return this.rangedFilter_
  6208. .getIndexedFilter()
  6209. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6210. }
  6211. else {
  6212. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6213. }
  6214. }
  6215. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6216. let filtered;
  6217. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6218. // Make sure we have a children node with the correct index, not a leaf node;
  6219. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6220. }
  6221. else {
  6222. if (this.limit_ * 2 < newSnap.numChildren() &&
  6223. newSnap.isIndexed(this.index_)) {
  6224. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6225. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6226. // anchor to the startPost, endPost, or last element as appropriate
  6227. let iterator;
  6228. if (this.reverse_) {
  6229. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6230. }
  6231. else {
  6232. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6233. }
  6234. let count = 0;
  6235. while (iterator.hasNext() && count < this.limit_) {
  6236. const next = iterator.getNext();
  6237. if (!this.withinDirectionalStart(next)) {
  6238. // if we have not reached the start, skip to the next element
  6239. continue;
  6240. }
  6241. else if (!this.withinDirectionalEnd(next)) {
  6242. // if we have reached the end, stop adding elements
  6243. break;
  6244. }
  6245. else {
  6246. filtered = filtered.updateImmediateChild(next.name, next.node);
  6247. count++;
  6248. }
  6249. }
  6250. }
  6251. else {
  6252. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6253. filtered = newSnap.withIndex(this.index_);
  6254. // Don't support priorities on queries
  6255. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6256. let iterator;
  6257. if (this.reverse_) {
  6258. iterator = filtered.getReverseIterator(this.index_);
  6259. }
  6260. else {
  6261. iterator = filtered.getIterator(this.index_);
  6262. }
  6263. let count = 0;
  6264. while (iterator.hasNext()) {
  6265. const next = iterator.getNext();
  6266. const inRange = count < this.limit_ &&
  6267. this.withinDirectionalStart(next) &&
  6268. this.withinDirectionalEnd(next);
  6269. if (inRange) {
  6270. count++;
  6271. }
  6272. else {
  6273. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6274. }
  6275. }
  6276. }
  6277. }
  6278. return this.rangedFilter_
  6279. .getIndexedFilter()
  6280. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6281. }
  6282. updatePriority(oldSnap, newPriority) {
  6283. // Don't support priorities on queries
  6284. return oldSnap;
  6285. }
  6286. filtersNodes() {
  6287. return true;
  6288. }
  6289. getIndexedFilter() {
  6290. return this.rangedFilter_.getIndexedFilter();
  6291. }
  6292. getIndex() {
  6293. return this.index_;
  6294. }
  6295. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6296. // TODO: rename all cache stuff etc to general snap terminology
  6297. let cmp;
  6298. if (this.reverse_) {
  6299. const indexCmp = this.index_.getCompare();
  6300. cmp = (a, b) => indexCmp(b, a);
  6301. }
  6302. else {
  6303. cmp = this.index_.getCompare();
  6304. }
  6305. const oldEventCache = snap;
  6306. assert(oldEventCache.numChildren() === this.limit_, '');
  6307. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6308. const windowBoundary = this.reverse_
  6309. ? oldEventCache.getFirstChild(this.index_)
  6310. : oldEventCache.getLastChild(this.index_);
  6311. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6312. if (oldEventCache.hasChild(childKey)) {
  6313. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6314. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6315. while (nextChild != null &&
  6316. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6317. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6318. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6319. // the limited filter...
  6320. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6321. }
  6322. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6323. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6324. if (remainsInWindow) {
  6325. if (changeAccumulator != null) {
  6326. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6327. }
  6328. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6329. }
  6330. else {
  6331. if (changeAccumulator != null) {
  6332. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6333. }
  6334. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6335. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6336. if (nextChildInRange) {
  6337. if (changeAccumulator != null) {
  6338. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6339. }
  6340. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6341. }
  6342. else {
  6343. return newEventCache;
  6344. }
  6345. }
  6346. }
  6347. else if (childSnap.isEmpty()) {
  6348. // we're deleting a node, but it was not in the window, so ignore it
  6349. return snap;
  6350. }
  6351. else if (inRange) {
  6352. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6353. if (changeAccumulator != null) {
  6354. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6355. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6356. }
  6357. return oldEventCache
  6358. .updateImmediateChild(childKey, childSnap)
  6359. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6360. }
  6361. else {
  6362. return snap;
  6363. }
  6364. }
  6365. else {
  6366. return snap;
  6367. }
  6368. }
  6369. }
  6370. /**
  6371. * @license
  6372. * Copyright 2017 Google LLC
  6373. *
  6374. * Licensed under the Apache License, Version 2.0 (the "License");
  6375. * you may not use this file except in compliance with the License.
  6376. * You may obtain a copy of the License at
  6377. *
  6378. * http://www.apache.org/licenses/LICENSE-2.0
  6379. *
  6380. * Unless required by applicable law or agreed to in writing, software
  6381. * distributed under the License is distributed on an "AS IS" BASIS,
  6382. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6383. * See the License for the specific language governing permissions and
  6384. * limitations under the License.
  6385. */
  6386. /**
  6387. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6388. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6389. * user-facing API level, so it is not done here.
  6390. *
  6391. * @internal
  6392. */
  6393. class QueryParams {
  6394. constructor() {
  6395. this.limitSet_ = false;
  6396. this.startSet_ = false;
  6397. this.startNameSet_ = false;
  6398. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6399. this.endSet_ = false;
  6400. this.endNameSet_ = false;
  6401. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6402. this.limit_ = 0;
  6403. this.viewFrom_ = '';
  6404. this.indexStartValue_ = null;
  6405. this.indexStartName_ = '';
  6406. this.indexEndValue_ = null;
  6407. this.indexEndName_ = '';
  6408. this.index_ = PRIORITY_INDEX;
  6409. }
  6410. hasStart() {
  6411. return this.startSet_;
  6412. }
  6413. /**
  6414. * @returns True if it would return from left.
  6415. */
  6416. isViewFromLeft() {
  6417. if (this.viewFrom_ === '') {
  6418. // limit(), rather than limitToFirst or limitToLast was called.
  6419. // This means that only one of startSet_ and endSet_ is true. Use them
  6420. // to calculate which side of the view to anchor to. If neither is set,
  6421. // anchor to the end.
  6422. return this.startSet_;
  6423. }
  6424. else {
  6425. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6426. }
  6427. }
  6428. /**
  6429. * Only valid to call if hasStart() returns true
  6430. */
  6431. getIndexStartValue() {
  6432. assert(this.startSet_, 'Only valid if start has been set');
  6433. return this.indexStartValue_;
  6434. }
  6435. /**
  6436. * Only valid to call if hasStart() returns true.
  6437. * Returns the starting key name for the range defined by these query parameters
  6438. */
  6439. getIndexStartName() {
  6440. assert(this.startSet_, 'Only valid if start has been set');
  6441. if (this.startNameSet_) {
  6442. return this.indexStartName_;
  6443. }
  6444. else {
  6445. return MIN_NAME;
  6446. }
  6447. }
  6448. hasEnd() {
  6449. return this.endSet_;
  6450. }
  6451. /**
  6452. * Only valid to call if hasEnd() returns true.
  6453. */
  6454. getIndexEndValue() {
  6455. assert(this.endSet_, 'Only valid if end has been set');
  6456. return this.indexEndValue_;
  6457. }
  6458. /**
  6459. * Only valid to call if hasEnd() returns true.
  6460. * Returns the end key name for the range defined by these query parameters
  6461. */
  6462. getIndexEndName() {
  6463. assert(this.endSet_, 'Only valid if end has been set');
  6464. if (this.endNameSet_) {
  6465. return this.indexEndName_;
  6466. }
  6467. else {
  6468. return MAX_NAME;
  6469. }
  6470. }
  6471. hasLimit() {
  6472. return this.limitSet_;
  6473. }
  6474. /**
  6475. * @returns True if a limit has been set and it has been explicitly anchored
  6476. */
  6477. hasAnchoredLimit() {
  6478. return this.limitSet_ && this.viewFrom_ !== '';
  6479. }
  6480. /**
  6481. * Only valid to call if hasLimit() returns true
  6482. */
  6483. getLimit() {
  6484. assert(this.limitSet_, 'Only valid if limit has been set');
  6485. return this.limit_;
  6486. }
  6487. getIndex() {
  6488. return this.index_;
  6489. }
  6490. loadsAllData() {
  6491. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6492. }
  6493. isDefault() {
  6494. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6495. }
  6496. copy() {
  6497. const copy = new QueryParams();
  6498. copy.limitSet_ = this.limitSet_;
  6499. copy.limit_ = this.limit_;
  6500. copy.startSet_ = this.startSet_;
  6501. copy.startAfterSet_ = this.startAfterSet_;
  6502. copy.indexStartValue_ = this.indexStartValue_;
  6503. copy.startNameSet_ = this.startNameSet_;
  6504. copy.indexStartName_ = this.indexStartName_;
  6505. copy.endSet_ = this.endSet_;
  6506. copy.endBeforeSet_ = this.endBeforeSet_;
  6507. copy.indexEndValue_ = this.indexEndValue_;
  6508. copy.endNameSet_ = this.endNameSet_;
  6509. copy.indexEndName_ = this.indexEndName_;
  6510. copy.index_ = this.index_;
  6511. copy.viewFrom_ = this.viewFrom_;
  6512. return copy;
  6513. }
  6514. }
  6515. function queryParamsGetNodeFilter(queryParams) {
  6516. if (queryParams.loadsAllData()) {
  6517. return new IndexedFilter(queryParams.getIndex());
  6518. }
  6519. else if (queryParams.hasLimit()) {
  6520. return new LimitedFilter(queryParams);
  6521. }
  6522. else {
  6523. return new RangedFilter(queryParams);
  6524. }
  6525. }
  6526. function queryParamsLimitToFirst(queryParams, newLimit) {
  6527. const newParams = queryParams.copy();
  6528. newParams.limitSet_ = true;
  6529. newParams.limit_ = newLimit;
  6530. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6531. return newParams;
  6532. }
  6533. function queryParamsLimitToLast(queryParams, newLimit) {
  6534. const newParams = queryParams.copy();
  6535. newParams.limitSet_ = true;
  6536. newParams.limit_ = newLimit;
  6537. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6538. return newParams;
  6539. }
  6540. function queryParamsStartAt(queryParams, indexValue, key) {
  6541. const newParams = queryParams.copy();
  6542. newParams.startSet_ = true;
  6543. if (indexValue === undefined) {
  6544. indexValue = null;
  6545. }
  6546. newParams.indexStartValue_ = indexValue;
  6547. if (key != null) {
  6548. newParams.startNameSet_ = true;
  6549. newParams.indexStartName_ = key;
  6550. }
  6551. else {
  6552. newParams.startNameSet_ = false;
  6553. newParams.indexStartName_ = '';
  6554. }
  6555. return newParams;
  6556. }
  6557. function queryParamsStartAfter(queryParams, indexValue, key) {
  6558. let params;
  6559. if (queryParams.index_ === KEY_INDEX || !!key) {
  6560. params = queryParamsStartAt(queryParams, indexValue, key);
  6561. }
  6562. else {
  6563. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6564. }
  6565. params.startAfterSet_ = true;
  6566. return params;
  6567. }
  6568. function queryParamsEndAt(queryParams, indexValue, key) {
  6569. const newParams = queryParams.copy();
  6570. newParams.endSet_ = true;
  6571. if (indexValue === undefined) {
  6572. indexValue = null;
  6573. }
  6574. newParams.indexEndValue_ = indexValue;
  6575. if (key !== undefined) {
  6576. newParams.endNameSet_ = true;
  6577. newParams.indexEndName_ = key;
  6578. }
  6579. else {
  6580. newParams.endNameSet_ = false;
  6581. newParams.indexEndName_ = '';
  6582. }
  6583. return newParams;
  6584. }
  6585. function queryParamsEndBefore(queryParams, indexValue, key) {
  6586. let params;
  6587. if (queryParams.index_ === KEY_INDEX || !!key) {
  6588. params = queryParamsEndAt(queryParams, indexValue, key);
  6589. }
  6590. else {
  6591. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6592. }
  6593. params.endBeforeSet_ = true;
  6594. return params;
  6595. }
  6596. function queryParamsOrderBy(queryParams, index) {
  6597. const newParams = queryParams.copy();
  6598. newParams.index_ = index;
  6599. return newParams;
  6600. }
  6601. /**
  6602. * Returns a set of REST query string parameters representing this query.
  6603. *
  6604. * @returns query string parameters
  6605. */
  6606. function queryParamsToRestQueryStringParameters(queryParams) {
  6607. const qs = {};
  6608. if (queryParams.isDefault()) {
  6609. return qs;
  6610. }
  6611. let orderBy;
  6612. if (queryParams.index_ === PRIORITY_INDEX) {
  6613. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6614. }
  6615. else if (queryParams.index_ === VALUE_INDEX) {
  6616. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6617. }
  6618. else if (queryParams.index_ === KEY_INDEX) {
  6619. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6620. }
  6621. else {
  6622. assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6623. orderBy = queryParams.index_.toString();
  6624. }
  6625. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);
  6626. if (queryParams.startSet_) {
  6627. const startParam = queryParams.startAfterSet_
  6628. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6629. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6630. qs[startParam] = stringify(queryParams.indexStartValue_);
  6631. if (queryParams.startNameSet_) {
  6632. qs[startParam] += ',' + stringify(queryParams.indexStartName_);
  6633. }
  6634. }
  6635. if (queryParams.endSet_) {
  6636. const endParam = queryParams.endBeforeSet_
  6637. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6638. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6639. qs[endParam] = stringify(queryParams.indexEndValue_);
  6640. if (queryParams.endNameSet_) {
  6641. qs[endParam] += ',' + stringify(queryParams.indexEndName_);
  6642. }
  6643. }
  6644. if (queryParams.limitSet_) {
  6645. if (queryParams.isViewFromLeft()) {
  6646. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6647. }
  6648. else {
  6649. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6650. }
  6651. }
  6652. return qs;
  6653. }
  6654. function queryParamsGetQueryObject(queryParams) {
  6655. const obj = {};
  6656. if (queryParams.startSet_) {
  6657. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6658. queryParams.indexStartValue_;
  6659. if (queryParams.startNameSet_) {
  6660. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6661. queryParams.indexStartName_;
  6662. }
  6663. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6664. !queryParams.startAfterSet_;
  6665. }
  6666. if (queryParams.endSet_) {
  6667. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6668. if (queryParams.endNameSet_) {
  6669. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6670. }
  6671. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6672. !queryParams.endBeforeSet_;
  6673. }
  6674. if (queryParams.limitSet_) {
  6675. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6676. let viewFrom = queryParams.viewFrom_;
  6677. if (viewFrom === '') {
  6678. if (queryParams.isViewFromLeft()) {
  6679. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6680. }
  6681. else {
  6682. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6683. }
  6684. }
  6685. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6686. }
  6687. // For now, priority index is the default, so we only specify if it's some other index
  6688. if (queryParams.index_ !== PRIORITY_INDEX) {
  6689. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6690. }
  6691. return obj;
  6692. }
  6693. /**
  6694. * @license
  6695. * Copyright 2017 Google LLC
  6696. *
  6697. * Licensed under the Apache License, Version 2.0 (the "License");
  6698. * you may not use this file except in compliance with the License.
  6699. * You may obtain a copy of the License at
  6700. *
  6701. * http://www.apache.org/licenses/LICENSE-2.0
  6702. *
  6703. * Unless required by applicable law or agreed to in writing, software
  6704. * distributed under the License is distributed on an "AS IS" BASIS,
  6705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6706. * See the License for the specific language governing permissions and
  6707. * limitations under the License.
  6708. */
  6709. /**
  6710. * An implementation of ServerActions that communicates with the server via REST requests.
  6711. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6712. * persistent connection (using WebSockets or long-polling)
  6713. */
  6714. class ReadonlyRestClient extends ServerActions {
  6715. /**
  6716. * @param repoInfo_ - Data about the namespace we are connecting to
  6717. * @param onDataUpdate_ - A callback for new data from the server
  6718. */
  6719. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6720. super();
  6721. this.repoInfo_ = repoInfo_;
  6722. this.onDataUpdate_ = onDataUpdate_;
  6723. this.authTokenProvider_ = authTokenProvider_;
  6724. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6725. /** @private {function(...[*])} */
  6726. this.log_ = logWrapper('p:rest:');
  6727. /**
  6728. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6729. * that's been removed. :-/
  6730. */
  6731. this.listens_ = {};
  6732. }
  6733. reportStats(stats) {
  6734. throw new Error('Method not implemented.');
  6735. }
  6736. static getListenId_(query, tag) {
  6737. if (tag !== undefined) {
  6738. return 'tag$' + tag;
  6739. }
  6740. else {
  6741. assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6742. return query._path.toString();
  6743. }
  6744. }
  6745. /** @inheritDoc */
  6746. listen(query, currentHashFn, tag, onComplete) {
  6747. const pathString = query._path.toString();
  6748. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6749. // Mark this listener so we can tell if it's removed.
  6750. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6751. const thisListen = {};
  6752. this.listens_[listenId] = thisListen;
  6753. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6754. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6755. let data = result;
  6756. if (error === 404) {
  6757. data = null;
  6758. error = null;
  6759. }
  6760. if (error === null) {
  6761. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6762. }
  6763. if (safeGet(this.listens_, listenId) === thisListen) {
  6764. let status;
  6765. if (!error) {
  6766. status = 'ok';
  6767. }
  6768. else if (error === 401) {
  6769. status = 'permission_denied';
  6770. }
  6771. else {
  6772. status = 'rest_error:' + error;
  6773. }
  6774. onComplete(status, null);
  6775. }
  6776. });
  6777. }
  6778. /** @inheritDoc */
  6779. unlisten(query, tag) {
  6780. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6781. delete this.listens_[listenId];
  6782. }
  6783. get(query) {
  6784. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6785. const pathString = query._path.toString();
  6786. const deferred = new Deferred();
  6787. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6788. let data = result;
  6789. if (error === 404) {
  6790. data = null;
  6791. error = null;
  6792. }
  6793. if (error === null) {
  6794. this.onDataUpdate_(pathString, data,
  6795. /*isMerge=*/ false,
  6796. /*tag=*/ null);
  6797. deferred.resolve(data);
  6798. }
  6799. else {
  6800. deferred.reject(new Error(data));
  6801. }
  6802. });
  6803. return deferred.promise;
  6804. }
  6805. /** @inheritDoc */
  6806. refreshAuthToken(token) {
  6807. // no-op since we just always call getToken.
  6808. }
  6809. /**
  6810. * Performs a REST request to the given path, with the provided query string parameters,
  6811. * and any auth credentials we have.
  6812. */
  6813. restRequest_(pathString, queryStringParameters = {}, callback) {
  6814. queryStringParameters['format'] = 'export';
  6815. return Promise.all([
  6816. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6817. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6818. ]).then(([authToken, appCheckToken]) => {
  6819. if (authToken && authToken.accessToken) {
  6820. queryStringParameters['auth'] = authToken.accessToken;
  6821. }
  6822. if (appCheckToken && appCheckToken.token) {
  6823. queryStringParameters['ac'] = appCheckToken.token;
  6824. }
  6825. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6826. this.repoInfo_.host +
  6827. pathString +
  6828. '?' +
  6829. 'ns=' +
  6830. this.repoInfo_.namespace +
  6831. querystring(queryStringParameters);
  6832. this.log_('Sending REST request for ' + url);
  6833. const xhr = new XMLHttpRequest();
  6834. xhr.onreadystatechange = () => {
  6835. if (callback && xhr.readyState === 4) {
  6836. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6837. let res = null;
  6838. if (xhr.status >= 200 && xhr.status < 300) {
  6839. try {
  6840. res = jsonEval(xhr.responseText);
  6841. }
  6842. catch (e) {
  6843. warn('Failed to parse JSON response for ' +
  6844. url +
  6845. ': ' +
  6846. xhr.responseText);
  6847. }
  6848. callback(null, res);
  6849. }
  6850. else {
  6851. // 401 and 404 are expected.
  6852. if (xhr.status !== 401 && xhr.status !== 404) {
  6853. warn('Got unsuccessful REST response for ' +
  6854. url +
  6855. ' Status: ' +
  6856. xhr.status);
  6857. }
  6858. callback(xhr.status);
  6859. }
  6860. callback = null;
  6861. }
  6862. };
  6863. xhr.open('GET', url, /*asynchronous=*/ true);
  6864. xhr.send();
  6865. });
  6866. }
  6867. }
  6868. /**
  6869. * @license
  6870. * Copyright 2017 Google LLC
  6871. *
  6872. * Licensed under the Apache License, Version 2.0 (the "License");
  6873. * you may not use this file except in compliance with the License.
  6874. * You may obtain a copy of the License at
  6875. *
  6876. * http://www.apache.org/licenses/LICENSE-2.0
  6877. *
  6878. * Unless required by applicable law or agreed to in writing, software
  6879. * distributed under the License is distributed on an "AS IS" BASIS,
  6880. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6881. * See the License for the specific language governing permissions and
  6882. * limitations under the License.
  6883. */
  6884. /**
  6885. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6886. */
  6887. class SnapshotHolder {
  6888. constructor() {
  6889. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6890. }
  6891. getNode(path) {
  6892. return this.rootNode_.getChild(path);
  6893. }
  6894. updateSnapshot(path, newSnapshotNode) {
  6895. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6896. }
  6897. }
  6898. /**
  6899. * @license
  6900. * Copyright 2017 Google LLC
  6901. *
  6902. * Licensed under the Apache License, Version 2.0 (the "License");
  6903. * you may not use this file except in compliance with the License.
  6904. * You may obtain a copy of the License at
  6905. *
  6906. * http://www.apache.org/licenses/LICENSE-2.0
  6907. *
  6908. * Unless required by applicable law or agreed to in writing, software
  6909. * distributed under the License is distributed on an "AS IS" BASIS,
  6910. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6911. * See the License for the specific language governing permissions and
  6912. * limitations under the License.
  6913. */
  6914. function newSparseSnapshotTree() {
  6915. return {
  6916. value: null,
  6917. children: new Map()
  6918. };
  6919. }
  6920. /**
  6921. * Stores the given node at the specified path. If there is already a node
  6922. * at a shallower path, it merges the new data into that snapshot node.
  6923. *
  6924. * @param path - Path to look up snapshot for.
  6925. * @param data - The new data, or null.
  6926. */
  6927. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6928. if (pathIsEmpty(path)) {
  6929. sparseSnapshotTree.value = data;
  6930. sparseSnapshotTree.children.clear();
  6931. }
  6932. else if (sparseSnapshotTree.value !== null) {
  6933. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6934. }
  6935. else {
  6936. const childKey = pathGetFront(path);
  6937. if (!sparseSnapshotTree.children.has(childKey)) {
  6938. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6939. }
  6940. const child = sparseSnapshotTree.children.get(childKey);
  6941. path = pathPopFront(path);
  6942. sparseSnapshotTreeRemember(child, path, data);
  6943. }
  6944. }
  6945. /**
  6946. * Purge the data at path from the cache.
  6947. *
  6948. * @param path - Path to look up snapshot for.
  6949. * @returns True if this node should now be removed.
  6950. */
  6951. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6952. if (pathIsEmpty(path)) {
  6953. sparseSnapshotTree.value = null;
  6954. sparseSnapshotTree.children.clear();
  6955. return true;
  6956. }
  6957. else {
  6958. if (sparseSnapshotTree.value !== null) {
  6959. if (sparseSnapshotTree.value.isLeafNode()) {
  6960. // We're trying to forget a node that doesn't exist
  6961. return false;
  6962. }
  6963. else {
  6964. const value = sparseSnapshotTree.value;
  6965. sparseSnapshotTree.value = null;
  6966. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6967. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6968. });
  6969. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6970. }
  6971. }
  6972. else if (sparseSnapshotTree.children.size > 0) {
  6973. const childKey = pathGetFront(path);
  6974. path = pathPopFront(path);
  6975. if (sparseSnapshotTree.children.has(childKey)) {
  6976. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6977. if (safeToRemove) {
  6978. sparseSnapshotTree.children.delete(childKey);
  6979. }
  6980. }
  6981. return sparseSnapshotTree.children.size === 0;
  6982. }
  6983. else {
  6984. return true;
  6985. }
  6986. }
  6987. }
  6988. /**
  6989. * Recursively iterates through all of the stored tree and calls the
  6990. * callback on each one.
  6991. *
  6992. * @param prefixPath - Path to look up node for.
  6993. * @param func - The function to invoke for each tree.
  6994. */
  6995. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  6996. if (sparseSnapshotTree.value !== null) {
  6997. func(prefixPath, sparseSnapshotTree.value);
  6998. }
  6999. else {
  7000. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  7001. const path = new Path(prefixPath.toString() + '/' + key);
  7002. sparseSnapshotTreeForEachTree(tree, path, func);
  7003. });
  7004. }
  7005. }
  7006. /**
  7007. * Iterates through each immediate child and triggers the callback.
  7008. * Only seems to be used in tests.
  7009. *
  7010. * @param func - The function to invoke for each child.
  7011. */
  7012. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7013. sparseSnapshotTree.children.forEach((tree, key) => {
  7014. func(key, tree);
  7015. });
  7016. }
  7017. /**
  7018. * @license
  7019. * Copyright 2017 Google LLC
  7020. *
  7021. * Licensed under the Apache License, Version 2.0 (the "License");
  7022. * you may not use this file except in compliance with the License.
  7023. * You may obtain a copy of the License at
  7024. *
  7025. * http://www.apache.org/licenses/LICENSE-2.0
  7026. *
  7027. * Unless required by applicable law or agreed to in writing, software
  7028. * distributed under the License is distributed on an "AS IS" BASIS,
  7029. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7030. * See the License for the specific language governing permissions and
  7031. * limitations under the License.
  7032. */
  7033. /**
  7034. * Returns the delta from the previous call to get stats.
  7035. *
  7036. * @param collection_ - The collection to "listen" to.
  7037. */
  7038. class StatsListener {
  7039. constructor(collection_) {
  7040. this.collection_ = collection_;
  7041. this.last_ = null;
  7042. }
  7043. get() {
  7044. const newStats = this.collection_.get();
  7045. const delta = Object.assign({}, newStats);
  7046. if (this.last_) {
  7047. each(this.last_, (stat, value) => {
  7048. delta[stat] = delta[stat] - value;
  7049. });
  7050. }
  7051. this.last_ = newStats;
  7052. return delta;
  7053. }
  7054. }
  7055. /**
  7056. * @license
  7057. * Copyright 2017 Google LLC
  7058. *
  7059. * Licensed under the Apache License, Version 2.0 (the "License");
  7060. * you may not use this file except in compliance with the License.
  7061. * You may obtain a copy of the License at
  7062. *
  7063. * http://www.apache.org/licenses/LICENSE-2.0
  7064. *
  7065. * Unless required by applicable law or agreed to in writing, software
  7066. * distributed under the License is distributed on an "AS IS" BASIS,
  7067. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7068. * See the License for the specific language governing permissions and
  7069. * limitations under the License.
  7070. */
  7071. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7072. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7073. // seconds to try to ensure the Firebase connection is established / settled.
  7074. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7075. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7076. // We'll continue to report stats on average every 5 minutes.
  7077. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7078. class StatsReporter {
  7079. constructor(collection, server_) {
  7080. this.server_ = server_;
  7081. this.statsToReport_ = {};
  7082. this.statsListener_ = new StatsListener(collection);
  7083. const timeout = FIRST_STATS_MIN_TIME +
  7084. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7085. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7086. }
  7087. reportStats_() {
  7088. const stats = this.statsListener_.get();
  7089. const reportedStats = {};
  7090. let haveStatsToReport = false;
  7091. each(stats, (stat, value) => {
  7092. if (value > 0 && contains(this.statsToReport_, stat)) {
  7093. reportedStats[stat] = value;
  7094. haveStatsToReport = true;
  7095. }
  7096. });
  7097. if (haveStatsToReport) {
  7098. this.server_.reportStats(reportedStats);
  7099. }
  7100. // queue our next run.
  7101. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7102. }
  7103. }
  7104. /**
  7105. * @license
  7106. * Copyright 2017 Google LLC
  7107. *
  7108. * Licensed under the Apache License, Version 2.0 (the "License");
  7109. * you may not use this file except in compliance with the License.
  7110. * You may obtain a copy of the License at
  7111. *
  7112. * http://www.apache.org/licenses/LICENSE-2.0
  7113. *
  7114. * Unless required by applicable law or agreed to in writing, software
  7115. * distributed under the License is distributed on an "AS IS" BASIS,
  7116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7117. * See the License for the specific language governing permissions and
  7118. * limitations under the License.
  7119. */
  7120. /**
  7121. *
  7122. * @enum
  7123. */
  7124. var OperationType;
  7125. (function (OperationType) {
  7126. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7127. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7128. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7129. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7130. })(OperationType || (OperationType = {}));
  7131. function newOperationSourceUser() {
  7132. return {
  7133. fromUser: true,
  7134. fromServer: false,
  7135. queryId: null,
  7136. tagged: false
  7137. };
  7138. }
  7139. function newOperationSourceServer() {
  7140. return {
  7141. fromUser: false,
  7142. fromServer: true,
  7143. queryId: null,
  7144. tagged: false
  7145. };
  7146. }
  7147. function newOperationSourceServerTaggedQuery(queryId) {
  7148. return {
  7149. fromUser: false,
  7150. fromServer: true,
  7151. queryId,
  7152. tagged: true
  7153. };
  7154. }
  7155. /**
  7156. * @license
  7157. * Copyright 2017 Google LLC
  7158. *
  7159. * Licensed under the Apache License, Version 2.0 (the "License");
  7160. * you may not use this file except in compliance with the License.
  7161. * You may obtain a copy of the License at
  7162. *
  7163. * http://www.apache.org/licenses/LICENSE-2.0
  7164. *
  7165. * Unless required by applicable law or agreed to in writing, software
  7166. * distributed under the License is distributed on an "AS IS" BASIS,
  7167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7168. * See the License for the specific language governing permissions and
  7169. * limitations under the License.
  7170. */
  7171. class AckUserWrite {
  7172. /**
  7173. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7174. */
  7175. constructor(
  7176. /** @inheritDoc */ path,
  7177. /** @inheritDoc */ affectedTree,
  7178. /** @inheritDoc */ revert) {
  7179. this.path = path;
  7180. this.affectedTree = affectedTree;
  7181. this.revert = revert;
  7182. /** @inheritDoc */
  7183. this.type = OperationType.ACK_USER_WRITE;
  7184. /** @inheritDoc */
  7185. this.source = newOperationSourceUser();
  7186. }
  7187. operationForChild(childName) {
  7188. if (!pathIsEmpty(this.path)) {
  7189. assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7190. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7191. }
  7192. else if (this.affectedTree.value != null) {
  7193. assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7194. // All child locations are affected as well; just return same operation.
  7195. return this;
  7196. }
  7197. else {
  7198. const childTree = this.affectedTree.subtree(new Path(childName));
  7199. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7200. }
  7201. }
  7202. }
  7203. /**
  7204. * @license
  7205. * Copyright 2017 Google LLC
  7206. *
  7207. * Licensed under the Apache License, Version 2.0 (the "License");
  7208. * you may not use this file except in compliance with the License.
  7209. * You may obtain a copy of the License at
  7210. *
  7211. * http://www.apache.org/licenses/LICENSE-2.0
  7212. *
  7213. * Unless required by applicable law or agreed to in writing, software
  7214. * distributed under the License is distributed on an "AS IS" BASIS,
  7215. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7216. * See the License for the specific language governing permissions and
  7217. * limitations under the License.
  7218. */
  7219. class ListenComplete {
  7220. constructor(source, path) {
  7221. this.source = source;
  7222. this.path = path;
  7223. /** @inheritDoc */
  7224. this.type = OperationType.LISTEN_COMPLETE;
  7225. }
  7226. operationForChild(childName) {
  7227. if (pathIsEmpty(this.path)) {
  7228. return new ListenComplete(this.source, newEmptyPath());
  7229. }
  7230. else {
  7231. return new ListenComplete(this.source, pathPopFront(this.path));
  7232. }
  7233. }
  7234. }
  7235. /**
  7236. * @license
  7237. * Copyright 2017 Google LLC
  7238. *
  7239. * Licensed under the Apache License, Version 2.0 (the "License");
  7240. * you may not use this file except in compliance with the License.
  7241. * You may obtain a copy of the License at
  7242. *
  7243. * http://www.apache.org/licenses/LICENSE-2.0
  7244. *
  7245. * Unless required by applicable law or agreed to in writing, software
  7246. * distributed under the License is distributed on an "AS IS" BASIS,
  7247. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7248. * See the License for the specific language governing permissions and
  7249. * limitations under the License.
  7250. */
  7251. class Overwrite {
  7252. constructor(source, path, snap) {
  7253. this.source = source;
  7254. this.path = path;
  7255. this.snap = snap;
  7256. /** @inheritDoc */
  7257. this.type = OperationType.OVERWRITE;
  7258. }
  7259. operationForChild(childName) {
  7260. if (pathIsEmpty(this.path)) {
  7261. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7262. }
  7263. else {
  7264. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7265. }
  7266. }
  7267. }
  7268. /**
  7269. * @license
  7270. * Copyright 2017 Google LLC
  7271. *
  7272. * Licensed under the Apache License, Version 2.0 (the "License");
  7273. * you may not use this file except in compliance with the License.
  7274. * You may obtain a copy of the License at
  7275. *
  7276. * http://www.apache.org/licenses/LICENSE-2.0
  7277. *
  7278. * Unless required by applicable law or agreed to in writing, software
  7279. * distributed under the License is distributed on an "AS IS" BASIS,
  7280. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7281. * See the License for the specific language governing permissions and
  7282. * limitations under the License.
  7283. */
  7284. class Merge {
  7285. constructor(
  7286. /** @inheritDoc */ source,
  7287. /** @inheritDoc */ path,
  7288. /** @inheritDoc */ children) {
  7289. this.source = source;
  7290. this.path = path;
  7291. this.children = children;
  7292. /** @inheritDoc */
  7293. this.type = OperationType.MERGE;
  7294. }
  7295. operationForChild(childName) {
  7296. if (pathIsEmpty(this.path)) {
  7297. const childTree = this.children.subtree(new Path(childName));
  7298. if (childTree.isEmpty()) {
  7299. // This child is unaffected
  7300. return null;
  7301. }
  7302. else if (childTree.value) {
  7303. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7304. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7305. }
  7306. else {
  7307. // This is a merge at a deeper level
  7308. return new Merge(this.source, newEmptyPath(), childTree);
  7309. }
  7310. }
  7311. else {
  7312. assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7313. return new Merge(this.source, pathPopFront(this.path), this.children);
  7314. }
  7315. }
  7316. toString() {
  7317. return ('Operation(' +
  7318. this.path +
  7319. ': ' +
  7320. this.source.toString() +
  7321. ' merge: ' +
  7322. this.children.toString() +
  7323. ')');
  7324. }
  7325. }
  7326. /**
  7327. * @license
  7328. * Copyright 2017 Google LLC
  7329. *
  7330. * Licensed under the Apache License, Version 2.0 (the "License");
  7331. * you may not use this file except in compliance with the License.
  7332. * You may obtain a copy of the License at
  7333. *
  7334. * http://www.apache.org/licenses/LICENSE-2.0
  7335. *
  7336. * Unless required by applicable law or agreed to in writing, software
  7337. * distributed under the License is distributed on an "AS IS" BASIS,
  7338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7339. * See the License for the specific language governing permissions and
  7340. * limitations under the License.
  7341. */
  7342. /**
  7343. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7344. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7345. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7346. * whether a node potentially had children removed due to a filter.
  7347. */
  7348. class CacheNode {
  7349. constructor(node_, fullyInitialized_, filtered_) {
  7350. this.node_ = node_;
  7351. this.fullyInitialized_ = fullyInitialized_;
  7352. this.filtered_ = filtered_;
  7353. }
  7354. /**
  7355. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7356. */
  7357. isFullyInitialized() {
  7358. return this.fullyInitialized_;
  7359. }
  7360. /**
  7361. * Returns whether this node is potentially missing children due to a filter applied to the node
  7362. */
  7363. isFiltered() {
  7364. return this.filtered_;
  7365. }
  7366. isCompleteForPath(path) {
  7367. if (pathIsEmpty(path)) {
  7368. return this.isFullyInitialized() && !this.filtered_;
  7369. }
  7370. const childKey = pathGetFront(path);
  7371. return this.isCompleteForChild(childKey);
  7372. }
  7373. isCompleteForChild(key) {
  7374. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7375. }
  7376. getNode() {
  7377. return this.node_;
  7378. }
  7379. }
  7380. /**
  7381. * @license
  7382. * Copyright 2017 Google LLC
  7383. *
  7384. * Licensed under the Apache License, Version 2.0 (the "License");
  7385. * you may not use this file except in compliance with the License.
  7386. * You may obtain a copy of the License at
  7387. *
  7388. * http://www.apache.org/licenses/LICENSE-2.0
  7389. *
  7390. * Unless required by applicable law or agreed to in writing, software
  7391. * distributed under the License is distributed on an "AS IS" BASIS,
  7392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7393. * See the License for the specific language governing permissions and
  7394. * limitations under the License.
  7395. */
  7396. /**
  7397. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7398. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7399. * for details.
  7400. *
  7401. */
  7402. class EventGenerator {
  7403. constructor(query_) {
  7404. this.query_ = query_;
  7405. this.index_ = this.query_._queryParams.getIndex();
  7406. }
  7407. }
  7408. /**
  7409. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7410. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7411. *
  7412. * Notes:
  7413. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7414. * our index.
  7415. * - prevName will be calculated based on the index ordering.
  7416. */
  7417. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7418. const events = [];
  7419. const moves = [];
  7420. changes.forEach(change => {
  7421. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7422. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7423. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7424. }
  7425. });
  7426. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7427. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7428. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7429. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7430. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7431. return events;
  7432. }
  7433. /**
  7434. * Given changes of a single change type, generate the corresponding events.
  7435. */
  7436. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7437. const filteredChanges = changes.filter(change => change.type === eventType);
  7438. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7439. filteredChanges.forEach(change => {
  7440. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7441. registrations.forEach(registration => {
  7442. if (registration.respondsTo(change.type)) {
  7443. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7444. }
  7445. });
  7446. });
  7447. }
  7448. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7449. if (change.type === 'value' || change.type === 'child_removed') {
  7450. return change;
  7451. }
  7452. else {
  7453. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7454. return change;
  7455. }
  7456. }
  7457. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7458. if (a.childName == null || b.childName == null) {
  7459. throw assertionError('Should only compare child_ events.');
  7460. }
  7461. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7462. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7463. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7464. }
  7465. /**
  7466. * @license
  7467. * Copyright 2017 Google LLC
  7468. *
  7469. * Licensed under the Apache License, Version 2.0 (the "License");
  7470. * you may not use this file except in compliance with the License.
  7471. * You may obtain a copy of the License at
  7472. *
  7473. * http://www.apache.org/licenses/LICENSE-2.0
  7474. *
  7475. * Unless required by applicable law or agreed to in writing, software
  7476. * distributed under the License is distributed on an "AS IS" BASIS,
  7477. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7478. * See the License for the specific language governing permissions and
  7479. * limitations under the License.
  7480. */
  7481. function newViewCache(eventCache, serverCache) {
  7482. return { eventCache, serverCache };
  7483. }
  7484. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7485. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7486. }
  7487. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7488. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7489. }
  7490. function viewCacheGetCompleteEventSnap(viewCache) {
  7491. return viewCache.eventCache.isFullyInitialized()
  7492. ? viewCache.eventCache.getNode()
  7493. : null;
  7494. }
  7495. function viewCacheGetCompleteServerSnap(viewCache) {
  7496. return viewCache.serverCache.isFullyInitialized()
  7497. ? viewCache.serverCache.getNode()
  7498. : null;
  7499. }
  7500. /**
  7501. * @license
  7502. * Copyright 2017 Google LLC
  7503. *
  7504. * Licensed under the Apache License, Version 2.0 (the "License");
  7505. * you may not use this file except in compliance with the License.
  7506. * You may obtain a copy of the License at
  7507. *
  7508. * http://www.apache.org/licenses/LICENSE-2.0
  7509. *
  7510. * Unless required by applicable law or agreed to in writing, software
  7511. * distributed under the License is distributed on an "AS IS" BASIS,
  7512. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7513. * See the License for the specific language governing permissions and
  7514. * limitations under the License.
  7515. */
  7516. let emptyChildrenSingleton;
  7517. /**
  7518. * Singleton empty children collection.
  7519. *
  7520. */
  7521. const EmptyChildren = () => {
  7522. if (!emptyChildrenSingleton) {
  7523. emptyChildrenSingleton = new SortedMap(stringCompare);
  7524. }
  7525. return emptyChildrenSingleton;
  7526. };
  7527. /**
  7528. * A tree with immutable elements.
  7529. */
  7530. class ImmutableTree {
  7531. constructor(value, children = EmptyChildren()) {
  7532. this.value = value;
  7533. this.children = children;
  7534. }
  7535. static fromObject(obj) {
  7536. let tree = new ImmutableTree(null);
  7537. each(obj, (childPath, childSnap) => {
  7538. tree = tree.set(new Path(childPath), childSnap);
  7539. });
  7540. return tree;
  7541. }
  7542. /**
  7543. * True if the value is empty and there are no children
  7544. */
  7545. isEmpty() {
  7546. return this.value === null && this.children.isEmpty();
  7547. }
  7548. /**
  7549. * Given a path and predicate, return the first node and the path to that node
  7550. * where the predicate returns true.
  7551. *
  7552. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7553. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7554. *
  7555. * @param relativePath - The remainder of the path
  7556. * @param predicate - The predicate to satisfy to return a node
  7557. */
  7558. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7559. if (this.value != null && predicate(this.value)) {
  7560. return { path: newEmptyPath(), value: this.value };
  7561. }
  7562. else {
  7563. if (pathIsEmpty(relativePath)) {
  7564. return null;
  7565. }
  7566. else {
  7567. const front = pathGetFront(relativePath);
  7568. const child = this.children.get(front);
  7569. if (child !== null) {
  7570. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7571. if (childExistingPathAndValue != null) {
  7572. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7573. return { path: fullPath, value: childExistingPathAndValue.value };
  7574. }
  7575. else {
  7576. return null;
  7577. }
  7578. }
  7579. else {
  7580. return null;
  7581. }
  7582. }
  7583. }
  7584. }
  7585. /**
  7586. * Find, if it exists, the shortest subpath of the given path that points a defined
  7587. * value in the tree
  7588. */
  7589. findRootMostValueAndPath(relativePath) {
  7590. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7591. }
  7592. /**
  7593. * @returns The subtree at the given path
  7594. */
  7595. subtree(relativePath) {
  7596. if (pathIsEmpty(relativePath)) {
  7597. return this;
  7598. }
  7599. else {
  7600. const front = pathGetFront(relativePath);
  7601. const childTree = this.children.get(front);
  7602. if (childTree !== null) {
  7603. return childTree.subtree(pathPopFront(relativePath));
  7604. }
  7605. else {
  7606. return new ImmutableTree(null);
  7607. }
  7608. }
  7609. }
  7610. /**
  7611. * Sets a value at the specified path.
  7612. *
  7613. * @param relativePath - Path to set value at.
  7614. * @param toSet - Value to set.
  7615. * @returns Resulting tree.
  7616. */
  7617. set(relativePath, toSet) {
  7618. if (pathIsEmpty(relativePath)) {
  7619. return new ImmutableTree(toSet, this.children);
  7620. }
  7621. else {
  7622. const front = pathGetFront(relativePath);
  7623. const child = this.children.get(front) || new ImmutableTree(null);
  7624. const newChild = child.set(pathPopFront(relativePath), toSet);
  7625. const newChildren = this.children.insert(front, newChild);
  7626. return new ImmutableTree(this.value, newChildren);
  7627. }
  7628. }
  7629. /**
  7630. * Removes the value at the specified path.
  7631. *
  7632. * @param relativePath - Path to value to remove.
  7633. * @returns Resulting tree.
  7634. */
  7635. remove(relativePath) {
  7636. if (pathIsEmpty(relativePath)) {
  7637. if (this.children.isEmpty()) {
  7638. return new ImmutableTree(null);
  7639. }
  7640. else {
  7641. return new ImmutableTree(null, this.children);
  7642. }
  7643. }
  7644. else {
  7645. const front = pathGetFront(relativePath);
  7646. const child = this.children.get(front);
  7647. if (child) {
  7648. const newChild = child.remove(pathPopFront(relativePath));
  7649. let newChildren;
  7650. if (newChild.isEmpty()) {
  7651. newChildren = this.children.remove(front);
  7652. }
  7653. else {
  7654. newChildren = this.children.insert(front, newChild);
  7655. }
  7656. if (this.value === null && newChildren.isEmpty()) {
  7657. return new ImmutableTree(null);
  7658. }
  7659. else {
  7660. return new ImmutableTree(this.value, newChildren);
  7661. }
  7662. }
  7663. else {
  7664. return this;
  7665. }
  7666. }
  7667. }
  7668. /**
  7669. * Gets a value from the tree.
  7670. *
  7671. * @param relativePath - Path to get value for.
  7672. * @returns Value at path, or null.
  7673. */
  7674. get(relativePath) {
  7675. if (pathIsEmpty(relativePath)) {
  7676. return this.value;
  7677. }
  7678. else {
  7679. const front = pathGetFront(relativePath);
  7680. const child = this.children.get(front);
  7681. if (child) {
  7682. return child.get(pathPopFront(relativePath));
  7683. }
  7684. else {
  7685. return null;
  7686. }
  7687. }
  7688. }
  7689. /**
  7690. * Replace the subtree at the specified path with the given new tree.
  7691. *
  7692. * @param relativePath - Path to replace subtree for.
  7693. * @param newTree - New tree.
  7694. * @returns Resulting tree.
  7695. */
  7696. setTree(relativePath, newTree) {
  7697. if (pathIsEmpty(relativePath)) {
  7698. return newTree;
  7699. }
  7700. else {
  7701. const front = pathGetFront(relativePath);
  7702. const child = this.children.get(front) || new ImmutableTree(null);
  7703. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7704. let newChildren;
  7705. if (newChild.isEmpty()) {
  7706. newChildren = this.children.remove(front);
  7707. }
  7708. else {
  7709. newChildren = this.children.insert(front, newChild);
  7710. }
  7711. return new ImmutableTree(this.value, newChildren);
  7712. }
  7713. }
  7714. /**
  7715. * Performs a depth first fold on this tree. Transforms a tree into a single
  7716. * value, given a function that operates on the path to a node, an optional
  7717. * current value, and a map of child names to folded subtrees
  7718. */
  7719. fold(fn) {
  7720. return this.fold_(newEmptyPath(), fn);
  7721. }
  7722. /**
  7723. * Recursive helper for public-facing fold() method
  7724. */
  7725. fold_(pathSoFar, fn) {
  7726. const accum = {};
  7727. this.children.inorderTraversal((childKey, childTree) => {
  7728. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7729. });
  7730. return fn(pathSoFar, this.value, accum);
  7731. }
  7732. /**
  7733. * Find the first matching value on the given path. Return the result of applying f to it.
  7734. */
  7735. findOnPath(path, f) {
  7736. return this.findOnPath_(path, newEmptyPath(), f);
  7737. }
  7738. findOnPath_(pathToFollow, pathSoFar, f) {
  7739. const result = this.value ? f(pathSoFar, this.value) : false;
  7740. if (result) {
  7741. return result;
  7742. }
  7743. else {
  7744. if (pathIsEmpty(pathToFollow)) {
  7745. return null;
  7746. }
  7747. else {
  7748. const front = pathGetFront(pathToFollow);
  7749. const nextChild = this.children.get(front);
  7750. if (nextChild) {
  7751. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7752. }
  7753. else {
  7754. return null;
  7755. }
  7756. }
  7757. }
  7758. }
  7759. foreachOnPath(path, f) {
  7760. return this.foreachOnPath_(path, newEmptyPath(), f);
  7761. }
  7762. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7763. if (pathIsEmpty(pathToFollow)) {
  7764. return this;
  7765. }
  7766. else {
  7767. if (this.value) {
  7768. f(currentRelativePath, this.value);
  7769. }
  7770. const front = pathGetFront(pathToFollow);
  7771. const nextChild = this.children.get(front);
  7772. if (nextChild) {
  7773. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7774. }
  7775. else {
  7776. return new ImmutableTree(null);
  7777. }
  7778. }
  7779. }
  7780. /**
  7781. * Calls the given function for each node in the tree that has a value.
  7782. *
  7783. * @param f - A function to be called with the path from the root of the tree to
  7784. * a node, and the value at that node. Called in depth-first order.
  7785. */
  7786. foreach(f) {
  7787. this.foreach_(newEmptyPath(), f);
  7788. }
  7789. foreach_(currentRelativePath, f) {
  7790. this.children.inorderTraversal((childName, childTree) => {
  7791. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7792. });
  7793. if (this.value) {
  7794. f(currentRelativePath, this.value);
  7795. }
  7796. }
  7797. foreachChild(f) {
  7798. this.children.inorderTraversal((childName, childTree) => {
  7799. if (childTree.value) {
  7800. f(childName, childTree.value);
  7801. }
  7802. });
  7803. }
  7804. }
  7805. /**
  7806. * @license
  7807. * Copyright 2017 Google LLC
  7808. *
  7809. * Licensed under the Apache License, Version 2.0 (the "License");
  7810. * you may not use this file except in compliance with the License.
  7811. * You may obtain a copy of the License at
  7812. *
  7813. * http://www.apache.org/licenses/LICENSE-2.0
  7814. *
  7815. * Unless required by applicable law or agreed to in writing, software
  7816. * distributed under the License is distributed on an "AS IS" BASIS,
  7817. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7818. * See the License for the specific language governing permissions and
  7819. * limitations under the License.
  7820. */
  7821. /**
  7822. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7823. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7824. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7825. * to reflect the write added.
  7826. */
  7827. class CompoundWrite {
  7828. constructor(writeTree_) {
  7829. this.writeTree_ = writeTree_;
  7830. }
  7831. static empty() {
  7832. return new CompoundWrite(new ImmutableTree(null));
  7833. }
  7834. }
  7835. function compoundWriteAddWrite(compoundWrite, path, node) {
  7836. if (pathIsEmpty(path)) {
  7837. return new CompoundWrite(new ImmutableTree(node));
  7838. }
  7839. else {
  7840. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7841. if (rootmost != null) {
  7842. const rootMostPath = rootmost.path;
  7843. let value = rootmost.value;
  7844. const relativePath = newRelativePath(rootMostPath, path);
  7845. value = value.updateChild(relativePath, node);
  7846. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7847. }
  7848. else {
  7849. const subtree = new ImmutableTree(node);
  7850. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7851. return new CompoundWrite(newWriteTree);
  7852. }
  7853. }
  7854. }
  7855. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7856. let newWrite = compoundWrite;
  7857. each(updates, (childKey, node) => {
  7858. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7859. });
  7860. return newWrite;
  7861. }
  7862. /**
  7863. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7864. * location, which must be removed by calling this method with that path.
  7865. *
  7866. * @param compoundWrite - The CompoundWrite to remove.
  7867. * @param path - The path at which a write and all deeper writes should be removed
  7868. * @returns The new CompoundWrite with the removed path
  7869. */
  7870. function compoundWriteRemoveWrite(compoundWrite, path) {
  7871. if (pathIsEmpty(path)) {
  7872. return CompoundWrite.empty();
  7873. }
  7874. else {
  7875. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7876. return new CompoundWrite(newWriteTree);
  7877. }
  7878. }
  7879. /**
  7880. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7881. * considered "complete".
  7882. *
  7883. * @param compoundWrite - The CompoundWrite to check.
  7884. * @param path - The path to check for
  7885. * @returns Whether there is a complete write at that path
  7886. */
  7887. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7888. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7889. }
  7890. /**
  7891. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7892. * writes from deeper paths, but will return child nodes from a more shallow path.
  7893. *
  7894. * @param compoundWrite - The CompoundWrite to get the node from.
  7895. * @param path - The path to get a complete write
  7896. * @returns The node if complete at that path, or null otherwise.
  7897. */
  7898. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7899. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7900. if (rootmost != null) {
  7901. return compoundWrite.writeTree_
  7902. .get(rootmost.path)
  7903. .getChild(newRelativePath(rootmost.path, path));
  7904. }
  7905. else {
  7906. return null;
  7907. }
  7908. }
  7909. /**
  7910. * Returns all children that are guaranteed to be a complete overwrite.
  7911. *
  7912. * @param compoundWrite - The CompoundWrite to get children from.
  7913. * @returns A list of all complete children.
  7914. */
  7915. function compoundWriteGetCompleteChildren(compoundWrite) {
  7916. const children = [];
  7917. const node = compoundWrite.writeTree_.value;
  7918. if (node != null) {
  7919. // If it's a leaf node, it has no children; so nothing to do.
  7920. if (!node.isLeafNode()) {
  7921. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7922. children.push(new NamedNode(childName, childNode));
  7923. });
  7924. }
  7925. }
  7926. else {
  7927. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7928. if (childTree.value != null) {
  7929. children.push(new NamedNode(childName, childTree.value));
  7930. }
  7931. });
  7932. }
  7933. return children;
  7934. }
  7935. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7936. if (pathIsEmpty(path)) {
  7937. return compoundWrite;
  7938. }
  7939. else {
  7940. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7941. if (shadowingNode != null) {
  7942. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7943. }
  7944. else {
  7945. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7946. }
  7947. }
  7948. }
  7949. /**
  7950. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7951. * @returns Whether this CompoundWrite is empty
  7952. */
  7953. function compoundWriteIsEmpty(compoundWrite) {
  7954. return compoundWrite.writeTree_.isEmpty();
  7955. }
  7956. /**
  7957. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7958. * node
  7959. * @param node - The node to apply this CompoundWrite to
  7960. * @returns The node with all writes applied
  7961. */
  7962. function compoundWriteApply(compoundWrite, node) {
  7963. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7964. }
  7965. function applySubtreeWrite(relativePath, writeTree, node) {
  7966. if (writeTree.value != null) {
  7967. // Since there a write is always a leaf, we're done here
  7968. return node.updateChild(relativePath, writeTree.value);
  7969. }
  7970. else {
  7971. let priorityWrite = null;
  7972. writeTree.children.inorderTraversal((childKey, childTree) => {
  7973. if (childKey === '.priority') {
  7974. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7975. // to apply priorities to empty nodes that are later filled
  7976. assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7977. priorityWrite = childTree.value;
  7978. }
  7979. else {
  7980. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7981. }
  7982. });
  7983. // If there was a priority write, we only apply it if the node is not empty
  7984. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7985. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7986. }
  7987. return node;
  7988. }
  7989. }
  7990. /**
  7991. * @license
  7992. * Copyright 2017 Google LLC
  7993. *
  7994. * Licensed under the Apache License, Version 2.0 (the "License");
  7995. * you may not use this file except in compliance with the License.
  7996. * You may obtain a copy of the License at
  7997. *
  7998. * http://www.apache.org/licenses/LICENSE-2.0
  7999. *
  8000. * Unless required by applicable law or agreed to in writing, software
  8001. * distributed under the License is distributed on an "AS IS" BASIS,
  8002. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8003. * See the License for the specific language governing permissions and
  8004. * limitations under the License.
  8005. */
  8006. /**
  8007. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8008. *
  8009. */
  8010. function writeTreeChildWrites(writeTree, path) {
  8011. return newWriteTreeRef(path, writeTree);
  8012. }
  8013. /**
  8014. * Record a new overwrite from user code.
  8015. *
  8016. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8017. */
  8018. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8019. assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8020. if (visible === undefined) {
  8021. visible = true;
  8022. }
  8023. writeTree.allWrites.push({
  8024. path,
  8025. snap,
  8026. writeId,
  8027. visible
  8028. });
  8029. if (visible) {
  8030. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8031. }
  8032. writeTree.lastWriteId = writeId;
  8033. }
  8034. /**
  8035. * Record a new merge from user code.
  8036. */
  8037. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8038. assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8039. writeTree.allWrites.push({
  8040. path,
  8041. children: changedChildren,
  8042. writeId,
  8043. visible: true
  8044. });
  8045. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8046. writeTree.lastWriteId = writeId;
  8047. }
  8048. function writeTreeGetWrite(writeTree, writeId) {
  8049. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8050. const record = writeTree.allWrites[i];
  8051. if (record.writeId === writeId) {
  8052. return record;
  8053. }
  8054. }
  8055. return null;
  8056. }
  8057. /**
  8058. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8059. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8060. *
  8061. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8062. * events as a result).
  8063. */
  8064. function writeTreeRemoveWrite(writeTree, writeId) {
  8065. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8066. // out of order.
  8067. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8068. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8069. const idx = writeTree.allWrites.findIndex(s => {
  8070. return s.writeId === writeId;
  8071. });
  8072. assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8073. const writeToRemove = writeTree.allWrites[idx];
  8074. writeTree.allWrites.splice(idx, 1);
  8075. let removedWriteWasVisible = writeToRemove.visible;
  8076. let removedWriteOverlapsWithOtherWrites = false;
  8077. let i = writeTree.allWrites.length - 1;
  8078. while (removedWriteWasVisible && i >= 0) {
  8079. const currentWrite = writeTree.allWrites[i];
  8080. if (currentWrite.visible) {
  8081. if (i >= idx &&
  8082. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8083. // The removed write was completely shadowed by a subsequent write.
  8084. removedWriteWasVisible = false;
  8085. }
  8086. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8087. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8088. removedWriteOverlapsWithOtherWrites = true;
  8089. }
  8090. }
  8091. i--;
  8092. }
  8093. if (!removedWriteWasVisible) {
  8094. return false;
  8095. }
  8096. else if (removedWriteOverlapsWithOtherWrites) {
  8097. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8098. writeTreeResetTree_(writeTree);
  8099. return true;
  8100. }
  8101. else {
  8102. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8103. if (writeToRemove.snap) {
  8104. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8105. }
  8106. else {
  8107. const children = writeToRemove.children;
  8108. each(children, (childName) => {
  8109. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8110. });
  8111. }
  8112. return true;
  8113. }
  8114. }
  8115. function writeTreeRecordContainsPath_(writeRecord, path) {
  8116. if (writeRecord.snap) {
  8117. return pathContains(writeRecord.path, path);
  8118. }
  8119. else {
  8120. for (const childName in writeRecord.children) {
  8121. if (writeRecord.children.hasOwnProperty(childName) &&
  8122. pathContains(pathChild(writeRecord.path, childName), path)) {
  8123. return true;
  8124. }
  8125. }
  8126. return false;
  8127. }
  8128. }
  8129. /**
  8130. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8131. */
  8132. function writeTreeResetTree_(writeTree) {
  8133. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8134. if (writeTree.allWrites.length > 0) {
  8135. writeTree.lastWriteId =
  8136. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8137. }
  8138. else {
  8139. writeTree.lastWriteId = -1;
  8140. }
  8141. }
  8142. /**
  8143. * The default filter used when constructing the tree. Keep everything that's visible.
  8144. */
  8145. function writeTreeDefaultFilter_(write) {
  8146. return write.visible;
  8147. }
  8148. /**
  8149. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8150. * event data at that path.
  8151. */
  8152. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8153. let compoundWrite = CompoundWrite.empty();
  8154. for (let i = 0; i < writes.length; ++i) {
  8155. const write = writes[i];
  8156. // Theory, a later set will either:
  8157. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8158. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8159. if (filter(write)) {
  8160. const writePath = write.path;
  8161. let relativePath;
  8162. if (write.snap) {
  8163. if (pathContains(treeRoot, writePath)) {
  8164. relativePath = newRelativePath(treeRoot, writePath);
  8165. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8166. }
  8167. else if (pathContains(writePath, treeRoot)) {
  8168. relativePath = newRelativePath(writePath, treeRoot);
  8169. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8170. }
  8171. else ;
  8172. }
  8173. else if (write.children) {
  8174. if (pathContains(treeRoot, writePath)) {
  8175. relativePath = newRelativePath(treeRoot, writePath);
  8176. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8177. }
  8178. else if (pathContains(writePath, treeRoot)) {
  8179. relativePath = newRelativePath(writePath, treeRoot);
  8180. if (pathIsEmpty(relativePath)) {
  8181. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8182. }
  8183. else {
  8184. const child = safeGet(write.children, pathGetFront(relativePath));
  8185. if (child) {
  8186. // There exists a child in this node that matches the root path
  8187. const deepNode = child.getChild(pathPopFront(relativePath));
  8188. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8189. }
  8190. }
  8191. }
  8192. else ;
  8193. }
  8194. else {
  8195. throw assertionError('WriteRecord should have .snap or .children');
  8196. }
  8197. }
  8198. }
  8199. return compoundWrite;
  8200. }
  8201. /**
  8202. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8203. * writes), attempt to calculate a complete snapshot for the given path
  8204. *
  8205. * @param writeIdsToExclude - An optional set to be excluded
  8206. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8207. */
  8208. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8209. if (!writeIdsToExclude && !includeHiddenWrites) {
  8210. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8211. if (shadowingNode != null) {
  8212. return shadowingNode;
  8213. }
  8214. else {
  8215. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8216. if (compoundWriteIsEmpty(subMerge)) {
  8217. return completeServerCache;
  8218. }
  8219. else if (completeServerCache == null &&
  8220. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8221. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8222. return null;
  8223. }
  8224. else {
  8225. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8226. return compoundWriteApply(subMerge, layeredCache);
  8227. }
  8228. }
  8229. }
  8230. else {
  8231. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8232. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8233. return completeServerCache;
  8234. }
  8235. else {
  8236. // If the server cache is null, and we don't have a complete cache, we need to return null
  8237. if (!includeHiddenWrites &&
  8238. completeServerCache == null &&
  8239. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8240. return null;
  8241. }
  8242. else {
  8243. const filter = function (write) {
  8244. return ((write.visible || includeHiddenWrites) &&
  8245. (!writeIdsToExclude ||
  8246. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8247. (pathContains(write.path, treePath) ||
  8248. pathContains(treePath, write.path)));
  8249. };
  8250. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8251. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8252. return compoundWriteApply(mergeAtPath, layeredCache);
  8253. }
  8254. }
  8255. }
  8256. }
  8257. /**
  8258. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8259. * Used when creating new views, to pre-fill their complete event children snapshot.
  8260. */
  8261. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8262. let completeChildren = ChildrenNode.EMPTY_NODE;
  8263. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8264. if (topLevelSet) {
  8265. if (!topLevelSet.isLeafNode()) {
  8266. // we're shadowing everything. Return the children.
  8267. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8268. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8269. });
  8270. }
  8271. return completeChildren;
  8272. }
  8273. else if (completeServerChildren) {
  8274. // Layer any children we have on top of this
  8275. // We know we don't have a top-level set, so just enumerate existing children
  8276. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8277. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8278. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8279. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8280. });
  8281. // Add any complete children we have from the set
  8282. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8283. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8284. });
  8285. return completeChildren;
  8286. }
  8287. else {
  8288. // We don't have anything to layer on top of. Layer on any children we have
  8289. // Note that we can return an empty snap if we have a defined delete
  8290. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8291. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8292. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8293. });
  8294. return completeChildren;
  8295. }
  8296. }
  8297. /**
  8298. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8299. * applied to the event cache.
  8300. *
  8301. * Possibilities:
  8302. *
  8303. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8304. *
  8305. * 2. Some write is completely shadowing. No events to be raised
  8306. *
  8307. * 3. Is partially shadowed. Events
  8308. *
  8309. * Either existingEventSnap or existingServerSnap must exist
  8310. */
  8311. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8312. assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8313. const path = pathChild(treePath, childPath);
  8314. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8315. // At this point we can probably guarantee that we're in case 2, meaning no events
  8316. // May need to check visibility while doing the findRootMostValueAndPath call
  8317. return null;
  8318. }
  8319. else {
  8320. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8321. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8322. if (compoundWriteIsEmpty(childMerge)) {
  8323. // We're not shadowing at all. Case 1
  8324. return existingServerSnap.getChild(childPath);
  8325. }
  8326. else {
  8327. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8328. // However this is tricky to find out, since user updates don't necessary change the server
  8329. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8330. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8331. // only check if the updates change the serverNode.
  8332. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8333. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8334. }
  8335. }
  8336. }
  8337. /**
  8338. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8339. * complete child for this ChildKey.
  8340. */
  8341. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8342. const path = pathChild(treePath, childKey);
  8343. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8344. if (shadowingNode != null) {
  8345. return shadowingNode;
  8346. }
  8347. else {
  8348. if (existingServerSnap.isCompleteForChild(childKey)) {
  8349. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8350. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8351. }
  8352. else {
  8353. return null;
  8354. }
  8355. }
  8356. }
  8357. /**
  8358. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8359. * a higher path, this will return the child of that write relative to the write and this path.
  8360. * Returns null if there is no write at this path.
  8361. */
  8362. function writeTreeShadowingWrite(writeTree, path) {
  8363. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8364. }
  8365. /**
  8366. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8367. * the window, but may now be in the window.
  8368. */
  8369. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8370. let toIterate;
  8371. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8372. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8373. if (shadowingNode != null) {
  8374. toIterate = shadowingNode;
  8375. }
  8376. else if (completeServerData != null) {
  8377. toIterate = compoundWriteApply(merge, completeServerData);
  8378. }
  8379. else {
  8380. // no children to iterate on
  8381. return [];
  8382. }
  8383. toIterate = toIterate.withIndex(index);
  8384. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8385. const nodes = [];
  8386. const cmp = index.getCompare();
  8387. const iter = reverse
  8388. ? toIterate.getReverseIteratorFrom(startPost, index)
  8389. : toIterate.getIteratorFrom(startPost, index);
  8390. let next = iter.getNext();
  8391. while (next && nodes.length < count) {
  8392. if (cmp(next, startPost) !== 0) {
  8393. nodes.push(next);
  8394. }
  8395. next = iter.getNext();
  8396. }
  8397. return nodes;
  8398. }
  8399. else {
  8400. return [];
  8401. }
  8402. }
  8403. function newWriteTree() {
  8404. return {
  8405. visibleWrites: CompoundWrite.empty(),
  8406. allWrites: [],
  8407. lastWriteId: -1
  8408. };
  8409. }
  8410. /**
  8411. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8412. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8413. * can lead to a more expensive calculation.
  8414. *
  8415. * @param writeIdsToExclude - Optional writes to exclude.
  8416. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8417. */
  8418. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8419. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8420. }
  8421. /**
  8422. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8423. * mix of the given server data and write data.
  8424. *
  8425. */
  8426. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8427. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8428. }
  8429. /**
  8430. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8431. * if anything, needs to be applied to the event cache.
  8432. *
  8433. * Possibilities:
  8434. *
  8435. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8436. *
  8437. * 2. Some write is completely shadowing. No events to be raised
  8438. *
  8439. * 3. Is partially shadowed. Events should be raised
  8440. *
  8441. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8442. *
  8443. *
  8444. */
  8445. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8446. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8447. }
  8448. /**
  8449. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8450. * a higher path, this will return the child of that write relative to the write and this path.
  8451. * Returns null if there is no write at this path.
  8452. *
  8453. */
  8454. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8455. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8456. }
  8457. /**
  8458. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8459. * the window, but may now be in the window
  8460. */
  8461. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8462. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8463. }
  8464. /**
  8465. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8466. * complete child for this ChildKey.
  8467. */
  8468. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8469. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8470. }
  8471. /**
  8472. * Return a WriteTreeRef for a child.
  8473. */
  8474. function writeTreeRefChild(writeTreeRef, childName) {
  8475. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8476. }
  8477. function newWriteTreeRef(path, writeTree) {
  8478. return {
  8479. treePath: path,
  8480. writeTree
  8481. };
  8482. }
  8483. /**
  8484. * @license
  8485. * Copyright 2017 Google LLC
  8486. *
  8487. * Licensed under the Apache License, Version 2.0 (the "License");
  8488. * you may not use this file except in compliance with the License.
  8489. * You may obtain a copy of the License at
  8490. *
  8491. * http://www.apache.org/licenses/LICENSE-2.0
  8492. *
  8493. * Unless required by applicable law or agreed to in writing, software
  8494. * distributed under the License is distributed on an "AS IS" BASIS,
  8495. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8496. * See the License for the specific language governing permissions and
  8497. * limitations under the License.
  8498. */
  8499. class ChildChangeAccumulator {
  8500. constructor() {
  8501. this.changeMap = new Map();
  8502. }
  8503. trackChildChange(change) {
  8504. const type = change.type;
  8505. const childKey = change.childName;
  8506. assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8507. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8508. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8509. assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8510. const oldChange = this.changeMap.get(childKey);
  8511. if (oldChange) {
  8512. const oldType = oldChange.type;
  8513. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8514. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8515. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8516. }
  8517. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8518. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8519. this.changeMap.delete(childKey);
  8520. }
  8521. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8522. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8523. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8524. }
  8525. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8526. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8527. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8528. }
  8529. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8530. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8531. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8532. }
  8533. else {
  8534. throw assertionError('Illegal combination of changes: ' +
  8535. change +
  8536. ' occurred after ' +
  8537. oldChange);
  8538. }
  8539. }
  8540. else {
  8541. this.changeMap.set(childKey, change);
  8542. }
  8543. }
  8544. getChanges() {
  8545. return Array.from(this.changeMap.values());
  8546. }
  8547. }
  8548. /**
  8549. * @license
  8550. * Copyright 2017 Google LLC
  8551. *
  8552. * Licensed under the Apache License, Version 2.0 (the "License");
  8553. * you may not use this file except in compliance with the License.
  8554. * You may obtain a copy of the License at
  8555. *
  8556. * http://www.apache.org/licenses/LICENSE-2.0
  8557. *
  8558. * Unless required by applicable law or agreed to in writing, software
  8559. * distributed under the License is distributed on an "AS IS" BASIS,
  8560. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8561. * See the License for the specific language governing permissions and
  8562. * limitations under the License.
  8563. */
  8564. /**
  8565. * An implementation of CompleteChildSource that never returns any additional children
  8566. */
  8567. // eslint-disable-next-line @typescript-eslint/naming-convention
  8568. class NoCompleteChildSource_ {
  8569. getCompleteChild(childKey) {
  8570. return null;
  8571. }
  8572. getChildAfterChild(index, child, reverse) {
  8573. return null;
  8574. }
  8575. }
  8576. /**
  8577. * Singleton instance.
  8578. */
  8579. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8580. /**
  8581. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8582. * old event caches available to calculate complete children.
  8583. */
  8584. class WriteTreeCompleteChildSource {
  8585. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8586. this.writes_ = writes_;
  8587. this.viewCache_ = viewCache_;
  8588. this.optCompleteServerCache_ = optCompleteServerCache_;
  8589. }
  8590. getCompleteChild(childKey) {
  8591. const node = this.viewCache_.eventCache;
  8592. if (node.isCompleteForChild(childKey)) {
  8593. return node.getNode().getImmediateChild(childKey);
  8594. }
  8595. else {
  8596. const serverNode = this.optCompleteServerCache_ != null
  8597. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8598. : this.viewCache_.serverCache;
  8599. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8600. }
  8601. }
  8602. getChildAfterChild(index, child, reverse) {
  8603. const completeServerData = this.optCompleteServerCache_ != null
  8604. ? this.optCompleteServerCache_
  8605. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8606. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8607. if (nodes.length === 0) {
  8608. return null;
  8609. }
  8610. else {
  8611. return nodes[0];
  8612. }
  8613. }
  8614. }
  8615. /**
  8616. * @license
  8617. * Copyright 2017 Google LLC
  8618. *
  8619. * Licensed under the Apache License, Version 2.0 (the "License");
  8620. * you may not use this file except in compliance with the License.
  8621. * You may obtain a copy of the License at
  8622. *
  8623. * http://www.apache.org/licenses/LICENSE-2.0
  8624. *
  8625. * Unless required by applicable law or agreed to in writing, software
  8626. * distributed under the License is distributed on an "AS IS" BASIS,
  8627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8628. * See the License for the specific language governing permissions and
  8629. * limitations under the License.
  8630. */
  8631. function newViewProcessor(filter) {
  8632. return { filter };
  8633. }
  8634. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8635. assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8636. assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8637. }
  8638. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8639. const accumulator = new ChildChangeAccumulator();
  8640. let newViewCache, filterServerNode;
  8641. if (operation.type === OperationType.OVERWRITE) {
  8642. const overwrite = operation;
  8643. if (overwrite.source.fromUser) {
  8644. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8645. }
  8646. else {
  8647. assert(overwrite.source.fromServer, 'Unknown source.');
  8648. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8649. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8650. // again
  8651. filterServerNode =
  8652. overwrite.source.tagged ||
  8653. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8654. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8655. }
  8656. }
  8657. else if (operation.type === OperationType.MERGE) {
  8658. const merge = operation;
  8659. if (merge.source.fromUser) {
  8660. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8661. }
  8662. else {
  8663. assert(merge.source.fromServer, 'Unknown source.');
  8664. // We filter the node if it's a tagged update or the node has been previously filtered
  8665. filterServerNode =
  8666. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8667. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8668. }
  8669. }
  8670. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8671. const ackUserWrite = operation;
  8672. if (!ackUserWrite.revert) {
  8673. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8674. }
  8675. else {
  8676. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8677. }
  8678. }
  8679. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8680. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8681. }
  8682. else {
  8683. throw assertionError('Unknown operation type: ' + operation.type);
  8684. }
  8685. const changes = accumulator.getChanges();
  8686. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8687. return { viewCache: newViewCache, changes };
  8688. }
  8689. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8690. const eventSnap = newViewCache.eventCache;
  8691. if (eventSnap.isFullyInitialized()) {
  8692. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8693. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8694. if (accumulator.length > 0 ||
  8695. !oldViewCache.eventCache.isFullyInitialized() ||
  8696. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8697. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8698. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8699. }
  8700. }
  8701. }
  8702. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8703. const oldEventSnap = viewCache.eventCache;
  8704. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8705. // we have a shadowing write, ignore changes
  8706. return viewCache;
  8707. }
  8708. else {
  8709. let newEventCache, serverNode;
  8710. if (pathIsEmpty(changePath)) {
  8711. // TODO: figure out how this plays with "sliding ack windows"
  8712. assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8713. if (viewCache.serverCache.isFiltered()) {
  8714. // We need to special case this, because we need to only apply writes to complete children, or
  8715. // we might end up raising events for incomplete children. If the server data is filtered deep
  8716. // writes cannot be guaranteed to be complete
  8717. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8718. const completeChildren = serverCache instanceof ChildrenNode
  8719. ? serverCache
  8720. : ChildrenNode.EMPTY_NODE;
  8721. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8722. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8723. }
  8724. else {
  8725. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8726. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8727. }
  8728. }
  8729. else {
  8730. const childKey = pathGetFront(changePath);
  8731. if (childKey === '.priority') {
  8732. assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8733. const oldEventNode = oldEventSnap.getNode();
  8734. serverNode = viewCache.serverCache.getNode();
  8735. // we might have overwrites for this priority
  8736. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8737. if (updatedPriority != null) {
  8738. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8739. }
  8740. else {
  8741. // priority didn't change, keep old node
  8742. newEventCache = oldEventSnap.getNode();
  8743. }
  8744. }
  8745. else {
  8746. const childChangePath = pathPopFront(changePath);
  8747. // update child
  8748. let newEventChild;
  8749. if (oldEventSnap.isCompleteForChild(childKey)) {
  8750. serverNode = viewCache.serverCache.getNode();
  8751. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8752. if (eventChildUpdate != null) {
  8753. newEventChild = oldEventSnap
  8754. .getNode()
  8755. .getImmediateChild(childKey)
  8756. .updateChild(childChangePath, eventChildUpdate);
  8757. }
  8758. else {
  8759. // Nothing changed, just keep the old child
  8760. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8761. }
  8762. }
  8763. else {
  8764. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8765. }
  8766. if (newEventChild != null) {
  8767. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8768. }
  8769. else {
  8770. // no complete child available or no change
  8771. newEventCache = oldEventSnap.getNode();
  8772. }
  8773. }
  8774. }
  8775. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8776. }
  8777. }
  8778. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8779. const oldServerSnap = oldViewCache.serverCache;
  8780. let newServerCache;
  8781. const serverFilter = filterServerNode
  8782. ? viewProcessor.filter
  8783. : viewProcessor.filter.getIndexedFilter();
  8784. if (pathIsEmpty(changePath)) {
  8785. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8786. }
  8787. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8788. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8789. const newServerNode = oldServerSnap
  8790. .getNode()
  8791. .updateChild(changePath, changedSnap);
  8792. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8793. }
  8794. else {
  8795. const childKey = pathGetFront(changePath);
  8796. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8797. pathGetLength(changePath) > 1) {
  8798. // We don't update incomplete nodes with updates intended for other listeners
  8799. return oldViewCache;
  8800. }
  8801. const childChangePath = pathPopFront(changePath);
  8802. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8803. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8804. if (childKey === '.priority') {
  8805. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8806. }
  8807. else {
  8808. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8809. }
  8810. }
  8811. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8812. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8813. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8814. }
  8815. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8816. const oldEventSnap = oldViewCache.eventCache;
  8817. let newViewCache, newEventCache;
  8818. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8819. if (pathIsEmpty(changePath)) {
  8820. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8821. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8822. }
  8823. else {
  8824. const childKey = pathGetFront(changePath);
  8825. if (childKey === '.priority') {
  8826. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8827. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8828. }
  8829. else {
  8830. const childChangePath = pathPopFront(changePath);
  8831. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8832. let newChild;
  8833. if (pathIsEmpty(childChangePath)) {
  8834. // Child overwrite, we can replace the child
  8835. newChild = changedSnap;
  8836. }
  8837. else {
  8838. const childNode = source.getCompleteChild(childKey);
  8839. if (childNode != null) {
  8840. if (pathGetBack(childChangePath) === '.priority' &&
  8841. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8842. // This is a priority update on an empty node. If this node exists on the server, the
  8843. // server will send down the priority in the update, so ignore for now
  8844. newChild = childNode;
  8845. }
  8846. else {
  8847. newChild = childNode.updateChild(childChangePath, changedSnap);
  8848. }
  8849. }
  8850. else {
  8851. // There is no complete child node available
  8852. newChild = ChildrenNode.EMPTY_NODE;
  8853. }
  8854. }
  8855. if (!oldChild.equals(newChild)) {
  8856. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8857. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8858. }
  8859. else {
  8860. newViewCache = oldViewCache;
  8861. }
  8862. }
  8863. }
  8864. return newViewCache;
  8865. }
  8866. function viewProcessorCacheHasChild(viewCache, childKey) {
  8867. return viewCache.eventCache.isCompleteForChild(childKey);
  8868. }
  8869. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8870. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8871. // window leaving room for new items. It's important we process these changes first, so we
  8872. // iterate the changes twice, first processing any that affect items currently in view.
  8873. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8874. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8875. // not the other.
  8876. let curViewCache = viewCache;
  8877. changedChildren.foreach((relativePath, childNode) => {
  8878. const writePath = pathChild(path, relativePath);
  8879. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8880. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8881. }
  8882. });
  8883. changedChildren.foreach((relativePath, childNode) => {
  8884. const writePath = pathChild(path, relativePath);
  8885. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8886. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8887. }
  8888. });
  8889. return curViewCache;
  8890. }
  8891. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8892. merge.foreach((relativePath, childNode) => {
  8893. node = node.updateChild(relativePath, childNode);
  8894. });
  8895. return node;
  8896. }
  8897. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8898. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8899. // wait for the complete data update coming soon.
  8900. if (viewCache.serverCache.getNode().isEmpty() &&
  8901. !viewCache.serverCache.isFullyInitialized()) {
  8902. return viewCache;
  8903. }
  8904. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8905. // window leaving room for new items. It's important we process these changes first, so we
  8906. // iterate the changes twice, first processing any that affect items currently in view.
  8907. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8908. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8909. // not the other.
  8910. let curViewCache = viewCache;
  8911. let viewMergeTree;
  8912. if (pathIsEmpty(path)) {
  8913. viewMergeTree = changedChildren;
  8914. }
  8915. else {
  8916. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8917. }
  8918. const serverNode = viewCache.serverCache.getNode();
  8919. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8920. if (serverNode.hasChild(childKey)) {
  8921. const serverChild = viewCache.serverCache
  8922. .getNode()
  8923. .getImmediateChild(childKey);
  8924. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8925. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8926. }
  8927. });
  8928. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8929. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8930. childMergeTree.value === null;
  8931. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8932. const serverChild = viewCache.serverCache
  8933. .getNode()
  8934. .getImmediateChild(childKey);
  8935. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8936. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8937. }
  8938. });
  8939. return curViewCache;
  8940. }
  8941. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8942. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8943. return viewCache;
  8944. }
  8945. // Only filter server node if it is currently filtered
  8946. const filterServerNode = viewCache.serverCache.isFiltered();
  8947. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8948. // now that it won't be shadowed.
  8949. const serverCache = viewCache.serverCache;
  8950. if (affectedTree.value != null) {
  8951. // This is an overwrite.
  8952. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8953. serverCache.isCompleteForPath(ackPath)) {
  8954. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8955. }
  8956. else if (pathIsEmpty(ackPath)) {
  8957. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8958. // should just re-apply whatever we have in our cache as a merge.
  8959. let changedChildren = new ImmutableTree(null);
  8960. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8961. changedChildren = changedChildren.set(new Path(name), node);
  8962. });
  8963. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8964. }
  8965. else {
  8966. return viewCache;
  8967. }
  8968. }
  8969. else {
  8970. // This is a merge.
  8971. let changedChildren = new ImmutableTree(null);
  8972. affectedTree.foreach((mergePath, value) => {
  8973. const serverCachePath = pathChild(ackPath, mergePath);
  8974. if (serverCache.isCompleteForPath(serverCachePath)) {
  8975. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8976. }
  8977. });
  8978. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8979. }
  8980. }
  8981. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8982. const oldServerNode = viewCache.serverCache;
  8983. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8984. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8985. }
  8986. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8987. let complete;
  8988. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8989. return viewCache;
  8990. }
  8991. else {
  8992. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  8993. const oldEventCache = viewCache.eventCache.getNode();
  8994. let newEventCache;
  8995. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  8996. let newNode;
  8997. if (viewCache.serverCache.isFullyInitialized()) {
  8998. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8999. }
  9000. else {
  9001. const serverChildren = viewCache.serverCache.getNode();
  9002. assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9003. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9004. }
  9005. newNode = newNode;
  9006. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9007. }
  9008. else {
  9009. const childKey = pathGetFront(path);
  9010. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9011. if (newChild == null &&
  9012. viewCache.serverCache.isCompleteForChild(childKey)) {
  9013. newChild = oldEventCache.getImmediateChild(childKey);
  9014. }
  9015. if (newChild != null) {
  9016. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9017. }
  9018. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9019. // No complete child available, delete the existing one, if any
  9020. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9021. }
  9022. else {
  9023. newEventCache = oldEventCache;
  9024. }
  9025. if (newEventCache.isEmpty() &&
  9026. viewCache.serverCache.isFullyInitialized()) {
  9027. // We might have reverted all child writes. Maybe the old event was a leaf node
  9028. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9029. if (complete.isLeafNode()) {
  9030. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9031. }
  9032. }
  9033. }
  9034. complete =
  9035. viewCache.serverCache.isFullyInitialized() ||
  9036. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9037. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9038. }
  9039. }
  9040. /**
  9041. * @license
  9042. * Copyright 2017 Google LLC
  9043. *
  9044. * Licensed under the Apache License, Version 2.0 (the "License");
  9045. * you may not use this file except in compliance with the License.
  9046. * You may obtain a copy of the License at
  9047. *
  9048. * http://www.apache.org/licenses/LICENSE-2.0
  9049. *
  9050. * Unless required by applicable law or agreed to in writing, software
  9051. * distributed under the License is distributed on an "AS IS" BASIS,
  9052. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9053. * See the License for the specific language governing permissions and
  9054. * limitations under the License.
  9055. */
  9056. /**
  9057. * A view represents a specific location and query that has 1 or more event registrations.
  9058. *
  9059. * It does several things:
  9060. * - Maintains the list of event registrations for this location/query.
  9061. * - Maintains a cache of the data visible for this location/query.
  9062. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9063. * registrations returns the set of events to be raised.
  9064. */
  9065. class View {
  9066. constructor(query_, initialViewCache) {
  9067. this.query_ = query_;
  9068. this.eventRegistrations_ = [];
  9069. const params = this.query_._queryParams;
  9070. const indexFilter = new IndexedFilter(params.getIndex());
  9071. const filter = queryParamsGetNodeFilter(params);
  9072. this.processor_ = newViewProcessor(filter);
  9073. const initialServerCache = initialViewCache.serverCache;
  9074. const initialEventCache = initialViewCache.eventCache;
  9075. // Don't filter server node with other filter than index, wait for tagged listen
  9076. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9077. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9078. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9079. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9080. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9081. this.eventGenerator_ = new EventGenerator(this.query_);
  9082. }
  9083. get query() {
  9084. return this.query_;
  9085. }
  9086. }
  9087. function viewGetServerCache(view) {
  9088. return view.viewCache_.serverCache.getNode();
  9089. }
  9090. function viewGetCompleteNode(view) {
  9091. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9092. }
  9093. function viewGetCompleteServerCache(view, path) {
  9094. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9095. if (cache) {
  9096. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9097. // we need to see if it contains the child we're interested in.
  9098. if (view.query._queryParams.loadsAllData() ||
  9099. (!pathIsEmpty(path) &&
  9100. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9101. return cache.getChild(path);
  9102. }
  9103. }
  9104. return null;
  9105. }
  9106. function viewIsEmpty(view) {
  9107. return view.eventRegistrations_.length === 0;
  9108. }
  9109. function viewAddEventRegistration(view, eventRegistration) {
  9110. view.eventRegistrations_.push(eventRegistration);
  9111. }
  9112. /**
  9113. * @param eventRegistration - If null, remove all callbacks.
  9114. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9115. * @returns Cancel events, if cancelError was provided.
  9116. */
  9117. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9118. const cancelEvents = [];
  9119. if (cancelError) {
  9120. assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9121. const path = view.query._path;
  9122. view.eventRegistrations_.forEach(registration => {
  9123. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9124. if (maybeEvent) {
  9125. cancelEvents.push(maybeEvent);
  9126. }
  9127. });
  9128. }
  9129. if (eventRegistration) {
  9130. let remaining = [];
  9131. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9132. const existing = view.eventRegistrations_[i];
  9133. if (!existing.matches(eventRegistration)) {
  9134. remaining.push(existing);
  9135. }
  9136. else if (eventRegistration.hasAnyCallback()) {
  9137. // We're removing just this one
  9138. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9139. break;
  9140. }
  9141. }
  9142. view.eventRegistrations_ = remaining;
  9143. }
  9144. else {
  9145. view.eventRegistrations_ = [];
  9146. }
  9147. return cancelEvents;
  9148. }
  9149. /**
  9150. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9151. */
  9152. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9153. if (operation.type === OperationType.MERGE &&
  9154. operation.source.queryId !== null) {
  9155. assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9156. assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9157. }
  9158. const oldViewCache = view.viewCache_;
  9159. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9160. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9161. assert(result.viewCache.serverCache.isFullyInitialized() ||
  9162. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9163. view.viewCache_ = result.viewCache;
  9164. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9165. }
  9166. function viewGetInitialEvents(view, registration) {
  9167. const eventSnap = view.viewCache_.eventCache;
  9168. const initialChanges = [];
  9169. if (!eventSnap.getNode().isLeafNode()) {
  9170. const eventNode = eventSnap.getNode();
  9171. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9172. initialChanges.push(changeChildAdded(key, childNode));
  9173. });
  9174. }
  9175. if (eventSnap.isFullyInitialized()) {
  9176. initialChanges.push(changeValue(eventSnap.getNode()));
  9177. }
  9178. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9179. }
  9180. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9181. const registrations = eventRegistration
  9182. ? [eventRegistration]
  9183. : view.eventRegistrations_;
  9184. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9185. }
  9186. /**
  9187. * @license
  9188. * Copyright 2017 Google LLC
  9189. *
  9190. * Licensed under the Apache License, Version 2.0 (the "License");
  9191. * you may not use this file except in compliance with the License.
  9192. * You may obtain a copy of the License at
  9193. *
  9194. * http://www.apache.org/licenses/LICENSE-2.0
  9195. *
  9196. * Unless required by applicable law or agreed to in writing, software
  9197. * distributed under the License is distributed on an "AS IS" BASIS,
  9198. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9199. * See the License for the specific language governing permissions and
  9200. * limitations under the License.
  9201. */
  9202. let referenceConstructor$1;
  9203. /**
  9204. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9205. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9206. * and user writes (set, transaction, update).
  9207. *
  9208. * It's responsible for:
  9209. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9210. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9211. * applyUserOverwrite, etc.)
  9212. */
  9213. class SyncPoint {
  9214. constructor() {
  9215. /**
  9216. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9217. * queryId and the value is the View for that query.
  9218. *
  9219. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9220. */
  9221. this.views = new Map();
  9222. }
  9223. }
  9224. function syncPointSetReferenceConstructor(val) {
  9225. assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9226. referenceConstructor$1 = val;
  9227. }
  9228. function syncPointGetReferenceConstructor() {
  9229. assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9230. return referenceConstructor$1;
  9231. }
  9232. function syncPointIsEmpty(syncPoint) {
  9233. return syncPoint.views.size === 0;
  9234. }
  9235. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9236. const queryId = operation.source.queryId;
  9237. if (queryId !== null) {
  9238. const view = syncPoint.views.get(queryId);
  9239. assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9240. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9241. }
  9242. else {
  9243. let events = [];
  9244. for (const view of syncPoint.views.values()) {
  9245. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9246. }
  9247. return events;
  9248. }
  9249. }
  9250. /**
  9251. * Get a view for the specified query.
  9252. *
  9253. * @param query - The query to return a view for
  9254. * @param writesCache
  9255. * @param serverCache
  9256. * @param serverCacheComplete
  9257. * @returns Events to raise.
  9258. */
  9259. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9260. const queryId = query._queryIdentifier;
  9261. const view = syncPoint.views.get(queryId);
  9262. if (!view) {
  9263. // TODO: make writesCache take flag for complete server node
  9264. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9265. let eventCacheComplete = false;
  9266. if (eventCache) {
  9267. eventCacheComplete = true;
  9268. }
  9269. else if (serverCache instanceof ChildrenNode) {
  9270. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9271. eventCacheComplete = false;
  9272. }
  9273. else {
  9274. eventCache = ChildrenNode.EMPTY_NODE;
  9275. eventCacheComplete = false;
  9276. }
  9277. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9278. return new View(query, viewCache);
  9279. }
  9280. return view;
  9281. }
  9282. /**
  9283. * Add an event callback for the specified query.
  9284. *
  9285. * @param query
  9286. * @param eventRegistration
  9287. * @param writesCache
  9288. * @param serverCache - Complete server cache, if we have it.
  9289. * @param serverCacheComplete
  9290. * @returns Events to raise.
  9291. */
  9292. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9293. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9294. if (!syncPoint.views.has(query._queryIdentifier)) {
  9295. syncPoint.views.set(query._queryIdentifier, view);
  9296. }
  9297. // This is guaranteed to exist now, we just created anything that was missing
  9298. viewAddEventRegistration(view, eventRegistration);
  9299. return viewGetInitialEvents(view, eventRegistration);
  9300. }
  9301. /**
  9302. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9303. *
  9304. * If query is the default query, we'll check all views for the specified eventRegistration.
  9305. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9306. *
  9307. * @param eventRegistration - If null, remove all callbacks.
  9308. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9309. * @returns removed queries and any cancel events
  9310. */
  9311. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9312. const queryId = query._queryIdentifier;
  9313. const removed = [];
  9314. let cancelEvents = [];
  9315. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9316. if (queryId === 'default') {
  9317. // When you do ref.off(...), we search all views for the registration to remove.
  9318. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9319. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9320. if (viewIsEmpty(view)) {
  9321. syncPoint.views.delete(viewQueryId);
  9322. // We'll deal with complete views later.
  9323. if (!view.query._queryParams.loadsAllData()) {
  9324. removed.push(view.query);
  9325. }
  9326. }
  9327. }
  9328. }
  9329. else {
  9330. // remove the callback from the specific view.
  9331. const view = syncPoint.views.get(queryId);
  9332. if (view) {
  9333. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9334. if (viewIsEmpty(view)) {
  9335. syncPoint.views.delete(queryId);
  9336. // We'll deal with complete views later.
  9337. if (!view.query._queryParams.loadsAllData()) {
  9338. removed.push(view.query);
  9339. }
  9340. }
  9341. }
  9342. }
  9343. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9344. // We removed our last complete view.
  9345. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9346. }
  9347. return { removed, events: cancelEvents };
  9348. }
  9349. function syncPointGetQueryViews(syncPoint) {
  9350. const result = [];
  9351. for (const view of syncPoint.views.values()) {
  9352. if (!view.query._queryParams.loadsAllData()) {
  9353. result.push(view);
  9354. }
  9355. }
  9356. return result;
  9357. }
  9358. /**
  9359. * @param path - The path to the desired complete snapshot
  9360. * @returns A complete cache, if it exists
  9361. */
  9362. function syncPointGetCompleteServerCache(syncPoint, path) {
  9363. let serverCache = null;
  9364. for (const view of syncPoint.views.values()) {
  9365. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9366. }
  9367. return serverCache;
  9368. }
  9369. function syncPointViewForQuery(syncPoint, query) {
  9370. const params = query._queryParams;
  9371. if (params.loadsAllData()) {
  9372. return syncPointGetCompleteView(syncPoint);
  9373. }
  9374. else {
  9375. const queryId = query._queryIdentifier;
  9376. return syncPoint.views.get(queryId);
  9377. }
  9378. }
  9379. function syncPointViewExistsForQuery(syncPoint, query) {
  9380. return syncPointViewForQuery(syncPoint, query) != null;
  9381. }
  9382. function syncPointHasCompleteView(syncPoint) {
  9383. return syncPointGetCompleteView(syncPoint) != null;
  9384. }
  9385. function syncPointGetCompleteView(syncPoint) {
  9386. for (const view of syncPoint.views.values()) {
  9387. if (view.query._queryParams.loadsAllData()) {
  9388. return view;
  9389. }
  9390. }
  9391. return null;
  9392. }
  9393. /**
  9394. * @license
  9395. * Copyright 2017 Google LLC
  9396. *
  9397. * Licensed under the Apache License, Version 2.0 (the "License");
  9398. * you may not use this file except in compliance with the License.
  9399. * You may obtain a copy of the License at
  9400. *
  9401. * http://www.apache.org/licenses/LICENSE-2.0
  9402. *
  9403. * Unless required by applicable law or agreed to in writing, software
  9404. * distributed under the License is distributed on an "AS IS" BASIS,
  9405. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9406. * See the License for the specific language governing permissions and
  9407. * limitations under the License.
  9408. */
  9409. let referenceConstructor;
  9410. function syncTreeSetReferenceConstructor(val) {
  9411. assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9412. referenceConstructor = val;
  9413. }
  9414. function syncTreeGetReferenceConstructor() {
  9415. assert(referenceConstructor, 'Reference.ts has not been loaded');
  9416. return referenceConstructor;
  9417. }
  9418. /**
  9419. * Static tracker for next query tag.
  9420. */
  9421. let syncTreeNextQueryTag_ = 1;
  9422. /**
  9423. * SyncTree is the central class for managing event callback registration, data caching, views
  9424. * (query processing), and event generation. There are typically two SyncTree instances for
  9425. * each Repo, one for the normal Firebase data, and one for the .info data.
  9426. *
  9427. * It has a number of responsibilities, including:
  9428. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9429. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9430. * (applyUserOverwrite(), applyUserMerge()).
  9431. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9432. * applyServerMerge()).
  9433. * - Generating user-facing events for server and user changes (all of the apply* methods
  9434. * return the set of events that need to be raised as a result).
  9435. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9436. * to the correct set of paths and queries to satisfy the current set of user event
  9437. * callbacks (listens are started/stopped using the provided listenProvider).
  9438. *
  9439. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9440. * events are returned to the caller rather than raised synchronously.
  9441. *
  9442. */
  9443. class SyncTree {
  9444. /**
  9445. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9446. * to server data.
  9447. */
  9448. constructor(listenProvider_) {
  9449. this.listenProvider_ = listenProvider_;
  9450. /**
  9451. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9452. */
  9453. this.syncPointTree_ = new ImmutableTree(null);
  9454. /**
  9455. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9456. */
  9457. this.pendingWriteTree_ = newWriteTree();
  9458. this.tagToQueryMap = new Map();
  9459. this.queryToTagMap = new Map();
  9460. }
  9461. }
  9462. /**
  9463. * Apply the data changes for a user-generated set() or transaction() call.
  9464. *
  9465. * @returns Events to raise.
  9466. */
  9467. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9468. // Record pending write.
  9469. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9470. if (!visible) {
  9471. return [];
  9472. }
  9473. else {
  9474. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9475. }
  9476. }
  9477. /**
  9478. * Apply the data from a user-generated update() call
  9479. *
  9480. * @returns Events to raise.
  9481. */
  9482. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9483. // Record pending merge.
  9484. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9485. const changeTree = ImmutableTree.fromObject(changedChildren);
  9486. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9487. }
  9488. /**
  9489. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9490. *
  9491. * @param revert - True if the given write failed and needs to be reverted
  9492. * @returns Events to raise.
  9493. */
  9494. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9495. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9496. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9497. if (!needToReevaluate) {
  9498. return [];
  9499. }
  9500. else {
  9501. let affectedTree = new ImmutableTree(null);
  9502. if (write.snap != null) {
  9503. // overwrite
  9504. affectedTree = affectedTree.set(newEmptyPath(), true);
  9505. }
  9506. else {
  9507. each(write.children, (pathString) => {
  9508. affectedTree = affectedTree.set(new Path(pathString), true);
  9509. });
  9510. }
  9511. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9512. }
  9513. }
  9514. /**
  9515. * Apply new server data for the specified path..
  9516. *
  9517. * @returns Events to raise.
  9518. */
  9519. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9520. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9521. }
  9522. /**
  9523. * Apply new server data to be merged in at the specified path.
  9524. *
  9525. * @returns Events to raise.
  9526. */
  9527. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9528. const changeTree = ImmutableTree.fromObject(changedChildren);
  9529. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9530. }
  9531. /**
  9532. * Apply a listen complete for a query
  9533. *
  9534. * @returns Events to raise.
  9535. */
  9536. function syncTreeApplyListenComplete(syncTree, path) {
  9537. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9538. }
  9539. /**
  9540. * Apply a listen complete for a tagged query
  9541. *
  9542. * @returns Events to raise.
  9543. */
  9544. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9545. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9546. if (queryKey) {
  9547. const r = syncTreeParseQueryKey_(queryKey);
  9548. const queryPath = r.path, queryId = r.queryId;
  9549. const relativePath = newRelativePath(queryPath, path);
  9550. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9551. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9552. }
  9553. else {
  9554. // We've already removed the query. No big deal, ignore the update
  9555. return [];
  9556. }
  9557. }
  9558. /**
  9559. * Remove event callback(s).
  9560. *
  9561. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9562. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9563. *
  9564. * @param eventRegistration - If null, all callbacks are removed.
  9565. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9566. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9567. * deduping needs to take place. This flag allows toggling of that behavior
  9568. * @returns Cancel events, if cancelError was provided.
  9569. */
  9570. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9571. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9572. const path = query._path;
  9573. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9574. let cancelEvents = [];
  9575. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9576. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9577. // not loadsAllData().
  9578. if (maybeSyncPoint &&
  9579. (query._queryIdentifier === 'default' ||
  9580. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9581. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9582. if (syncPointIsEmpty(maybeSyncPoint)) {
  9583. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9584. }
  9585. const removed = removedAndEvents.removed;
  9586. cancelEvents = removedAndEvents.events;
  9587. if (!skipListenerDedup) {
  9588. /**
  9589. * We may have just removed one of many listeners and can short-circuit this whole process
  9590. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9591. * properly set up.
  9592. */
  9593. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9594. // queryId === 'default'
  9595. const removingDefault = -1 !==
  9596. removed.findIndex(query => {
  9597. return query._queryParams.loadsAllData();
  9598. });
  9599. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9600. if (removingDefault && !covered) {
  9601. const subtree = syncTree.syncPointTree_.subtree(path);
  9602. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9603. // removal
  9604. if (!subtree.isEmpty()) {
  9605. // We need to fold over our subtree and collect the listeners to send
  9606. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9607. // Ok, we've collected all the listens we need. Set them up.
  9608. for (let i = 0; i < newViews.length; ++i) {
  9609. const view = newViews[i], newQuery = view.query;
  9610. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9611. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9612. }
  9613. }
  9614. // Otherwise there's nothing below us, so nothing we need to start listening on
  9615. }
  9616. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9617. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9618. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9619. if (!covered && removed.length > 0 && !cancelError) {
  9620. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9621. // default. Otherwise, we need to iterate through and cancel each individual query
  9622. if (removingDefault) {
  9623. // We don't tag default listeners
  9624. const defaultTag = null;
  9625. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9626. }
  9627. else {
  9628. removed.forEach((queryToRemove) => {
  9629. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9630. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9631. });
  9632. }
  9633. }
  9634. }
  9635. // Now, clear all of the tags we're tracking for the removed listens
  9636. syncTreeRemoveTags_(syncTree, removed);
  9637. }
  9638. return cancelEvents;
  9639. }
  9640. /**
  9641. * Apply new server data for the specified tagged query.
  9642. *
  9643. * @returns Events to raise.
  9644. */
  9645. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9646. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9647. if (queryKey != null) {
  9648. const r = syncTreeParseQueryKey_(queryKey);
  9649. const queryPath = r.path, queryId = r.queryId;
  9650. const relativePath = newRelativePath(queryPath, path);
  9651. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9652. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9653. }
  9654. else {
  9655. // Query must have been removed already
  9656. return [];
  9657. }
  9658. }
  9659. /**
  9660. * Apply server data to be merged in for the specified tagged query.
  9661. *
  9662. * @returns Events to raise.
  9663. */
  9664. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9665. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9666. if (queryKey) {
  9667. const r = syncTreeParseQueryKey_(queryKey);
  9668. const queryPath = r.path, queryId = r.queryId;
  9669. const relativePath = newRelativePath(queryPath, path);
  9670. const changeTree = ImmutableTree.fromObject(changedChildren);
  9671. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9672. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9673. }
  9674. else {
  9675. // We've already removed the query. No big deal, ignore the update
  9676. return [];
  9677. }
  9678. }
  9679. /**
  9680. * Add an event callback for the specified query.
  9681. *
  9682. * @returns Events to raise.
  9683. */
  9684. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9685. const path = query._path;
  9686. let serverCache = null;
  9687. let foundAncestorDefaultView = false;
  9688. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9689. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9690. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9691. const relativePath = newRelativePath(pathToSyncPoint, path);
  9692. serverCache =
  9693. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9694. foundAncestorDefaultView =
  9695. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9696. });
  9697. let syncPoint = syncTree.syncPointTree_.get(path);
  9698. if (!syncPoint) {
  9699. syncPoint = new SyncPoint();
  9700. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9701. }
  9702. else {
  9703. foundAncestorDefaultView =
  9704. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9705. serverCache =
  9706. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9707. }
  9708. let serverCacheComplete;
  9709. if (serverCache != null) {
  9710. serverCacheComplete = true;
  9711. }
  9712. else {
  9713. serverCacheComplete = false;
  9714. serverCache = ChildrenNode.EMPTY_NODE;
  9715. const subtree = syncTree.syncPointTree_.subtree(path);
  9716. subtree.foreachChild((childName, childSyncPoint) => {
  9717. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9718. if (completeCache) {
  9719. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9720. }
  9721. });
  9722. }
  9723. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9724. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9725. // We need to track a tag for this query
  9726. const queryKey = syncTreeMakeQueryKey_(query);
  9727. assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9728. const tag = syncTreeGetNextQueryTag_();
  9729. syncTree.queryToTagMap.set(queryKey, tag);
  9730. syncTree.tagToQueryMap.set(tag, queryKey);
  9731. }
  9732. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9733. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9734. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9735. const view = syncPointViewForQuery(syncPoint, query);
  9736. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9737. }
  9738. return events;
  9739. }
  9740. /**
  9741. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9742. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9743. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9744. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9745. *
  9746. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9747. *
  9748. * @param path - The path to the data we want
  9749. * @param writeIdsToExclude - A specific set to be excluded
  9750. */
  9751. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9752. const includeHiddenSets = true;
  9753. const writeTree = syncTree.pendingWriteTree_;
  9754. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9755. const relativePath = newRelativePath(pathSoFar, path);
  9756. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9757. if (serverCache) {
  9758. return serverCache;
  9759. }
  9760. });
  9761. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9762. }
  9763. function syncTreeGetServerValue(syncTree, query) {
  9764. const path = query._path;
  9765. let serverCache = null;
  9766. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9767. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9768. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9769. const relativePath = newRelativePath(pathToSyncPoint, path);
  9770. serverCache =
  9771. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9772. });
  9773. let syncPoint = syncTree.syncPointTree_.get(path);
  9774. if (!syncPoint) {
  9775. syncPoint = new SyncPoint();
  9776. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9777. }
  9778. else {
  9779. serverCache =
  9780. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9781. }
  9782. const serverCacheComplete = serverCache != null;
  9783. const serverCacheNode = serverCacheComplete
  9784. ? new CacheNode(serverCache, true, false)
  9785. : null;
  9786. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9787. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9788. return viewGetCompleteNode(view);
  9789. }
  9790. /**
  9791. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9792. *
  9793. * NOTES:
  9794. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9795. *
  9796. * - We call applyOperation() on each SyncPoint passing three things:
  9797. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9798. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9799. * 3. A snapshot Node with cached server data, if we have it.
  9800. *
  9801. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9802. */
  9803. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9804. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9805. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9806. }
  9807. /**
  9808. * Recursive helper for applyOperationToSyncPoints_
  9809. */
  9810. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9811. if (pathIsEmpty(operation.path)) {
  9812. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9813. }
  9814. else {
  9815. const syncPoint = syncPointTree.get(newEmptyPath());
  9816. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9817. if (serverCache == null && syncPoint != null) {
  9818. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9819. }
  9820. let events = [];
  9821. const childName = pathGetFront(operation.path);
  9822. const childOperation = operation.operationForChild(childName);
  9823. const childTree = syncPointTree.children.get(childName);
  9824. if (childTree && childOperation) {
  9825. const childServerCache = serverCache
  9826. ? serverCache.getImmediateChild(childName)
  9827. : null;
  9828. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9829. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9830. }
  9831. if (syncPoint) {
  9832. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9833. }
  9834. return events;
  9835. }
  9836. }
  9837. /**
  9838. * Recursive helper for applyOperationToSyncPoints_
  9839. */
  9840. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9841. const syncPoint = syncPointTree.get(newEmptyPath());
  9842. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9843. if (serverCache == null && syncPoint != null) {
  9844. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9845. }
  9846. let events = [];
  9847. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9848. const childServerCache = serverCache
  9849. ? serverCache.getImmediateChild(childName)
  9850. : null;
  9851. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9852. const childOperation = operation.operationForChild(childName);
  9853. if (childOperation) {
  9854. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9855. }
  9856. });
  9857. if (syncPoint) {
  9858. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9859. }
  9860. return events;
  9861. }
  9862. function syncTreeCreateListenerForView_(syncTree, view) {
  9863. const query = view.query;
  9864. const tag = syncTreeTagForQuery(syncTree, query);
  9865. return {
  9866. hashFn: () => {
  9867. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9868. return cache.hash();
  9869. },
  9870. onComplete: (status) => {
  9871. if (status === 'ok') {
  9872. if (tag) {
  9873. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9874. }
  9875. else {
  9876. return syncTreeApplyListenComplete(syncTree, query._path);
  9877. }
  9878. }
  9879. else {
  9880. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9881. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9882. const error = errorForServerCode(status, query);
  9883. return syncTreeRemoveEventRegistration(syncTree, query,
  9884. /*eventRegistration*/ null, error);
  9885. }
  9886. }
  9887. };
  9888. }
  9889. /**
  9890. * Return the tag associated with the given query.
  9891. */
  9892. function syncTreeTagForQuery(syncTree, query) {
  9893. const queryKey = syncTreeMakeQueryKey_(query);
  9894. return syncTree.queryToTagMap.get(queryKey);
  9895. }
  9896. /**
  9897. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9898. */
  9899. function syncTreeMakeQueryKey_(query) {
  9900. return query._path.toString() + '$' + query._queryIdentifier;
  9901. }
  9902. /**
  9903. * Return the query associated with the given tag, if we have one
  9904. */
  9905. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9906. return syncTree.tagToQueryMap.get(tag);
  9907. }
  9908. /**
  9909. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9910. */
  9911. function syncTreeParseQueryKey_(queryKey) {
  9912. const splitIndex = queryKey.indexOf('$');
  9913. assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9914. return {
  9915. queryId: queryKey.substr(splitIndex + 1),
  9916. path: new Path(queryKey.substr(0, splitIndex))
  9917. };
  9918. }
  9919. /**
  9920. * A helper method to apply tagged operations
  9921. */
  9922. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9923. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9924. assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9925. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9926. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9927. }
  9928. /**
  9929. * This collapses multiple unfiltered views into a single view, since we only need a single
  9930. * listener for them.
  9931. */
  9932. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9933. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9934. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9935. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9936. return [completeView];
  9937. }
  9938. else {
  9939. // No complete view here, flatten any deeper listens into an array
  9940. let views = [];
  9941. if (maybeChildSyncPoint) {
  9942. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9943. }
  9944. each(childMap, (_key, childViews) => {
  9945. views = views.concat(childViews);
  9946. });
  9947. return views;
  9948. }
  9949. });
  9950. }
  9951. /**
  9952. * Normalizes a query to a query we send the server for listening
  9953. *
  9954. * @returns The normalized query
  9955. */
  9956. function syncTreeQueryForListening_(query) {
  9957. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9958. // We treat queries that load all data as default queries
  9959. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9960. // from Query
  9961. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9962. }
  9963. else {
  9964. return query;
  9965. }
  9966. }
  9967. function syncTreeRemoveTags_(syncTree, queries) {
  9968. for (let j = 0; j < queries.length; ++j) {
  9969. const removedQuery = queries[j];
  9970. if (!removedQuery._queryParams.loadsAllData()) {
  9971. // We should have a tag for this
  9972. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9973. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9974. syncTree.queryToTagMap.delete(removedQueryKey);
  9975. syncTree.tagToQueryMap.delete(removedQueryTag);
  9976. }
  9977. }
  9978. }
  9979. /**
  9980. * Static accessor for query tags.
  9981. */
  9982. function syncTreeGetNextQueryTag_() {
  9983. return syncTreeNextQueryTag_++;
  9984. }
  9985. /**
  9986. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9987. *
  9988. * @returns This method can return events to support synchronous data sources
  9989. */
  9990. function syncTreeSetupListener_(syncTree, query, view) {
  9991. const path = query._path;
  9992. const tag = syncTreeTagForQuery(syncTree, query);
  9993. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9994. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  9995. const subtree = syncTree.syncPointTree_.subtree(path);
  9996. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  9997. // may need to shadow other listens as well.
  9998. if (tag) {
  9999. assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10000. }
  10001. else {
  10002. // Shadow everything at or below this location, this is a default listener.
  10003. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  10004. if (!pathIsEmpty(relativePath) &&
  10005. maybeChildSyncPoint &&
  10006. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10007. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10008. }
  10009. else {
  10010. // No default listener here, flatten any deeper queries into an array
  10011. let queries = [];
  10012. if (maybeChildSyncPoint) {
  10013. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10014. }
  10015. each(childMap, (_key, childQueries) => {
  10016. queries = queries.concat(childQueries);
  10017. });
  10018. return queries;
  10019. }
  10020. });
  10021. for (let i = 0; i < queriesToStop.length; ++i) {
  10022. const queryToStop = queriesToStop[i];
  10023. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10024. }
  10025. }
  10026. return events;
  10027. }
  10028. /**
  10029. * @license
  10030. * Copyright 2017 Google LLC
  10031. *
  10032. * Licensed under the Apache License, Version 2.0 (the "License");
  10033. * you may not use this file except in compliance with the License.
  10034. * You may obtain a copy of the License at
  10035. *
  10036. * http://www.apache.org/licenses/LICENSE-2.0
  10037. *
  10038. * Unless required by applicable law or agreed to in writing, software
  10039. * distributed under the License is distributed on an "AS IS" BASIS,
  10040. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10041. * See the License for the specific language governing permissions and
  10042. * limitations under the License.
  10043. */
  10044. class ExistingValueProvider {
  10045. constructor(node_) {
  10046. this.node_ = node_;
  10047. }
  10048. getImmediateChild(childName) {
  10049. const child = this.node_.getImmediateChild(childName);
  10050. return new ExistingValueProvider(child);
  10051. }
  10052. node() {
  10053. return this.node_;
  10054. }
  10055. }
  10056. class DeferredValueProvider {
  10057. constructor(syncTree, path) {
  10058. this.syncTree_ = syncTree;
  10059. this.path_ = path;
  10060. }
  10061. getImmediateChild(childName) {
  10062. const childPath = pathChild(this.path_, childName);
  10063. return new DeferredValueProvider(this.syncTree_, childPath);
  10064. }
  10065. node() {
  10066. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10067. }
  10068. }
  10069. /**
  10070. * Generate placeholders for deferred values.
  10071. */
  10072. const generateWithValues = function (values) {
  10073. values = values || {};
  10074. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10075. return values;
  10076. };
  10077. /**
  10078. * Value to use when firing local events. When writing server values, fire
  10079. * local events with an approximate value, otherwise return value as-is.
  10080. */
  10081. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10082. if (!value || typeof value !== 'object') {
  10083. return value;
  10084. }
  10085. assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10086. if (typeof value['.sv'] === 'string') {
  10087. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10088. }
  10089. else if (typeof value['.sv'] === 'object') {
  10090. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10091. }
  10092. else {
  10093. assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10094. }
  10095. };
  10096. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10097. switch (op) {
  10098. case 'timestamp':
  10099. return serverValues['timestamp'];
  10100. default:
  10101. assert(false, 'Unexpected server value: ' + op);
  10102. }
  10103. };
  10104. const resolveComplexDeferredValue = function (op, existing, unused) {
  10105. if (!op.hasOwnProperty('increment')) {
  10106. assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10107. }
  10108. const delta = op['increment'];
  10109. if (typeof delta !== 'number') {
  10110. assert(false, 'Unexpected increment value: ' + delta);
  10111. }
  10112. const existingNode = existing.node();
  10113. assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10114. // Incrementing a non-number sets the value to the incremented amount
  10115. if (!existingNode.isLeafNode()) {
  10116. return delta;
  10117. }
  10118. const leaf = existingNode;
  10119. const existingVal = leaf.getValue();
  10120. if (typeof existingVal !== 'number') {
  10121. return delta;
  10122. }
  10123. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10124. return existingVal + delta;
  10125. };
  10126. /**
  10127. * Recursively replace all deferred values and priorities in the tree with the
  10128. * specified generated replacement values.
  10129. * @param path - path to which write is relative
  10130. * @param node - new data written at path
  10131. * @param syncTree - current data
  10132. */
  10133. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10134. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10135. };
  10136. /**
  10137. * Recursively replace all deferred values and priorities in the node with the
  10138. * specified generated replacement values. If there are no server values in the node,
  10139. * it'll be returned as-is.
  10140. */
  10141. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10142. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10143. };
  10144. function resolveDeferredValue(node, existingVal, serverValues) {
  10145. const rawPri = node.getPriority().val();
  10146. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10147. let newNode;
  10148. if (node.isLeafNode()) {
  10149. const leafNode = node;
  10150. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10151. if (value !== leafNode.getValue() ||
  10152. priority !== leafNode.getPriority().val()) {
  10153. return new LeafNode(value, nodeFromJSON(priority));
  10154. }
  10155. else {
  10156. return node;
  10157. }
  10158. }
  10159. else {
  10160. const childrenNode = node;
  10161. newNode = childrenNode;
  10162. if (priority !== childrenNode.getPriority().val()) {
  10163. newNode = newNode.updatePriority(new LeafNode(priority));
  10164. }
  10165. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10166. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10167. if (newChildNode !== childNode) {
  10168. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10169. }
  10170. });
  10171. return newNode;
  10172. }
  10173. }
  10174. /**
  10175. * @license
  10176. * Copyright 2017 Google LLC
  10177. *
  10178. * Licensed under the Apache License, Version 2.0 (the "License");
  10179. * you may not use this file except in compliance with the License.
  10180. * You may obtain a copy of the License at
  10181. *
  10182. * http://www.apache.org/licenses/LICENSE-2.0
  10183. *
  10184. * Unless required by applicable law or agreed to in writing, software
  10185. * distributed under the License is distributed on an "AS IS" BASIS,
  10186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10187. * See the License for the specific language governing permissions and
  10188. * limitations under the License.
  10189. */
  10190. /**
  10191. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10192. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10193. * children.
  10194. */
  10195. class Tree {
  10196. /**
  10197. * @param name - Optional name of the node.
  10198. * @param parent - Optional parent node.
  10199. * @param node - Optional node to wrap.
  10200. */
  10201. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10202. this.name = name;
  10203. this.parent = parent;
  10204. this.node = node;
  10205. }
  10206. }
  10207. /**
  10208. * Returns a sub-Tree for the given path.
  10209. *
  10210. * @param pathObj - Path to look up.
  10211. * @returns Tree for path.
  10212. */
  10213. function treeSubTree(tree, pathObj) {
  10214. // TODO: Require pathObj to be Path?
  10215. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10216. let child = tree, next = pathGetFront(path);
  10217. while (next !== null) {
  10218. const childNode = safeGet(child.node.children, next) || {
  10219. children: {},
  10220. childCount: 0
  10221. };
  10222. child = new Tree(next, child, childNode);
  10223. path = pathPopFront(path);
  10224. next = pathGetFront(path);
  10225. }
  10226. return child;
  10227. }
  10228. /**
  10229. * Returns the data associated with this tree node.
  10230. *
  10231. * @returns The data or null if no data exists.
  10232. */
  10233. function treeGetValue(tree) {
  10234. return tree.node.value;
  10235. }
  10236. /**
  10237. * Sets data to this tree node.
  10238. *
  10239. * @param value - Value to set.
  10240. */
  10241. function treeSetValue(tree, value) {
  10242. tree.node.value = value;
  10243. treeUpdateParents(tree);
  10244. }
  10245. /**
  10246. * @returns Whether the tree has any children.
  10247. */
  10248. function treeHasChildren(tree) {
  10249. return tree.node.childCount > 0;
  10250. }
  10251. /**
  10252. * @returns Whethe rthe tree is empty (no value or children).
  10253. */
  10254. function treeIsEmpty(tree) {
  10255. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10256. }
  10257. /**
  10258. * Calls action for each child of this tree node.
  10259. *
  10260. * @param action - Action to be called for each child.
  10261. */
  10262. function treeForEachChild(tree, action) {
  10263. each(tree.node.children, (child, childTree) => {
  10264. action(new Tree(child, tree, childTree));
  10265. });
  10266. }
  10267. /**
  10268. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10269. *
  10270. * @param action - Action to be called for each child.
  10271. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10272. * false.
  10273. * @param childrenFirst - Whether to call action on children before calling it on
  10274. * parent.
  10275. */
  10276. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10277. if (includeSelf && !childrenFirst) {
  10278. action(tree);
  10279. }
  10280. treeForEachChild(tree, child => {
  10281. treeForEachDescendant(child, action, true, childrenFirst);
  10282. });
  10283. if (includeSelf && childrenFirst) {
  10284. action(tree);
  10285. }
  10286. }
  10287. /**
  10288. * Calls action on each ancestor node.
  10289. *
  10290. * @param action - Action to be called on each parent; return
  10291. * true to abort.
  10292. * @param includeSelf - Whether to call action on this node as well.
  10293. * @returns true if the action callback returned true.
  10294. */
  10295. function treeForEachAncestor(tree, action, includeSelf) {
  10296. let node = includeSelf ? tree : tree.parent;
  10297. while (node !== null) {
  10298. if (action(node)) {
  10299. return true;
  10300. }
  10301. node = node.parent;
  10302. }
  10303. return false;
  10304. }
  10305. /**
  10306. * @returns The path of this tree node, as a Path.
  10307. */
  10308. function treeGetPath(tree) {
  10309. return new Path(tree.parent === null
  10310. ? tree.name
  10311. : treeGetPath(tree.parent) + '/' + tree.name);
  10312. }
  10313. /**
  10314. * Adds or removes this child from its parent based on whether it's empty or not.
  10315. */
  10316. function treeUpdateParents(tree) {
  10317. if (tree.parent !== null) {
  10318. treeUpdateChild(tree.parent, tree.name, tree);
  10319. }
  10320. }
  10321. /**
  10322. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10323. *
  10324. * @param childName - The name of the child to update.
  10325. * @param child - The child to update.
  10326. */
  10327. function treeUpdateChild(tree, childName, child) {
  10328. const childEmpty = treeIsEmpty(child);
  10329. const childExists = contains(tree.node.children, childName);
  10330. if (childEmpty && childExists) {
  10331. delete tree.node.children[childName];
  10332. tree.node.childCount--;
  10333. treeUpdateParents(tree);
  10334. }
  10335. else if (!childEmpty && !childExists) {
  10336. tree.node.children[childName] = child.node;
  10337. tree.node.childCount++;
  10338. treeUpdateParents(tree);
  10339. }
  10340. }
  10341. /**
  10342. * @license
  10343. * Copyright 2017 Google LLC
  10344. *
  10345. * Licensed under the Apache License, Version 2.0 (the "License");
  10346. * you may not use this file except in compliance with the License.
  10347. * You may obtain a copy of the License at
  10348. *
  10349. * http://www.apache.org/licenses/LICENSE-2.0
  10350. *
  10351. * Unless required by applicable law or agreed to in writing, software
  10352. * distributed under the License is distributed on an "AS IS" BASIS,
  10353. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10354. * See the License for the specific language governing permissions and
  10355. * limitations under the License.
  10356. */
  10357. /**
  10358. * True for invalid Firebase keys
  10359. */
  10360. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10361. /**
  10362. * True for invalid Firebase paths.
  10363. * Allows '/' in paths.
  10364. */
  10365. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10366. /**
  10367. * Maximum number of characters to allow in leaf value
  10368. */
  10369. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10370. const isValidKey = function (key) {
  10371. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10372. };
  10373. const isValidPathString = function (pathString) {
  10374. return (typeof pathString === 'string' &&
  10375. pathString.length !== 0 &&
  10376. !INVALID_PATH_REGEX_.test(pathString));
  10377. };
  10378. const isValidRootPathString = function (pathString) {
  10379. if (pathString) {
  10380. // Allow '/.info/' at the beginning.
  10381. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10382. }
  10383. return isValidPathString(pathString);
  10384. };
  10385. const isValidPriority = function (priority) {
  10386. return (priority === null ||
  10387. typeof priority === 'string' ||
  10388. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10389. (priority &&
  10390. typeof priority === 'object' &&
  10391. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10392. contains(priority, '.sv')));
  10393. };
  10394. /**
  10395. * Pre-validate a datum passed as an argument to Firebase function.
  10396. */
  10397. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10398. if (optional && value === undefined) {
  10399. return;
  10400. }
  10401. validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
  10402. };
  10403. /**
  10404. * Validate a data object client-side before sending to server.
  10405. */
  10406. const validateFirebaseData = function (errorPrefix, data, path_) {
  10407. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10408. if (data === undefined) {
  10409. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10410. }
  10411. if (typeof data === 'function') {
  10412. throw new Error(errorPrefix +
  10413. 'contains a function ' +
  10414. validationPathToErrorString(path) +
  10415. ' with contents = ' +
  10416. data.toString());
  10417. }
  10418. if (isInvalidJSONNumber(data)) {
  10419. throw new Error(errorPrefix +
  10420. 'contains ' +
  10421. data.toString() +
  10422. ' ' +
  10423. validationPathToErrorString(path));
  10424. }
  10425. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10426. if (typeof data === 'string' &&
  10427. data.length > MAX_LEAF_SIZE_ / 3 &&
  10428. stringLength(data) > MAX_LEAF_SIZE_) {
  10429. throw new Error(errorPrefix +
  10430. 'contains a string greater than ' +
  10431. MAX_LEAF_SIZE_ +
  10432. ' utf8 bytes ' +
  10433. validationPathToErrorString(path) +
  10434. " ('" +
  10435. data.substring(0, 50) +
  10436. "...')");
  10437. }
  10438. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10439. // to save extra walking of large objects.
  10440. if (data && typeof data === 'object') {
  10441. let hasDotValue = false;
  10442. let hasActualChild = false;
  10443. each(data, (key, value) => {
  10444. if (key === '.value') {
  10445. hasDotValue = true;
  10446. }
  10447. else if (key !== '.priority' && key !== '.sv') {
  10448. hasActualChild = true;
  10449. if (!isValidKey(key)) {
  10450. throw new Error(errorPrefix +
  10451. ' contains an invalid key (' +
  10452. key +
  10453. ') ' +
  10454. validationPathToErrorString(path) +
  10455. '. Keys must be non-empty strings ' +
  10456. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10457. }
  10458. }
  10459. validationPathPush(path, key);
  10460. validateFirebaseData(errorPrefix, value, path);
  10461. validationPathPop(path);
  10462. });
  10463. if (hasDotValue && hasActualChild) {
  10464. throw new Error(errorPrefix +
  10465. ' contains ".value" child ' +
  10466. validationPathToErrorString(path) +
  10467. ' in addition to actual children.');
  10468. }
  10469. }
  10470. };
  10471. /**
  10472. * Pre-validate paths passed in the firebase function.
  10473. */
  10474. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10475. let i, curPath;
  10476. for (i = 0; i < mergePaths.length; i++) {
  10477. curPath = mergePaths[i];
  10478. const keys = pathSlice(curPath);
  10479. for (let j = 0; j < keys.length; j++) {
  10480. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10481. else if (!isValidKey(keys[j])) {
  10482. throw new Error(errorPrefix +
  10483. 'contains an invalid key (' +
  10484. keys[j] +
  10485. ') in path ' +
  10486. curPath.toString() +
  10487. '. Keys must be non-empty strings ' +
  10488. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10489. }
  10490. }
  10491. }
  10492. // Check that update keys are not descendants of each other.
  10493. // We rely on the property that sorting guarantees that ancestors come
  10494. // right before descendants.
  10495. mergePaths.sort(pathCompare);
  10496. let prevPath = null;
  10497. for (i = 0; i < mergePaths.length; i++) {
  10498. curPath = mergePaths[i];
  10499. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10500. throw new Error(errorPrefix +
  10501. 'contains a path ' +
  10502. prevPath.toString() +
  10503. ' that is ancestor of another path ' +
  10504. curPath.toString());
  10505. }
  10506. prevPath = curPath;
  10507. }
  10508. };
  10509. /**
  10510. * pre-validate an object passed as an argument to firebase function (
  10511. * must be an object - e.g. for firebase.update()).
  10512. */
  10513. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10514. if (optional && data === undefined) {
  10515. return;
  10516. }
  10517. const errorPrefix$1 = errorPrefix(fnName, 'values');
  10518. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10519. throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
  10520. }
  10521. const mergePaths = [];
  10522. each(data, (key, value) => {
  10523. const curPath = new Path(key);
  10524. validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
  10525. if (pathGetBack(curPath) === '.priority') {
  10526. if (!isValidPriority(value)) {
  10527. throw new Error(errorPrefix$1 +
  10528. "contains an invalid value for '" +
  10529. curPath.toString() +
  10530. "', which must be a valid " +
  10531. 'Firebase priority (a string, finite number, server value, or null).');
  10532. }
  10533. }
  10534. mergePaths.push(curPath);
  10535. });
  10536. validateFirebaseMergePaths(errorPrefix$1, mergePaths);
  10537. };
  10538. const validatePriority = function (fnName, priority, optional) {
  10539. if (optional && priority === undefined) {
  10540. return;
  10541. }
  10542. if (isInvalidJSONNumber(priority)) {
  10543. throw new Error(errorPrefix(fnName, 'priority') +
  10544. 'is ' +
  10545. priority.toString() +
  10546. ', but must be a valid Firebase priority (a string, finite number, ' +
  10547. 'server value, or null).');
  10548. }
  10549. // Special case to allow importing data with a .sv.
  10550. if (!isValidPriority(priority)) {
  10551. throw new Error(errorPrefix(fnName, 'priority') +
  10552. 'must be a valid Firebase priority ' +
  10553. '(a string, finite number, server value, or null).');
  10554. }
  10555. };
  10556. const validateKey = function (fnName, argumentName, key, optional) {
  10557. if (optional && key === undefined) {
  10558. return;
  10559. }
  10560. if (!isValidKey(key)) {
  10561. throw new Error(errorPrefix(fnName, argumentName) +
  10562. 'was an invalid key = "' +
  10563. key +
  10564. '". Firebase keys must be non-empty strings and ' +
  10565. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10566. }
  10567. };
  10568. /**
  10569. * @internal
  10570. */
  10571. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10572. if (optional && pathString === undefined) {
  10573. return;
  10574. }
  10575. if (!isValidPathString(pathString)) {
  10576. throw new Error(errorPrefix(fnName, argumentName) +
  10577. 'was an invalid path = "' +
  10578. pathString +
  10579. '". Paths must be non-empty strings and ' +
  10580. 'can\'t contain ".", "#", "$", "[", or "]"');
  10581. }
  10582. };
  10583. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10584. if (pathString) {
  10585. // Allow '/.info/' at the beginning.
  10586. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10587. }
  10588. validatePathString(fnName, argumentName, pathString, optional);
  10589. };
  10590. /**
  10591. * @internal
  10592. */
  10593. const validateWritablePath = function (fnName, path) {
  10594. if (pathGetFront(path) === '.info') {
  10595. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10596. }
  10597. };
  10598. const validateUrl = function (fnName, parsedUrl) {
  10599. // TODO = Validate server better.
  10600. const pathString = parsedUrl.path.toString();
  10601. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10602. parsedUrl.repoInfo.host.length === 0 ||
  10603. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10604. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10605. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10606. throw new Error(errorPrefix(fnName, 'url') +
  10607. 'must be a valid firebase URL and ' +
  10608. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10609. }
  10610. };
  10611. /**
  10612. * @license
  10613. * Copyright 2017 Google LLC
  10614. *
  10615. * Licensed under the Apache License, Version 2.0 (the "License");
  10616. * you may not use this file except in compliance with the License.
  10617. * You may obtain a copy of the License at
  10618. *
  10619. * http://www.apache.org/licenses/LICENSE-2.0
  10620. *
  10621. * Unless required by applicable law or agreed to in writing, software
  10622. * distributed under the License is distributed on an "AS IS" BASIS,
  10623. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10624. * See the License for the specific language governing permissions and
  10625. * limitations under the License.
  10626. */
  10627. /**
  10628. * The event queue serves a few purposes:
  10629. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10630. * events being queued.
  10631. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10632. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10633. * left off, ensuring that the events are still raised synchronously and in order.
  10634. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10635. * events are raised synchronously.
  10636. *
  10637. * NOTE: This can all go away if/when we move to async events.
  10638. *
  10639. */
  10640. class EventQueue {
  10641. constructor() {
  10642. this.eventLists_ = [];
  10643. /**
  10644. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10645. */
  10646. this.recursionDepth_ = 0;
  10647. }
  10648. }
  10649. /**
  10650. * @param eventDataList - The new events to queue.
  10651. */
  10652. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10653. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10654. let currList = null;
  10655. for (let i = 0; i < eventDataList.length; i++) {
  10656. const data = eventDataList[i];
  10657. const path = data.getPath();
  10658. if (currList !== null && !pathEquals(path, currList.path)) {
  10659. eventQueue.eventLists_.push(currList);
  10660. currList = null;
  10661. }
  10662. if (currList === null) {
  10663. currList = { events: [], path };
  10664. }
  10665. currList.events.push(data);
  10666. }
  10667. if (currList) {
  10668. eventQueue.eventLists_.push(currList);
  10669. }
  10670. }
  10671. /**
  10672. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10673. * for the specified path.
  10674. *
  10675. * It is assumed that the new events are all for the specified path.
  10676. *
  10677. * @param path - The path to raise events for.
  10678. * @param eventDataList - The new events to raise.
  10679. */
  10680. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10681. eventQueueQueueEvents(eventQueue, eventDataList);
  10682. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10683. }
  10684. /**
  10685. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10686. * locations related to the specified change path (i.e. all ancestors and descendants).
  10687. *
  10688. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10689. *
  10690. * @param changedPath - The path to raise events for.
  10691. * @param eventDataList - The events to raise
  10692. */
  10693. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10694. eventQueueQueueEvents(eventQueue, eventDataList);
  10695. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10696. pathContains(changedPath, eventPath));
  10697. }
  10698. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10699. eventQueue.recursionDepth_++;
  10700. let sentAll = true;
  10701. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10702. const eventList = eventQueue.eventLists_[i];
  10703. if (eventList) {
  10704. const eventPath = eventList.path;
  10705. if (predicate(eventPath)) {
  10706. eventListRaise(eventQueue.eventLists_[i]);
  10707. eventQueue.eventLists_[i] = null;
  10708. }
  10709. else {
  10710. sentAll = false;
  10711. }
  10712. }
  10713. }
  10714. if (sentAll) {
  10715. eventQueue.eventLists_ = [];
  10716. }
  10717. eventQueue.recursionDepth_--;
  10718. }
  10719. /**
  10720. * Iterates through the list and raises each event
  10721. */
  10722. function eventListRaise(eventList) {
  10723. for (let i = 0; i < eventList.events.length; i++) {
  10724. const eventData = eventList.events[i];
  10725. if (eventData !== null) {
  10726. eventList.events[i] = null;
  10727. const eventFn = eventData.getEventRunner();
  10728. if (logger) {
  10729. log('event: ' + eventData.toString());
  10730. }
  10731. exceptionGuard(eventFn);
  10732. }
  10733. }
  10734. }
  10735. /**
  10736. * @license
  10737. * Copyright 2017 Google LLC
  10738. *
  10739. * Licensed under the Apache License, Version 2.0 (the "License");
  10740. * you may not use this file except in compliance with the License.
  10741. * You may obtain a copy of the License at
  10742. *
  10743. * http://www.apache.org/licenses/LICENSE-2.0
  10744. *
  10745. * Unless required by applicable law or agreed to in writing, software
  10746. * distributed under the License is distributed on an "AS IS" BASIS,
  10747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10748. * See the License for the specific language governing permissions and
  10749. * limitations under the License.
  10750. */
  10751. const INTERRUPT_REASON = 'repo_interrupt';
  10752. /**
  10753. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10754. * things this ensure that if there's ever a bug causing a mismatch between
  10755. * client / server hashes for some data, we won't retry indefinitely.
  10756. */
  10757. const MAX_TRANSACTION_RETRIES = 25;
  10758. /**
  10759. * A connection to a single data repository.
  10760. */
  10761. class Repo {
  10762. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10763. this.repoInfo_ = repoInfo_;
  10764. this.forceRestClient_ = forceRestClient_;
  10765. this.authTokenProvider_ = authTokenProvider_;
  10766. this.appCheckProvider_ = appCheckProvider_;
  10767. this.dataUpdateCount = 0;
  10768. this.statsListener_ = null;
  10769. this.eventQueue_ = new EventQueue();
  10770. this.nextWriteId_ = 1;
  10771. this.interceptServerDataCallback_ = null;
  10772. /** A list of data pieces and paths to be set when this client disconnects. */
  10773. this.onDisconnect_ = newSparseSnapshotTree();
  10774. /** Stores queues of outstanding transactions for Firebase locations. */
  10775. this.transactionQueueTree_ = new Tree();
  10776. // TODO: This should be @private but it's used by test_access.js and internal.js
  10777. this.persistentConnection_ = null;
  10778. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10779. this.key = this.repoInfo_.toURLString();
  10780. }
  10781. /**
  10782. * @returns The URL corresponding to the root of this Firebase.
  10783. */
  10784. toString() {
  10785. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10786. }
  10787. }
  10788. function repoStart(repo, appId, authOverride) {
  10789. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10790. if (repo.forceRestClient_ || beingCrawled()) {
  10791. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10792. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10793. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10794. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10795. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10796. }
  10797. else {
  10798. // Validate authOverride
  10799. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10800. if (typeof authOverride !== 'object') {
  10801. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10802. }
  10803. try {
  10804. stringify(authOverride);
  10805. }
  10806. catch (e) {
  10807. throw new Error('Invalid authOverride provided: ' + e);
  10808. }
  10809. }
  10810. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10811. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10812. }, (connectStatus) => {
  10813. repoOnConnectStatus(repo, connectStatus);
  10814. }, (updates) => {
  10815. repoOnServerInfoUpdate(repo, updates);
  10816. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10817. repo.server_ = repo.persistentConnection_;
  10818. }
  10819. repo.authTokenProvider_.addTokenChangeListener(token => {
  10820. repo.server_.refreshAuthToken(token);
  10821. });
  10822. repo.appCheckProvider_.addTokenChangeListener(result => {
  10823. repo.server_.refreshAppCheckToken(result.token);
  10824. });
  10825. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10826. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10827. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10828. // Used for .info.
  10829. repo.infoData_ = new SnapshotHolder();
  10830. repo.infoSyncTree_ = new SyncTree({
  10831. startListening: (query, tag, currentHashFn, onComplete) => {
  10832. let infoEvents = [];
  10833. const node = repo.infoData_.getNode(query._path);
  10834. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10835. // on initial data...
  10836. if (!node.isEmpty()) {
  10837. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10838. setTimeout(() => {
  10839. onComplete('ok');
  10840. }, 0);
  10841. }
  10842. return infoEvents;
  10843. },
  10844. stopListening: () => { }
  10845. });
  10846. repoUpdateInfo(repo, 'connected', false);
  10847. repo.serverSyncTree_ = new SyncTree({
  10848. startListening: (query, tag, currentHashFn, onComplete) => {
  10849. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10850. const events = onComplete(status, data);
  10851. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10852. });
  10853. // No synchronous events for network-backed sync trees
  10854. return [];
  10855. },
  10856. stopListening: (query, tag) => {
  10857. repo.server_.unlisten(query, tag);
  10858. }
  10859. });
  10860. }
  10861. /**
  10862. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10863. */
  10864. function repoServerTime(repo) {
  10865. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10866. const offset = offsetNode.val() || 0;
  10867. return new Date().getTime() + offset;
  10868. }
  10869. /**
  10870. * Generate ServerValues using some variables from the repo object.
  10871. */
  10872. function repoGenerateServerValues(repo) {
  10873. return generateWithValues({
  10874. timestamp: repoServerTime(repo)
  10875. });
  10876. }
  10877. /**
  10878. * Called by realtime when we get new messages from the server.
  10879. */
  10880. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10881. // For testing.
  10882. repo.dataUpdateCount++;
  10883. const path = new Path(pathString);
  10884. data = repo.interceptServerDataCallback_
  10885. ? repo.interceptServerDataCallback_(pathString, data)
  10886. : data;
  10887. let events = [];
  10888. if (tag) {
  10889. if (isMerge) {
  10890. const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
  10891. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10892. }
  10893. else {
  10894. const taggedSnap = nodeFromJSON(data);
  10895. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10896. }
  10897. }
  10898. else if (isMerge) {
  10899. const changedChildren = map(data, (raw) => nodeFromJSON(raw));
  10900. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10901. }
  10902. else {
  10903. const snap = nodeFromJSON(data);
  10904. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10905. }
  10906. let affectedPath = path;
  10907. if (events.length > 0) {
  10908. // Since we have a listener outstanding for each transaction, receiving any events
  10909. // is a proxy for some change having occurred.
  10910. affectedPath = repoRerunTransactions(repo, path);
  10911. }
  10912. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10913. }
  10914. function repoOnConnectStatus(repo, connectStatus) {
  10915. repoUpdateInfo(repo, 'connected', connectStatus);
  10916. if (connectStatus === false) {
  10917. repoRunOnDisconnectEvents(repo);
  10918. }
  10919. }
  10920. function repoOnServerInfoUpdate(repo, updates) {
  10921. each(updates, (key, value) => {
  10922. repoUpdateInfo(repo, key, value);
  10923. });
  10924. }
  10925. function repoUpdateInfo(repo, pathString, value) {
  10926. const path = new Path('/.info/' + pathString);
  10927. const newNode = nodeFromJSON(value);
  10928. repo.infoData_.updateSnapshot(path, newNode);
  10929. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10930. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10931. }
  10932. function repoGetNextWriteId(repo) {
  10933. return repo.nextWriteId_++;
  10934. }
  10935. /**
  10936. * The purpose of `getValue` is to return the latest known value
  10937. * satisfying `query`.
  10938. *
  10939. * This method will first check for in-memory cached values
  10940. * belonging to active listeners. If they are found, such values
  10941. * are considered to be the most up-to-date.
  10942. *
  10943. * If the client is not connected, this method will wait until the
  10944. * repo has established a connection and then request the value for `query`.
  10945. * If the client is not able to retrieve the query result for another reason,
  10946. * it reports an error.
  10947. *
  10948. * @param query - The query to surface a value for.
  10949. */
  10950. function repoGetValue(repo, query, eventRegistration) {
  10951. // Only active queries are cached. There is no persisted cache.
  10952. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10953. if (cached != null) {
  10954. return Promise.resolve(cached);
  10955. }
  10956. return repo.server_.get(query).then(payload => {
  10957. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10958. /**
  10959. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10960. * Add an event registration,
  10961. * Update data at the path,
  10962. * Raise any events,
  10963. * Cleanup the SyncTree
  10964. */
  10965. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10966. let events;
  10967. if (query._queryParams.loadsAllData()) {
  10968. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10969. }
  10970. else {
  10971. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10972. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10973. }
  10974. /*
  10975. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10976. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10977. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10978. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10979. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10980. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10981. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10982. * ensure the corresponding child events will get fired.
  10983. */
  10984. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10985. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10986. return node;
  10987. }, err => {
  10988. repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
  10989. return Promise.reject(new Error(err));
  10990. });
  10991. }
  10992. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  10993. repoLog(repo, 'set', {
  10994. path: path.toString(),
  10995. value: newVal,
  10996. priority: newPriority
  10997. });
  10998. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  10999. // (b) store unresolved paths on JSON parse
  11000. const serverValues = repoGenerateServerValues(repo);
  11001. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11002. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11003. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11004. const writeId = repoGetNextWriteId(repo);
  11005. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11006. eventQueueQueueEvents(repo.eventQueue_, events);
  11007. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11008. const success = status === 'ok';
  11009. if (!success) {
  11010. warn('set at ' + path + ' failed: ' + status);
  11011. }
  11012. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11013. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11014. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11015. });
  11016. const affectedPath = repoAbortTransactions(repo, path);
  11017. repoRerunTransactions(repo, affectedPath);
  11018. // We queued the events above, so just flush the queue here
  11019. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11020. }
  11021. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11022. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11023. // Start with our existing data and merge each child into it.
  11024. let empty = true;
  11025. const serverValues = repoGenerateServerValues(repo);
  11026. const changedChildren = {};
  11027. each(childrenToMerge, (changedKey, changedValue) => {
  11028. empty = false;
  11029. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11030. });
  11031. if (!empty) {
  11032. const writeId = repoGetNextWriteId(repo);
  11033. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11034. eventQueueQueueEvents(repo.eventQueue_, events);
  11035. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11036. const success = status === 'ok';
  11037. if (!success) {
  11038. warn('update at ' + path + ' failed: ' + status);
  11039. }
  11040. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11041. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11042. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11043. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11044. });
  11045. each(childrenToMerge, (changedPath) => {
  11046. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11047. repoRerunTransactions(repo, affectedPath);
  11048. });
  11049. // We queued the events above, so just flush the queue here
  11050. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11051. }
  11052. else {
  11053. log("update() called with empty data. Don't do anything.");
  11054. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11055. }
  11056. }
  11057. /**
  11058. * Applies all of the changes stored up in the onDisconnect_ tree.
  11059. */
  11060. function repoRunOnDisconnectEvents(repo) {
  11061. repoLog(repo, 'onDisconnectEvents');
  11062. const serverValues = repoGenerateServerValues(repo);
  11063. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11064. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11065. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11066. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11067. });
  11068. let events = [];
  11069. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11070. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11071. const affectedPath = repoAbortTransactions(repo, path);
  11072. repoRerunTransactions(repo, affectedPath);
  11073. });
  11074. repo.onDisconnect_ = newSparseSnapshotTree();
  11075. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11076. }
  11077. function repoOnDisconnectCancel(repo, path, onComplete) {
  11078. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11079. if (status === 'ok') {
  11080. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11081. }
  11082. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11083. });
  11084. }
  11085. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11086. const newNode = nodeFromJSON(value);
  11087. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11088. if (status === 'ok') {
  11089. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11090. }
  11091. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11092. });
  11093. }
  11094. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11095. const newNode = nodeFromJSON(value, priority);
  11096. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11097. if (status === 'ok') {
  11098. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11099. }
  11100. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11101. });
  11102. }
  11103. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11104. if (isEmpty(childrenToMerge)) {
  11105. log("onDisconnect().update() called with empty data. Don't do anything.");
  11106. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11107. return;
  11108. }
  11109. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11110. if (status === 'ok') {
  11111. each(childrenToMerge, (childName, childNode) => {
  11112. const newChildNode = nodeFromJSON(childNode);
  11113. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11114. });
  11115. }
  11116. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11117. });
  11118. }
  11119. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11120. let events;
  11121. if (pathGetFront(query._path) === '.info') {
  11122. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11123. }
  11124. else {
  11125. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11126. }
  11127. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11128. }
  11129. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11130. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11131. // a little bit by handling the return values anyways.
  11132. let events;
  11133. if (pathGetFront(query._path) === '.info') {
  11134. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11135. }
  11136. else {
  11137. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11138. }
  11139. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11140. }
  11141. function repoInterrupt(repo) {
  11142. if (repo.persistentConnection_) {
  11143. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11144. }
  11145. }
  11146. function repoResume(repo) {
  11147. if (repo.persistentConnection_) {
  11148. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11149. }
  11150. }
  11151. function repoLog(repo, ...varArgs) {
  11152. let prefix = '';
  11153. if (repo.persistentConnection_) {
  11154. prefix = repo.persistentConnection_.id + ':';
  11155. }
  11156. log(prefix, ...varArgs);
  11157. }
  11158. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11159. if (callback) {
  11160. exceptionGuard(() => {
  11161. if (status === 'ok') {
  11162. callback(null);
  11163. }
  11164. else {
  11165. const code = (status || 'error').toUpperCase();
  11166. let message = code;
  11167. if (errorReason) {
  11168. message += ': ' + errorReason;
  11169. }
  11170. const error = new Error(message);
  11171. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11172. error.code = code;
  11173. callback(error);
  11174. }
  11175. });
  11176. }
  11177. }
  11178. /**
  11179. * Creates a new transaction, adds it to the transactions we're tracking, and
  11180. * sends it to the server if possible.
  11181. *
  11182. * @param path - Path at which to do transaction.
  11183. * @param transactionUpdate - Update callback.
  11184. * @param onComplete - Completion callback.
  11185. * @param unwatcher - Function that will be called when the transaction no longer
  11186. * need data updates for `path`.
  11187. * @param applyLocally - Whether or not to make intermediate results visible
  11188. */
  11189. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11190. repoLog(repo, 'transaction on ' + path);
  11191. // Initialize transaction.
  11192. const transaction = {
  11193. path,
  11194. update: transactionUpdate,
  11195. onComplete,
  11196. // One of TransactionStatus enums.
  11197. status: null,
  11198. // Used when combining transactions at different locations to figure out
  11199. // which one goes first.
  11200. order: LUIDGenerator(),
  11201. // Whether to raise local events for this transaction.
  11202. applyLocally,
  11203. // Count of how many times we've retried the transaction.
  11204. retryCount: 0,
  11205. // Function to call to clean up our .on() listener.
  11206. unwatcher,
  11207. // Stores why a transaction was aborted.
  11208. abortReason: null,
  11209. currentWriteId: null,
  11210. currentInputSnapshot: null,
  11211. currentOutputSnapshotRaw: null,
  11212. currentOutputSnapshotResolved: null
  11213. };
  11214. // Run transaction initially.
  11215. const currentState = repoGetLatestState(repo, path, undefined);
  11216. transaction.currentInputSnapshot = currentState;
  11217. const newVal = transaction.update(currentState.val());
  11218. if (newVal === undefined) {
  11219. // Abort transaction.
  11220. transaction.unwatcher();
  11221. transaction.currentOutputSnapshotRaw = null;
  11222. transaction.currentOutputSnapshotResolved = null;
  11223. if (transaction.onComplete) {
  11224. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11225. }
  11226. }
  11227. else {
  11228. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11229. // Mark as run and add to our queue.
  11230. transaction.status = 0 /* TransactionStatus.RUN */;
  11231. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11232. const nodeQueue = treeGetValue(queueNode) || [];
  11233. nodeQueue.push(transaction);
  11234. treeSetValue(queueNode, nodeQueue);
  11235. // Update visibleData and raise events
  11236. // Note: We intentionally raise events after updating all of our
  11237. // transaction state, since the user could start new transactions from the
  11238. // event callbacks.
  11239. let priorityForNode;
  11240. if (typeof newVal === 'object' &&
  11241. newVal !== null &&
  11242. contains(newVal, '.priority')) {
  11243. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11244. priorityForNode = safeGet(newVal, '.priority');
  11245. assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11246. 'Priority must be a valid string, finite number, server value, or null.');
  11247. }
  11248. else {
  11249. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11250. ChildrenNode.EMPTY_NODE;
  11251. priorityForNode = currentNode.getPriority().val();
  11252. }
  11253. const serverValues = repoGenerateServerValues(repo);
  11254. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11255. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11256. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11257. transaction.currentOutputSnapshotResolved = newNode;
  11258. transaction.currentWriteId = repoGetNextWriteId(repo);
  11259. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11260. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11261. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11262. }
  11263. }
  11264. /**
  11265. * @param excludeSets - A specific set to exclude
  11266. */
  11267. function repoGetLatestState(repo, path, excludeSets) {
  11268. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11269. ChildrenNode.EMPTY_NODE);
  11270. }
  11271. /**
  11272. * Sends any already-run transactions that aren't waiting for outstanding
  11273. * transactions to complete.
  11274. *
  11275. * Externally it's called with no arguments, but it calls itself recursively
  11276. * with a particular transactionQueueTree node to recurse through the tree.
  11277. *
  11278. * @param node - transactionQueueTree node to start at.
  11279. */
  11280. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11281. // Before recursing, make sure any completed transactions are removed.
  11282. if (!node) {
  11283. repoPruneCompletedTransactionsBelowNode(repo, node);
  11284. }
  11285. if (treeGetValue(node)) {
  11286. const queue = repoBuildTransactionQueue(repo, node);
  11287. assert(queue.length > 0, 'Sending zero length transaction queue');
  11288. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11289. // If they're all run (and not sent), we can send them. Else, we must wait.
  11290. if (allRun) {
  11291. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11292. }
  11293. }
  11294. else if (treeHasChildren(node)) {
  11295. treeForEachChild(node, childNode => {
  11296. repoSendReadyTransactions(repo, childNode);
  11297. });
  11298. }
  11299. }
  11300. /**
  11301. * Given a list of run transactions, send them to the server and then handle
  11302. * the result (success or failure).
  11303. *
  11304. * @param path - The location of the queue.
  11305. * @param queue - Queue of transactions under the specified location.
  11306. */
  11307. function repoSendTransactionQueue(repo, path, queue) {
  11308. // Mark transactions as sent and increment retry count!
  11309. const setsToIgnore = queue.map(txn => {
  11310. return txn.currentWriteId;
  11311. });
  11312. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11313. let snapToSend = latestState;
  11314. const latestHash = latestState.hash();
  11315. for (let i = 0; i < queue.length; i++) {
  11316. const txn = queue[i];
  11317. assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11318. txn.status = 1 /* TransactionStatus.SENT */;
  11319. txn.retryCount++;
  11320. const relativePath = newRelativePath(path, txn.path);
  11321. // If we've gotten to this point, the output snapshot must be defined.
  11322. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11323. }
  11324. const dataToSend = snapToSend.val(true);
  11325. const pathToSend = path;
  11326. // Send the put.
  11327. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11328. repoLog(repo, 'transaction put response', {
  11329. path: pathToSend.toString(),
  11330. status
  11331. });
  11332. let events = [];
  11333. if (status === 'ok') {
  11334. // Queue up the callbacks and fire them after cleaning up all of our
  11335. // transaction state, since the callback could trigger more
  11336. // transactions or sets.
  11337. const callbacks = [];
  11338. for (let i = 0; i < queue.length; i++) {
  11339. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11340. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11341. if (queue[i].onComplete) {
  11342. // We never unset the output snapshot, and given that this
  11343. // transaction is complete, it should be set
  11344. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11345. }
  11346. queue[i].unwatcher();
  11347. }
  11348. // Now remove the completed transactions.
  11349. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11350. // There may be pending transactions that we can now send.
  11351. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11352. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11353. // Finally, trigger onComplete callbacks.
  11354. for (let i = 0; i < callbacks.length; i++) {
  11355. exceptionGuard(callbacks[i]);
  11356. }
  11357. }
  11358. else {
  11359. // transactions are no longer sent. Update their status appropriately.
  11360. if (status === 'datastale') {
  11361. for (let i = 0; i < queue.length; i++) {
  11362. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11363. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11364. }
  11365. else {
  11366. queue[i].status = 0 /* TransactionStatus.RUN */;
  11367. }
  11368. }
  11369. }
  11370. else {
  11371. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11372. for (let i = 0; i < queue.length; i++) {
  11373. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11374. queue[i].abortReason = status;
  11375. }
  11376. }
  11377. repoRerunTransactions(repo, path);
  11378. }
  11379. }, latestHash);
  11380. }
  11381. /**
  11382. * Finds all transactions dependent on the data at changedPath and reruns them.
  11383. *
  11384. * Should be called any time cached data changes.
  11385. *
  11386. * Return the highest path that was affected by rerunning transactions. This
  11387. * is the path at which events need to be raised for.
  11388. *
  11389. * @param changedPath - The path in mergedData that changed.
  11390. * @returns The rootmost path that was affected by rerunning transactions.
  11391. */
  11392. function repoRerunTransactions(repo, changedPath) {
  11393. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11394. const path = treeGetPath(rootMostTransactionNode);
  11395. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11396. repoRerunTransactionQueue(repo, queue, path);
  11397. return path;
  11398. }
  11399. /**
  11400. * Does all the work of rerunning transactions (as well as cleans up aborted
  11401. * transactions and whatnot).
  11402. *
  11403. * @param queue - The queue of transactions to run.
  11404. * @param path - The path the queue is for.
  11405. */
  11406. function repoRerunTransactionQueue(repo, queue, path) {
  11407. if (queue.length === 0) {
  11408. return; // Nothing to do!
  11409. }
  11410. // Queue up the callbacks and fire them after cleaning up all of our
  11411. // transaction state, since the callback could trigger more transactions or
  11412. // sets.
  11413. const callbacks = [];
  11414. let events = [];
  11415. // Ignore all of the sets we're going to re-run.
  11416. const txnsToRerun = queue.filter(q => {
  11417. return q.status === 0 /* TransactionStatus.RUN */;
  11418. });
  11419. const setsToIgnore = txnsToRerun.map(q => {
  11420. return q.currentWriteId;
  11421. });
  11422. for (let i = 0; i < queue.length; i++) {
  11423. const transaction = queue[i];
  11424. const relativePath = newRelativePath(path, transaction.path);
  11425. let abortTransaction = false, abortReason;
  11426. assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11427. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11428. abortTransaction = true;
  11429. abortReason = transaction.abortReason;
  11430. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11431. }
  11432. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11433. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11434. abortTransaction = true;
  11435. abortReason = 'maxretry';
  11436. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11437. }
  11438. else {
  11439. // This code reruns a transaction
  11440. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11441. transaction.currentInputSnapshot = currentNode;
  11442. const newData = queue[i].update(currentNode.val());
  11443. if (newData !== undefined) {
  11444. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11445. let newDataNode = nodeFromJSON(newData);
  11446. const hasExplicitPriority = typeof newData === 'object' &&
  11447. newData != null &&
  11448. contains(newData, '.priority');
  11449. if (!hasExplicitPriority) {
  11450. // Keep the old priority if there wasn't a priority explicitly specified.
  11451. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11452. }
  11453. const oldWriteId = transaction.currentWriteId;
  11454. const serverValues = repoGenerateServerValues(repo);
  11455. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11456. transaction.currentOutputSnapshotRaw = newDataNode;
  11457. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11458. transaction.currentWriteId = repoGetNextWriteId(repo);
  11459. // Mutates setsToIgnore in place
  11460. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11461. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11462. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11463. }
  11464. else {
  11465. abortTransaction = true;
  11466. abortReason = 'nodata';
  11467. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11468. }
  11469. }
  11470. }
  11471. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11472. events = [];
  11473. if (abortTransaction) {
  11474. // Abort.
  11475. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11476. // Removing a listener can trigger pruning which can muck with
  11477. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11478. // until we're done.
  11479. (function (unwatcher) {
  11480. setTimeout(unwatcher, Math.floor(0));
  11481. })(queue[i].unwatcher);
  11482. if (queue[i].onComplete) {
  11483. if (abortReason === 'nodata') {
  11484. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11485. }
  11486. else {
  11487. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11488. }
  11489. }
  11490. }
  11491. }
  11492. // Clean up completed transactions.
  11493. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11494. // Now fire callbacks, now that we're in a good, known state.
  11495. for (let i = 0; i < callbacks.length; i++) {
  11496. exceptionGuard(callbacks[i]);
  11497. }
  11498. // Try to send the transaction result to the server.
  11499. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11500. }
  11501. /**
  11502. * Returns the rootmost ancestor node of the specified path that has a pending
  11503. * transaction on it, or just returns the node for the given path if there are
  11504. * no pending transactions on any ancestor.
  11505. *
  11506. * @param path - The location to start at.
  11507. * @returns The rootmost node with a transaction.
  11508. */
  11509. function repoGetAncestorTransactionNode(repo, path) {
  11510. let front;
  11511. // Start at the root and walk deeper into the tree towards path until we
  11512. // find a node with pending transactions.
  11513. let transactionNode = repo.transactionQueueTree_;
  11514. front = pathGetFront(path);
  11515. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11516. transactionNode = treeSubTree(transactionNode, front);
  11517. path = pathPopFront(path);
  11518. front = pathGetFront(path);
  11519. }
  11520. return transactionNode;
  11521. }
  11522. /**
  11523. * Builds the queue of all transactions at or below the specified
  11524. * transactionNode.
  11525. *
  11526. * @param transactionNode
  11527. * @returns The generated queue.
  11528. */
  11529. function repoBuildTransactionQueue(repo, transactionNode) {
  11530. // Walk any child transaction queues and aggregate them into a single queue.
  11531. const transactionQueue = [];
  11532. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11533. // Sort them by the order the transactions were created.
  11534. transactionQueue.sort((a, b) => a.order - b.order);
  11535. return transactionQueue;
  11536. }
  11537. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11538. const nodeQueue = treeGetValue(node);
  11539. if (nodeQueue) {
  11540. for (let i = 0; i < nodeQueue.length; i++) {
  11541. queue.push(nodeQueue[i]);
  11542. }
  11543. }
  11544. treeForEachChild(node, child => {
  11545. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11546. });
  11547. }
  11548. /**
  11549. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11550. */
  11551. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11552. const queue = treeGetValue(node);
  11553. if (queue) {
  11554. let to = 0;
  11555. for (let from = 0; from < queue.length; from++) {
  11556. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11557. queue[to] = queue[from];
  11558. to++;
  11559. }
  11560. }
  11561. queue.length = to;
  11562. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11563. }
  11564. treeForEachChild(node, childNode => {
  11565. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11566. });
  11567. }
  11568. /**
  11569. * Aborts all transactions on ancestors or descendants of the specified path.
  11570. * Called when doing a set() or update() since we consider them incompatible
  11571. * with transactions.
  11572. *
  11573. * @param path - Path for which we want to abort related transactions.
  11574. */
  11575. function repoAbortTransactions(repo, path) {
  11576. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11577. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11578. treeForEachAncestor(transactionNode, (node) => {
  11579. repoAbortTransactionsOnNode(repo, node);
  11580. });
  11581. repoAbortTransactionsOnNode(repo, transactionNode);
  11582. treeForEachDescendant(transactionNode, (node) => {
  11583. repoAbortTransactionsOnNode(repo, node);
  11584. });
  11585. return affectedPath;
  11586. }
  11587. /**
  11588. * Abort transactions stored in this transaction queue node.
  11589. *
  11590. * @param node - Node to abort transactions for.
  11591. */
  11592. function repoAbortTransactionsOnNode(repo, node) {
  11593. const queue = treeGetValue(node);
  11594. if (queue) {
  11595. // Queue up the callbacks and fire them after cleaning up all of our
  11596. // transaction state, since the callback could trigger more transactions
  11597. // or sets.
  11598. const callbacks = [];
  11599. // Go through queue. Any already-sent transactions must be marked for
  11600. // abort, while the unsent ones can be immediately aborted and removed.
  11601. let events = [];
  11602. let lastSent = -1;
  11603. for (let i = 0; i < queue.length; i++) {
  11604. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11605. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11606. assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11607. lastSent = i;
  11608. // Mark transaction for abort when it comes back.
  11609. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11610. queue[i].abortReason = 'set';
  11611. }
  11612. else {
  11613. assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11614. // We can abort it immediately.
  11615. queue[i].unwatcher();
  11616. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11617. if (queue[i].onComplete) {
  11618. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11619. }
  11620. }
  11621. }
  11622. if (lastSent === -1) {
  11623. // We're not waiting for any sent transactions. We can clear the queue.
  11624. treeSetValue(node, undefined);
  11625. }
  11626. else {
  11627. // Remove the transactions we aborted.
  11628. queue.length = lastSent + 1;
  11629. }
  11630. // Now fire the callbacks.
  11631. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11632. for (let i = 0; i < callbacks.length; i++) {
  11633. exceptionGuard(callbacks[i]);
  11634. }
  11635. }
  11636. }
  11637. /**
  11638. * @license
  11639. * Copyright 2017 Google LLC
  11640. *
  11641. * Licensed under the Apache License, Version 2.0 (the "License");
  11642. * you may not use this file except in compliance with the License.
  11643. * You may obtain a copy of the License at
  11644. *
  11645. * http://www.apache.org/licenses/LICENSE-2.0
  11646. *
  11647. * Unless required by applicable law or agreed to in writing, software
  11648. * distributed under the License is distributed on an "AS IS" BASIS,
  11649. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11650. * See the License for the specific language governing permissions and
  11651. * limitations under the License.
  11652. */
  11653. function decodePath(pathString) {
  11654. let pathStringDecoded = '';
  11655. const pieces = pathString.split('/');
  11656. for (let i = 0; i < pieces.length; i++) {
  11657. if (pieces[i].length > 0) {
  11658. let piece = pieces[i];
  11659. try {
  11660. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11661. }
  11662. catch (e) { }
  11663. pathStringDecoded += '/' + piece;
  11664. }
  11665. }
  11666. return pathStringDecoded;
  11667. }
  11668. /**
  11669. * @returns key value hash
  11670. */
  11671. function decodeQuery(queryString) {
  11672. const results = {};
  11673. if (queryString.charAt(0) === '?') {
  11674. queryString = queryString.substring(1);
  11675. }
  11676. for (const segment of queryString.split('&')) {
  11677. if (segment.length === 0) {
  11678. continue;
  11679. }
  11680. const kv = segment.split('=');
  11681. if (kv.length === 2) {
  11682. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11683. }
  11684. else {
  11685. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11686. }
  11687. }
  11688. return results;
  11689. }
  11690. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11691. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11692. if (parsedUrl.domain === 'firebase.com') {
  11693. fatal(parsedUrl.host +
  11694. ' is no longer supported. ' +
  11695. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11696. }
  11697. // Catch common error of uninitialized namespace value.
  11698. if ((!namespace || namespace === 'undefined') &&
  11699. parsedUrl.domain !== 'localhost') {
  11700. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11701. }
  11702. if (!parsedUrl.secure) {
  11703. warnIfPageIsSecure();
  11704. }
  11705. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11706. return {
  11707. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11708. /*persistenceKey=*/ '',
  11709. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11710. path: new Path(parsedUrl.pathString)
  11711. };
  11712. };
  11713. const parseDatabaseURL = function (dataURL) {
  11714. // Default to empty strings in the event of a malformed string.
  11715. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11716. // Always default to SSL, unless otherwise specified.
  11717. let secure = true, scheme = 'https', port = 443;
  11718. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11719. if (typeof dataURL === 'string') {
  11720. // Parse scheme.
  11721. let colonInd = dataURL.indexOf('//');
  11722. if (colonInd >= 0) {
  11723. scheme = dataURL.substring(0, colonInd - 1);
  11724. dataURL = dataURL.substring(colonInd + 2);
  11725. }
  11726. // Parse host, path, and query string.
  11727. let slashInd = dataURL.indexOf('/');
  11728. if (slashInd === -1) {
  11729. slashInd = dataURL.length;
  11730. }
  11731. let questionMarkInd = dataURL.indexOf('?');
  11732. if (questionMarkInd === -1) {
  11733. questionMarkInd = dataURL.length;
  11734. }
  11735. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11736. if (slashInd < questionMarkInd) {
  11737. // For pathString, questionMarkInd will always come after slashInd
  11738. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11739. }
  11740. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11741. // If we have a port, use scheme for determining if it's secure.
  11742. colonInd = host.indexOf(':');
  11743. if (colonInd >= 0) {
  11744. secure = scheme === 'https' || scheme === 'wss';
  11745. port = parseInt(host.substring(colonInd + 1), 10);
  11746. }
  11747. else {
  11748. colonInd = host.length;
  11749. }
  11750. const hostWithoutPort = host.slice(0, colonInd);
  11751. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11752. domain = 'localhost';
  11753. }
  11754. else if (hostWithoutPort.split('.').length <= 2) {
  11755. domain = hostWithoutPort;
  11756. }
  11757. else {
  11758. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11759. const dotInd = host.indexOf('.');
  11760. subdomain = host.substring(0, dotInd).toLowerCase();
  11761. domain = host.substring(dotInd + 1);
  11762. // Normalize namespaces to lowercase to share storage / connection.
  11763. namespace = subdomain;
  11764. }
  11765. // Always treat the value of the `ns` as the namespace name if it is present.
  11766. if ('ns' in queryParams) {
  11767. namespace = queryParams['ns'];
  11768. }
  11769. }
  11770. return {
  11771. host,
  11772. port,
  11773. domain,
  11774. subdomain,
  11775. secure,
  11776. scheme,
  11777. pathString,
  11778. namespace
  11779. };
  11780. };
  11781. /**
  11782. * @license
  11783. * Copyright 2017 Google LLC
  11784. *
  11785. * Licensed under the Apache License, Version 2.0 (the "License");
  11786. * you may not use this file except in compliance with the License.
  11787. * You may obtain a copy of the License at
  11788. *
  11789. * http://www.apache.org/licenses/LICENSE-2.0
  11790. *
  11791. * Unless required by applicable law or agreed to in writing, software
  11792. * distributed under the License is distributed on an "AS IS" BASIS,
  11793. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11794. * See the License for the specific language governing permissions and
  11795. * limitations under the License.
  11796. */
  11797. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11798. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11799. /**
  11800. * Fancy ID generator that creates 20-character string identifiers with the
  11801. * following properties:
  11802. *
  11803. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11804. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11805. * collide with other clients' IDs.
  11806. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11807. * that will sort properly).
  11808. * 4. They're monotonically increasing. Even if you generate more than one in
  11809. * the same timestamp, the latter ones will sort after the former ones. We do
  11810. * this by using the previous random bits but "incrementing" them by 1 (only
  11811. * in the case of a timestamp collision).
  11812. */
  11813. const nextPushId = (function () {
  11814. // Timestamp of last push, used to prevent local collisions if you push twice
  11815. // in one ms.
  11816. let lastPushTime = 0;
  11817. // We generate 72-bits of randomness which get turned into 12 characters and
  11818. // appended to the timestamp to prevent collisions with other clients. We
  11819. // store the last characters we generated because in the event of a collision,
  11820. // we'll use those same characters except "incremented" by one.
  11821. const lastRandChars = [];
  11822. return function (now) {
  11823. const duplicateTime = now === lastPushTime;
  11824. lastPushTime = now;
  11825. let i;
  11826. const timeStampChars = new Array(8);
  11827. for (i = 7; i >= 0; i--) {
  11828. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11829. // NOTE: Can't use << here because javascript will convert to int and lose
  11830. // the upper bits.
  11831. now = Math.floor(now / 64);
  11832. }
  11833. assert(now === 0, 'Cannot push at time == 0');
  11834. let id = timeStampChars.join('');
  11835. if (!duplicateTime) {
  11836. for (i = 0; i < 12; i++) {
  11837. lastRandChars[i] = Math.floor(Math.random() * 64);
  11838. }
  11839. }
  11840. else {
  11841. // If the timestamp hasn't changed since last push, use the same random
  11842. // number, except incremented by 1.
  11843. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11844. lastRandChars[i] = 0;
  11845. }
  11846. lastRandChars[i]++;
  11847. }
  11848. for (i = 0; i < 12; i++) {
  11849. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11850. }
  11851. assert(id.length === 20, 'nextPushId: Length should be 20.');
  11852. return id;
  11853. };
  11854. })();
  11855. /**
  11856. * @license
  11857. * Copyright 2017 Google LLC
  11858. *
  11859. * Licensed under the Apache License, Version 2.0 (the "License");
  11860. * you may not use this file except in compliance with the License.
  11861. * You may obtain a copy of the License at
  11862. *
  11863. * http://www.apache.org/licenses/LICENSE-2.0
  11864. *
  11865. * Unless required by applicable law or agreed to in writing, software
  11866. * distributed under the License is distributed on an "AS IS" BASIS,
  11867. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11868. * See the License for the specific language governing permissions and
  11869. * limitations under the License.
  11870. */
  11871. /**
  11872. * Encapsulates the data needed to raise an event
  11873. */
  11874. class DataEvent {
  11875. /**
  11876. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11877. * @param eventRegistration - The function to call to with the event data. User provided
  11878. * @param snapshot - The data backing the event
  11879. * @param prevName - Optional, the name of the previous child for child_* events.
  11880. */
  11881. constructor(eventType, eventRegistration, snapshot, prevName) {
  11882. this.eventType = eventType;
  11883. this.eventRegistration = eventRegistration;
  11884. this.snapshot = snapshot;
  11885. this.prevName = prevName;
  11886. }
  11887. getPath() {
  11888. const ref = this.snapshot.ref;
  11889. if (this.eventType === 'value') {
  11890. return ref._path;
  11891. }
  11892. else {
  11893. return ref.parent._path;
  11894. }
  11895. }
  11896. getEventType() {
  11897. return this.eventType;
  11898. }
  11899. getEventRunner() {
  11900. return this.eventRegistration.getEventRunner(this);
  11901. }
  11902. toString() {
  11903. return (this.getPath().toString() +
  11904. ':' +
  11905. this.eventType +
  11906. ':' +
  11907. stringify(this.snapshot.exportVal()));
  11908. }
  11909. }
  11910. class CancelEvent {
  11911. constructor(eventRegistration, error, path) {
  11912. this.eventRegistration = eventRegistration;
  11913. this.error = error;
  11914. this.path = path;
  11915. }
  11916. getPath() {
  11917. return this.path;
  11918. }
  11919. getEventType() {
  11920. return 'cancel';
  11921. }
  11922. getEventRunner() {
  11923. return this.eventRegistration.getEventRunner(this);
  11924. }
  11925. toString() {
  11926. return this.path.toString() + ':cancel';
  11927. }
  11928. }
  11929. /**
  11930. * @license
  11931. * Copyright 2017 Google LLC
  11932. *
  11933. * Licensed under the Apache License, Version 2.0 (the "License");
  11934. * you may not use this file except in compliance with the License.
  11935. * You may obtain a copy of the License at
  11936. *
  11937. * http://www.apache.org/licenses/LICENSE-2.0
  11938. *
  11939. * Unless required by applicable law or agreed to in writing, software
  11940. * distributed under the License is distributed on an "AS IS" BASIS,
  11941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11942. * See the License for the specific language governing permissions and
  11943. * limitations under the License.
  11944. */
  11945. /**
  11946. * A wrapper class that converts events from the database@exp SDK to the legacy
  11947. * Database SDK. Events are not converted directly as event registration relies
  11948. * on reference comparison of the original user callback (see `matches()`) and
  11949. * relies on equality of the legacy SDK's `context` object.
  11950. */
  11951. class CallbackContext {
  11952. constructor(snapshotCallback, cancelCallback) {
  11953. this.snapshotCallback = snapshotCallback;
  11954. this.cancelCallback = cancelCallback;
  11955. }
  11956. onValue(expDataSnapshot, previousChildName) {
  11957. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11958. }
  11959. onCancel(error) {
  11960. assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11961. return this.cancelCallback.call(null, error);
  11962. }
  11963. get hasCancelCallback() {
  11964. return !!this.cancelCallback;
  11965. }
  11966. matches(other) {
  11967. return (this.snapshotCallback === other.snapshotCallback ||
  11968. (this.snapshotCallback.userCallback !== undefined &&
  11969. this.snapshotCallback.userCallback ===
  11970. other.snapshotCallback.userCallback &&
  11971. this.snapshotCallback.context === other.snapshotCallback.context));
  11972. }
  11973. }
  11974. /**
  11975. * @license
  11976. * Copyright 2021 Google LLC
  11977. *
  11978. * Licensed under the Apache License, Version 2.0 (the "License");
  11979. * you may not use this file except in compliance with the License.
  11980. * You may obtain a copy of the License at
  11981. *
  11982. * http://www.apache.org/licenses/LICENSE-2.0
  11983. *
  11984. * Unless required by applicable law or agreed to in writing, software
  11985. * distributed under the License is distributed on an "AS IS" BASIS,
  11986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11987. * See the License for the specific language governing permissions and
  11988. * limitations under the License.
  11989. */
  11990. /**
  11991. * The `onDisconnect` class allows you to write or clear data when your client
  11992. * disconnects from the Database server. These updates occur whether your
  11993. * client disconnects cleanly or not, so you can rely on them to clean up data
  11994. * even if a connection is dropped or a client crashes.
  11995. *
  11996. * The `onDisconnect` class is most commonly used to manage presence in
  11997. * applications where it is useful to detect how many clients are connected and
  11998. * when other clients disconnect. See
  11999. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12000. * for more information.
  12001. *
  12002. * To avoid problems when a connection is dropped before the requests can be
  12003. * transferred to the Database server, these functions should be called before
  12004. * writing any data.
  12005. *
  12006. * Note that `onDisconnect` operations are only triggered once. If you want an
  12007. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12008. * the `onDisconnect` operations each time you reconnect.
  12009. */
  12010. class OnDisconnect {
  12011. /** @hideconstructor */
  12012. constructor(_repo, _path) {
  12013. this._repo = _repo;
  12014. this._path = _path;
  12015. }
  12016. /**
  12017. * Cancels all previously queued `onDisconnect()` set or update events for this
  12018. * location and all children.
  12019. *
  12020. * If a write has been queued for this location via a `set()` or `update()` at a
  12021. * parent location, the write at this location will be canceled, though writes
  12022. * to sibling locations will still occur.
  12023. *
  12024. * @returns Resolves when synchronization to the server is complete.
  12025. */
  12026. cancel() {
  12027. const deferred = new Deferred();
  12028. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12029. return deferred.promise;
  12030. }
  12031. /**
  12032. * Ensures the data at this location is deleted when the client is disconnected
  12033. * (due to closing the browser, navigating to a new page, or network issues).
  12034. *
  12035. * @returns Resolves when synchronization to the server is complete.
  12036. */
  12037. remove() {
  12038. validateWritablePath('OnDisconnect.remove', this._path);
  12039. const deferred = new Deferred();
  12040. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12041. return deferred.promise;
  12042. }
  12043. /**
  12044. * Ensures the data at this location is set to the specified value when the
  12045. * client is disconnected (due to closing the browser, navigating to a new page,
  12046. * or network issues).
  12047. *
  12048. * `set()` is especially useful for implementing "presence" systems, where a
  12049. * value should be changed or cleared when a user disconnects so that they
  12050. * appear "offline" to other users. See
  12051. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12052. * for more information.
  12053. *
  12054. * Note that `onDisconnect` operations are only triggered once. If you want an
  12055. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12056. * the `onDisconnect` operations each time.
  12057. *
  12058. * @param value - The value to be written to this location on disconnect (can
  12059. * be an object, array, string, number, boolean, or null).
  12060. * @returns Resolves when synchronization to the Database is complete.
  12061. */
  12062. set(value) {
  12063. validateWritablePath('OnDisconnect.set', this._path);
  12064. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12065. const deferred = new Deferred();
  12066. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12067. return deferred.promise;
  12068. }
  12069. /**
  12070. * Ensures the data at this location is set to the specified value and priority
  12071. * when the client is disconnected (due to closing the browser, navigating to a
  12072. * new page, or network issues).
  12073. *
  12074. * @param value - The value to be written to this location on disconnect (can
  12075. * be an object, array, string, number, boolean, or null).
  12076. * @param priority - The priority to be written (string, number, or null).
  12077. * @returns Resolves when synchronization to the Database is complete.
  12078. */
  12079. setWithPriority(value, priority) {
  12080. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12081. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12082. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12083. const deferred = new Deferred();
  12084. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12085. return deferred.promise;
  12086. }
  12087. /**
  12088. * Writes multiple values at this location when the client is disconnected (due
  12089. * to closing the browser, navigating to a new page, or network issues).
  12090. *
  12091. * The `values` argument contains multiple property-value pairs that will be
  12092. * written to the Database together. Each child property can either be a simple
  12093. * property (for example, "name") or a relative path (for example, "name/first")
  12094. * from the current location to the data to update.
  12095. *
  12096. * As opposed to the `set()` method, `update()` can be use to selectively update
  12097. * only the referenced properties at the current location (instead of replacing
  12098. * all the child properties at the current location).
  12099. *
  12100. * @param values - Object containing multiple values.
  12101. * @returns Resolves when synchronization to the Database is complete.
  12102. */
  12103. update(values) {
  12104. validateWritablePath('OnDisconnect.update', this._path);
  12105. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12106. const deferred = new Deferred();
  12107. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12108. return deferred.promise;
  12109. }
  12110. }
  12111. /**
  12112. * @license
  12113. * Copyright 2020 Google LLC
  12114. *
  12115. * Licensed under the Apache License, Version 2.0 (the "License");
  12116. * you may not use this file except in compliance with the License.
  12117. * You may obtain a copy of the License at
  12118. *
  12119. * http://www.apache.org/licenses/LICENSE-2.0
  12120. *
  12121. * Unless required by applicable law or agreed to in writing, software
  12122. * distributed under the License is distributed on an "AS IS" BASIS,
  12123. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12124. * See the License for the specific language governing permissions and
  12125. * limitations under the License.
  12126. */
  12127. /**
  12128. * @internal
  12129. */
  12130. class QueryImpl {
  12131. /**
  12132. * @hideconstructor
  12133. */
  12134. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12135. this._repo = _repo;
  12136. this._path = _path;
  12137. this._queryParams = _queryParams;
  12138. this._orderByCalled = _orderByCalled;
  12139. }
  12140. get key() {
  12141. if (pathIsEmpty(this._path)) {
  12142. return null;
  12143. }
  12144. else {
  12145. return pathGetBack(this._path);
  12146. }
  12147. }
  12148. get ref() {
  12149. return new ReferenceImpl(this._repo, this._path);
  12150. }
  12151. get _queryIdentifier() {
  12152. const obj = queryParamsGetQueryObject(this._queryParams);
  12153. const id = ObjectToUniqueKey(obj);
  12154. return id === '{}' ? 'default' : id;
  12155. }
  12156. /**
  12157. * An object representation of the query parameters used by this Query.
  12158. */
  12159. get _queryObject() {
  12160. return queryParamsGetQueryObject(this._queryParams);
  12161. }
  12162. isEqual(other) {
  12163. other = getModularInstance(other);
  12164. if (!(other instanceof QueryImpl)) {
  12165. return false;
  12166. }
  12167. const sameRepo = this._repo === other._repo;
  12168. const samePath = pathEquals(this._path, other._path);
  12169. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12170. return sameRepo && samePath && sameQueryIdentifier;
  12171. }
  12172. toJSON() {
  12173. return this.toString();
  12174. }
  12175. toString() {
  12176. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12177. }
  12178. }
  12179. /**
  12180. * Validates that no other order by call has been made
  12181. */
  12182. function validateNoPreviousOrderByCall(query, fnName) {
  12183. if (query._orderByCalled === true) {
  12184. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12185. }
  12186. }
  12187. /**
  12188. * Validates start/end values for queries.
  12189. */
  12190. function validateQueryEndpoints(params) {
  12191. let startNode = null;
  12192. let endNode = null;
  12193. if (params.hasStart()) {
  12194. startNode = params.getIndexStartValue();
  12195. }
  12196. if (params.hasEnd()) {
  12197. endNode = params.getIndexEndValue();
  12198. }
  12199. if (params.getIndex() === KEY_INDEX) {
  12200. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12201. 'startAt(), endAt(), or equalTo().';
  12202. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12203. 'endAt(), endBefore(), or equalTo() must be a string.';
  12204. if (params.hasStart()) {
  12205. const startName = params.getIndexStartName();
  12206. if (startName !== MIN_NAME) {
  12207. throw new Error(tooManyArgsError);
  12208. }
  12209. else if (typeof startNode !== 'string') {
  12210. throw new Error(wrongArgTypeError);
  12211. }
  12212. }
  12213. if (params.hasEnd()) {
  12214. const endName = params.getIndexEndName();
  12215. if (endName !== MAX_NAME) {
  12216. throw new Error(tooManyArgsError);
  12217. }
  12218. else if (typeof endNode !== 'string') {
  12219. throw new Error(wrongArgTypeError);
  12220. }
  12221. }
  12222. }
  12223. else if (params.getIndex() === PRIORITY_INDEX) {
  12224. if ((startNode != null && !isValidPriority(startNode)) ||
  12225. (endNode != null && !isValidPriority(endNode))) {
  12226. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12227. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12228. '(null, a number, or a string).');
  12229. }
  12230. }
  12231. else {
  12232. assert(params.getIndex() instanceof PathIndex ||
  12233. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12234. if ((startNode != null && typeof startNode === 'object') ||
  12235. (endNode != null && typeof endNode === 'object')) {
  12236. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12237. 'equalTo() cannot be an object.');
  12238. }
  12239. }
  12240. }
  12241. /**
  12242. * Validates that limit* has been called with the correct combination of parameters
  12243. */
  12244. function validateLimit(params) {
  12245. if (params.hasStart() &&
  12246. params.hasEnd() &&
  12247. params.hasLimit() &&
  12248. !params.hasAnchoredLimit()) {
  12249. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12250. 'limitToFirst() or limitToLast() instead.');
  12251. }
  12252. }
  12253. /**
  12254. * @internal
  12255. */
  12256. class ReferenceImpl extends QueryImpl {
  12257. /** @hideconstructor */
  12258. constructor(repo, path) {
  12259. super(repo, path, new QueryParams(), false);
  12260. }
  12261. get parent() {
  12262. const parentPath = pathParent(this._path);
  12263. return parentPath === null
  12264. ? null
  12265. : new ReferenceImpl(this._repo, parentPath);
  12266. }
  12267. get root() {
  12268. let ref = this;
  12269. while (ref.parent !== null) {
  12270. ref = ref.parent;
  12271. }
  12272. return ref;
  12273. }
  12274. }
  12275. /**
  12276. * A `DataSnapshot` contains data from a Database location.
  12277. *
  12278. * Any time you read data from the Database, you receive the data as a
  12279. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12280. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12281. * JavaScript object by calling the `val()` method. Alternatively, you can
  12282. * traverse into the snapshot by calling `child()` to return child snapshots
  12283. * (which you could then call `val()` on).
  12284. *
  12285. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12286. * a Database location. It cannot be modified and will never change (to modify
  12287. * data, you always call the `set()` method on a `Reference` directly).
  12288. */
  12289. class DataSnapshot {
  12290. /**
  12291. * @param _node - A SnapshotNode to wrap.
  12292. * @param ref - The location this snapshot came from.
  12293. * @param _index - The iteration order for this snapshot
  12294. * @hideconstructor
  12295. */
  12296. constructor(_node,
  12297. /**
  12298. * The location of this DataSnapshot.
  12299. */
  12300. ref, _index) {
  12301. this._node = _node;
  12302. this.ref = ref;
  12303. this._index = _index;
  12304. }
  12305. /**
  12306. * Gets the priority value of the data in this `DataSnapshot`.
  12307. *
  12308. * Applications need not use priority but can order collections by
  12309. * ordinary properties (see
  12310. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12311. * ).
  12312. */
  12313. get priority() {
  12314. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12315. return this._node.getPriority().val();
  12316. }
  12317. /**
  12318. * The key (last part of the path) of the location of this `DataSnapshot`.
  12319. *
  12320. * The last token in a Database location is considered its key. For example,
  12321. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12322. * `DataSnapshot` will return the key for the location that generated it.
  12323. * However, accessing the key on the root URL of a Database will return
  12324. * `null`.
  12325. */
  12326. get key() {
  12327. return this.ref.key;
  12328. }
  12329. /** Returns the number of child properties of this `DataSnapshot`. */
  12330. get size() {
  12331. return this._node.numChildren();
  12332. }
  12333. /**
  12334. * Gets another `DataSnapshot` for the location at the specified relative path.
  12335. *
  12336. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12337. * another `DataSnapshot` for the location at the specified relative path. The
  12338. * relative path can either be a simple child name (for example, "ada") or a
  12339. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12340. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12341. * whose value is `null`) is returned.
  12342. *
  12343. * @param path - A relative path to the location of child data.
  12344. */
  12345. child(path) {
  12346. const childPath = new Path(path);
  12347. const childRef = child(this.ref, path);
  12348. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12349. }
  12350. /**
  12351. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12352. * efficient than using `snapshot.val() !== null`.
  12353. */
  12354. exists() {
  12355. return !this._node.isEmpty();
  12356. }
  12357. /**
  12358. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12359. *
  12360. * The `exportVal()` method is similar to `val()`, except priority information
  12361. * is included (if available), making it suitable for backing up your data.
  12362. *
  12363. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12364. * Array, string, number, boolean, or `null`).
  12365. */
  12366. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12367. exportVal() {
  12368. return this._node.val(true);
  12369. }
  12370. /**
  12371. * Enumerates the top-level children in the `DataSnapshot`.
  12372. *
  12373. * Because of the way JavaScript objects work, the ordering of data in the
  12374. * JavaScript object returned by `val()` is not guaranteed to match the
  12375. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12376. * where `forEach()` comes in handy. It guarantees the children of a
  12377. * `DataSnapshot` will be iterated in their query order.
  12378. *
  12379. * If no explicit `orderBy*()` method is used, results are returned
  12380. * ordered by key (unless priorities are used, in which case, results are
  12381. * returned by priority).
  12382. *
  12383. * @param action - A function that will be called for each child DataSnapshot.
  12384. * The callback can return true to cancel further enumeration.
  12385. * @returns true if enumeration was canceled due to your callback returning
  12386. * true.
  12387. */
  12388. forEach(action) {
  12389. if (this._node.isLeafNode()) {
  12390. return false;
  12391. }
  12392. const childrenNode = this._node;
  12393. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12394. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12395. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12396. });
  12397. }
  12398. /**
  12399. * Returns true if the specified child path has (non-null) data.
  12400. *
  12401. * @param path - A relative path to the location of a potential child.
  12402. * @returns `true` if data exists at the specified child path; else
  12403. * `false`.
  12404. */
  12405. hasChild(path) {
  12406. const childPath = new Path(path);
  12407. return !this._node.getChild(childPath).isEmpty();
  12408. }
  12409. /**
  12410. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12411. * properties.
  12412. *
  12413. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12414. * children. If it does, you can enumerate them using `forEach()`. If it
  12415. * doesn't, then either this snapshot contains a primitive value (which can be
  12416. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12417. * `null`).
  12418. *
  12419. * @returns true if this snapshot has any children; else false.
  12420. */
  12421. hasChildren() {
  12422. if (this._node.isLeafNode()) {
  12423. return false;
  12424. }
  12425. else {
  12426. return !this._node.isEmpty();
  12427. }
  12428. }
  12429. /**
  12430. * Returns a JSON-serializable representation of this object.
  12431. */
  12432. toJSON() {
  12433. return this.exportVal();
  12434. }
  12435. /**
  12436. * Extracts a JavaScript value from a `DataSnapshot`.
  12437. *
  12438. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12439. * scalar type (string, number, or boolean), an array, or an object. It may
  12440. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12441. * data).
  12442. *
  12443. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12444. * Array, string, number, boolean, or `null`).
  12445. */
  12446. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12447. val() {
  12448. return this._node.val();
  12449. }
  12450. }
  12451. /**
  12452. *
  12453. * Returns a `Reference` representing the location in the Database
  12454. * corresponding to the provided path. If no path is provided, the `Reference`
  12455. * will point to the root of the Database.
  12456. *
  12457. * @param db - The database instance to obtain a reference for.
  12458. * @param path - Optional path representing the location the returned
  12459. * `Reference` will point. If not provided, the returned `Reference` will
  12460. * point to the root of the Database.
  12461. * @returns If a path is provided, a `Reference`
  12462. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12463. * root of the Database.
  12464. */
  12465. function ref(db, path) {
  12466. db = getModularInstance(db);
  12467. db._checkNotDeleted('ref');
  12468. return path !== undefined ? child(db._root, path) : db._root;
  12469. }
  12470. /**
  12471. * Returns a `Reference` representing the location in the Database
  12472. * corresponding to the provided Firebase URL.
  12473. *
  12474. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12475. * has a different domain than the current `Database` instance.
  12476. *
  12477. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12478. * and are not applied to the returned `Reference`.
  12479. *
  12480. * @param db - The database instance to obtain a reference for.
  12481. * @param url - The Firebase URL at which the returned `Reference` will
  12482. * point.
  12483. * @returns A `Reference` pointing to the provided
  12484. * Firebase URL.
  12485. */
  12486. function refFromURL(db, url) {
  12487. db = getModularInstance(db);
  12488. db._checkNotDeleted('refFromURL');
  12489. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12490. validateUrl('refFromURL', parsedURL);
  12491. const repoInfo = parsedURL.repoInfo;
  12492. if (!db._repo.repoInfo_.isCustomHost() &&
  12493. repoInfo.host !== db._repo.repoInfo_.host) {
  12494. fatal('refFromURL' +
  12495. ': Host name does not match the current database: ' +
  12496. '(found ' +
  12497. repoInfo.host +
  12498. ' but expected ' +
  12499. db._repo.repoInfo_.host +
  12500. ')');
  12501. }
  12502. return ref(db, parsedURL.path.toString());
  12503. }
  12504. /**
  12505. * Gets a `Reference` for the location at the specified relative path.
  12506. *
  12507. * The relative path can either be a simple child name (for example, "ada") or
  12508. * a deeper slash-separated path (for example, "ada/name/first").
  12509. *
  12510. * @param parent - The parent location.
  12511. * @param path - A relative path from this location to the desired child
  12512. * location.
  12513. * @returns The specified child location.
  12514. */
  12515. function child(parent, path) {
  12516. parent = getModularInstance(parent);
  12517. if (pathGetFront(parent._path) === null) {
  12518. validateRootPathString('child', 'path', path, false);
  12519. }
  12520. else {
  12521. validatePathString('child', 'path', path, false);
  12522. }
  12523. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12524. }
  12525. /**
  12526. * Returns an `OnDisconnect` object - see
  12527. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12528. * for more information on how to use it.
  12529. *
  12530. * @param ref - The reference to add OnDisconnect triggers for.
  12531. */
  12532. function onDisconnect(ref) {
  12533. ref = getModularInstance(ref);
  12534. return new OnDisconnect(ref._repo, ref._path);
  12535. }
  12536. /**
  12537. * Generates a new child location using a unique key and returns its
  12538. * `Reference`.
  12539. *
  12540. * This is the most common pattern for adding data to a collection of items.
  12541. *
  12542. * If you provide a value to `push()`, the value is written to the
  12543. * generated location. If you don't pass a value, nothing is written to the
  12544. * database and the child remains empty (but you can use the `Reference`
  12545. * elsewhere).
  12546. *
  12547. * The unique keys generated by `push()` are ordered by the current time, so the
  12548. * resulting list of items is chronologically sorted. The keys are also
  12549. * designed to be unguessable (they contain 72 random bits of entropy).
  12550. *
  12551. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12552. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12553. *
  12554. * @param parent - The parent location.
  12555. * @param value - Optional value to be written at the generated location.
  12556. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12557. * but can be used immediately as the `Reference` to the child location.
  12558. */
  12559. function push(parent, value) {
  12560. parent = getModularInstance(parent);
  12561. validateWritablePath('push', parent._path);
  12562. validateFirebaseDataArg('push', value, parent._path, true);
  12563. const now = repoServerTime(parent._repo);
  12564. const name = nextPushId(now);
  12565. // push() returns a ThennableReference whose promise is fulfilled with a
  12566. // regular Reference. We use child() to create handles to two different
  12567. // references. The first is turned into a ThennableReference below by adding
  12568. // then() and catch() methods and is used as the return value of push(). The
  12569. // second remains a regular Reference and is used as the fulfilled value of
  12570. // the first ThennableReference.
  12571. const thennablePushRef = child(parent, name);
  12572. const pushRef = child(parent, name);
  12573. let promise;
  12574. if (value != null) {
  12575. promise = set(pushRef, value).then(() => pushRef);
  12576. }
  12577. else {
  12578. promise = Promise.resolve(pushRef);
  12579. }
  12580. thennablePushRef.then = promise.then.bind(promise);
  12581. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12582. return thennablePushRef;
  12583. }
  12584. /**
  12585. * Removes the data at this Database location.
  12586. *
  12587. * Any data at child locations will also be deleted.
  12588. *
  12589. * The effect of the remove will be visible immediately and the corresponding
  12590. * event 'value' will be triggered. Synchronization of the remove to the
  12591. * Firebase servers will also be started, and the returned Promise will resolve
  12592. * when complete. If provided, the onComplete callback will be called
  12593. * asynchronously after synchronization has finished.
  12594. *
  12595. * @param ref - The location to remove.
  12596. * @returns Resolves when remove on server is complete.
  12597. */
  12598. function remove(ref) {
  12599. validateWritablePath('remove', ref._path);
  12600. return set(ref, null);
  12601. }
  12602. /**
  12603. * Writes data to this Database location.
  12604. *
  12605. * This will overwrite any data at this location and all child locations.
  12606. *
  12607. * The effect of the write will be visible immediately, and the corresponding
  12608. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12609. * the data to the Firebase servers will also be started, and the returned
  12610. * Promise will resolve when complete. If provided, the `onComplete` callback
  12611. * will be called asynchronously after synchronization has finished.
  12612. *
  12613. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12614. * all data at this location and all child locations will be deleted.
  12615. *
  12616. * `set()` will remove any priority stored at this location, so if priority is
  12617. * meant to be preserved, you need to use `setWithPriority()` instead.
  12618. *
  12619. * Note that modifying data with `set()` will cancel any pending transactions
  12620. * at that location, so extreme care should be taken if mixing `set()` and
  12621. * `transaction()` to modify the same data.
  12622. *
  12623. * A single `set()` will generate a single "value" event at the location where
  12624. * the `set()` was performed.
  12625. *
  12626. * @param ref - The location to write to.
  12627. * @param value - The value to be written (string, number, boolean, object,
  12628. * array, or null).
  12629. * @returns Resolves when write to server is complete.
  12630. */
  12631. function set(ref, value) {
  12632. ref = getModularInstance(ref);
  12633. validateWritablePath('set', ref._path);
  12634. validateFirebaseDataArg('set', value, ref._path, false);
  12635. const deferred = new Deferred();
  12636. repoSetWithPriority(ref._repo, ref._path, value,
  12637. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12638. return deferred.promise;
  12639. }
  12640. /**
  12641. * Sets a priority for the data at this Database location.
  12642. *
  12643. * Applications need not use priority but can order collections by
  12644. * ordinary properties (see
  12645. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12646. * ).
  12647. *
  12648. * @param ref - The location to write to.
  12649. * @param priority - The priority to be written (string, number, or null).
  12650. * @returns Resolves when write to server is complete.
  12651. */
  12652. function setPriority(ref, priority) {
  12653. ref = getModularInstance(ref);
  12654. validateWritablePath('setPriority', ref._path);
  12655. validatePriority('setPriority', priority, false);
  12656. const deferred = new Deferred();
  12657. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12658. return deferred.promise;
  12659. }
  12660. /**
  12661. * Writes data the Database location. Like `set()` but also specifies the
  12662. * priority for that data.
  12663. *
  12664. * Applications need not use priority but can order collections by
  12665. * ordinary properties (see
  12666. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12667. * ).
  12668. *
  12669. * @param ref - The location to write to.
  12670. * @param value - The value to be written (string, number, boolean, object,
  12671. * array, or null).
  12672. * @param priority - The priority to be written (string, number, or null).
  12673. * @returns Resolves when write to server is complete.
  12674. */
  12675. function setWithPriority(ref, value, priority) {
  12676. validateWritablePath('setWithPriority', ref._path);
  12677. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12678. validatePriority('setWithPriority', priority, false);
  12679. if (ref.key === '.length' || ref.key === '.keys') {
  12680. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12681. }
  12682. const deferred = new Deferred();
  12683. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12684. return deferred.promise;
  12685. }
  12686. /**
  12687. * Writes multiple values to the Database at once.
  12688. *
  12689. * The `values` argument contains multiple property-value pairs that will be
  12690. * written to the Database together. Each child property can either be a simple
  12691. * property (for example, "name") or a relative path (for example,
  12692. * "name/first") from the current location to the data to update.
  12693. *
  12694. * As opposed to the `set()` method, `update()` can be use to selectively update
  12695. * only the referenced properties at the current location (instead of replacing
  12696. * all the child properties at the current location).
  12697. *
  12698. * The effect of the write will be visible immediately, and the corresponding
  12699. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12700. * the data to the Firebase servers will also be started, and the returned
  12701. * Promise will resolve when complete. If provided, the `onComplete` callback
  12702. * will be called asynchronously after synchronization has finished.
  12703. *
  12704. * A single `update()` will generate a single "value" event at the location
  12705. * where the `update()` was performed, regardless of how many children were
  12706. * modified.
  12707. *
  12708. * Note that modifying data with `update()` will cancel any pending
  12709. * transactions at that location, so extreme care should be taken if mixing
  12710. * `update()` and `transaction()` to modify the same data.
  12711. *
  12712. * Passing `null` to `update()` will remove the data at this location.
  12713. *
  12714. * See
  12715. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12716. *
  12717. * @param ref - The location to write to.
  12718. * @param values - Object containing multiple values.
  12719. * @returns Resolves when update on server is complete.
  12720. */
  12721. function update(ref, values) {
  12722. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12723. const deferred = new Deferred();
  12724. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12725. return deferred.promise;
  12726. }
  12727. /**
  12728. * Gets the most up-to-date result for this query.
  12729. *
  12730. * @param query - The query to run.
  12731. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12732. * available, or rejects if the client is unable to return a value (e.g., if the
  12733. * server is unreachable and there is nothing cached).
  12734. */
  12735. function get(query) {
  12736. query = getModularInstance(query);
  12737. const callbackContext = new CallbackContext(() => { });
  12738. const container = new ValueEventRegistration(callbackContext);
  12739. return repoGetValue(query._repo, query, container).then(node => {
  12740. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12741. });
  12742. }
  12743. /**
  12744. * Represents registration for 'value' events.
  12745. */
  12746. class ValueEventRegistration {
  12747. constructor(callbackContext) {
  12748. this.callbackContext = callbackContext;
  12749. }
  12750. respondsTo(eventType) {
  12751. return eventType === 'value';
  12752. }
  12753. createEvent(change, query) {
  12754. const index = query._queryParams.getIndex();
  12755. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12756. }
  12757. getEventRunner(eventData) {
  12758. if (eventData.getEventType() === 'cancel') {
  12759. return () => this.callbackContext.onCancel(eventData.error);
  12760. }
  12761. else {
  12762. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12763. }
  12764. }
  12765. createCancelEvent(error, path) {
  12766. if (this.callbackContext.hasCancelCallback) {
  12767. return new CancelEvent(this, error, path);
  12768. }
  12769. else {
  12770. return null;
  12771. }
  12772. }
  12773. matches(other) {
  12774. if (!(other instanceof ValueEventRegistration)) {
  12775. return false;
  12776. }
  12777. else if (!other.callbackContext || !this.callbackContext) {
  12778. // If no callback specified, we consider it to match any callback.
  12779. return true;
  12780. }
  12781. else {
  12782. return other.callbackContext.matches(this.callbackContext);
  12783. }
  12784. }
  12785. hasAnyCallback() {
  12786. return this.callbackContext !== null;
  12787. }
  12788. }
  12789. /**
  12790. * Represents the registration of a child_x event.
  12791. */
  12792. class ChildEventRegistration {
  12793. constructor(eventType, callbackContext) {
  12794. this.eventType = eventType;
  12795. this.callbackContext = callbackContext;
  12796. }
  12797. respondsTo(eventType) {
  12798. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12799. eventToCheck =
  12800. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12801. return this.eventType === eventToCheck;
  12802. }
  12803. createCancelEvent(error, path) {
  12804. if (this.callbackContext.hasCancelCallback) {
  12805. return new CancelEvent(this, error, path);
  12806. }
  12807. else {
  12808. return null;
  12809. }
  12810. }
  12811. createEvent(change, query) {
  12812. assert(change.childName != null, 'Child events should have a childName.');
  12813. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12814. const index = query._queryParams.getIndex();
  12815. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12816. }
  12817. getEventRunner(eventData) {
  12818. if (eventData.getEventType() === 'cancel') {
  12819. return () => this.callbackContext.onCancel(eventData.error);
  12820. }
  12821. else {
  12822. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12823. }
  12824. }
  12825. matches(other) {
  12826. if (other instanceof ChildEventRegistration) {
  12827. return (this.eventType === other.eventType &&
  12828. (!this.callbackContext ||
  12829. !other.callbackContext ||
  12830. this.callbackContext.matches(other.callbackContext)));
  12831. }
  12832. return false;
  12833. }
  12834. hasAnyCallback() {
  12835. return !!this.callbackContext;
  12836. }
  12837. }
  12838. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12839. let cancelCallback;
  12840. if (typeof cancelCallbackOrListenOptions === 'object') {
  12841. cancelCallback = undefined;
  12842. options = cancelCallbackOrListenOptions;
  12843. }
  12844. if (typeof cancelCallbackOrListenOptions === 'function') {
  12845. cancelCallback = cancelCallbackOrListenOptions;
  12846. }
  12847. if (options && options.onlyOnce) {
  12848. const userCallback = callback;
  12849. const onceCallback = (dataSnapshot, previousChildName) => {
  12850. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12851. userCallback(dataSnapshot, previousChildName);
  12852. };
  12853. onceCallback.userCallback = callback.userCallback;
  12854. onceCallback.context = callback.context;
  12855. callback = onceCallback;
  12856. }
  12857. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12858. const container = eventType === 'value'
  12859. ? new ValueEventRegistration(callbackContext)
  12860. : new ChildEventRegistration(eventType, callbackContext);
  12861. repoAddEventCallbackForQuery(query._repo, query, container);
  12862. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12863. }
  12864. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12865. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12866. }
  12867. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12868. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12869. }
  12870. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12871. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12872. }
  12873. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12874. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12875. }
  12876. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12877. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12878. }
  12879. /**
  12880. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12881. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12882. * the respective `on*` callbacks.
  12883. *
  12884. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12885. * will not automatically remove listeners registered on child nodes, `off()`
  12886. * must also be called on any child listeners to remove the callback.
  12887. *
  12888. * If a callback is not specified, all callbacks for the specified eventType
  12889. * will be removed. Similarly, if no eventType is specified, all callbacks
  12890. * for the `Reference` will be removed.
  12891. *
  12892. * Individual listeners can also be removed by invoking their unsubscribe
  12893. * callbacks.
  12894. *
  12895. * @param query - The query that the listener was registered with.
  12896. * @param eventType - One of the following strings: "value", "child_added",
  12897. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12898. * for the `Reference` will be removed.
  12899. * @param callback - The callback function that was passed to `on()` or
  12900. * `undefined` to remove all callbacks.
  12901. */
  12902. function off(query, eventType, callback) {
  12903. let container = null;
  12904. const expCallback = callback ? new CallbackContext(callback) : null;
  12905. if (eventType === 'value') {
  12906. container = new ValueEventRegistration(expCallback);
  12907. }
  12908. else if (eventType) {
  12909. container = new ChildEventRegistration(eventType, expCallback);
  12910. }
  12911. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12912. }
  12913. /**
  12914. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12915. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12916. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12917. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12918. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12919. * {@link orderByValue} or {@link equalTo} and
  12920. * can then be passed to {@link query} to create a new query instance that
  12921. * also contains this `QueryConstraint`.
  12922. */
  12923. class QueryConstraint {
  12924. }
  12925. class QueryEndAtConstraint extends QueryConstraint {
  12926. constructor(_value, _key) {
  12927. super();
  12928. this._value = _value;
  12929. this._key = _key;
  12930. }
  12931. _apply(query) {
  12932. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12933. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12934. validateLimit(newParams);
  12935. validateQueryEndpoints(newParams);
  12936. if (query._queryParams.hasEnd()) {
  12937. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12938. 'endBefore or equalTo).');
  12939. }
  12940. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12941. }
  12942. }
  12943. /**
  12944. * Creates a `QueryConstraint` with the specified ending point.
  12945. *
  12946. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12947. * allows you to choose arbitrary starting and ending points for your queries.
  12948. *
  12949. * The ending point is inclusive, so children with exactly the specified value
  12950. * will be included in the query. The optional key argument can be used to
  12951. * further limit the range of the query. If it is specified, then children that
  12952. * have exactly the specified value must also have a key name less than or equal
  12953. * to the specified key.
  12954. *
  12955. * You can read more about `endAt()` in
  12956. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12957. *
  12958. * @param value - The value to end at. The argument type depends on which
  12959. * `orderBy*()` function was used in this query. Specify a value that matches
  12960. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12961. * value must be a string.
  12962. * @param key - The child key to end at, among the children with the previously
  12963. * specified priority. This argument is only allowed if ordering by child,
  12964. * value, or priority.
  12965. */
  12966. function endAt(value, key) {
  12967. validateKey('endAt', 'key', key, true);
  12968. return new QueryEndAtConstraint(value, key);
  12969. }
  12970. class QueryEndBeforeConstraint extends QueryConstraint {
  12971. constructor(_value, _key) {
  12972. super();
  12973. this._value = _value;
  12974. this._key = _key;
  12975. }
  12976. _apply(query) {
  12977. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12978. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12979. validateLimit(newParams);
  12980. validateQueryEndpoints(newParams);
  12981. if (query._queryParams.hasEnd()) {
  12982. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12983. 'endBefore or equalTo).');
  12984. }
  12985. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12986. }
  12987. }
  12988. /**
  12989. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  12990. *
  12991. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12992. * allows you to choose arbitrary starting and ending points for your queries.
  12993. *
  12994. * The ending point is exclusive. If only a value is provided, children
  12995. * with a value less than the specified value will be included in the query.
  12996. * If a key is specified, then children must have a value less than or equal
  12997. * to the specified value and a key name less than the specified key.
  12998. *
  12999. * @param value - The value to end before. The argument type depends on which
  13000. * `orderBy*()` function was used in this query. Specify a value that matches
  13001. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13002. * value must be a string.
  13003. * @param key - The child key to end before, among the children with the
  13004. * previously specified priority. This argument is only allowed if ordering by
  13005. * child, value, or priority.
  13006. */
  13007. function endBefore(value, key) {
  13008. validateKey('endBefore', 'key', key, true);
  13009. return new QueryEndBeforeConstraint(value, key);
  13010. }
  13011. class QueryStartAtConstraint extends QueryConstraint {
  13012. constructor(_value, _key) {
  13013. super();
  13014. this._value = _value;
  13015. this._key = _key;
  13016. }
  13017. _apply(query) {
  13018. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13019. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13020. validateLimit(newParams);
  13021. validateQueryEndpoints(newParams);
  13022. if (query._queryParams.hasStart()) {
  13023. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13024. 'startBefore or equalTo).');
  13025. }
  13026. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13027. }
  13028. }
  13029. /**
  13030. * Creates a `QueryConstraint` with the specified starting point.
  13031. *
  13032. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13033. * allows you to choose arbitrary starting and ending points for your queries.
  13034. *
  13035. * The starting point is inclusive, so children with exactly the specified value
  13036. * will be included in the query. The optional key argument can be used to
  13037. * further limit the range of the query. If it is specified, then children that
  13038. * have exactly the specified value must also have a key name greater than or
  13039. * equal to the specified key.
  13040. *
  13041. * You can read more about `startAt()` in
  13042. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13043. *
  13044. * @param value - The value to start at. The argument type depends on which
  13045. * `orderBy*()` function was used in this query. Specify a value that matches
  13046. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13047. * value must be a string.
  13048. * @param key - The child key to start at. This argument is only allowed if
  13049. * ordering by child, value, or priority.
  13050. */
  13051. function startAt(value = null, key) {
  13052. validateKey('startAt', 'key', key, true);
  13053. return new QueryStartAtConstraint(value, key);
  13054. }
  13055. class QueryStartAfterConstraint extends QueryConstraint {
  13056. constructor(_value, _key) {
  13057. super();
  13058. this._value = _value;
  13059. this._key = _key;
  13060. }
  13061. _apply(query) {
  13062. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13063. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13064. validateLimit(newParams);
  13065. validateQueryEndpoints(newParams);
  13066. if (query._queryParams.hasStart()) {
  13067. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13068. 'startAfter, or equalTo).');
  13069. }
  13070. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13071. }
  13072. }
  13073. /**
  13074. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13075. *
  13076. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13077. * allows you to choose arbitrary starting and ending points for your queries.
  13078. *
  13079. * The starting point is exclusive. If only a value is provided, children
  13080. * with a value greater than the specified value will be included in the query.
  13081. * If a key is specified, then children must have a value greater than or equal
  13082. * to the specified value and a a key name greater than the specified key.
  13083. *
  13084. * @param value - The value to start after. The argument type depends on which
  13085. * `orderBy*()` function was used in this query. Specify a value that matches
  13086. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13087. * value must be a string.
  13088. * @param key - The child key to start after. This argument is only allowed if
  13089. * ordering by child, value, or priority.
  13090. */
  13091. function startAfter(value, key) {
  13092. validateKey('startAfter', 'key', key, true);
  13093. return new QueryStartAfterConstraint(value, key);
  13094. }
  13095. class QueryLimitToFirstConstraint extends QueryConstraint {
  13096. constructor(_limit) {
  13097. super();
  13098. this._limit = _limit;
  13099. }
  13100. _apply(query) {
  13101. if (query._queryParams.hasLimit()) {
  13102. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13103. 'or limitToLast).');
  13104. }
  13105. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13106. }
  13107. }
  13108. /**
  13109. * Creates a new `QueryConstraint` that if limited to the first specific number
  13110. * of children.
  13111. *
  13112. * The `limitToFirst()` method is used to set a maximum number of children to be
  13113. * synced for a given callback. If we set a limit of 100, we will initially only
  13114. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13115. * stored in our Database, a `child_added` event will fire for each message.
  13116. * However, if we have over 100 messages, we will only receive a `child_added`
  13117. * event for the first 100 ordered messages. As items change, we will receive
  13118. * `child_removed` events for each item that drops out of the active list so
  13119. * that the total number stays at 100.
  13120. *
  13121. * You can read more about `limitToFirst()` in
  13122. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13123. *
  13124. * @param limit - The maximum number of nodes to include in this query.
  13125. */
  13126. function limitToFirst(limit) {
  13127. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13128. throw new Error('limitToFirst: First argument must be a positive integer.');
  13129. }
  13130. return new QueryLimitToFirstConstraint(limit);
  13131. }
  13132. class QueryLimitToLastConstraint extends QueryConstraint {
  13133. constructor(_limit) {
  13134. super();
  13135. this._limit = _limit;
  13136. }
  13137. _apply(query) {
  13138. if (query._queryParams.hasLimit()) {
  13139. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13140. 'or limitToLast).');
  13141. }
  13142. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13143. }
  13144. }
  13145. /**
  13146. * Creates a new `QueryConstraint` that is limited to return only the last
  13147. * specified number of children.
  13148. *
  13149. * The `limitToLast()` method is used to set a maximum number of children to be
  13150. * synced for a given callback. If we set a limit of 100, we will initially only
  13151. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13152. * stored in our Database, a `child_added` event will fire for each message.
  13153. * However, if we have over 100 messages, we will only receive a `child_added`
  13154. * event for the last 100 ordered messages. As items change, we will receive
  13155. * `child_removed` events for each item that drops out of the active list so
  13156. * that the total number stays at 100.
  13157. *
  13158. * You can read more about `limitToLast()` in
  13159. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13160. *
  13161. * @param limit - The maximum number of nodes to include in this query.
  13162. */
  13163. function limitToLast(limit) {
  13164. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13165. throw new Error('limitToLast: First argument must be a positive integer.');
  13166. }
  13167. return new QueryLimitToLastConstraint(limit);
  13168. }
  13169. class QueryOrderByChildConstraint extends QueryConstraint {
  13170. constructor(_path) {
  13171. super();
  13172. this._path = _path;
  13173. }
  13174. _apply(query) {
  13175. validateNoPreviousOrderByCall(query, 'orderByChild');
  13176. const parsedPath = new Path(this._path);
  13177. if (pathIsEmpty(parsedPath)) {
  13178. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13179. }
  13180. const index = new PathIndex(parsedPath);
  13181. const newParams = queryParamsOrderBy(query._queryParams, index);
  13182. validateQueryEndpoints(newParams);
  13183. return new QueryImpl(query._repo, query._path, newParams,
  13184. /*orderByCalled=*/ true);
  13185. }
  13186. }
  13187. /**
  13188. * Creates a new `QueryConstraint` that orders by the specified child key.
  13189. *
  13190. * Queries can only order by one key at a time. Calling `orderByChild()`
  13191. * multiple times on the same query is an error.
  13192. *
  13193. * Firebase queries allow you to order your data by any child key on the fly.
  13194. * However, if you know in advance what your indexes will be, you can define
  13195. * them via the .indexOn rule in your Security Rules for better performance. See
  13196. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13197. * rule for more information.
  13198. *
  13199. * You can read more about `orderByChild()` in
  13200. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13201. *
  13202. * @param path - The path to order by.
  13203. */
  13204. function orderByChild(path) {
  13205. if (path === '$key') {
  13206. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13207. }
  13208. else if (path === '$priority') {
  13209. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13210. }
  13211. else if (path === '$value') {
  13212. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13213. }
  13214. validatePathString('orderByChild', 'path', path, false);
  13215. return new QueryOrderByChildConstraint(path);
  13216. }
  13217. class QueryOrderByKeyConstraint extends QueryConstraint {
  13218. _apply(query) {
  13219. validateNoPreviousOrderByCall(query, 'orderByKey');
  13220. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13221. validateQueryEndpoints(newParams);
  13222. return new QueryImpl(query._repo, query._path, newParams,
  13223. /*orderByCalled=*/ true);
  13224. }
  13225. }
  13226. /**
  13227. * Creates a new `QueryConstraint` that orders by the key.
  13228. *
  13229. * Sorts the results of a query by their (ascending) key values.
  13230. *
  13231. * You can read more about `orderByKey()` in
  13232. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13233. */
  13234. function orderByKey() {
  13235. return new QueryOrderByKeyConstraint();
  13236. }
  13237. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13238. _apply(query) {
  13239. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13240. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13241. validateQueryEndpoints(newParams);
  13242. return new QueryImpl(query._repo, query._path, newParams,
  13243. /*orderByCalled=*/ true);
  13244. }
  13245. }
  13246. /**
  13247. * Creates a new `QueryConstraint` that orders by priority.
  13248. *
  13249. * Applications need not use priority but can order collections by
  13250. * ordinary properties (see
  13251. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13252. * for alternatives to priority.
  13253. */
  13254. function orderByPriority() {
  13255. return new QueryOrderByPriorityConstraint();
  13256. }
  13257. class QueryOrderByValueConstraint extends QueryConstraint {
  13258. _apply(query) {
  13259. validateNoPreviousOrderByCall(query, 'orderByValue');
  13260. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13261. validateQueryEndpoints(newParams);
  13262. return new QueryImpl(query._repo, query._path, newParams,
  13263. /*orderByCalled=*/ true);
  13264. }
  13265. }
  13266. /**
  13267. * Creates a new `QueryConstraint` that orders by value.
  13268. *
  13269. * If the children of a query are all scalar values (string, number, or
  13270. * boolean), you can order the results by their (ascending) values.
  13271. *
  13272. * You can read more about `orderByValue()` in
  13273. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13274. */
  13275. function orderByValue() {
  13276. return new QueryOrderByValueConstraint();
  13277. }
  13278. class QueryEqualToValueConstraint extends QueryConstraint {
  13279. constructor(_value, _key) {
  13280. super();
  13281. this._value = _value;
  13282. this._key = _key;
  13283. }
  13284. _apply(query) {
  13285. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13286. if (query._queryParams.hasStart()) {
  13287. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13288. 'equalTo).');
  13289. }
  13290. if (query._queryParams.hasEnd()) {
  13291. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13292. 'equalTo).');
  13293. }
  13294. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13295. }
  13296. }
  13297. /**
  13298. * Creates a `QueryConstraint` that includes children that match the specified
  13299. * value.
  13300. *
  13301. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13302. * allows you to choose arbitrary starting and ending points for your queries.
  13303. *
  13304. * The optional key argument can be used to further limit the range of the
  13305. * query. If it is specified, then children that have exactly the specified
  13306. * value must also have exactly the specified key as their key name. This can be
  13307. * used to filter result sets with many matches for the same value.
  13308. *
  13309. * You can read more about `equalTo()` in
  13310. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13311. *
  13312. * @param value - The value to match for. The argument type depends on which
  13313. * `orderBy*()` function was used in this query. Specify a value that matches
  13314. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13315. * value must be a string.
  13316. * @param key - The child key to start at, among the children with the
  13317. * previously specified priority. This argument is only allowed if ordering by
  13318. * child, value, or priority.
  13319. */
  13320. function equalTo(value, key) {
  13321. validateKey('equalTo', 'key', key, true);
  13322. return new QueryEqualToValueConstraint(value, key);
  13323. }
  13324. /**
  13325. * Creates a new immutable instance of `Query` that is extended to also include
  13326. * additional query constraints.
  13327. *
  13328. * @param query - The Query instance to use as a base for the new constraints.
  13329. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13330. * @throws if any of the provided query constraints cannot be combined with the
  13331. * existing or new constraints.
  13332. */
  13333. function query(query, ...queryConstraints) {
  13334. let queryImpl = getModularInstance(query);
  13335. for (const constraint of queryConstraints) {
  13336. queryImpl = constraint._apply(queryImpl);
  13337. }
  13338. return queryImpl;
  13339. }
  13340. /**
  13341. * Define reference constructor in various modules
  13342. *
  13343. * We are doing this here to avoid several circular
  13344. * dependency issues
  13345. */
  13346. syncPointSetReferenceConstructor(ReferenceImpl);
  13347. syncTreeSetReferenceConstructor(ReferenceImpl);
  13348. /**
  13349. * @license
  13350. * Copyright 2020 Google LLC
  13351. *
  13352. * Licensed under the Apache License, Version 2.0 (the "License");
  13353. * you may not use this file except in compliance with the License.
  13354. * You may obtain a copy of the License at
  13355. *
  13356. * http://www.apache.org/licenses/LICENSE-2.0
  13357. *
  13358. * Unless required by applicable law or agreed to in writing, software
  13359. * distributed under the License is distributed on an "AS IS" BASIS,
  13360. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13361. * See the License for the specific language governing permissions and
  13362. * limitations under the License.
  13363. */
  13364. /**
  13365. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13366. * modifying this definition, consult the definition in:
  13367. *
  13368. * https://github.com/firebase/firebase-admin-node
  13369. *
  13370. * and make sure the two are consistent.
  13371. */
  13372. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13373. /**
  13374. * Creates and caches `Repo` instances.
  13375. */
  13376. const repos = {};
  13377. /**
  13378. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13379. */
  13380. let useRestClient = false;
  13381. /**
  13382. * Update an existing `Repo` in place to point to a new host/port.
  13383. */
  13384. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13385. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13386. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13387. /*isUsingEmulator=*/ true);
  13388. if (tokenProvider) {
  13389. repo.authTokenProvider_ = tokenProvider;
  13390. }
  13391. }
  13392. /**
  13393. * This function should only ever be called to CREATE a new database instance.
  13394. * @internal
  13395. */
  13396. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13397. let dbUrl = url || app.options.databaseURL;
  13398. if (dbUrl === undefined) {
  13399. if (!app.options.projectId) {
  13400. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13401. ' a Project ID when calling firebase.initializeApp().');
  13402. }
  13403. log('Using default host for project ', app.options.projectId);
  13404. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13405. }
  13406. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13407. let repoInfo = parsedUrl.repoInfo;
  13408. let isEmulator;
  13409. let dbEmulatorHost = undefined;
  13410. if (typeof process !== 'undefined' && process.env) {
  13411. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13412. }
  13413. if (dbEmulatorHost) {
  13414. isEmulator = true;
  13415. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13416. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13417. repoInfo = parsedUrl.repoInfo;
  13418. }
  13419. else {
  13420. isEmulator = !parsedUrl.repoInfo.secure;
  13421. }
  13422. const authTokenProvider = nodeAdmin && isEmulator
  13423. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13424. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13425. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13426. if (!pathIsEmpty(parsedUrl.path)) {
  13427. fatal('Database URL must point to the root of a Firebase Database ' +
  13428. '(not including a child path).');
  13429. }
  13430. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13431. return new Database(repo, app);
  13432. }
  13433. /**
  13434. * Remove the repo and make sure it is disconnected.
  13435. *
  13436. */
  13437. function repoManagerDeleteRepo(repo, appName) {
  13438. const appRepos = repos[appName];
  13439. // This should never happen...
  13440. if (!appRepos || appRepos[repo.key] !== repo) {
  13441. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13442. }
  13443. repoInterrupt(repo);
  13444. delete appRepos[repo.key];
  13445. }
  13446. /**
  13447. * Ensures a repo doesn't already exist and then creates one using the
  13448. * provided app.
  13449. *
  13450. * @param repoInfo - The metadata about the Repo
  13451. * @returns The Repo object for the specified server / repoName.
  13452. */
  13453. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13454. let appRepos = repos[app.name];
  13455. if (!appRepos) {
  13456. appRepos = {};
  13457. repos[app.name] = appRepos;
  13458. }
  13459. let repo = appRepos[repoInfo.toURLString()];
  13460. if (repo) {
  13461. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13462. }
  13463. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13464. appRepos[repoInfo.toURLString()] = repo;
  13465. return repo;
  13466. }
  13467. /**
  13468. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13469. */
  13470. function repoManagerForceRestClient(forceRestClient) {
  13471. useRestClient = forceRestClient;
  13472. }
  13473. /**
  13474. * Class representing a Firebase Realtime Database.
  13475. */
  13476. class Database {
  13477. /** @hideconstructor */
  13478. constructor(_repoInternal,
  13479. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13480. app) {
  13481. this._repoInternal = _repoInternal;
  13482. this.app = app;
  13483. /** Represents a `Database` instance. */
  13484. this['type'] = 'database';
  13485. /** Track if the instance has been used (root or repo accessed) */
  13486. this._instanceStarted = false;
  13487. }
  13488. get _repo() {
  13489. if (!this._instanceStarted) {
  13490. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13491. this._instanceStarted = true;
  13492. }
  13493. return this._repoInternal;
  13494. }
  13495. get _root() {
  13496. if (!this._rootInternal) {
  13497. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13498. }
  13499. return this._rootInternal;
  13500. }
  13501. _delete() {
  13502. if (this._rootInternal !== null) {
  13503. repoManagerDeleteRepo(this._repo, this.app.name);
  13504. this._repoInternal = null;
  13505. this._rootInternal = null;
  13506. }
  13507. return Promise.resolve();
  13508. }
  13509. _checkNotDeleted(apiName) {
  13510. if (this._rootInternal === null) {
  13511. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13512. }
  13513. }
  13514. }
  13515. function checkTransportInit() {
  13516. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13517. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13518. }
  13519. }
  13520. /**
  13521. * Force the use of websockets instead of longPolling.
  13522. */
  13523. function forceWebSockets() {
  13524. checkTransportInit();
  13525. BrowserPollConnection.forceDisallow();
  13526. }
  13527. /**
  13528. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13529. */
  13530. function forceLongPolling() {
  13531. checkTransportInit();
  13532. WebSocketConnection.forceDisallow();
  13533. BrowserPollConnection.forceAllow();
  13534. }
  13535. /**
  13536. * Returns the instance of the Realtime Database SDK that is associated
  13537. * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
  13538. * with default settings if no instance exists or if the existing instance uses
  13539. * a custom database URL.
  13540. *
  13541. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  13542. * Database instance is associated with.
  13543. * @param url - The URL of the Realtime Database instance to connect to. If not
  13544. * provided, the SDK connects to the default instance of the Firebase App.
  13545. * @returns The `Database` instance of the provided app.
  13546. */
  13547. function getDatabase(app = getApp(), url) {
  13548. const db = _getProvider(app, 'database').getImmediate({
  13549. identifier: url
  13550. });
  13551. if (!db._instanceStarted) {
  13552. const emulator = getDefaultEmulatorHostnameAndPort('database');
  13553. if (emulator) {
  13554. connectDatabaseEmulator(db, ...emulator);
  13555. }
  13556. }
  13557. return db;
  13558. }
  13559. /**
  13560. * Modify the provided instance to communicate with the Realtime Database
  13561. * emulator.
  13562. *
  13563. * <p>Note: This method must be called before performing any other operation.
  13564. *
  13565. * @param db - The instance to modify.
  13566. * @param host - The emulator host (ex: localhost)
  13567. * @param port - The emulator port (ex: 8080)
  13568. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13569. */
  13570. function connectDatabaseEmulator(db, host, port, options = {}) {
  13571. db = getModularInstance(db);
  13572. db._checkNotDeleted('useEmulator');
  13573. if (db._instanceStarted) {
  13574. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13575. }
  13576. const repo = db._repoInternal;
  13577. let tokenProvider = undefined;
  13578. if (repo.repoInfo_.nodeAdmin) {
  13579. if (options.mockUserToken) {
  13580. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13581. }
  13582. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13583. }
  13584. else if (options.mockUserToken) {
  13585. const token = typeof options.mockUserToken === 'string'
  13586. ? options.mockUserToken
  13587. : createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13588. tokenProvider = new EmulatorTokenProvider(token);
  13589. }
  13590. // Modify the repo to apply emulator settings
  13591. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13592. }
  13593. /**
  13594. * Disconnects from the server (all Database operations will be completed
  13595. * offline).
  13596. *
  13597. * The client automatically maintains a persistent connection to the Database
  13598. * server, which will remain active indefinitely and reconnect when
  13599. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13600. * to control the client connection in cases where a persistent connection is
  13601. * undesirable.
  13602. *
  13603. * While offline, the client will no longer receive data updates from the
  13604. * Database. However, all Database operations performed locally will continue to
  13605. * immediately fire events, allowing your application to continue behaving
  13606. * normally. Additionally, each operation performed locally will automatically
  13607. * be queued and retried upon reconnection to the Database server.
  13608. *
  13609. * To reconnect to the Database and begin receiving remote events, see
  13610. * `goOnline()`.
  13611. *
  13612. * @param db - The instance to disconnect.
  13613. */
  13614. function goOffline(db) {
  13615. db = getModularInstance(db);
  13616. db._checkNotDeleted('goOffline');
  13617. repoInterrupt(db._repo);
  13618. }
  13619. /**
  13620. * Reconnects to the server and synchronizes the offline Database state
  13621. * with the server state.
  13622. *
  13623. * This method should be used after disabling the active connection with
  13624. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13625. * and fire the appropriate events so that your client "catches up"
  13626. * automatically.
  13627. *
  13628. * @param db - The instance to reconnect.
  13629. */
  13630. function goOnline(db) {
  13631. db = getModularInstance(db);
  13632. db._checkNotDeleted('goOnline');
  13633. repoResume(db._repo);
  13634. }
  13635. function enableLogging(logger, persistent) {
  13636. enableLogging$1(logger, persistent);
  13637. }
  13638. /**
  13639. * @license
  13640. * Copyright 2021 Google LLC
  13641. *
  13642. * Licensed under the Apache License, Version 2.0 (the "License");
  13643. * you may not use this file except in compliance with the License.
  13644. * You may obtain a copy of the License at
  13645. *
  13646. * http://www.apache.org/licenses/LICENSE-2.0
  13647. *
  13648. * Unless required by applicable law or agreed to in writing, software
  13649. * distributed under the License is distributed on an "AS IS" BASIS,
  13650. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13651. * See the License for the specific language governing permissions and
  13652. * limitations under the License.
  13653. */
  13654. function registerDatabase(variant) {
  13655. setSDKVersion(SDK_VERSION$1);
  13656. _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {
  13657. const app = container.getProvider('app').getImmediate();
  13658. const authProvider = container.getProvider('auth-internal');
  13659. const appCheckProvider = container.getProvider('app-check-internal');
  13660. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  13661. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  13662. registerVersion(name, version, variant);
  13663. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  13664. registerVersion(name, version, 'esm2017');
  13665. }
  13666. /**
  13667. * @license
  13668. * Copyright 2020 Google LLC
  13669. *
  13670. * Licensed under the Apache License, Version 2.0 (the "License");
  13671. * you may not use this file except in compliance with the License.
  13672. * You may obtain a copy of the License at
  13673. *
  13674. * http://www.apache.org/licenses/LICENSE-2.0
  13675. *
  13676. * Unless required by applicable law or agreed to in writing, software
  13677. * distributed under the License is distributed on an "AS IS" BASIS,
  13678. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13679. * See the License for the specific language governing permissions and
  13680. * limitations under the License.
  13681. */
  13682. const SERVER_TIMESTAMP = {
  13683. '.sv': 'timestamp'
  13684. };
  13685. /**
  13686. * Returns a placeholder value for auto-populating the current timestamp (time
  13687. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13688. * servers.
  13689. */
  13690. function serverTimestamp() {
  13691. return SERVER_TIMESTAMP;
  13692. }
  13693. /**
  13694. * Returns a placeholder value that can be used to atomically increment the
  13695. * current database value by the provided delta.
  13696. *
  13697. * @param delta - the amount to modify the current value atomically.
  13698. * @returns A placeholder value for modifying data atomically server-side.
  13699. */
  13700. function increment(delta) {
  13701. return {
  13702. '.sv': {
  13703. 'increment': delta
  13704. }
  13705. };
  13706. }
  13707. /**
  13708. * @license
  13709. * Copyright 2020 Google LLC
  13710. *
  13711. * Licensed under the Apache License, Version 2.0 (the "License");
  13712. * you may not use this file except in compliance with the License.
  13713. * You may obtain a copy of the License at
  13714. *
  13715. * http://www.apache.org/licenses/LICENSE-2.0
  13716. *
  13717. * Unless required by applicable law or agreed to in writing, software
  13718. * distributed under the License is distributed on an "AS IS" BASIS,
  13719. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13720. * See the License for the specific language governing permissions and
  13721. * limitations under the License.
  13722. */
  13723. /**
  13724. * A type for the resolve value of {@link runTransaction}.
  13725. */
  13726. class TransactionResult {
  13727. /** @hideconstructor */
  13728. constructor(
  13729. /** Whether the transaction was successfully committed. */
  13730. committed,
  13731. /** The resulting data snapshot. */
  13732. snapshot) {
  13733. this.committed = committed;
  13734. this.snapshot = snapshot;
  13735. }
  13736. /** Returns a JSON-serializable representation of this object. */
  13737. toJSON() {
  13738. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13739. }
  13740. }
  13741. /**
  13742. * Atomically modifies the data at this location.
  13743. *
  13744. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13745. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13746. * used to modify the existing value to a new value, ensuring there are no
  13747. * conflicts with other clients writing to the same location at the same time.
  13748. *
  13749. * To accomplish this, you pass `runTransaction()` an update function which is
  13750. * used to transform the current value into a new value. If another client
  13751. * writes to the location before your new value is successfully written, your
  13752. * update function will be called again with the new current value, and the
  13753. * write will be retried. This will happen repeatedly until your write succeeds
  13754. * without conflict or you abort the transaction by not returning a value from
  13755. * your update function.
  13756. *
  13757. * Note: Modifying data with `set()` will cancel any pending transactions at
  13758. * that location, so extreme care should be taken if mixing `set()` and
  13759. * `runTransaction()` to update the same data.
  13760. *
  13761. * Note: When using transactions with Security and Firebase Rules in place, be
  13762. * aware that a client needs `.read` access in addition to `.write` access in
  13763. * order to perform a transaction. This is because the client-side nature of
  13764. * transactions requires the client to read the data in order to transactionally
  13765. * update it.
  13766. *
  13767. * @param ref - The location to atomically modify.
  13768. * @param transactionUpdate - A developer-supplied function which will be passed
  13769. * the current data stored at this location (as a JavaScript object). The
  13770. * function should return the new value it would like written (as a JavaScript
  13771. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13772. * transaction will be aborted and the data at this location will not be
  13773. * modified.
  13774. * @param options - An options object to configure transactions.
  13775. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13776. * callback to handle success and failure.
  13777. */
  13778. function runTransaction(ref,
  13779. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13780. transactionUpdate, options) {
  13781. var _a;
  13782. ref = getModularInstance(ref);
  13783. validateWritablePath('Reference.transaction', ref._path);
  13784. if (ref.key === '.length' || ref.key === '.keys') {
  13785. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13786. }
  13787. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13788. const deferred = new Deferred();
  13789. const promiseComplete = (error, committed, node) => {
  13790. let dataSnapshot = null;
  13791. if (error) {
  13792. deferred.reject(error);
  13793. }
  13794. else {
  13795. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13796. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13797. }
  13798. };
  13799. // Add a watch to make sure we get server updates.
  13800. const unwatcher = onValue(ref, () => { });
  13801. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13802. return deferred.promise;
  13803. }
  13804. /**
  13805. * @license
  13806. * Copyright 2017 Google LLC
  13807. *
  13808. * Licensed under the Apache License, Version 2.0 (the "License");
  13809. * you may not use this file except in compliance with the License.
  13810. * You may obtain a copy of the License at
  13811. *
  13812. * http://www.apache.org/licenses/LICENSE-2.0
  13813. *
  13814. * Unless required by applicable law or agreed to in writing, software
  13815. * distributed under the License is distributed on an "AS IS" BASIS,
  13816. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13817. * See the License for the specific language governing permissions and
  13818. * limitations under the License.
  13819. */
  13820. PersistentConnection;
  13821. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13822. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13823. this.sendRequest('q', { p: pathString }, onComplete);
  13824. };
  13825. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13826. PersistentConnection.prototype.echo = function (data, onEcho) {
  13827. this.sendRequest('echo', { d: data }, onEcho);
  13828. };
  13829. // RealTimeConnection properties that we use in tests.
  13830. Connection;
  13831. /**
  13832. * @internal
  13833. */
  13834. const hijackHash = function (newHash) {
  13835. const oldPut = PersistentConnection.prototype.put;
  13836. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13837. if (hash !== undefined) {
  13838. hash = newHash();
  13839. }
  13840. oldPut.call(this, pathString, data, onComplete, hash);
  13841. };
  13842. return function () {
  13843. PersistentConnection.prototype.put = oldPut;
  13844. };
  13845. };
  13846. RepoInfo;
  13847. /**
  13848. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13849. * @internal
  13850. */
  13851. const forceRestClient = function (forceRestClient) {
  13852. repoManagerForceRestClient(forceRestClient);
  13853. };
  13854. /**
  13855. * Firebase Realtime Database
  13856. *
  13857. * @packageDocumentation
  13858. */
  13859. registerDatabase();
  13860. export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };
  13861. //# sourceMappingURL=index.esm2017.js.map