index.standalone.js 538 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var Websocket = require('faye-websocket');
  4. var util = require('@firebase/util');
  5. var logger$1 = require('@firebase/logger');
  6. var component = require('@firebase/component');
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket);
  9. /**
  10. * @license
  11. * Copyright 2017 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. const PROTOCOL_VERSION = '5';
  26. const VERSION_PARAM = 'v';
  27. const TRANSPORT_SESSION_PARAM = 's';
  28. const REFERER_PARAM = 'r';
  29. const FORGE_REF = 'f';
  30. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  31. // firebase.corp.google.com
  32. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  33. const LAST_SESSION_PARAM = 'ls';
  34. const APPLICATION_ID_PARAM = 'p';
  35. const APP_CHECK_TOKEN_PARAM = 'ac';
  36. const WEBSOCKET = 'websocket';
  37. const LONG_POLLING = 'long_polling';
  38. /**
  39. * @license
  40. * Copyright 2017 Google LLC
  41. *
  42. * Licensed under the Apache License, Version 2.0 (the "License");
  43. * you may not use this file except in compliance with the License.
  44. * You may obtain a copy of the License at
  45. *
  46. * http://www.apache.org/licenses/LICENSE-2.0
  47. *
  48. * Unless required by applicable law or agreed to in writing, software
  49. * distributed under the License is distributed on an "AS IS" BASIS,
  50. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  51. * See the License for the specific language governing permissions and
  52. * limitations under the License.
  53. */
  54. /**
  55. * Wraps a DOM Storage object and:
  56. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  57. * - prefixes names with "firebase:" to avoid collisions with app data.
  58. *
  59. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  60. * and one for localStorage.
  61. *
  62. */
  63. class DOMStorageWrapper {
  64. /**
  65. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  66. */
  67. constructor(domStorage_) {
  68. this.domStorage_ = domStorage_;
  69. // Use a prefix to avoid collisions with other stuff saved by the app.
  70. this.prefix_ = 'firebase:';
  71. }
  72. /**
  73. * @param key - The key to save the value under
  74. * @param value - The value being stored, or null to remove the key.
  75. */
  76. set(key, value) {
  77. if (value == null) {
  78. this.domStorage_.removeItem(this.prefixedName_(key));
  79. }
  80. else {
  81. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  82. }
  83. }
  84. /**
  85. * @returns The value that was stored under this key, or null
  86. */
  87. get(key) {
  88. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  89. if (storedVal == null) {
  90. return null;
  91. }
  92. else {
  93. return util.jsonEval(storedVal);
  94. }
  95. }
  96. remove(key) {
  97. this.domStorage_.removeItem(this.prefixedName_(key));
  98. }
  99. prefixedName_(name) {
  100. return this.prefix_ + name;
  101. }
  102. toString() {
  103. return this.domStorage_.toString();
  104. }
  105. }
  106. /**
  107. * @license
  108. * Copyright 2017 Google LLC
  109. *
  110. * Licensed under the Apache License, Version 2.0 (the "License");
  111. * you may not use this file except in compliance with the License.
  112. * You may obtain a copy of the License at
  113. *
  114. * http://www.apache.org/licenses/LICENSE-2.0
  115. *
  116. * Unless required by applicable law or agreed to in writing, software
  117. * distributed under the License is distributed on an "AS IS" BASIS,
  118. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  119. * See the License for the specific language governing permissions and
  120. * limitations under the License.
  121. */
  122. /**
  123. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  124. * (TODO: create interface for both to implement).
  125. */
  126. class MemoryStorage {
  127. constructor() {
  128. this.cache_ = {};
  129. this.isInMemoryStorage = true;
  130. }
  131. set(key, value) {
  132. if (value == null) {
  133. delete this.cache_[key];
  134. }
  135. else {
  136. this.cache_[key] = value;
  137. }
  138. }
  139. get(key) {
  140. if (util.contains(this.cache_, key)) {
  141. return this.cache_[key];
  142. }
  143. return null;
  144. }
  145. remove(key) {
  146. delete this.cache_[key];
  147. }
  148. }
  149. /**
  150. * @license
  151. * Copyright 2017 Google LLC
  152. *
  153. * Licensed under the Apache License, Version 2.0 (the "License");
  154. * you may not use this file except in compliance with the License.
  155. * You may obtain a copy of the License at
  156. *
  157. * http://www.apache.org/licenses/LICENSE-2.0
  158. *
  159. * Unless required by applicable law or agreed to in writing, software
  160. * distributed under the License is distributed on an "AS IS" BASIS,
  161. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  162. * See the License for the specific language governing permissions and
  163. * limitations under the License.
  164. */
  165. /**
  166. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  167. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  168. * to reflect this type
  169. *
  170. * @param domStorageName - Name of the underlying storage object
  171. * (e.g. 'localStorage' or 'sessionStorage').
  172. * @returns Turning off type information until a common interface is defined.
  173. */
  174. const createStoragefor = function (domStorageName) {
  175. try {
  176. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  177. // so it must be inside the try/catch.
  178. if (typeof window !== 'undefined' &&
  179. typeof window[domStorageName] !== 'undefined') {
  180. // Need to test cache. Just because it's here doesn't mean it works
  181. const domStorage = window[domStorageName];
  182. domStorage.setItem('firebase:sentinel', 'cache');
  183. domStorage.removeItem('firebase:sentinel');
  184. return new DOMStorageWrapper(domStorage);
  185. }
  186. }
  187. catch (e) { }
  188. // Failed to create wrapper. Just return in-memory storage.
  189. // TODO: log?
  190. return new MemoryStorage();
  191. };
  192. /** A storage object that lasts across sessions */
  193. const PersistentStorage = createStoragefor('localStorage');
  194. /** A storage object that only lasts one session */
  195. const SessionStorage = createStoragefor('sessionStorage');
  196. /**
  197. * @license
  198. * Copyright 2017 Google LLC
  199. *
  200. * Licensed under the Apache License, Version 2.0 (the "License");
  201. * you may not use this file except in compliance with the License.
  202. * You may obtain a copy of the License at
  203. *
  204. * http://www.apache.org/licenses/LICENSE-2.0
  205. *
  206. * Unless required by applicable law or agreed to in writing, software
  207. * distributed under the License is distributed on an "AS IS" BASIS,
  208. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  209. * See the License for the specific language governing permissions and
  210. * limitations under the License.
  211. */
  212. const logClient = new logger$1.Logger('@firebase/database');
  213. /**
  214. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  215. */
  216. const LUIDGenerator = (function () {
  217. let id = 1;
  218. return function () {
  219. return id++;
  220. };
  221. })();
  222. /**
  223. * Sha1 hash of the input string
  224. * @param str - The string to hash
  225. * @returns {!string} The resulting hash
  226. */
  227. const sha1 = function (str) {
  228. const utf8Bytes = util.stringToByteArray(str);
  229. const sha1 = new util.Sha1();
  230. sha1.update(utf8Bytes);
  231. const sha1Bytes = sha1.digest();
  232. return util.base64.encodeByteArray(sha1Bytes);
  233. };
  234. const buildLogMessage_ = function (...varArgs) {
  235. let message = '';
  236. for (let i = 0; i < varArgs.length; i++) {
  237. const arg = varArgs[i];
  238. if (Array.isArray(arg) ||
  239. (arg &&
  240. typeof arg === 'object' &&
  241. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  242. typeof arg.length === 'number')) {
  243. message += buildLogMessage_.apply(null, arg);
  244. }
  245. else if (typeof arg === 'object') {
  246. message += util.stringify(arg);
  247. }
  248. else {
  249. message += arg;
  250. }
  251. message += ' ';
  252. }
  253. return message;
  254. };
  255. /**
  256. * Use this for all debug messages in Firebase.
  257. */
  258. let logger = null;
  259. /**
  260. * Flag to check for log availability on first log message
  261. */
  262. let firstLog_ = true;
  263. /**
  264. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  265. * @param logger_ - A flag to turn on logging, or a custom logger
  266. * @param persistent - Whether or not to persist logging settings across refreshes
  267. */
  268. const enableLogging$1 = function (logger_, persistent) {
  269. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  270. if (logger_ === true) {
  271. logClient.logLevel = logger$1.LogLevel.VERBOSE;
  272. logger = logClient.log.bind(logClient);
  273. if (persistent) {
  274. SessionStorage.set('logging_enabled', true);
  275. }
  276. }
  277. else if (typeof logger_ === 'function') {
  278. logger = logger_;
  279. }
  280. else {
  281. logger = null;
  282. SessionStorage.remove('logging_enabled');
  283. }
  284. };
  285. const log = function (...varArgs) {
  286. if (firstLog_ === true) {
  287. firstLog_ = false;
  288. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  289. enableLogging$1(true);
  290. }
  291. }
  292. if (logger) {
  293. const message = buildLogMessage_.apply(null, varArgs);
  294. logger(message);
  295. }
  296. };
  297. const logWrapper = function (prefix) {
  298. return function (...varArgs) {
  299. log(prefix, ...varArgs);
  300. };
  301. };
  302. const error = function (...varArgs) {
  303. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  304. logClient.error(message);
  305. };
  306. const fatal = function (...varArgs) {
  307. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  308. logClient.error(message);
  309. throw new Error(message);
  310. };
  311. const warn = function (...varArgs) {
  312. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  313. logClient.warn(message);
  314. };
  315. /**
  316. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  317. * does not use https.
  318. */
  319. const warnIfPageIsSecure = function () {
  320. // Be very careful accessing browser globals. Who knows what may or may not exist.
  321. if (typeof window !== 'undefined' &&
  322. window.location &&
  323. window.location.protocol &&
  324. window.location.protocol.indexOf('https:') !== -1) {
  325. warn('Insecure Firebase access from a secure page. ' +
  326. 'Please use https in calls to new Firebase().');
  327. }
  328. };
  329. /**
  330. * Returns true if data is NaN, or +/- Infinity.
  331. */
  332. const isInvalidJSONNumber = function (data) {
  333. return (typeof data === 'number' &&
  334. (data !== data || // NaN
  335. data === Number.POSITIVE_INFINITY ||
  336. data === Number.NEGATIVE_INFINITY));
  337. };
  338. const executeWhenDOMReady = function (fn) {
  339. if (util.isNodeSdk() || document.readyState === 'complete') {
  340. fn();
  341. }
  342. else {
  343. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  344. // fire before onload), but fall back to onload.
  345. let called = false;
  346. const wrappedFn = function () {
  347. if (!document.body) {
  348. setTimeout(wrappedFn, Math.floor(10));
  349. return;
  350. }
  351. if (!called) {
  352. called = true;
  353. fn();
  354. }
  355. };
  356. if (document.addEventListener) {
  357. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  358. // fallback to onload.
  359. window.addEventListener('load', wrappedFn, false);
  360. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  361. }
  362. else if (document.attachEvent) {
  363. // IE.
  364. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  365. document.attachEvent('onreadystatechange', () => {
  366. if (document.readyState === 'complete') {
  367. wrappedFn();
  368. }
  369. });
  370. // fallback to onload.
  371. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  372. window.attachEvent('onload', wrappedFn);
  373. // jQuery has an extra hack for IE that we could employ (based on
  374. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  375. // I'm hoping we don't need it.
  376. }
  377. }
  378. };
  379. /**
  380. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  381. */
  382. const MIN_NAME = '[MIN_NAME]';
  383. /**
  384. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  385. */
  386. const MAX_NAME = '[MAX_NAME]';
  387. /**
  388. * Compares valid Firebase key names, plus min and max name
  389. */
  390. const nameCompare = function (a, b) {
  391. if (a === b) {
  392. return 0;
  393. }
  394. else if (a === MIN_NAME || b === MAX_NAME) {
  395. return -1;
  396. }
  397. else if (b === MIN_NAME || a === MAX_NAME) {
  398. return 1;
  399. }
  400. else {
  401. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  402. if (aAsInt !== null) {
  403. if (bAsInt !== null) {
  404. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  405. }
  406. else {
  407. return -1;
  408. }
  409. }
  410. else if (bAsInt !== null) {
  411. return 1;
  412. }
  413. else {
  414. return a < b ? -1 : 1;
  415. }
  416. }
  417. };
  418. /**
  419. * @returns {!number} comparison result.
  420. */
  421. const stringCompare = function (a, b) {
  422. if (a === b) {
  423. return 0;
  424. }
  425. else if (a < b) {
  426. return -1;
  427. }
  428. else {
  429. return 1;
  430. }
  431. };
  432. const requireKey = function (key, obj) {
  433. if (obj && key in obj) {
  434. return obj[key];
  435. }
  436. else {
  437. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  438. }
  439. };
  440. const ObjectToUniqueKey = function (obj) {
  441. if (typeof obj !== 'object' || obj === null) {
  442. return util.stringify(obj);
  443. }
  444. const keys = [];
  445. // eslint-disable-next-line guard-for-in
  446. for (const k in obj) {
  447. keys.push(k);
  448. }
  449. // Export as json, but with the keys sorted.
  450. keys.sort();
  451. let key = '{';
  452. for (let i = 0; i < keys.length; i++) {
  453. if (i !== 0) {
  454. key += ',';
  455. }
  456. key += util.stringify(keys[i]);
  457. key += ':';
  458. key += ObjectToUniqueKey(obj[keys[i]]);
  459. }
  460. key += '}';
  461. return key;
  462. };
  463. /**
  464. * Splits a string into a number of smaller segments of maximum size
  465. * @param str - The string
  466. * @param segsize - The maximum number of chars in the string.
  467. * @returns The string, split into appropriately-sized chunks
  468. */
  469. const splitStringBySize = function (str, segsize) {
  470. const len = str.length;
  471. if (len <= segsize) {
  472. return [str];
  473. }
  474. const dataSegs = [];
  475. for (let c = 0; c < len; c += segsize) {
  476. if (c + segsize > len) {
  477. dataSegs.push(str.substring(c, len));
  478. }
  479. else {
  480. dataSegs.push(str.substring(c, c + segsize));
  481. }
  482. }
  483. return dataSegs;
  484. };
  485. /**
  486. * Apply a function to each (key, value) pair in an object or
  487. * apply a function to each (index, value) pair in an array
  488. * @param obj - The object or array to iterate over
  489. * @param fn - The function to apply
  490. */
  491. function each(obj, fn) {
  492. for (const key in obj) {
  493. if (obj.hasOwnProperty(key)) {
  494. fn(key, obj[key]);
  495. }
  496. }
  497. }
  498. /**
  499. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  500. * I made one modification at the end and removed the NaN / Infinity
  501. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  502. * @param v - A double
  503. *
  504. */
  505. const doubleToIEEE754String = function (v) {
  506. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  507. const ebits = 11, fbits = 52;
  508. const bias = (1 << (ebits - 1)) - 1;
  509. let s, e, f, ln, i;
  510. // Compute sign, exponent, fraction
  511. // Skip NaN / Infinity handling --MJL.
  512. if (v === 0) {
  513. e = 0;
  514. f = 0;
  515. s = 1 / v === -Infinity ? 1 : 0;
  516. }
  517. else {
  518. s = v < 0;
  519. v = Math.abs(v);
  520. if (v >= Math.pow(2, 1 - bias)) {
  521. // Normalized
  522. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  523. e = ln + bias;
  524. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  525. }
  526. else {
  527. // Denormalized
  528. e = 0;
  529. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  530. }
  531. }
  532. // Pack sign, exponent, fraction
  533. const bits = [];
  534. for (i = fbits; i; i -= 1) {
  535. bits.push(f % 2 ? 1 : 0);
  536. f = Math.floor(f / 2);
  537. }
  538. for (i = ebits; i; i -= 1) {
  539. bits.push(e % 2 ? 1 : 0);
  540. e = Math.floor(e / 2);
  541. }
  542. bits.push(s ? 1 : 0);
  543. bits.reverse();
  544. const str = bits.join('');
  545. // Return the data as a hex string. --MJL
  546. let hexByteString = '';
  547. for (i = 0; i < 64; i += 8) {
  548. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  549. if (hexByte.length === 1) {
  550. hexByte = '0' + hexByte;
  551. }
  552. hexByteString = hexByteString + hexByte;
  553. }
  554. return hexByteString.toLowerCase();
  555. };
  556. /**
  557. * Used to detect if we're in a Chrome content script (which executes in an
  558. * isolated environment where long-polling doesn't work).
  559. */
  560. const isChromeExtensionContentScript = function () {
  561. return !!(typeof window === 'object' &&
  562. window['chrome'] &&
  563. window['chrome']['extension'] &&
  564. !/^chrome/.test(window.location.href));
  565. };
  566. /**
  567. * Used to detect if we're in a Windows 8 Store app.
  568. */
  569. const isWindowsStoreApp = function () {
  570. // Check for the presence of a couple WinRT globals
  571. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  572. };
  573. /**
  574. * Converts a server error code to a JavaScript Error
  575. */
  576. function errorForServerCode(code, query) {
  577. let reason = 'Unknown Error';
  578. if (code === 'too_big') {
  579. reason =
  580. 'The data requested exceeds the maximum size ' +
  581. 'that can be accessed with a single request.';
  582. }
  583. else if (code === 'permission_denied') {
  584. reason = "Client doesn't have permission to access the desired data.";
  585. }
  586. else if (code === 'unavailable') {
  587. reason = 'The service is unavailable';
  588. }
  589. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  590. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  591. error.code = code.toUpperCase();
  592. return error;
  593. }
  594. /**
  595. * Used to test for integer-looking strings
  596. */
  597. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  598. /**
  599. * For use in keys, the minimum possible 32-bit integer.
  600. */
  601. const INTEGER_32_MIN = -2147483648;
  602. /**
  603. * For use in keys, the maximum possible 32-bit integer.
  604. */
  605. const INTEGER_32_MAX = 2147483647;
  606. /**
  607. * If the string contains a 32-bit integer, return it. Else return null.
  608. */
  609. const tryParseInt = function (str) {
  610. if (INTEGER_REGEXP_.test(str)) {
  611. const intVal = Number(str);
  612. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  613. return intVal;
  614. }
  615. }
  616. return null;
  617. };
  618. /**
  619. * Helper to run some code but catch any exceptions and re-throw them later.
  620. * Useful for preventing user callbacks from breaking internal code.
  621. *
  622. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  623. * convenient (we don't have to try to figure out when is a safe point to
  624. * re-throw it), and the behavior seems reasonable:
  625. *
  626. * * If you aren't pausing on exceptions, you get an error in the console with
  627. * the correct stack trace.
  628. * * If you're pausing on all exceptions, the debugger will pause on your
  629. * exception and then again when we rethrow it.
  630. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  631. * on us re-throwing it.
  632. *
  633. * @param fn - The code to guard.
  634. */
  635. const exceptionGuard = function (fn) {
  636. try {
  637. fn();
  638. }
  639. catch (e) {
  640. // Re-throw exception when it's safe.
  641. setTimeout(() => {
  642. // It used to be that "throw e" would result in a good console error with
  643. // relevant context, but as of Chrome 39, you just get the firebase.js
  644. // file/line number where we re-throw it, which is useless. So we log
  645. // e.stack explicitly.
  646. const stack = e.stack || '';
  647. warn('Exception was thrown by user callback.', stack);
  648. throw e;
  649. }, Math.floor(0));
  650. }
  651. };
  652. /**
  653. * @returns {boolean} true if we think we're currently being crawled.
  654. */
  655. const beingCrawled = function () {
  656. const userAgent = (typeof window === 'object' &&
  657. window['navigator'] &&
  658. window['navigator']['userAgent']) ||
  659. '';
  660. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  661. // believe to support JavaScript/AJAX rendering.
  662. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  663. // would have seen the page" is flaky if we don't treat it as a crawler.
  664. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  665. };
  666. /**
  667. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  668. *
  669. * It is removed with clearTimeout() as normal.
  670. *
  671. * @param fn - Function to run.
  672. * @param time - Milliseconds to wait before running.
  673. * @returns The setTimeout() return value.
  674. */
  675. const setTimeoutNonBlocking = function (fn, time) {
  676. const timeout = setTimeout(fn, time);
  677. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  678. if (typeof timeout === 'number' &&
  679. // @ts-ignore Is only defined in Deno environments.
  680. typeof Deno !== 'undefined' &&
  681. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  682. Deno['unrefTimer']) {
  683. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  684. Deno.unrefTimer(timeout);
  685. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  686. }
  687. else if (typeof timeout === 'object' && timeout['unref']) {
  688. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  689. timeout['unref']();
  690. }
  691. return timeout;
  692. };
  693. /**
  694. * @license
  695. * Copyright 2017 Google LLC
  696. *
  697. * Licensed under the Apache License, Version 2.0 (the "License");
  698. * you may not use this file except in compliance with the License.
  699. * You may obtain a copy of the License at
  700. *
  701. * http://www.apache.org/licenses/LICENSE-2.0
  702. *
  703. * Unless required by applicable law or agreed to in writing, software
  704. * distributed under the License is distributed on an "AS IS" BASIS,
  705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  706. * See the License for the specific language governing permissions and
  707. * limitations under the License.
  708. */
  709. /**
  710. * A class that holds metadata about a Repo object
  711. */
  712. class RepoInfo {
  713. /**
  714. * @param host - Hostname portion of the url for the repo
  715. * @param secure - Whether or not this repo is accessed over ssl
  716. * @param namespace - The namespace represented by the repo
  717. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  718. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  719. * @param persistenceKey - Override the default session persistence storage key
  720. */
  721. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {
  722. this.secure = secure;
  723. this.namespace = namespace;
  724. this.webSocketOnly = webSocketOnly;
  725. this.nodeAdmin = nodeAdmin;
  726. this.persistenceKey = persistenceKey;
  727. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  728. this.isUsingEmulator = isUsingEmulator;
  729. this._host = host.toLowerCase();
  730. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  731. this.internalHost =
  732. PersistentStorage.get('host:' + host) || this._host;
  733. }
  734. isCacheableHost() {
  735. return this.internalHost.substr(0, 2) === 's-';
  736. }
  737. isCustomHost() {
  738. return (this._domain !== 'firebaseio.com' &&
  739. this._domain !== 'firebaseio-demo.com');
  740. }
  741. get host() {
  742. return this._host;
  743. }
  744. set host(newHost) {
  745. if (newHost !== this.internalHost) {
  746. this.internalHost = newHost;
  747. if (this.isCacheableHost()) {
  748. PersistentStorage.set('host:' + this._host, this.internalHost);
  749. }
  750. }
  751. }
  752. toString() {
  753. let str = this.toURLString();
  754. if (this.persistenceKey) {
  755. str += '<' + this.persistenceKey + '>';
  756. }
  757. return str;
  758. }
  759. toURLString() {
  760. const protocol = this.secure ? 'https://' : 'http://';
  761. const query = this.includeNamespaceInQueryParams
  762. ? `?ns=${this.namespace}`
  763. : '';
  764. return `${protocol}${this.host}/${query}`;
  765. }
  766. }
  767. function repoInfoNeedsQueryParam(repoInfo) {
  768. return (repoInfo.host !== repoInfo.internalHost ||
  769. repoInfo.isCustomHost() ||
  770. repoInfo.includeNamespaceInQueryParams);
  771. }
  772. /**
  773. * Returns the websocket URL for this repo
  774. * @param repoInfo - RepoInfo object
  775. * @param type - of connection
  776. * @param params - list
  777. * @returns The URL for this repo
  778. */
  779. function repoInfoConnectionURL(repoInfo, type, params) {
  780. util.assert(typeof type === 'string', 'typeof type must == string');
  781. util.assert(typeof params === 'object', 'typeof params must == object');
  782. let connURL;
  783. if (type === WEBSOCKET) {
  784. connURL =
  785. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  786. }
  787. else if (type === LONG_POLLING) {
  788. connURL =
  789. (repoInfo.secure ? 'https://' : 'http://') +
  790. repoInfo.internalHost +
  791. '/.lp?';
  792. }
  793. else {
  794. throw new Error('Unknown connection type: ' + type);
  795. }
  796. if (repoInfoNeedsQueryParam(repoInfo)) {
  797. params['ns'] = repoInfo.namespace;
  798. }
  799. const pairs = [];
  800. each(params, (key, value) => {
  801. pairs.push(key + '=' + value);
  802. });
  803. return connURL + pairs.join('&');
  804. }
  805. /**
  806. * @license
  807. * Copyright 2017 Google LLC
  808. *
  809. * Licensed under the Apache License, Version 2.0 (the "License");
  810. * you may not use this file except in compliance with the License.
  811. * You may obtain a copy of the License at
  812. *
  813. * http://www.apache.org/licenses/LICENSE-2.0
  814. *
  815. * Unless required by applicable law or agreed to in writing, software
  816. * distributed under the License is distributed on an "AS IS" BASIS,
  817. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  818. * See the License for the specific language governing permissions and
  819. * limitations under the License.
  820. */
  821. /**
  822. * Tracks a collection of stats.
  823. */
  824. class StatsCollection {
  825. constructor() {
  826. this.counters_ = {};
  827. }
  828. incrementCounter(name, amount = 1) {
  829. if (!util.contains(this.counters_, name)) {
  830. this.counters_[name] = 0;
  831. }
  832. this.counters_[name] += amount;
  833. }
  834. get() {
  835. return util.deepCopy(this.counters_);
  836. }
  837. }
  838. /**
  839. * @license
  840. * Copyright 2017 Google LLC
  841. *
  842. * Licensed under the Apache License, Version 2.0 (the "License");
  843. * you may not use this file except in compliance with the License.
  844. * You may obtain a copy of the License at
  845. *
  846. * http://www.apache.org/licenses/LICENSE-2.0
  847. *
  848. * Unless required by applicable law or agreed to in writing, software
  849. * distributed under the License is distributed on an "AS IS" BASIS,
  850. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  851. * See the License for the specific language governing permissions and
  852. * limitations under the License.
  853. */
  854. const collections = {};
  855. const reporters = {};
  856. function statsManagerGetCollection(repoInfo) {
  857. const hashString = repoInfo.toString();
  858. if (!collections[hashString]) {
  859. collections[hashString] = new StatsCollection();
  860. }
  861. return collections[hashString];
  862. }
  863. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  864. const hashString = repoInfo.toString();
  865. if (!reporters[hashString]) {
  866. reporters[hashString] = creatorFunction();
  867. }
  868. return reporters[hashString];
  869. }
  870. /**
  871. * @license
  872. * Copyright 2019 Google LLC
  873. *
  874. * Licensed under the Apache License, Version 2.0 (the "License");
  875. * you may not use this file except in compliance with the License.
  876. * You may obtain a copy of the License at
  877. *
  878. * http://www.apache.org/licenses/LICENSE-2.0
  879. *
  880. * Unless required by applicable law or agreed to in writing, software
  881. * distributed under the License is distributed on an "AS IS" BASIS,
  882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  883. * See the License for the specific language governing permissions and
  884. * limitations under the License.
  885. */
  886. /** The semver (www.semver.org) version of the SDK. */
  887. let SDK_VERSION = '';
  888. /**
  889. * SDK_VERSION should be set before any database instance is created
  890. * @internal
  891. */
  892. function setSDKVersion(version) {
  893. SDK_VERSION = version;
  894. }
  895. /**
  896. * @license
  897. * Copyright 2017 Google LLC
  898. *
  899. * Licensed under the Apache License, Version 2.0 (the "License");
  900. * you may not use this file except in compliance with the License.
  901. * You may obtain a copy of the License at
  902. *
  903. * http://www.apache.org/licenses/LICENSE-2.0
  904. *
  905. * Unless required by applicable law or agreed to in writing, software
  906. * distributed under the License is distributed on an "AS IS" BASIS,
  907. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  908. * See the License for the specific language governing permissions and
  909. * limitations under the License.
  910. */
  911. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  912. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  913. let WebSocketImpl = null;
  914. if (typeof MozWebSocket !== 'undefined') {
  915. WebSocketImpl = MozWebSocket;
  916. }
  917. else if (typeof WebSocket !== 'undefined') {
  918. WebSocketImpl = WebSocket;
  919. }
  920. function setWebSocketImpl(impl) {
  921. WebSocketImpl = impl;
  922. }
  923. /**
  924. * Create a new websocket connection with the given callbacks.
  925. */
  926. class WebSocketConnection {
  927. /**
  928. * @param connId identifier for this transport
  929. * @param repoInfo The info for the websocket endpoint.
  930. * @param applicationId The Firebase App ID for this project.
  931. * @param appCheckToken The App Check Token for this client.
  932. * @param authToken The Auth Token for this client.
  933. * @param transportSessionId Optional transportSessionId if this is connecting
  934. * to an existing transport session
  935. * @param lastSessionId Optional lastSessionId if there was a previous
  936. * connection
  937. */
  938. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  939. this.connId = connId;
  940. this.applicationId = applicationId;
  941. this.appCheckToken = appCheckToken;
  942. this.authToken = authToken;
  943. this.keepaliveTimer = null;
  944. this.frames = null;
  945. this.totalFrames = 0;
  946. this.bytesSent = 0;
  947. this.bytesReceived = 0;
  948. this.log_ = logWrapper(this.connId);
  949. this.stats_ = statsManagerGetCollection(repoInfo);
  950. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  951. this.nodeAdmin = repoInfo.nodeAdmin;
  952. }
  953. /**
  954. * @param repoInfo - The info for the websocket endpoint.
  955. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  956. * session
  957. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  958. * @returns connection url
  959. */
  960. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  961. const urlParams = {};
  962. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  963. if (!util.isNodeSdk() &&
  964. typeof location !== 'undefined' &&
  965. location.hostname &&
  966. FORGE_DOMAIN_RE.test(location.hostname)) {
  967. urlParams[REFERER_PARAM] = FORGE_REF;
  968. }
  969. if (transportSessionId) {
  970. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  971. }
  972. if (lastSessionId) {
  973. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  974. }
  975. if (appCheckToken) {
  976. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  977. }
  978. if (applicationId) {
  979. urlParams[APPLICATION_ID_PARAM] = applicationId;
  980. }
  981. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  982. }
  983. /**
  984. * @param onMessage - Callback when messages arrive
  985. * @param onDisconnect - Callback with connection lost.
  986. */
  987. open(onMessage, onDisconnect) {
  988. this.onDisconnect = onDisconnect;
  989. this.onMessage = onMessage;
  990. this.log_('Websocket connecting to ' + this.connURL);
  991. this.everConnected_ = false;
  992. // Assume failure until proven otherwise.
  993. PersistentStorage.set('previous_websocket_failure', true);
  994. try {
  995. let options;
  996. if (util.isNodeSdk()) {
  997. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  998. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  999. options = {
  1000. headers: {
  1001. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  1002. 'X-Firebase-GMPID': this.applicationId || ''
  1003. }
  1004. };
  1005. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1006. // Note that we send the credentials here even if they aren't admin credentials, which is
  1007. // not a problem.
  1008. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1009. // through the websocket connection once it is established.
  1010. if (this.authToken) {
  1011. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1012. }
  1013. if (this.appCheckToken) {
  1014. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1015. }
  1016. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1017. const env = process['env'];
  1018. const proxy = this.connURL.indexOf('wss://') === 0
  1019. ? env['HTTPS_PROXY'] || env['https_proxy']
  1020. : env['HTTP_PROXY'] || env['http_proxy'];
  1021. if (proxy) {
  1022. options['proxy'] = { origin: proxy };
  1023. }
  1024. }
  1025. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1026. }
  1027. catch (e) {
  1028. this.log_('Error instantiating WebSocket.');
  1029. const error = e.message || e.data;
  1030. if (error) {
  1031. this.log_(error);
  1032. }
  1033. this.onClosed_();
  1034. return;
  1035. }
  1036. this.mySock.onopen = () => {
  1037. this.log_('Websocket connected.');
  1038. this.everConnected_ = true;
  1039. };
  1040. this.mySock.onclose = () => {
  1041. this.log_('Websocket connection was disconnected.');
  1042. this.mySock = null;
  1043. this.onClosed_();
  1044. };
  1045. this.mySock.onmessage = m => {
  1046. this.handleIncomingFrame(m);
  1047. };
  1048. this.mySock.onerror = e => {
  1049. this.log_('WebSocket error. Closing connection.');
  1050. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1051. const error = e.message || e.data;
  1052. if (error) {
  1053. this.log_(error);
  1054. }
  1055. this.onClosed_();
  1056. };
  1057. }
  1058. /**
  1059. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1060. */
  1061. start() { }
  1062. static forceDisallow() {
  1063. WebSocketConnection.forceDisallow_ = true;
  1064. }
  1065. static isAvailable() {
  1066. let isOldAndroid = false;
  1067. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1068. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1069. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1070. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1071. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1072. isOldAndroid = true;
  1073. }
  1074. }
  1075. }
  1076. return (!isOldAndroid &&
  1077. WebSocketImpl !== null &&
  1078. !WebSocketConnection.forceDisallow_);
  1079. }
  1080. /**
  1081. * Returns true if we previously failed to connect with this transport.
  1082. */
  1083. static previouslyFailed() {
  1084. // If our persistent storage is actually only in-memory storage,
  1085. // we default to assuming that it previously failed to be safe.
  1086. return (PersistentStorage.isInMemoryStorage ||
  1087. PersistentStorage.get('previous_websocket_failure') === true);
  1088. }
  1089. markConnectionHealthy() {
  1090. PersistentStorage.remove('previous_websocket_failure');
  1091. }
  1092. appendFrame_(data) {
  1093. this.frames.push(data);
  1094. if (this.frames.length === this.totalFrames) {
  1095. const fullMess = this.frames.join('');
  1096. this.frames = null;
  1097. const jsonMess = util.jsonEval(fullMess);
  1098. //handle the message
  1099. this.onMessage(jsonMess);
  1100. }
  1101. }
  1102. /**
  1103. * @param frameCount - The number of frames we are expecting from the server
  1104. */
  1105. handleNewFrameCount_(frameCount) {
  1106. this.totalFrames = frameCount;
  1107. this.frames = [];
  1108. }
  1109. /**
  1110. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1111. * @returns Any remaining data to be process, or null if there is none
  1112. */
  1113. extractFrameCount_(data) {
  1114. util.assert(this.frames === null, 'We already have a frame buffer');
  1115. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1116. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1117. if (data.length <= 6) {
  1118. const frameCount = Number(data);
  1119. if (!isNaN(frameCount)) {
  1120. this.handleNewFrameCount_(frameCount);
  1121. return null;
  1122. }
  1123. }
  1124. this.handleNewFrameCount_(1);
  1125. return data;
  1126. }
  1127. /**
  1128. * Process a websocket frame that has arrived from the server.
  1129. * @param mess - The frame data
  1130. */
  1131. handleIncomingFrame(mess) {
  1132. if (this.mySock === null) {
  1133. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1134. }
  1135. const data = mess['data'];
  1136. this.bytesReceived += data.length;
  1137. this.stats_.incrementCounter('bytes_received', data.length);
  1138. this.resetKeepAlive();
  1139. if (this.frames !== null) {
  1140. // we're buffering
  1141. this.appendFrame_(data);
  1142. }
  1143. else {
  1144. // try to parse out a frame count, otherwise, assume 1 and process it
  1145. const remainingData = this.extractFrameCount_(data);
  1146. if (remainingData !== null) {
  1147. this.appendFrame_(remainingData);
  1148. }
  1149. }
  1150. }
  1151. /**
  1152. * Send a message to the server
  1153. * @param data - The JSON object to transmit
  1154. */
  1155. send(data) {
  1156. this.resetKeepAlive();
  1157. const dataStr = util.stringify(data);
  1158. this.bytesSent += dataStr.length;
  1159. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1160. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1161. //up into multiple pieces if it doesn't fit in one request.
  1162. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1163. //Send the length header
  1164. if (dataSegs.length > 1) {
  1165. this.sendString_(String(dataSegs.length));
  1166. }
  1167. //Send the actual data in segments.
  1168. for (let i = 0; i < dataSegs.length; i++) {
  1169. this.sendString_(dataSegs[i]);
  1170. }
  1171. }
  1172. shutdown_() {
  1173. this.isClosed_ = true;
  1174. if (this.keepaliveTimer) {
  1175. clearInterval(this.keepaliveTimer);
  1176. this.keepaliveTimer = null;
  1177. }
  1178. if (this.mySock) {
  1179. this.mySock.close();
  1180. this.mySock = null;
  1181. }
  1182. }
  1183. onClosed_() {
  1184. if (!this.isClosed_) {
  1185. this.log_('WebSocket is closing itself');
  1186. this.shutdown_();
  1187. // since this is an internal close, trigger the close listener
  1188. if (this.onDisconnect) {
  1189. this.onDisconnect(this.everConnected_);
  1190. this.onDisconnect = null;
  1191. }
  1192. }
  1193. }
  1194. /**
  1195. * External-facing close handler.
  1196. * Close the websocket and kill the connection.
  1197. */
  1198. close() {
  1199. if (!this.isClosed_) {
  1200. this.log_('WebSocket is being closed');
  1201. this.shutdown_();
  1202. }
  1203. }
  1204. /**
  1205. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1206. * the last activity.
  1207. */
  1208. resetKeepAlive() {
  1209. clearInterval(this.keepaliveTimer);
  1210. this.keepaliveTimer = setInterval(() => {
  1211. //If there has been no websocket activity for a while, send a no-op
  1212. if (this.mySock) {
  1213. this.sendString_('0');
  1214. }
  1215. this.resetKeepAlive();
  1216. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1217. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1218. }
  1219. /**
  1220. * Send a string over the websocket.
  1221. *
  1222. * @param str - String to send.
  1223. */
  1224. sendString_(str) {
  1225. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1226. // calls for some unknown reason. We treat these as an error and disconnect.
  1227. // See https://app.asana.com/0/58926111402292/68021340250410
  1228. try {
  1229. this.mySock.send(str);
  1230. }
  1231. catch (e) {
  1232. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1233. setTimeout(this.onClosed_.bind(this), 0);
  1234. }
  1235. }
  1236. }
  1237. /**
  1238. * Number of response before we consider the connection "healthy."
  1239. */
  1240. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1241. /**
  1242. * Time to wait for the connection te become healthy before giving up.
  1243. */
  1244. WebSocketConnection.healthyTimeout = 30000;
  1245. /**
  1246. * @license
  1247. * Copyright 2021 Google LLC
  1248. *
  1249. * Licensed under the Apache License, Version 2.0 (the "License");
  1250. * you may not use this file except in compliance with the License.
  1251. * You may obtain a copy of the License at
  1252. *
  1253. * http://www.apache.org/licenses/LICENSE-2.0
  1254. *
  1255. * Unless required by applicable law or agreed to in writing, software
  1256. * distributed under the License is distributed on an "AS IS" BASIS,
  1257. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1258. * See the License for the specific language governing permissions and
  1259. * limitations under the License.
  1260. */
  1261. /**
  1262. * Abstraction around AppCheck's token fetching capabilities.
  1263. */
  1264. class AppCheckTokenProvider {
  1265. constructor(appName_, appCheckProvider) {
  1266. this.appName_ = appName_;
  1267. this.appCheckProvider = appCheckProvider;
  1268. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1269. if (!this.appCheck) {
  1270. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  1271. }
  1272. }
  1273. getToken(forceRefresh) {
  1274. if (!this.appCheck) {
  1275. return new Promise((resolve, reject) => {
  1276. // Support delayed initialization of FirebaseAppCheck. This allows our
  1277. // customers to initialize the RTDB SDK before initializing Firebase
  1278. // AppCheck and ensures that all requests are authenticated if a token
  1279. // becomes available before the timeout below expires.
  1280. setTimeout(() => {
  1281. if (this.appCheck) {
  1282. this.getToken(forceRefresh).then(resolve, reject);
  1283. }
  1284. else {
  1285. resolve(null);
  1286. }
  1287. }, 0);
  1288. });
  1289. }
  1290. return this.appCheck.getToken(forceRefresh);
  1291. }
  1292. addTokenChangeListener(listener) {
  1293. var _a;
  1294. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  1295. }
  1296. notifyForInvalidToken() {
  1297. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  1298. 'are invalid. This usually indicates your app was not initialized correctly.');
  1299. }
  1300. }
  1301. /**
  1302. * @license
  1303. * Copyright 2017 Google LLC
  1304. *
  1305. * Licensed under the Apache License, Version 2.0 (the "License");
  1306. * you may not use this file except in compliance with the License.
  1307. * You may obtain a copy of the License at
  1308. *
  1309. * http://www.apache.org/licenses/LICENSE-2.0
  1310. *
  1311. * Unless required by applicable law or agreed to in writing, software
  1312. * distributed under the License is distributed on an "AS IS" BASIS,
  1313. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1314. * See the License for the specific language governing permissions and
  1315. * limitations under the License.
  1316. */
  1317. /**
  1318. * Abstraction around FirebaseApp's token fetching capabilities.
  1319. */
  1320. class FirebaseAuthTokenProvider {
  1321. constructor(appName_, firebaseOptions_, authProvider_) {
  1322. this.appName_ = appName_;
  1323. this.firebaseOptions_ = firebaseOptions_;
  1324. this.authProvider_ = authProvider_;
  1325. this.auth_ = null;
  1326. this.auth_ = authProvider_.getImmediate({ optional: true });
  1327. if (!this.auth_) {
  1328. authProvider_.onInit(auth => (this.auth_ = auth));
  1329. }
  1330. }
  1331. getToken(forceRefresh) {
  1332. if (!this.auth_) {
  1333. return new Promise((resolve, reject) => {
  1334. // Support delayed initialization of FirebaseAuth. This allows our
  1335. // customers to initialize the RTDB SDK before initializing Firebase
  1336. // Auth and ensures that all requests are authenticated if a token
  1337. // becomes available before the timeout below expires.
  1338. setTimeout(() => {
  1339. if (this.auth_) {
  1340. this.getToken(forceRefresh).then(resolve, reject);
  1341. }
  1342. else {
  1343. resolve(null);
  1344. }
  1345. }, 0);
  1346. });
  1347. }
  1348. return this.auth_.getToken(forceRefresh).catch(error => {
  1349. // TODO: Need to figure out all the cases this is raised and whether
  1350. // this makes sense.
  1351. if (error && error.code === 'auth/token-not-initialized') {
  1352. log('Got auth/token-not-initialized error. Treating as null token.');
  1353. return null;
  1354. }
  1355. else {
  1356. return Promise.reject(error);
  1357. }
  1358. });
  1359. }
  1360. addTokenChangeListener(listener) {
  1361. // TODO: We might want to wrap the listener and call it with no args to
  1362. // avoid a leaky abstraction, but that makes removing the listener harder.
  1363. if (this.auth_) {
  1364. this.auth_.addAuthTokenListener(listener);
  1365. }
  1366. else {
  1367. this.authProvider_
  1368. .get()
  1369. .then(auth => auth.addAuthTokenListener(listener));
  1370. }
  1371. }
  1372. removeTokenChangeListener(listener) {
  1373. this.authProvider_
  1374. .get()
  1375. .then(auth => auth.removeAuthTokenListener(listener));
  1376. }
  1377. notifyForInvalidToken() {
  1378. let errorMessage = 'Provided authentication credentials for the app named "' +
  1379. this.appName_ +
  1380. '" are invalid. This usually indicates your app was not ' +
  1381. 'initialized correctly. ';
  1382. if ('credential' in this.firebaseOptions_) {
  1383. errorMessage +=
  1384. 'Make sure the "credential" property provided to initializeApp() ' +
  1385. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1386. 'project.';
  1387. }
  1388. else if ('serviceAccount' in this.firebaseOptions_) {
  1389. errorMessage +=
  1390. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1391. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1392. 'project.';
  1393. }
  1394. else {
  1395. errorMessage +=
  1396. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1397. 'initializeApp() match the values provided for your app at ' +
  1398. 'https://console.firebase.google.com/.';
  1399. }
  1400. warn(errorMessage);
  1401. }
  1402. }
  1403. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1404. class EmulatorTokenProvider {
  1405. constructor(accessToken) {
  1406. this.accessToken = accessToken;
  1407. }
  1408. getToken(forceRefresh) {
  1409. return Promise.resolve({
  1410. accessToken: this.accessToken
  1411. });
  1412. }
  1413. addTokenChangeListener(listener) {
  1414. // Invoke the listener immediately to match the behavior in Firebase Auth
  1415. // (see packages/auth/src/auth.js#L1807)
  1416. listener(this.accessToken);
  1417. }
  1418. removeTokenChangeListener(listener) { }
  1419. notifyForInvalidToken() { }
  1420. }
  1421. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1422. EmulatorTokenProvider.OWNER = 'owner';
  1423. /**
  1424. * @license
  1425. * Copyright 2017 Google LLC
  1426. *
  1427. * Licensed under the Apache License, Version 2.0 (the "License");
  1428. * you may not use this file except in compliance with the License.
  1429. * You may obtain a copy of the License at
  1430. *
  1431. * http://www.apache.org/licenses/LICENSE-2.0
  1432. *
  1433. * Unless required by applicable law or agreed to in writing, software
  1434. * distributed under the License is distributed on an "AS IS" BASIS,
  1435. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1436. * See the License for the specific language governing permissions and
  1437. * limitations under the License.
  1438. */
  1439. /**
  1440. * This class ensures the packets from the server arrive in order
  1441. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1442. */
  1443. class PacketReceiver {
  1444. /**
  1445. * @param onMessage_
  1446. */
  1447. constructor(onMessage_) {
  1448. this.onMessage_ = onMessage_;
  1449. this.pendingResponses = [];
  1450. this.currentResponseNum = 0;
  1451. this.closeAfterResponse = -1;
  1452. this.onClose = null;
  1453. }
  1454. closeAfter(responseNum, callback) {
  1455. this.closeAfterResponse = responseNum;
  1456. this.onClose = callback;
  1457. if (this.closeAfterResponse < this.currentResponseNum) {
  1458. this.onClose();
  1459. this.onClose = null;
  1460. }
  1461. }
  1462. /**
  1463. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1464. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1465. * browsers will respond in the same order as the requests we sent
  1466. */
  1467. handleResponse(requestNum, data) {
  1468. this.pendingResponses[requestNum] = data;
  1469. while (this.pendingResponses[this.currentResponseNum]) {
  1470. const toProcess = this.pendingResponses[this.currentResponseNum];
  1471. delete this.pendingResponses[this.currentResponseNum];
  1472. for (let i = 0; i < toProcess.length; ++i) {
  1473. if (toProcess[i]) {
  1474. exceptionGuard(() => {
  1475. this.onMessage_(toProcess[i]);
  1476. });
  1477. }
  1478. }
  1479. if (this.currentResponseNum === this.closeAfterResponse) {
  1480. if (this.onClose) {
  1481. this.onClose();
  1482. this.onClose = null;
  1483. }
  1484. break;
  1485. }
  1486. this.currentResponseNum++;
  1487. }
  1488. }
  1489. }
  1490. /**
  1491. * @license
  1492. * Copyright 2017 Google LLC
  1493. *
  1494. * Licensed under the Apache License, Version 2.0 (the "License");
  1495. * you may not use this file except in compliance with the License.
  1496. * You may obtain a copy of the License at
  1497. *
  1498. * http://www.apache.org/licenses/LICENSE-2.0
  1499. *
  1500. * Unless required by applicable law or agreed to in writing, software
  1501. * distributed under the License is distributed on an "AS IS" BASIS,
  1502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1503. * See the License for the specific language governing permissions and
  1504. * limitations under the License.
  1505. */
  1506. // URL query parameters associated with longpolling
  1507. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1508. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1509. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1510. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1511. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1512. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1513. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1514. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1515. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1516. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1517. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1518. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1519. //Data size constants.
  1520. //TODO: Perf: the maximum length actually differs from browser to browser.
  1521. // We should check what browser we're on and set accordingly.
  1522. const MAX_URL_DATA_SIZE = 1870;
  1523. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1524. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1525. /**
  1526. * Keepalive period
  1527. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1528. * length of 30 seconds that we can't exceed.
  1529. */
  1530. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1531. /**
  1532. * How long to wait before aborting a long-polling connection attempt.
  1533. */
  1534. const LP_CONNECT_TIMEOUT = 30000;
  1535. /**
  1536. * This class manages a single long-polling connection.
  1537. */
  1538. class BrowserPollConnection {
  1539. /**
  1540. * @param connId An identifier for this connection, used for logging
  1541. * @param repoInfo The info for the endpoint to send data to.
  1542. * @param applicationId The Firebase App ID for this project.
  1543. * @param appCheckToken The AppCheck token for this client.
  1544. * @param authToken The AuthToken to use for this connection.
  1545. * @param transportSessionId Optional transportSessionid if we are
  1546. * reconnecting for an existing transport session
  1547. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1548. * already created a connection previously
  1549. */
  1550. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1551. this.connId = connId;
  1552. this.repoInfo = repoInfo;
  1553. this.applicationId = applicationId;
  1554. this.appCheckToken = appCheckToken;
  1555. this.authToken = authToken;
  1556. this.transportSessionId = transportSessionId;
  1557. this.lastSessionId = lastSessionId;
  1558. this.bytesSent = 0;
  1559. this.bytesReceived = 0;
  1560. this.everConnected_ = false;
  1561. this.log_ = logWrapper(connId);
  1562. this.stats_ = statsManagerGetCollection(repoInfo);
  1563. this.urlFn = (params) => {
  1564. // Always add the token if we have one.
  1565. if (this.appCheckToken) {
  1566. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1567. }
  1568. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1569. };
  1570. }
  1571. /**
  1572. * @param onMessage - Callback when messages arrive
  1573. * @param onDisconnect - Callback with connection lost.
  1574. */
  1575. open(onMessage, onDisconnect) {
  1576. this.curSegmentNum = 0;
  1577. this.onDisconnect_ = onDisconnect;
  1578. this.myPacketOrderer = new PacketReceiver(onMessage);
  1579. this.isClosed_ = false;
  1580. this.connectTimeoutTimer_ = setTimeout(() => {
  1581. this.log_('Timed out trying to connect.');
  1582. // Make sure we clear the host cache
  1583. this.onClosed_();
  1584. this.connectTimeoutTimer_ = null;
  1585. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1586. }, Math.floor(LP_CONNECT_TIMEOUT));
  1587. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1588. executeWhenDOMReady(() => {
  1589. if (this.isClosed_) {
  1590. return;
  1591. }
  1592. //Set up a callback that gets triggered once a connection is set up.
  1593. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1594. const [command, arg1, arg2, arg3, arg4] = args;
  1595. this.incrementIncomingBytes_(args);
  1596. if (!this.scriptTagHolder) {
  1597. return; // we closed the connection.
  1598. }
  1599. if (this.connectTimeoutTimer_) {
  1600. clearTimeout(this.connectTimeoutTimer_);
  1601. this.connectTimeoutTimer_ = null;
  1602. }
  1603. this.everConnected_ = true;
  1604. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1605. this.id = arg1;
  1606. this.password = arg2;
  1607. }
  1608. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1609. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1610. if (arg1) {
  1611. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1612. // through our already open polls), so don't send any more.
  1613. this.scriptTagHolder.sendNewPolls = false;
  1614. // arg1 in this case is the last response number sent by the server. We should try to receive
  1615. // all of the responses up to this one before closing
  1616. this.myPacketOrderer.closeAfter(arg1, () => {
  1617. this.onClosed_();
  1618. });
  1619. }
  1620. else {
  1621. this.onClosed_();
  1622. }
  1623. }
  1624. else {
  1625. throw new Error('Unrecognized command received: ' + command);
  1626. }
  1627. }, (...args) => {
  1628. const [pN, data] = args;
  1629. this.incrementIncomingBytes_(args);
  1630. this.myPacketOrderer.handleResponse(pN, data);
  1631. }, () => {
  1632. this.onClosed_();
  1633. }, this.urlFn);
  1634. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1635. //from cache.
  1636. const urlParams = {};
  1637. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1638. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1639. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1640. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1641. this.scriptTagHolder.uniqueCallbackIdentifier;
  1642. }
  1643. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1644. if (this.transportSessionId) {
  1645. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1646. }
  1647. if (this.lastSessionId) {
  1648. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1649. }
  1650. if (this.applicationId) {
  1651. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1652. }
  1653. if (this.appCheckToken) {
  1654. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1655. }
  1656. if (typeof location !== 'undefined' &&
  1657. location.hostname &&
  1658. FORGE_DOMAIN_RE.test(location.hostname)) {
  1659. urlParams[REFERER_PARAM] = FORGE_REF;
  1660. }
  1661. const connectURL = this.urlFn(urlParams);
  1662. this.log_('Connecting via long-poll to ' + connectURL);
  1663. this.scriptTagHolder.addTag(connectURL, () => {
  1664. /* do nothing */
  1665. });
  1666. });
  1667. }
  1668. /**
  1669. * Call this when a handshake has completed successfully and we want to consider the connection established
  1670. */
  1671. start() {
  1672. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1673. this.addDisconnectPingFrame(this.id, this.password);
  1674. }
  1675. /**
  1676. * Forces long polling to be considered as a potential transport
  1677. */
  1678. static forceAllow() {
  1679. BrowserPollConnection.forceAllow_ = true;
  1680. }
  1681. /**
  1682. * Forces longpolling to not be considered as a potential transport
  1683. */
  1684. static forceDisallow() {
  1685. BrowserPollConnection.forceDisallow_ = true;
  1686. }
  1687. // Static method, use string literal so it can be accessed in a generic way
  1688. static isAvailable() {
  1689. if (util.isNodeSdk()) {
  1690. return false;
  1691. }
  1692. else if (BrowserPollConnection.forceAllow_) {
  1693. return true;
  1694. }
  1695. else {
  1696. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1697. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1698. return (!BrowserPollConnection.forceDisallow_ &&
  1699. typeof document !== 'undefined' &&
  1700. document.createElement != null &&
  1701. !isChromeExtensionContentScript() &&
  1702. !isWindowsStoreApp());
  1703. }
  1704. }
  1705. /**
  1706. * No-op for polling
  1707. */
  1708. markConnectionHealthy() { }
  1709. /**
  1710. * Stops polling and cleans up the iframe
  1711. */
  1712. shutdown_() {
  1713. this.isClosed_ = true;
  1714. if (this.scriptTagHolder) {
  1715. this.scriptTagHolder.close();
  1716. this.scriptTagHolder = null;
  1717. }
  1718. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1719. if (this.myDisconnFrame) {
  1720. document.body.removeChild(this.myDisconnFrame);
  1721. this.myDisconnFrame = null;
  1722. }
  1723. if (this.connectTimeoutTimer_) {
  1724. clearTimeout(this.connectTimeoutTimer_);
  1725. this.connectTimeoutTimer_ = null;
  1726. }
  1727. }
  1728. /**
  1729. * Triggered when this transport is closed
  1730. */
  1731. onClosed_() {
  1732. if (!this.isClosed_) {
  1733. this.log_('Longpoll is closing itself');
  1734. this.shutdown_();
  1735. if (this.onDisconnect_) {
  1736. this.onDisconnect_(this.everConnected_);
  1737. this.onDisconnect_ = null;
  1738. }
  1739. }
  1740. }
  1741. /**
  1742. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1743. * that we've left.
  1744. */
  1745. close() {
  1746. if (!this.isClosed_) {
  1747. this.log_('Longpoll is being closed.');
  1748. this.shutdown_();
  1749. }
  1750. }
  1751. /**
  1752. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1753. * broken into chunks (since URLs have a small maximum length).
  1754. * @param data - The JSON data to transmit.
  1755. */
  1756. send(data) {
  1757. const dataStr = util.stringify(data);
  1758. this.bytesSent += dataStr.length;
  1759. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1760. //first, lets get the base64-encoded data
  1761. const base64data = util.base64Encode(dataStr);
  1762. //We can only fit a certain amount in each URL, so we need to split this request
  1763. //up into multiple pieces if it doesn't fit in one request.
  1764. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1765. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1766. //of segments so that we can reassemble the packet on the server.
  1767. for (let i = 0; i < dataSegs.length; i++) {
  1768. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1769. this.curSegmentNum++;
  1770. }
  1771. }
  1772. /**
  1773. * This is how we notify the server that we're leaving.
  1774. * We aren't able to send requests with DHTML on a window close event, but we can
  1775. * trigger XHR requests in some browsers (everything but Opera basically).
  1776. */
  1777. addDisconnectPingFrame(id, pw) {
  1778. if (util.isNodeSdk()) {
  1779. return;
  1780. }
  1781. this.myDisconnFrame = document.createElement('iframe');
  1782. const urlParams = {};
  1783. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1784. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1785. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1786. this.myDisconnFrame.src = this.urlFn(urlParams);
  1787. this.myDisconnFrame.style.display = 'none';
  1788. document.body.appendChild(this.myDisconnFrame);
  1789. }
  1790. /**
  1791. * Used to track the bytes received by this client
  1792. */
  1793. incrementIncomingBytes_(args) {
  1794. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1795. const bytesReceived = util.stringify(args).length;
  1796. this.bytesReceived += bytesReceived;
  1797. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1798. }
  1799. }
  1800. /*********************************************************************************************
  1801. * A wrapper around an iframe that is used as a long-polling script holder.
  1802. *********************************************************************************************/
  1803. class FirebaseIFrameScriptHolder {
  1804. /**
  1805. * @param commandCB - The callback to be called when control commands are received from the server.
  1806. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1807. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1808. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1809. */
  1810. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1811. this.onDisconnect = onDisconnect;
  1812. this.urlFn = urlFn;
  1813. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1814. //problems in some browsers.
  1815. this.outstandingRequests = new Set();
  1816. //A queue of the pending segments waiting for transmission to the server.
  1817. this.pendingSegs = [];
  1818. //A serial number. We use this for two things:
  1819. // 1) A way to ensure the browser doesn't cache responses to polls
  1820. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1821. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1822. // JSONP code in the order it was added to the iframe.
  1823. this.currentSerial = Math.floor(Math.random() * 100000000);
  1824. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1825. // incoming data from the server that we're waiting for).
  1826. this.sendNewPolls = true;
  1827. if (!util.isNodeSdk()) {
  1828. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1829. //iframes where we put the long-polling script tags. We have two callbacks:
  1830. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1831. // 2) Message Callback - Triggered when new data arrives.
  1832. this.uniqueCallbackIdentifier = LUIDGenerator();
  1833. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1834. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1835. onMessageCB;
  1836. //Create an iframe for us to add script tags to.
  1837. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1838. // Set the iframe's contents.
  1839. let script = '';
  1840. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1841. // for ie9, but ie8 needs to do it again in the document itself.
  1842. if (this.myIFrame.src &&
  1843. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1844. const currentDomain = document.domain;
  1845. script = '<script>document.domain="' + currentDomain + '";</script>';
  1846. }
  1847. const iframeContents = '<html><body>' + script + '</body></html>';
  1848. try {
  1849. this.myIFrame.doc.open();
  1850. this.myIFrame.doc.write(iframeContents);
  1851. this.myIFrame.doc.close();
  1852. }
  1853. catch (e) {
  1854. log('frame writing exception');
  1855. if (e.stack) {
  1856. log(e.stack);
  1857. }
  1858. log(e);
  1859. }
  1860. }
  1861. else {
  1862. this.commandCB = commandCB;
  1863. this.onMessageCB = onMessageCB;
  1864. }
  1865. }
  1866. /**
  1867. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1868. * actually use.
  1869. */
  1870. static createIFrame_() {
  1871. const iframe = document.createElement('iframe');
  1872. iframe.style.display = 'none';
  1873. // This is necessary in order to initialize the document inside the iframe
  1874. if (document.body) {
  1875. document.body.appendChild(iframe);
  1876. try {
  1877. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1878. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1879. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1880. const a = iframe.contentWindow.document;
  1881. if (!a) {
  1882. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1883. log('No IE domain setting required');
  1884. }
  1885. }
  1886. catch (e) {
  1887. const domain = document.domain;
  1888. iframe.src =
  1889. "javascript:void((function(){document.open();document.domain='" +
  1890. domain +
  1891. "';document.close();})())";
  1892. }
  1893. }
  1894. else {
  1895. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1896. // never gets hit.
  1897. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1898. }
  1899. // Get the document of the iframe in a browser-specific way.
  1900. if (iframe.contentDocument) {
  1901. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1902. }
  1903. else if (iframe.contentWindow) {
  1904. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1905. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1906. }
  1907. else if (iframe.document) {
  1908. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1909. iframe.doc = iframe.document; //others?
  1910. }
  1911. return iframe;
  1912. }
  1913. /**
  1914. * Cancel all outstanding queries and remove the frame.
  1915. */
  1916. close() {
  1917. //Mark this iframe as dead, so no new requests are sent.
  1918. this.alive = false;
  1919. if (this.myIFrame) {
  1920. //We have to actually remove all of the html inside this iframe before removing it from the
  1921. //window, or IE will continue loading and executing the script tags we've already added, which
  1922. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1923. this.myIFrame.doc.body.textContent = '';
  1924. setTimeout(() => {
  1925. if (this.myIFrame !== null) {
  1926. document.body.removeChild(this.myIFrame);
  1927. this.myIFrame = null;
  1928. }
  1929. }, Math.floor(0));
  1930. }
  1931. // Protect from being called recursively.
  1932. const onDisconnect = this.onDisconnect;
  1933. if (onDisconnect) {
  1934. this.onDisconnect = null;
  1935. onDisconnect();
  1936. }
  1937. }
  1938. /**
  1939. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1940. * @param id - The ID of this connection
  1941. * @param pw - The password for this connection
  1942. */
  1943. startLongPoll(id, pw) {
  1944. this.myID = id;
  1945. this.myPW = pw;
  1946. this.alive = true;
  1947. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1948. while (this.newRequest_()) { }
  1949. }
  1950. /**
  1951. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1952. * too many outstanding requests and we are still alive.
  1953. *
  1954. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1955. * needed.
  1956. */
  1957. newRequest_() {
  1958. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1959. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1960. // close the old request.
  1961. if (this.alive &&
  1962. this.sendNewPolls &&
  1963. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1964. //construct our url
  1965. this.currentSerial++;
  1966. const urlParams = {};
  1967. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1968. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1969. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1970. let theURL = this.urlFn(urlParams);
  1971. //Now add as much data as we can.
  1972. let curDataString = '';
  1973. let i = 0;
  1974. while (this.pendingSegs.length > 0) {
  1975. //first, lets see if the next segment will fit.
  1976. const nextSeg = this.pendingSegs[0];
  1977. if (nextSeg.d.length +
  1978. SEG_HEADER_SIZE +
  1979. curDataString.length <=
  1980. MAX_URL_DATA_SIZE) {
  1981. //great, the segment will fit. Lets append it.
  1982. const theSeg = this.pendingSegs.shift();
  1983. curDataString =
  1984. curDataString +
  1985. '&' +
  1986. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1987. i +
  1988. '=' +
  1989. theSeg.seg +
  1990. '&' +
  1991. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1992. i +
  1993. '=' +
  1994. theSeg.ts +
  1995. '&' +
  1996. FIREBASE_LONGPOLL_DATA_PARAM +
  1997. i +
  1998. '=' +
  1999. theSeg.d;
  2000. i++;
  2001. }
  2002. else {
  2003. break;
  2004. }
  2005. }
  2006. theURL = theURL + curDataString;
  2007. this.addLongPollTag_(theURL, this.currentSerial);
  2008. return true;
  2009. }
  2010. else {
  2011. return false;
  2012. }
  2013. }
  2014. /**
  2015. * Queue a packet for transmission to the server.
  2016. * @param segnum - A sequential id for this packet segment used for reassembly
  2017. * @param totalsegs - The total number of segments in this packet
  2018. * @param data - The data for this segment.
  2019. */
  2020. enqueueSegment(segnum, totalsegs, data) {
  2021. //add this to the queue of segments to send.
  2022. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2023. //send the data immediately if there isn't already data being transmitted, unless
  2024. //startLongPoll hasn't been called yet.
  2025. if (this.alive) {
  2026. this.newRequest_();
  2027. }
  2028. }
  2029. /**
  2030. * Add a script tag for a regular long-poll request.
  2031. * @param url - The URL of the script tag.
  2032. * @param serial - The serial number of the request.
  2033. */
  2034. addLongPollTag_(url, serial) {
  2035. //remember that we sent this request.
  2036. this.outstandingRequests.add(serial);
  2037. const doNewRequest = () => {
  2038. this.outstandingRequests.delete(serial);
  2039. this.newRequest_();
  2040. };
  2041. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2042. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2043. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2044. const readyStateCB = () => {
  2045. // Request completed. Cancel the keepalive.
  2046. clearTimeout(keepaliveTimeout);
  2047. // Trigger a new request so we can continue receiving data.
  2048. doNewRequest();
  2049. };
  2050. this.addTag(url, readyStateCB);
  2051. }
  2052. /**
  2053. * Add an arbitrary script tag to the iframe.
  2054. * @param url - The URL for the script tag source.
  2055. * @param loadCB - A callback to be triggered once the script has loaded.
  2056. */
  2057. addTag(url, loadCB) {
  2058. if (util.isNodeSdk()) {
  2059. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2060. this.doNodeLongPoll(url, loadCB);
  2061. }
  2062. else {
  2063. setTimeout(() => {
  2064. try {
  2065. // if we're already closed, don't add this poll
  2066. if (!this.sendNewPolls) {
  2067. return;
  2068. }
  2069. const newScript = this.myIFrame.doc.createElement('script');
  2070. newScript.type = 'text/javascript';
  2071. newScript.async = true;
  2072. newScript.src = url;
  2073. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2074. newScript.onload = newScript.onreadystatechange =
  2075. function () {
  2076. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2077. const rstate = newScript.readyState;
  2078. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2079. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2080. newScript.onload = newScript.onreadystatechange = null;
  2081. if (newScript.parentNode) {
  2082. newScript.parentNode.removeChild(newScript);
  2083. }
  2084. loadCB();
  2085. }
  2086. };
  2087. newScript.onerror = () => {
  2088. log('Long-poll script failed to load: ' + url);
  2089. this.sendNewPolls = false;
  2090. this.close();
  2091. };
  2092. this.myIFrame.doc.body.appendChild(newScript);
  2093. }
  2094. catch (e) {
  2095. // TODO: we should make this error visible somehow
  2096. }
  2097. }, Math.floor(1));
  2098. }
  2099. }
  2100. }
  2101. /**
  2102. * @license
  2103. * Copyright 2017 Google LLC
  2104. *
  2105. * Licensed under the Apache License, Version 2.0 (the "License");
  2106. * you may not use this file except in compliance with the License.
  2107. * You may obtain a copy of the License at
  2108. *
  2109. * http://www.apache.org/licenses/LICENSE-2.0
  2110. *
  2111. * Unless required by applicable law or agreed to in writing, software
  2112. * distributed under the License is distributed on an "AS IS" BASIS,
  2113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2114. * See the License for the specific language governing permissions and
  2115. * limitations under the License.
  2116. */
  2117. /**
  2118. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2119. * lifecycle.
  2120. *
  2121. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2122. * they are available.
  2123. */
  2124. class TransportManager {
  2125. /**
  2126. * @param repoInfo - Metadata around the namespace we're connecting to
  2127. */
  2128. constructor(repoInfo) {
  2129. this.initTransports_(repoInfo);
  2130. }
  2131. static get ALL_TRANSPORTS() {
  2132. return [BrowserPollConnection, WebSocketConnection];
  2133. }
  2134. /**
  2135. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2136. * TransportManager has already set up transports_
  2137. */
  2138. static get IS_TRANSPORT_INITIALIZED() {
  2139. return this.globalTransportInitialized_;
  2140. }
  2141. initTransports_(repoInfo) {
  2142. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2143. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2144. if (repoInfo.webSocketOnly) {
  2145. if (!isWebSocketsAvailable) {
  2146. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2147. }
  2148. isSkipPollConnection = true;
  2149. }
  2150. if (isSkipPollConnection) {
  2151. this.transports_ = [WebSocketConnection];
  2152. }
  2153. else {
  2154. const transports = (this.transports_ = []);
  2155. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2156. if (transport && transport['isAvailable']()) {
  2157. transports.push(transport);
  2158. }
  2159. }
  2160. TransportManager.globalTransportInitialized_ = true;
  2161. }
  2162. }
  2163. /**
  2164. * @returns The constructor for the initial transport to use
  2165. */
  2166. initialTransport() {
  2167. if (this.transports_.length > 0) {
  2168. return this.transports_[0];
  2169. }
  2170. else {
  2171. throw new Error('No transports available');
  2172. }
  2173. }
  2174. /**
  2175. * @returns The constructor for the next transport, or null
  2176. */
  2177. upgradeTransport() {
  2178. if (this.transports_.length > 1) {
  2179. return this.transports_[1];
  2180. }
  2181. else {
  2182. return null;
  2183. }
  2184. }
  2185. }
  2186. // Keeps track of whether the TransportManager has already chosen a transport to use
  2187. TransportManager.globalTransportInitialized_ = false;
  2188. /**
  2189. * @license
  2190. * Copyright 2017 Google LLC
  2191. *
  2192. * Licensed under the Apache License, Version 2.0 (the "License");
  2193. * you may not use this file except in compliance with the License.
  2194. * You may obtain a copy of the License at
  2195. *
  2196. * http://www.apache.org/licenses/LICENSE-2.0
  2197. *
  2198. * Unless required by applicable law or agreed to in writing, software
  2199. * distributed under the License is distributed on an "AS IS" BASIS,
  2200. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2201. * See the License for the specific language governing permissions and
  2202. * limitations under the License.
  2203. */
  2204. // Abort upgrade attempt if it takes longer than 60s.
  2205. const UPGRADE_TIMEOUT = 60000;
  2206. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2207. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2208. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2209. // 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)
  2210. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2211. // but we've sent/received enough bytes, we don't cancel the connection.
  2212. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2213. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2214. const MESSAGE_TYPE = 't';
  2215. const MESSAGE_DATA = 'd';
  2216. const CONTROL_SHUTDOWN = 's';
  2217. const CONTROL_RESET = 'r';
  2218. const CONTROL_ERROR = 'e';
  2219. const CONTROL_PONG = 'o';
  2220. const SWITCH_ACK = 'a';
  2221. const END_TRANSMISSION = 'n';
  2222. const PING = 'p';
  2223. const SERVER_HELLO = 'h';
  2224. /**
  2225. * Creates a new real-time connection to the server using whichever method works
  2226. * best in the current browser.
  2227. */
  2228. class Connection {
  2229. /**
  2230. * @param id - an id for this connection
  2231. * @param repoInfo_ - the info for the endpoint to connect to
  2232. * @param applicationId_ - the Firebase App ID for this project
  2233. * @param appCheckToken_ - The App Check Token for this device.
  2234. * @param authToken_ - The auth token for this session.
  2235. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2236. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2237. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2238. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2239. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2240. */
  2241. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2242. this.id = id;
  2243. this.repoInfo_ = repoInfo_;
  2244. this.applicationId_ = applicationId_;
  2245. this.appCheckToken_ = appCheckToken_;
  2246. this.authToken_ = authToken_;
  2247. this.onMessage_ = onMessage_;
  2248. this.onReady_ = onReady_;
  2249. this.onDisconnect_ = onDisconnect_;
  2250. this.onKill_ = onKill_;
  2251. this.lastSessionId = lastSessionId;
  2252. this.connectionCount = 0;
  2253. this.pendingDataMessages = [];
  2254. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2255. this.log_ = logWrapper('c:' + this.id + ':');
  2256. this.transportManager_ = new TransportManager(repoInfo_);
  2257. this.log_('Connection created');
  2258. this.start_();
  2259. }
  2260. /**
  2261. * Starts a connection attempt
  2262. */
  2263. start_() {
  2264. const conn = this.transportManager_.initialTransport();
  2265. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2266. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2267. // can consider the transport healthy.
  2268. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2269. const onMessageReceived = this.connReceiver_(this.conn_);
  2270. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2271. this.tx_ = this.conn_;
  2272. this.rx_ = this.conn_;
  2273. this.secondaryConn_ = null;
  2274. this.isHealthy_ = false;
  2275. /*
  2276. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2277. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2278. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2279. * still have the context of your originating frame.
  2280. */
  2281. setTimeout(() => {
  2282. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2283. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2284. }, Math.floor(0));
  2285. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2286. if (healthyTimeoutMS > 0) {
  2287. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2288. this.healthyTimeout_ = null;
  2289. if (!this.isHealthy_) {
  2290. if (this.conn_ &&
  2291. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2292. this.log_('Connection exceeded healthy timeout but has received ' +
  2293. this.conn_.bytesReceived +
  2294. ' bytes. Marking connection healthy.');
  2295. this.isHealthy_ = true;
  2296. this.conn_.markConnectionHealthy();
  2297. }
  2298. else if (this.conn_ &&
  2299. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2300. this.log_('Connection exceeded healthy timeout but has sent ' +
  2301. this.conn_.bytesSent +
  2302. ' bytes. Leaving connection alive.');
  2303. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2304. // the server.
  2305. }
  2306. else {
  2307. this.log_('Closing unhealthy connection after timeout.');
  2308. this.close();
  2309. }
  2310. }
  2311. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2312. }, Math.floor(healthyTimeoutMS));
  2313. }
  2314. }
  2315. nextTransportId_() {
  2316. return 'c:' + this.id + ':' + this.connectionCount++;
  2317. }
  2318. disconnReceiver_(conn) {
  2319. return everConnected => {
  2320. if (conn === this.conn_) {
  2321. this.onConnectionLost_(everConnected);
  2322. }
  2323. else if (conn === this.secondaryConn_) {
  2324. this.log_('Secondary connection lost.');
  2325. this.onSecondaryConnectionLost_();
  2326. }
  2327. else {
  2328. this.log_('closing an old connection');
  2329. }
  2330. };
  2331. }
  2332. connReceiver_(conn) {
  2333. return (message) => {
  2334. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2335. if (conn === this.rx_) {
  2336. this.onPrimaryMessageReceived_(message);
  2337. }
  2338. else if (conn === this.secondaryConn_) {
  2339. this.onSecondaryMessageReceived_(message);
  2340. }
  2341. else {
  2342. this.log_('message on old connection');
  2343. }
  2344. }
  2345. };
  2346. }
  2347. /**
  2348. * @param dataMsg - An arbitrary data message to be sent to the server
  2349. */
  2350. sendRequest(dataMsg) {
  2351. // wrap in a data message envelope and send it on
  2352. const msg = { t: 'd', d: dataMsg };
  2353. this.sendData_(msg);
  2354. }
  2355. tryCleanupConnection() {
  2356. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2357. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2358. this.conn_ = this.secondaryConn_;
  2359. this.secondaryConn_ = null;
  2360. // the server will shutdown the old connection
  2361. }
  2362. }
  2363. onSecondaryControl_(controlData) {
  2364. if (MESSAGE_TYPE in controlData) {
  2365. const cmd = controlData[MESSAGE_TYPE];
  2366. if (cmd === SWITCH_ACK) {
  2367. this.upgradeIfSecondaryHealthy_();
  2368. }
  2369. else if (cmd === CONTROL_RESET) {
  2370. // Most likely the session wasn't valid. Abandon the switch attempt
  2371. this.log_('Got a reset on secondary, closing it');
  2372. this.secondaryConn_.close();
  2373. // If we were already using this connection for something, than we need to fully close
  2374. if (this.tx_ === this.secondaryConn_ ||
  2375. this.rx_ === this.secondaryConn_) {
  2376. this.close();
  2377. }
  2378. }
  2379. else if (cmd === CONTROL_PONG) {
  2380. this.log_('got pong on secondary.');
  2381. this.secondaryResponsesRequired_--;
  2382. this.upgradeIfSecondaryHealthy_();
  2383. }
  2384. }
  2385. }
  2386. onSecondaryMessageReceived_(parsedData) {
  2387. const layer = requireKey('t', parsedData);
  2388. const data = requireKey('d', parsedData);
  2389. if (layer === 'c') {
  2390. this.onSecondaryControl_(data);
  2391. }
  2392. else if (layer === 'd') {
  2393. // got a data message, but we're still second connection. Need to buffer it up
  2394. this.pendingDataMessages.push(data);
  2395. }
  2396. else {
  2397. throw new Error('Unknown protocol layer: ' + layer);
  2398. }
  2399. }
  2400. upgradeIfSecondaryHealthy_() {
  2401. if (this.secondaryResponsesRequired_ <= 0) {
  2402. this.log_('Secondary connection is healthy.');
  2403. this.isHealthy_ = true;
  2404. this.secondaryConn_.markConnectionHealthy();
  2405. this.proceedWithUpgrade_();
  2406. }
  2407. else {
  2408. // Send a ping to make sure the connection is healthy.
  2409. this.log_('sending ping on secondary.');
  2410. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2411. }
  2412. }
  2413. proceedWithUpgrade_() {
  2414. // tell this connection to consider itself open
  2415. this.secondaryConn_.start();
  2416. // send ack
  2417. this.log_('sending client ack on secondary');
  2418. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2419. // send end packet on primary transport, switch to sending on this one
  2420. // can receive on this one, buffer responses until end received on primary transport
  2421. this.log_('Ending transmission on primary');
  2422. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2423. this.tx_ = this.secondaryConn_;
  2424. this.tryCleanupConnection();
  2425. }
  2426. onPrimaryMessageReceived_(parsedData) {
  2427. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2428. const layer = requireKey('t', parsedData);
  2429. const data = requireKey('d', parsedData);
  2430. if (layer === 'c') {
  2431. this.onControl_(data);
  2432. }
  2433. else if (layer === 'd') {
  2434. this.onDataMessage_(data);
  2435. }
  2436. }
  2437. onDataMessage_(message) {
  2438. this.onPrimaryResponse_();
  2439. // We don't do anything with data messages, just kick them up a level
  2440. this.onMessage_(message);
  2441. }
  2442. onPrimaryResponse_() {
  2443. if (!this.isHealthy_) {
  2444. this.primaryResponsesRequired_--;
  2445. if (this.primaryResponsesRequired_ <= 0) {
  2446. this.log_('Primary connection is healthy.');
  2447. this.isHealthy_ = true;
  2448. this.conn_.markConnectionHealthy();
  2449. }
  2450. }
  2451. }
  2452. onControl_(controlData) {
  2453. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2454. if (MESSAGE_DATA in controlData) {
  2455. const payload = controlData[MESSAGE_DATA];
  2456. if (cmd === SERVER_HELLO) {
  2457. const handshakePayload = Object.assign({}, payload);
  2458. if (this.repoInfo_.isUsingEmulator) {
  2459. // 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.
  2460. handshakePayload.h = this.repoInfo_.host;
  2461. }
  2462. this.onHandshake_(handshakePayload);
  2463. }
  2464. else if (cmd === END_TRANSMISSION) {
  2465. this.log_('recvd end transmission on primary');
  2466. this.rx_ = this.secondaryConn_;
  2467. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2468. this.onDataMessage_(this.pendingDataMessages[i]);
  2469. }
  2470. this.pendingDataMessages = [];
  2471. this.tryCleanupConnection();
  2472. }
  2473. else if (cmd === CONTROL_SHUTDOWN) {
  2474. // This was previously the 'onKill' callback passed to the lower-level connection
  2475. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2476. this.onConnectionShutdown_(payload);
  2477. }
  2478. else if (cmd === CONTROL_RESET) {
  2479. // payload in this case is the host we should contact
  2480. this.onReset_(payload);
  2481. }
  2482. else if (cmd === CONTROL_ERROR) {
  2483. error('Server Error: ' + payload);
  2484. }
  2485. else if (cmd === CONTROL_PONG) {
  2486. this.log_('got pong on primary.');
  2487. this.onPrimaryResponse_();
  2488. this.sendPingOnPrimaryIfNecessary_();
  2489. }
  2490. else {
  2491. error('Unknown control packet command: ' + cmd);
  2492. }
  2493. }
  2494. }
  2495. /**
  2496. * @param handshake - The handshake data returned from the server
  2497. */
  2498. onHandshake_(handshake) {
  2499. const timestamp = handshake.ts;
  2500. const version = handshake.v;
  2501. const host = handshake.h;
  2502. this.sessionId = handshake.s;
  2503. this.repoInfo_.host = host;
  2504. // if we've already closed the connection, then don't bother trying to progress further
  2505. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2506. this.conn_.start();
  2507. this.onConnectionEstablished_(this.conn_, timestamp);
  2508. if (PROTOCOL_VERSION !== version) {
  2509. warn('Protocol version mismatch detected');
  2510. }
  2511. // TODO: do we want to upgrade? when? maybe a delay?
  2512. this.tryStartUpgrade_();
  2513. }
  2514. }
  2515. tryStartUpgrade_() {
  2516. const conn = this.transportManager_.upgradeTransport();
  2517. if (conn) {
  2518. this.startUpgrade_(conn);
  2519. }
  2520. }
  2521. startUpgrade_(conn) {
  2522. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2523. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2524. // can consider the transport healthy.
  2525. this.secondaryResponsesRequired_ =
  2526. conn['responsesRequiredToBeHealthy'] || 0;
  2527. const onMessage = this.connReceiver_(this.secondaryConn_);
  2528. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2529. this.secondaryConn_.open(onMessage, onDisconnect);
  2530. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2531. setTimeoutNonBlocking(() => {
  2532. if (this.secondaryConn_) {
  2533. this.log_('Timed out trying to upgrade.');
  2534. this.secondaryConn_.close();
  2535. }
  2536. }, Math.floor(UPGRADE_TIMEOUT));
  2537. }
  2538. onReset_(host) {
  2539. this.log_('Reset packet received. New host: ' + host);
  2540. this.repoInfo_.host = host;
  2541. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2542. // We don't currently support resets after the connection has already been established
  2543. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2544. this.close();
  2545. }
  2546. else {
  2547. // Close whatever connections we have open and start again.
  2548. this.closeConnections_();
  2549. this.start_();
  2550. }
  2551. }
  2552. onConnectionEstablished_(conn, timestamp) {
  2553. this.log_('Realtime connection established.');
  2554. this.conn_ = conn;
  2555. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2556. if (this.onReady_) {
  2557. this.onReady_(timestamp, this.sessionId);
  2558. this.onReady_ = null;
  2559. }
  2560. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2561. // send some pings.
  2562. if (this.primaryResponsesRequired_ === 0) {
  2563. this.log_('Primary connection is healthy.');
  2564. this.isHealthy_ = true;
  2565. }
  2566. else {
  2567. setTimeoutNonBlocking(() => {
  2568. this.sendPingOnPrimaryIfNecessary_();
  2569. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2570. }
  2571. }
  2572. sendPingOnPrimaryIfNecessary_() {
  2573. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2574. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2575. this.log_('sending ping on primary.');
  2576. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2577. }
  2578. }
  2579. onSecondaryConnectionLost_() {
  2580. const conn = this.secondaryConn_;
  2581. this.secondaryConn_ = null;
  2582. if (this.tx_ === conn || this.rx_ === conn) {
  2583. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2584. this.close();
  2585. }
  2586. }
  2587. /**
  2588. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2589. * we should flush the host cache
  2590. */
  2591. onConnectionLost_(everConnected) {
  2592. this.conn_ = null;
  2593. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2594. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2595. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2596. this.log_('Realtime connection failed.');
  2597. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2598. if (this.repoInfo_.isCacheableHost()) {
  2599. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2600. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2601. this.repoInfo_.internalHost = this.repoInfo_.host;
  2602. }
  2603. }
  2604. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2605. this.log_('Realtime connection lost.');
  2606. }
  2607. this.close();
  2608. }
  2609. onConnectionShutdown_(reason) {
  2610. this.log_('Connection shutdown command received. Shutting down...');
  2611. if (this.onKill_) {
  2612. this.onKill_(reason);
  2613. this.onKill_ = null;
  2614. }
  2615. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2616. // so clear the callback.
  2617. this.onDisconnect_ = null;
  2618. this.close();
  2619. }
  2620. sendData_(data) {
  2621. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2622. throw 'Connection is not connected';
  2623. }
  2624. else {
  2625. this.tx_.send(data);
  2626. }
  2627. }
  2628. /**
  2629. * Cleans up this connection, calling the appropriate callbacks
  2630. */
  2631. close() {
  2632. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2633. this.log_('Closing realtime connection.');
  2634. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2635. this.closeConnections_();
  2636. if (this.onDisconnect_) {
  2637. this.onDisconnect_();
  2638. this.onDisconnect_ = null;
  2639. }
  2640. }
  2641. }
  2642. closeConnections_() {
  2643. this.log_('Shutting down all connections');
  2644. if (this.conn_) {
  2645. this.conn_.close();
  2646. this.conn_ = null;
  2647. }
  2648. if (this.secondaryConn_) {
  2649. this.secondaryConn_.close();
  2650. this.secondaryConn_ = null;
  2651. }
  2652. if (this.healthyTimeout_) {
  2653. clearTimeout(this.healthyTimeout_);
  2654. this.healthyTimeout_ = null;
  2655. }
  2656. }
  2657. }
  2658. /**
  2659. * @license
  2660. * Copyright 2017 Google LLC
  2661. *
  2662. * Licensed under the Apache License, Version 2.0 (the "License");
  2663. * you may not use this file except in compliance with the License.
  2664. * You may obtain a copy of the License at
  2665. *
  2666. * http://www.apache.org/licenses/LICENSE-2.0
  2667. *
  2668. * Unless required by applicable law or agreed to in writing, software
  2669. * distributed under the License is distributed on an "AS IS" BASIS,
  2670. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2671. * See the License for the specific language governing permissions and
  2672. * limitations under the License.
  2673. */
  2674. /**
  2675. * Interface defining the set of actions that can be performed against the Firebase server
  2676. * (basically corresponds to our wire protocol).
  2677. *
  2678. * @interface
  2679. */
  2680. class ServerActions {
  2681. put(pathString, data, onComplete, hash) { }
  2682. merge(pathString, data, onComplete, hash) { }
  2683. /**
  2684. * Refreshes the auth token for the current connection.
  2685. * @param token - The authentication token
  2686. */
  2687. refreshAuthToken(token) { }
  2688. /**
  2689. * Refreshes the app check token for the current connection.
  2690. * @param token The app check token
  2691. */
  2692. refreshAppCheckToken(token) { }
  2693. onDisconnectPut(pathString, data, onComplete) { }
  2694. onDisconnectMerge(pathString, data, onComplete) { }
  2695. onDisconnectCancel(pathString, onComplete) { }
  2696. reportStats(stats) { }
  2697. }
  2698. /**
  2699. * @license
  2700. * Copyright 2017 Google LLC
  2701. *
  2702. * Licensed under the Apache License, Version 2.0 (the "License");
  2703. * you may not use this file except in compliance with the License.
  2704. * You may obtain a copy of the License at
  2705. *
  2706. * http://www.apache.org/licenses/LICENSE-2.0
  2707. *
  2708. * Unless required by applicable law or agreed to in writing, software
  2709. * distributed under the License is distributed on an "AS IS" BASIS,
  2710. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2711. * See the License for the specific language governing permissions and
  2712. * limitations under the License.
  2713. */
  2714. /**
  2715. * Base class to be used if you want to emit events. Call the constructor with
  2716. * the set of allowed event names.
  2717. */
  2718. class EventEmitter {
  2719. constructor(allowedEvents_) {
  2720. this.allowedEvents_ = allowedEvents_;
  2721. this.listeners_ = {};
  2722. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2723. }
  2724. /**
  2725. * To be called by derived classes to trigger events.
  2726. */
  2727. trigger(eventType, ...varArgs) {
  2728. if (Array.isArray(this.listeners_[eventType])) {
  2729. // Clone the list, since callbacks could add/remove listeners.
  2730. const listeners = [...this.listeners_[eventType]];
  2731. for (let i = 0; i < listeners.length; i++) {
  2732. listeners[i].callback.apply(listeners[i].context, varArgs);
  2733. }
  2734. }
  2735. }
  2736. on(eventType, callback, context) {
  2737. this.validateEventType_(eventType);
  2738. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2739. this.listeners_[eventType].push({ callback, context });
  2740. const eventData = this.getInitialEvent(eventType);
  2741. if (eventData) {
  2742. callback.apply(context, eventData);
  2743. }
  2744. }
  2745. off(eventType, callback, context) {
  2746. this.validateEventType_(eventType);
  2747. const listeners = this.listeners_[eventType] || [];
  2748. for (let i = 0; i < listeners.length; i++) {
  2749. if (listeners[i].callback === callback &&
  2750. (!context || context === listeners[i].context)) {
  2751. listeners.splice(i, 1);
  2752. return;
  2753. }
  2754. }
  2755. }
  2756. validateEventType_(eventType) {
  2757. util.assert(this.allowedEvents_.find(et => {
  2758. return et === eventType;
  2759. }), 'Unknown event: ' + eventType);
  2760. }
  2761. }
  2762. /**
  2763. * @license
  2764. * Copyright 2017 Google LLC
  2765. *
  2766. * Licensed under the Apache License, Version 2.0 (the "License");
  2767. * you may not use this file except in compliance with the License.
  2768. * You may obtain a copy of the License at
  2769. *
  2770. * http://www.apache.org/licenses/LICENSE-2.0
  2771. *
  2772. * Unless required by applicable law or agreed to in writing, software
  2773. * distributed under the License is distributed on an "AS IS" BASIS,
  2774. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2775. * See the License for the specific language governing permissions and
  2776. * limitations under the License.
  2777. */
  2778. /**
  2779. * Monitors online state (as reported by window.online/offline events).
  2780. *
  2781. * The expectation is that this could have many false positives (thinks we are online
  2782. * when we're not), but no false negatives. So we can safely use it to determine when
  2783. * we definitely cannot reach the internet.
  2784. */
  2785. class OnlineMonitor extends EventEmitter {
  2786. constructor() {
  2787. super(['online']);
  2788. this.online_ = true;
  2789. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2790. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2791. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2792. // for Cordova.
  2793. if (typeof window !== 'undefined' &&
  2794. typeof window.addEventListener !== 'undefined' &&
  2795. !util.isMobileCordova()) {
  2796. window.addEventListener('online', () => {
  2797. if (!this.online_) {
  2798. this.online_ = true;
  2799. this.trigger('online', true);
  2800. }
  2801. }, false);
  2802. window.addEventListener('offline', () => {
  2803. if (this.online_) {
  2804. this.online_ = false;
  2805. this.trigger('online', false);
  2806. }
  2807. }, false);
  2808. }
  2809. }
  2810. static getInstance() {
  2811. return new OnlineMonitor();
  2812. }
  2813. getInitialEvent(eventType) {
  2814. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2815. return [this.online_];
  2816. }
  2817. currentlyOnline() {
  2818. return this.online_;
  2819. }
  2820. }
  2821. /**
  2822. * @license
  2823. * Copyright 2017 Google LLC
  2824. *
  2825. * Licensed under the Apache License, Version 2.0 (the "License");
  2826. * you may not use this file except in compliance with the License.
  2827. * You may obtain a copy of the License at
  2828. *
  2829. * http://www.apache.org/licenses/LICENSE-2.0
  2830. *
  2831. * Unless required by applicable law or agreed to in writing, software
  2832. * distributed under the License is distributed on an "AS IS" BASIS,
  2833. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2834. * See the License for the specific language governing permissions and
  2835. * limitations under the License.
  2836. */
  2837. /** Maximum key depth. */
  2838. const MAX_PATH_DEPTH = 32;
  2839. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2840. const MAX_PATH_LENGTH_BYTES = 768;
  2841. /**
  2842. * An immutable object representing a parsed path. It's immutable so that you
  2843. * can pass them around to other functions without worrying about them changing
  2844. * it.
  2845. */
  2846. class Path {
  2847. /**
  2848. * @param pathOrString - Path string to parse, or another path, or the raw
  2849. * tokens array
  2850. */
  2851. constructor(pathOrString, pieceNum) {
  2852. if (pieceNum === void 0) {
  2853. this.pieces_ = pathOrString.split('/');
  2854. // Remove empty pieces.
  2855. let copyTo = 0;
  2856. for (let i = 0; i < this.pieces_.length; i++) {
  2857. if (this.pieces_[i].length > 0) {
  2858. this.pieces_[copyTo] = this.pieces_[i];
  2859. copyTo++;
  2860. }
  2861. }
  2862. this.pieces_.length = copyTo;
  2863. this.pieceNum_ = 0;
  2864. }
  2865. else {
  2866. this.pieces_ = pathOrString;
  2867. this.pieceNum_ = pieceNum;
  2868. }
  2869. }
  2870. toString() {
  2871. let pathString = '';
  2872. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2873. if (this.pieces_[i] !== '') {
  2874. pathString += '/' + this.pieces_[i];
  2875. }
  2876. }
  2877. return pathString || '/';
  2878. }
  2879. }
  2880. function newEmptyPath() {
  2881. return new Path('');
  2882. }
  2883. function pathGetFront(path) {
  2884. if (path.pieceNum_ >= path.pieces_.length) {
  2885. return null;
  2886. }
  2887. return path.pieces_[path.pieceNum_];
  2888. }
  2889. /**
  2890. * @returns The number of segments in this path
  2891. */
  2892. function pathGetLength(path) {
  2893. return path.pieces_.length - path.pieceNum_;
  2894. }
  2895. function pathPopFront(path) {
  2896. let pieceNum = path.pieceNum_;
  2897. if (pieceNum < path.pieces_.length) {
  2898. pieceNum++;
  2899. }
  2900. return new Path(path.pieces_, pieceNum);
  2901. }
  2902. function pathGetBack(path) {
  2903. if (path.pieceNum_ < path.pieces_.length) {
  2904. return path.pieces_[path.pieces_.length - 1];
  2905. }
  2906. return null;
  2907. }
  2908. function pathToUrlEncodedString(path) {
  2909. let pathString = '';
  2910. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2911. if (path.pieces_[i] !== '') {
  2912. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2913. }
  2914. }
  2915. return pathString || '/';
  2916. }
  2917. /**
  2918. * Shallow copy of the parts of the path.
  2919. *
  2920. */
  2921. function pathSlice(path, begin = 0) {
  2922. return path.pieces_.slice(path.pieceNum_ + begin);
  2923. }
  2924. function pathParent(path) {
  2925. if (path.pieceNum_ >= path.pieces_.length) {
  2926. return null;
  2927. }
  2928. const pieces = [];
  2929. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2930. pieces.push(path.pieces_[i]);
  2931. }
  2932. return new Path(pieces, 0);
  2933. }
  2934. function pathChild(path, childPathObj) {
  2935. const pieces = [];
  2936. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2937. pieces.push(path.pieces_[i]);
  2938. }
  2939. if (childPathObj instanceof Path) {
  2940. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2941. pieces.push(childPathObj.pieces_[i]);
  2942. }
  2943. }
  2944. else {
  2945. const childPieces = childPathObj.split('/');
  2946. for (let i = 0; i < childPieces.length; i++) {
  2947. if (childPieces[i].length > 0) {
  2948. pieces.push(childPieces[i]);
  2949. }
  2950. }
  2951. }
  2952. return new Path(pieces, 0);
  2953. }
  2954. /**
  2955. * @returns True if there are no segments in this path
  2956. */
  2957. function pathIsEmpty(path) {
  2958. return path.pieceNum_ >= path.pieces_.length;
  2959. }
  2960. /**
  2961. * @returns The path from outerPath to innerPath
  2962. */
  2963. function newRelativePath(outerPath, innerPath) {
  2964. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2965. if (outer === null) {
  2966. return innerPath;
  2967. }
  2968. else if (outer === inner) {
  2969. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2970. }
  2971. else {
  2972. throw new Error('INTERNAL ERROR: innerPath (' +
  2973. innerPath +
  2974. ') is not within ' +
  2975. 'outerPath (' +
  2976. outerPath +
  2977. ')');
  2978. }
  2979. }
  2980. /**
  2981. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2982. */
  2983. function pathCompare(left, right) {
  2984. const leftKeys = pathSlice(left, 0);
  2985. const rightKeys = pathSlice(right, 0);
  2986. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2987. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2988. if (cmp !== 0) {
  2989. return cmp;
  2990. }
  2991. }
  2992. if (leftKeys.length === rightKeys.length) {
  2993. return 0;
  2994. }
  2995. return leftKeys.length < rightKeys.length ? -1 : 1;
  2996. }
  2997. /**
  2998. * @returns true if paths are the same.
  2999. */
  3000. function pathEquals(path, other) {
  3001. if (pathGetLength(path) !== pathGetLength(other)) {
  3002. return false;
  3003. }
  3004. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3005. if (path.pieces_[i] !== other.pieces_[j]) {
  3006. return false;
  3007. }
  3008. }
  3009. return true;
  3010. }
  3011. /**
  3012. * @returns True if this path is a parent of (or the same as) other
  3013. */
  3014. function pathContains(path, other) {
  3015. let i = path.pieceNum_;
  3016. let j = other.pieceNum_;
  3017. if (pathGetLength(path) > pathGetLength(other)) {
  3018. return false;
  3019. }
  3020. while (i < path.pieces_.length) {
  3021. if (path.pieces_[i] !== other.pieces_[j]) {
  3022. return false;
  3023. }
  3024. ++i;
  3025. ++j;
  3026. }
  3027. return true;
  3028. }
  3029. /**
  3030. * Dynamic (mutable) path used to count path lengths.
  3031. *
  3032. * This class is used to efficiently check paths for valid
  3033. * length (in UTF8 bytes) and depth (used in path validation).
  3034. *
  3035. * Throws Error exception if path is ever invalid.
  3036. *
  3037. * The definition of a path always begins with '/'.
  3038. */
  3039. class ValidationPath {
  3040. /**
  3041. * @param path - Initial Path.
  3042. * @param errorPrefix_ - Prefix for any error messages.
  3043. */
  3044. constructor(path, errorPrefix_) {
  3045. this.errorPrefix_ = errorPrefix_;
  3046. this.parts_ = pathSlice(path, 0);
  3047. /** Initialize to number of '/' chars needed in path. */
  3048. this.byteLength_ = Math.max(1, this.parts_.length);
  3049. for (let i = 0; i < this.parts_.length; i++) {
  3050. this.byteLength_ += util.stringLength(this.parts_[i]);
  3051. }
  3052. validationPathCheckValid(this);
  3053. }
  3054. }
  3055. function validationPathPush(validationPath, child) {
  3056. // Count the needed '/'
  3057. if (validationPath.parts_.length > 0) {
  3058. validationPath.byteLength_ += 1;
  3059. }
  3060. validationPath.parts_.push(child);
  3061. validationPath.byteLength_ += util.stringLength(child);
  3062. validationPathCheckValid(validationPath);
  3063. }
  3064. function validationPathPop(validationPath) {
  3065. const last = validationPath.parts_.pop();
  3066. validationPath.byteLength_ -= util.stringLength(last);
  3067. // Un-count the previous '/'
  3068. if (validationPath.parts_.length > 0) {
  3069. validationPath.byteLength_ -= 1;
  3070. }
  3071. }
  3072. function validationPathCheckValid(validationPath) {
  3073. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3074. throw new Error(validationPath.errorPrefix_ +
  3075. 'has a key path longer than ' +
  3076. MAX_PATH_LENGTH_BYTES +
  3077. ' bytes (' +
  3078. validationPath.byteLength_ +
  3079. ').');
  3080. }
  3081. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3082. throw new Error(validationPath.errorPrefix_ +
  3083. 'path specified exceeds the maximum depth that can be written (' +
  3084. MAX_PATH_DEPTH +
  3085. ') or object contains a cycle ' +
  3086. validationPathToErrorString(validationPath));
  3087. }
  3088. }
  3089. /**
  3090. * String for use in error messages - uses '.' notation for path.
  3091. */
  3092. function validationPathToErrorString(validationPath) {
  3093. if (validationPath.parts_.length === 0) {
  3094. return '';
  3095. }
  3096. return "in property '" + validationPath.parts_.join('.') + "'";
  3097. }
  3098. /**
  3099. * @license
  3100. * Copyright 2017 Google LLC
  3101. *
  3102. * Licensed under the Apache License, Version 2.0 (the "License");
  3103. * you may not use this file except in compliance with the License.
  3104. * You may obtain a copy of the License at
  3105. *
  3106. * http://www.apache.org/licenses/LICENSE-2.0
  3107. *
  3108. * Unless required by applicable law or agreed to in writing, software
  3109. * distributed under the License is distributed on an "AS IS" BASIS,
  3110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3111. * See the License for the specific language governing permissions and
  3112. * limitations under the License.
  3113. */
  3114. class VisibilityMonitor extends EventEmitter {
  3115. constructor() {
  3116. super(['visible']);
  3117. let hidden;
  3118. let visibilityChange;
  3119. if (typeof document !== 'undefined' &&
  3120. typeof document.addEventListener !== 'undefined') {
  3121. if (typeof document['hidden'] !== 'undefined') {
  3122. // Opera 12.10 and Firefox 18 and later support
  3123. visibilityChange = 'visibilitychange';
  3124. hidden = 'hidden';
  3125. }
  3126. else if (typeof document['mozHidden'] !== 'undefined') {
  3127. visibilityChange = 'mozvisibilitychange';
  3128. hidden = 'mozHidden';
  3129. }
  3130. else if (typeof document['msHidden'] !== 'undefined') {
  3131. visibilityChange = 'msvisibilitychange';
  3132. hidden = 'msHidden';
  3133. }
  3134. else if (typeof document['webkitHidden'] !== 'undefined') {
  3135. visibilityChange = 'webkitvisibilitychange';
  3136. hidden = 'webkitHidden';
  3137. }
  3138. }
  3139. // Initially, we always assume we are visible. This ensures that in browsers
  3140. // without page visibility support or in cases where we are never visible
  3141. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3142. // reconnects
  3143. this.visible_ = true;
  3144. if (visibilityChange) {
  3145. document.addEventListener(visibilityChange, () => {
  3146. const visible = !document[hidden];
  3147. if (visible !== this.visible_) {
  3148. this.visible_ = visible;
  3149. this.trigger('visible', visible);
  3150. }
  3151. }, false);
  3152. }
  3153. }
  3154. static getInstance() {
  3155. return new VisibilityMonitor();
  3156. }
  3157. getInitialEvent(eventType) {
  3158. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3159. return [this.visible_];
  3160. }
  3161. }
  3162. /**
  3163. * @license
  3164. * Copyright 2017 Google LLC
  3165. *
  3166. * Licensed under the Apache License, Version 2.0 (the "License");
  3167. * you may not use this file except in compliance with the License.
  3168. * You may obtain a copy of the License at
  3169. *
  3170. * http://www.apache.org/licenses/LICENSE-2.0
  3171. *
  3172. * Unless required by applicable law or agreed to in writing, software
  3173. * distributed under the License is distributed on an "AS IS" BASIS,
  3174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3175. * See the License for the specific language governing permissions and
  3176. * limitations under the License.
  3177. */
  3178. const RECONNECT_MIN_DELAY = 1000;
  3179. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3180. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3181. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3182. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3183. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3184. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3185. const INVALID_TOKEN_THRESHOLD = 3;
  3186. /**
  3187. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3188. *
  3189. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3190. * in quotes to make sure the closure compiler does not minify them.
  3191. */
  3192. class PersistentConnection extends ServerActions {
  3193. /**
  3194. * @param repoInfo_ - Data about the namespace we are connecting to
  3195. * @param applicationId_ - The Firebase App ID for this project
  3196. * @param onDataUpdate_ - A callback for new data from the server
  3197. */
  3198. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3199. super();
  3200. this.repoInfo_ = repoInfo_;
  3201. this.applicationId_ = applicationId_;
  3202. this.onDataUpdate_ = onDataUpdate_;
  3203. this.onConnectStatus_ = onConnectStatus_;
  3204. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3205. this.authTokenProvider_ = authTokenProvider_;
  3206. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3207. this.authOverride_ = authOverride_;
  3208. // Used for diagnostic logging.
  3209. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3210. this.log_ = logWrapper('p:' + this.id + ':');
  3211. this.interruptReasons_ = {};
  3212. this.listens = new Map();
  3213. this.outstandingPuts_ = [];
  3214. this.outstandingGets_ = [];
  3215. this.outstandingPutCount_ = 0;
  3216. this.outstandingGetCount_ = 0;
  3217. this.onDisconnectRequestQueue_ = [];
  3218. this.connected_ = false;
  3219. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3220. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3221. this.securityDebugCallback_ = null;
  3222. this.lastSessionId = null;
  3223. this.establishConnectionTimer_ = null;
  3224. this.visible_ = false;
  3225. // Before we get connected, we keep a queue of pending messages to send.
  3226. this.requestCBHash_ = {};
  3227. this.requestNumber_ = 0;
  3228. this.realtime_ = null;
  3229. this.authToken_ = null;
  3230. this.appCheckToken_ = null;
  3231. this.forceTokenRefresh_ = false;
  3232. this.invalidAuthTokenCount_ = 0;
  3233. this.invalidAppCheckTokenCount_ = 0;
  3234. this.firstConnection_ = true;
  3235. this.lastConnectionAttemptTime_ = null;
  3236. this.lastConnectionEstablishedTime_ = null;
  3237. if (authOverride_ && !util.isNodeSdk()) {
  3238. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3239. }
  3240. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3241. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3242. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3243. }
  3244. }
  3245. sendRequest(action, body, onResponse) {
  3246. const curReqNum = ++this.requestNumber_;
  3247. const msg = { r: curReqNum, a: action, b: body };
  3248. this.log_(util.stringify(msg));
  3249. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3250. this.realtime_.sendRequest(msg);
  3251. if (onResponse) {
  3252. this.requestCBHash_[curReqNum] = onResponse;
  3253. }
  3254. }
  3255. get(query) {
  3256. this.initConnection_();
  3257. const deferred = new util.Deferred();
  3258. const request = {
  3259. p: query._path.toString(),
  3260. q: query._queryObject
  3261. };
  3262. const outstandingGet = {
  3263. action: 'g',
  3264. request,
  3265. onComplete: (message) => {
  3266. const payload = message['d'];
  3267. if (message['s'] === 'ok') {
  3268. deferred.resolve(payload);
  3269. }
  3270. else {
  3271. deferred.reject(payload);
  3272. }
  3273. }
  3274. };
  3275. this.outstandingGets_.push(outstandingGet);
  3276. this.outstandingGetCount_++;
  3277. const index = this.outstandingGets_.length - 1;
  3278. if (this.connected_) {
  3279. this.sendGet_(index);
  3280. }
  3281. return deferred.promise;
  3282. }
  3283. listen(query, currentHashFn, tag, onComplete) {
  3284. this.initConnection_();
  3285. const queryId = query._queryIdentifier;
  3286. const pathString = query._path.toString();
  3287. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3288. if (!this.listens.has(pathString)) {
  3289. this.listens.set(pathString, new Map());
  3290. }
  3291. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3292. util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3293. const listenSpec = {
  3294. onComplete,
  3295. hashFn: currentHashFn,
  3296. query,
  3297. tag
  3298. };
  3299. this.listens.get(pathString).set(queryId, listenSpec);
  3300. if (this.connected_) {
  3301. this.sendListen_(listenSpec);
  3302. }
  3303. }
  3304. sendGet_(index) {
  3305. const get = this.outstandingGets_[index];
  3306. this.sendRequest('g', get.request, (message) => {
  3307. delete this.outstandingGets_[index];
  3308. this.outstandingGetCount_--;
  3309. if (this.outstandingGetCount_ === 0) {
  3310. this.outstandingGets_ = [];
  3311. }
  3312. if (get.onComplete) {
  3313. get.onComplete(message);
  3314. }
  3315. });
  3316. }
  3317. sendListen_(listenSpec) {
  3318. const query = listenSpec.query;
  3319. const pathString = query._path.toString();
  3320. const queryId = query._queryIdentifier;
  3321. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3322. const req = { /*path*/ p: pathString };
  3323. const action = 'q';
  3324. // Only bother to send query if it's non-default.
  3325. if (listenSpec.tag) {
  3326. req['q'] = query._queryObject;
  3327. req['t'] = listenSpec.tag;
  3328. }
  3329. req[ /*hash*/'h'] = listenSpec.hashFn();
  3330. this.sendRequest(action, req, (message) => {
  3331. const payload = message[ /*data*/'d'];
  3332. const status = message[ /*status*/'s'];
  3333. // print warnings in any case...
  3334. PersistentConnection.warnOnListenWarnings_(payload, query);
  3335. const currentListenSpec = this.listens.get(pathString) &&
  3336. this.listens.get(pathString).get(queryId);
  3337. // only trigger actions if the listen hasn't been removed and readded
  3338. if (currentListenSpec === listenSpec) {
  3339. this.log_('listen response', message);
  3340. if (status !== 'ok') {
  3341. this.removeListen_(pathString, queryId);
  3342. }
  3343. if (listenSpec.onComplete) {
  3344. listenSpec.onComplete(status, payload);
  3345. }
  3346. }
  3347. });
  3348. }
  3349. static warnOnListenWarnings_(payload, query) {
  3350. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  3351. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3352. const warnings = util.safeGet(payload, 'w');
  3353. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3354. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3355. const indexPath = query._path.toString();
  3356. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3357. `filtered on the client. Consider adding ${indexSpec} at ` +
  3358. `${indexPath} to your security rules for better performance.`);
  3359. }
  3360. }
  3361. }
  3362. refreshAuthToken(token) {
  3363. this.authToken_ = token;
  3364. this.log_('Auth token refreshed');
  3365. if (this.authToken_) {
  3366. this.tryAuth();
  3367. }
  3368. else {
  3369. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3370. //the credential so we dont become authenticated next time we connect.
  3371. if (this.connected_) {
  3372. this.sendRequest('unauth', {}, () => { });
  3373. }
  3374. }
  3375. this.reduceReconnectDelayIfAdminCredential_(token);
  3376. }
  3377. reduceReconnectDelayIfAdminCredential_(credential) {
  3378. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3379. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3380. const isFirebaseSecret = credential && credential.length === 40;
  3381. if (isFirebaseSecret || util.isAdmin(credential)) {
  3382. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3383. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3384. }
  3385. }
  3386. refreshAppCheckToken(token) {
  3387. this.appCheckToken_ = token;
  3388. this.log_('App check token refreshed');
  3389. if (this.appCheckToken_) {
  3390. this.tryAppCheck();
  3391. }
  3392. else {
  3393. //If we're connected we want to let the server know to unauthenticate us.
  3394. //If we're not connected, simply delete the credential so we dont become
  3395. // authenticated next time we connect.
  3396. if (this.connected_) {
  3397. this.sendRequest('unappeck', {}, () => { });
  3398. }
  3399. }
  3400. }
  3401. /**
  3402. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3403. * a auth revoked (the connection is closed).
  3404. */
  3405. tryAuth() {
  3406. if (this.connected_ && this.authToken_) {
  3407. const token = this.authToken_;
  3408. const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth';
  3409. const requestData = { cred: token };
  3410. if (this.authOverride_ === null) {
  3411. requestData['noauth'] = true;
  3412. }
  3413. else if (typeof this.authOverride_ === 'object') {
  3414. requestData['authvar'] = this.authOverride_;
  3415. }
  3416. this.sendRequest(authMethod, requestData, (res) => {
  3417. const status = res[ /*status*/'s'];
  3418. const data = res[ /*data*/'d'] || 'error';
  3419. if (this.authToken_ === token) {
  3420. if (status === 'ok') {
  3421. this.invalidAuthTokenCount_ = 0;
  3422. }
  3423. else {
  3424. // Triggers reconnect and force refresh for auth token
  3425. this.onAuthRevoked_(status, data);
  3426. }
  3427. }
  3428. });
  3429. }
  3430. }
  3431. /**
  3432. * Attempts to authenticate with the given token. If the authentication
  3433. * attempt fails, it's triggered like the token was revoked (the connection is
  3434. * closed).
  3435. */
  3436. tryAppCheck() {
  3437. if (this.connected_ && this.appCheckToken_) {
  3438. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3439. const status = res[ /*status*/'s'];
  3440. const data = res[ /*data*/'d'] || 'error';
  3441. if (status === 'ok') {
  3442. this.invalidAppCheckTokenCount_ = 0;
  3443. }
  3444. else {
  3445. this.onAppCheckRevoked_(status, data);
  3446. }
  3447. });
  3448. }
  3449. }
  3450. /**
  3451. * @inheritDoc
  3452. */
  3453. unlisten(query, tag) {
  3454. const pathString = query._path.toString();
  3455. const queryId = query._queryIdentifier;
  3456. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3457. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3458. const listen = this.removeListen_(pathString, queryId);
  3459. if (listen && this.connected_) {
  3460. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3461. }
  3462. }
  3463. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3464. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3465. const req = { /*path*/ p: pathString };
  3466. const action = 'n';
  3467. // Only bother sending queryId if it's non-default.
  3468. if (tag) {
  3469. req['q'] = queryObj;
  3470. req['t'] = tag;
  3471. }
  3472. this.sendRequest(action, req);
  3473. }
  3474. onDisconnectPut(pathString, data, onComplete) {
  3475. this.initConnection_();
  3476. if (this.connected_) {
  3477. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3478. }
  3479. else {
  3480. this.onDisconnectRequestQueue_.push({
  3481. pathString,
  3482. action: 'o',
  3483. data,
  3484. onComplete
  3485. });
  3486. }
  3487. }
  3488. onDisconnectMerge(pathString, data, onComplete) {
  3489. this.initConnection_();
  3490. if (this.connected_) {
  3491. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3492. }
  3493. else {
  3494. this.onDisconnectRequestQueue_.push({
  3495. pathString,
  3496. action: 'om',
  3497. data,
  3498. onComplete
  3499. });
  3500. }
  3501. }
  3502. onDisconnectCancel(pathString, onComplete) {
  3503. this.initConnection_();
  3504. if (this.connected_) {
  3505. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3506. }
  3507. else {
  3508. this.onDisconnectRequestQueue_.push({
  3509. pathString,
  3510. action: 'oc',
  3511. data: null,
  3512. onComplete
  3513. });
  3514. }
  3515. }
  3516. sendOnDisconnect_(action, pathString, data, onComplete) {
  3517. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3518. this.log_('onDisconnect ' + action, request);
  3519. this.sendRequest(action, request, (response) => {
  3520. if (onComplete) {
  3521. setTimeout(() => {
  3522. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3523. }, Math.floor(0));
  3524. }
  3525. });
  3526. }
  3527. put(pathString, data, onComplete, hash) {
  3528. this.putInternal('p', pathString, data, onComplete, hash);
  3529. }
  3530. merge(pathString, data, onComplete, hash) {
  3531. this.putInternal('m', pathString, data, onComplete, hash);
  3532. }
  3533. putInternal(action, pathString, data, onComplete, hash) {
  3534. this.initConnection_();
  3535. const request = {
  3536. /*path*/ p: pathString,
  3537. /*data*/ d: data
  3538. };
  3539. if (hash !== undefined) {
  3540. request[ /*hash*/'h'] = hash;
  3541. }
  3542. // TODO: Only keep track of the most recent put for a given path?
  3543. this.outstandingPuts_.push({
  3544. action,
  3545. request,
  3546. onComplete
  3547. });
  3548. this.outstandingPutCount_++;
  3549. const index = this.outstandingPuts_.length - 1;
  3550. if (this.connected_) {
  3551. this.sendPut_(index);
  3552. }
  3553. else {
  3554. this.log_('Buffering put: ' + pathString);
  3555. }
  3556. }
  3557. sendPut_(index) {
  3558. const action = this.outstandingPuts_[index].action;
  3559. const request = this.outstandingPuts_[index].request;
  3560. const onComplete = this.outstandingPuts_[index].onComplete;
  3561. this.outstandingPuts_[index].queued = this.connected_;
  3562. this.sendRequest(action, request, (message) => {
  3563. this.log_(action + ' response', message);
  3564. delete this.outstandingPuts_[index];
  3565. this.outstandingPutCount_--;
  3566. // Clean up array occasionally.
  3567. if (this.outstandingPutCount_ === 0) {
  3568. this.outstandingPuts_ = [];
  3569. }
  3570. if (onComplete) {
  3571. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3572. }
  3573. });
  3574. }
  3575. reportStats(stats) {
  3576. // If we're not connected, we just drop the stats.
  3577. if (this.connected_) {
  3578. const request = { /*counters*/ c: stats };
  3579. this.log_('reportStats', request);
  3580. this.sendRequest(/*stats*/ 's', request, result => {
  3581. const status = result[ /*status*/'s'];
  3582. if (status !== 'ok') {
  3583. const errorReason = result[ /* data */'d'];
  3584. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3585. }
  3586. });
  3587. }
  3588. }
  3589. onDataMessage_(message) {
  3590. if ('r' in message) {
  3591. // this is a response
  3592. this.log_('from server: ' + util.stringify(message));
  3593. const reqNum = message['r'];
  3594. const onResponse = this.requestCBHash_[reqNum];
  3595. if (onResponse) {
  3596. delete this.requestCBHash_[reqNum];
  3597. onResponse(message[ /*body*/'b']);
  3598. }
  3599. }
  3600. else if ('error' in message) {
  3601. throw 'A server-side error has occurred: ' + message['error'];
  3602. }
  3603. else if ('a' in message) {
  3604. // a and b are action and body, respectively
  3605. this.onDataPush_(message['a'], message['b']);
  3606. }
  3607. }
  3608. onDataPush_(action, body) {
  3609. this.log_('handleServerMessage', action, body);
  3610. if (action === 'd') {
  3611. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3612. /*isMerge*/ false, body['t']);
  3613. }
  3614. else if (action === 'm') {
  3615. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3616. /*isMerge=*/ true, body['t']);
  3617. }
  3618. else if (action === 'c') {
  3619. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3620. }
  3621. else if (action === 'ac') {
  3622. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3623. }
  3624. else if (action === 'apc') {
  3625. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3626. }
  3627. else if (action === 'sd') {
  3628. this.onSecurityDebugPacket_(body);
  3629. }
  3630. else {
  3631. error('Unrecognized action received from server: ' +
  3632. util.stringify(action) +
  3633. '\nAre you using the latest client?');
  3634. }
  3635. }
  3636. onReady_(timestamp, sessionId) {
  3637. this.log_('connection ready');
  3638. this.connected_ = true;
  3639. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3640. this.handleTimestamp_(timestamp);
  3641. this.lastSessionId = sessionId;
  3642. if (this.firstConnection_) {
  3643. this.sendConnectStats_();
  3644. }
  3645. this.restoreState_();
  3646. this.firstConnection_ = false;
  3647. this.onConnectStatus_(true);
  3648. }
  3649. scheduleConnect_(timeout) {
  3650. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3651. if (this.establishConnectionTimer_) {
  3652. clearTimeout(this.establishConnectionTimer_);
  3653. }
  3654. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3655. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3656. this.establishConnectionTimer_ = setTimeout(() => {
  3657. this.establishConnectionTimer_ = null;
  3658. this.establishConnection_();
  3659. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3660. }, Math.floor(timeout));
  3661. }
  3662. initConnection_() {
  3663. if (!this.realtime_ && this.firstConnection_) {
  3664. this.scheduleConnect_(0);
  3665. }
  3666. }
  3667. onVisible_(visible) {
  3668. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3669. if (visible &&
  3670. !this.visible_ &&
  3671. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3672. this.log_('Window became visible. Reducing delay.');
  3673. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3674. if (!this.realtime_) {
  3675. this.scheduleConnect_(0);
  3676. }
  3677. }
  3678. this.visible_ = visible;
  3679. }
  3680. onOnline_(online) {
  3681. if (online) {
  3682. this.log_('Browser went online.');
  3683. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3684. if (!this.realtime_) {
  3685. this.scheduleConnect_(0);
  3686. }
  3687. }
  3688. else {
  3689. this.log_('Browser went offline. Killing connection.');
  3690. if (this.realtime_) {
  3691. this.realtime_.close();
  3692. }
  3693. }
  3694. }
  3695. onRealtimeDisconnect_() {
  3696. this.log_('data client disconnected');
  3697. this.connected_ = false;
  3698. this.realtime_ = null;
  3699. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3700. this.cancelSentTransactions_();
  3701. // Clear out the pending requests.
  3702. this.requestCBHash_ = {};
  3703. if (this.shouldReconnect_()) {
  3704. if (!this.visible_) {
  3705. this.log_("Window isn't visible. Delaying reconnect.");
  3706. this.reconnectDelay_ = this.maxReconnectDelay_;
  3707. this.lastConnectionAttemptTime_ = new Date().getTime();
  3708. }
  3709. else if (this.lastConnectionEstablishedTime_) {
  3710. // If we've been connected long enough, reset reconnect delay to minimum.
  3711. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3712. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3713. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3714. }
  3715. this.lastConnectionEstablishedTime_ = null;
  3716. }
  3717. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3718. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3719. reconnectDelay = Math.random() * reconnectDelay;
  3720. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3721. this.scheduleConnect_(reconnectDelay);
  3722. // Adjust reconnect delay for next time.
  3723. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3724. }
  3725. this.onConnectStatus_(false);
  3726. }
  3727. async establishConnection_() {
  3728. if (this.shouldReconnect_()) {
  3729. this.log_('Making a connection attempt');
  3730. this.lastConnectionAttemptTime_ = new Date().getTime();
  3731. this.lastConnectionEstablishedTime_ = null;
  3732. const onDataMessage = this.onDataMessage_.bind(this);
  3733. const onReady = this.onReady_.bind(this);
  3734. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3735. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3736. const lastSessionId = this.lastSessionId;
  3737. let canceled = false;
  3738. let connection = null;
  3739. const closeFn = function () {
  3740. if (connection) {
  3741. connection.close();
  3742. }
  3743. else {
  3744. canceled = true;
  3745. onDisconnect();
  3746. }
  3747. };
  3748. const sendRequestFn = function (msg) {
  3749. util.assert(connection, "sendRequest call when we're not connected not allowed.");
  3750. connection.sendRequest(msg);
  3751. };
  3752. this.realtime_ = {
  3753. close: closeFn,
  3754. sendRequest: sendRequestFn
  3755. };
  3756. const forceRefresh = this.forceTokenRefresh_;
  3757. this.forceTokenRefresh_ = false;
  3758. try {
  3759. // First fetch auth and app check token, and establish connection after
  3760. // fetching the token was successful
  3761. const [authToken, appCheckToken] = await Promise.all([
  3762. this.authTokenProvider_.getToken(forceRefresh),
  3763. this.appCheckTokenProvider_.getToken(forceRefresh)
  3764. ]);
  3765. if (!canceled) {
  3766. log('getToken() completed. Creating connection.');
  3767. this.authToken_ = authToken && authToken.accessToken;
  3768. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3769. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3770. /* onKill= */ reason => {
  3771. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3772. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3773. }, lastSessionId);
  3774. }
  3775. else {
  3776. log('getToken() completed but was canceled');
  3777. }
  3778. }
  3779. catch (error) {
  3780. this.log_('Failed to get token: ' + error);
  3781. if (!canceled) {
  3782. if (this.repoInfo_.nodeAdmin) {
  3783. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3784. // But getToken() may also just have temporarily failed, so we still want to
  3785. // continue retrying.
  3786. warn(error);
  3787. }
  3788. closeFn();
  3789. }
  3790. }
  3791. }
  3792. }
  3793. interrupt(reason) {
  3794. log('Interrupting connection for reason: ' + reason);
  3795. this.interruptReasons_[reason] = true;
  3796. if (this.realtime_) {
  3797. this.realtime_.close();
  3798. }
  3799. else {
  3800. if (this.establishConnectionTimer_) {
  3801. clearTimeout(this.establishConnectionTimer_);
  3802. this.establishConnectionTimer_ = null;
  3803. }
  3804. if (this.connected_) {
  3805. this.onRealtimeDisconnect_();
  3806. }
  3807. }
  3808. }
  3809. resume(reason) {
  3810. log('Resuming connection for reason: ' + reason);
  3811. delete this.interruptReasons_[reason];
  3812. if (util.isEmpty(this.interruptReasons_)) {
  3813. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3814. if (!this.realtime_) {
  3815. this.scheduleConnect_(0);
  3816. }
  3817. }
  3818. }
  3819. handleTimestamp_(timestamp) {
  3820. const delta = timestamp - new Date().getTime();
  3821. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3822. }
  3823. cancelSentTransactions_() {
  3824. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3825. const put = this.outstandingPuts_[i];
  3826. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3827. if (put.onComplete) {
  3828. put.onComplete('disconnect');
  3829. }
  3830. delete this.outstandingPuts_[i];
  3831. this.outstandingPutCount_--;
  3832. }
  3833. }
  3834. // Clean up array occasionally.
  3835. if (this.outstandingPutCount_ === 0) {
  3836. this.outstandingPuts_ = [];
  3837. }
  3838. }
  3839. onListenRevoked_(pathString, query) {
  3840. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3841. let queryId;
  3842. if (!query) {
  3843. queryId = 'default';
  3844. }
  3845. else {
  3846. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3847. }
  3848. const listen = this.removeListen_(pathString, queryId);
  3849. if (listen && listen.onComplete) {
  3850. listen.onComplete('permission_denied');
  3851. }
  3852. }
  3853. removeListen_(pathString, queryId) {
  3854. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3855. let listen;
  3856. if (this.listens.has(normalizedPathString)) {
  3857. const map = this.listens.get(normalizedPathString);
  3858. listen = map.get(queryId);
  3859. map.delete(queryId);
  3860. if (map.size === 0) {
  3861. this.listens.delete(normalizedPathString);
  3862. }
  3863. }
  3864. else {
  3865. // all listens for this path has already been removed
  3866. listen = undefined;
  3867. }
  3868. return listen;
  3869. }
  3870. onAuthRevoked_(statusCode, explanation) {
  3871. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3872. this.authToken_ = null;
  3873. this.forceTokenRefresh_ = true;
  3874. this.realtime_.close();
  3875. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3876. // We'll wait a couple times before logging the warning / increasing the
  3877. // retry period since oauth tokens will report as "invalid" if they're
  3878. // just expired. Plus there may be transient issues that resolve themselves.
  3879. this.invalidAuthTokenCount_++;
  3880. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3881. // Set a long reconnect delay because recovery is unlikely
  3882. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3883. // Notify the auth token provider that the token is invalid, which will log
  3884. // a warning
  3885. this.authTokenProvider_.notifyForInvalidToken();
  3886. }
  3887. }
  3888. }
  3889. onAppCheckRevoked_(statusCode, explanation) {
  3890. log('App check token revoked: ' + statusCode + '/' + explanation);
  3891. this.appCheckToken_ = null;
  3892. this.forceTokenRefresh_ = true;
  3893. // Note: We don't close the connection as the developer may not have
  3894. // enforcement enabled. The backend closes connections with enforcements.
  3895. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3896. // We'll wait a couple times before logging the warning / increasing the
  3897. // retry period since oauth tokens will report as "invalid" if they're
  3898. // just expired. Plus there may be transient issues that resolve themselves.
  3899. this.invalidAppCheckTokenCount_++;
  3900. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3901. this.appCheckTokenProvider_.notifyForInvalidToken();
  3902. }
  3903. }
  3904. }
  3905. onSecurityDebugPacket_(body) {
  3906. if (this.securityDebugCallback_) {
  3907. this.securityDebugCallback_(body);
  3908. }
  3909. else {
  3910. if ('msg' in body) {
  3911. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3912. }
  3913. }
  3914. }
  3915. restoreState_() {
  3916. //Re-authenticate ourselves if we have a credential stored.
  3917. this.tryAuth();
  3918. this.tryAppCheck();
  3919. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3920. // make sure to send listens before puts.
  3921. for (const queries of this.listens.values()) {
  3922. for (const listenSpec of queries.values()) {
  3923. this.sendListen_(listenSpec);
  3924. }
  3925. }
  3926. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3927. if (this.outstandingPuts_[i]) {
  3928. this.sendPut_(i);
  3929. }
  3930. }
  3931. while (this.onDisconnectRequestQueue_.length) {
  3932. const request = this.onDisconnectRequestQueue_.shift();
  3933. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3934. }
  3935. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3936. if (this.outstandingGets_[i]) {
  3937. this.sendGet_(i);
  3938. }
  3939. }
  3940. }
  3941. /**
  3942. * Sends client stats for first connection
  3943. */
  3944. sendConnectStats_() {
  3945. const stats = {};
  3946. let clientName = 'js';
  3947. if (util.isNodeSdk()) {
  3948. if (this.repoInfo_.nodeAdmin) {
  3949. clientName = 'admin_node';
  3950. }
  3951. else {
  3952. clientName = 'node';
  3953. }
  3954. }
  3955. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3956. if (util.isMobileCordova()) {
  3957. stats['framework.cordova'] = 1;
  3958. }
  3959. else if (util.isReactNative()) {
  3960. stats['framework.reactnative'] = 1;
  3961. }
  3962. this.reportStats(stats);
  3963. }
  3964. shouldReconnect_() {
  3965. const online = OnlineMonitor.getInstance().currentlyOnline();
  3966. return util.isEmpty(this.interruptReasons_) && online;
  3967. }
  3968. }
  3969. PersistentConnection.nextPersistentConnectionId_ = 0;
  3970. /**
  3971. * Counter for number of connections created. Mainly used for tagging in the logs
  3972. */
  3973. PersistentConnection.nextConnectionId_ = 0;
  3974. /**
  3975. * @license
  3976. * Copyright 2017 Google LLC
  3977. *
  3978. * Licensed under the Apache License, Version 2.0 (the "License");
  3979. * you may not use this file except in compliance with the License.
  3980. * You may obtain a copy of the License at
  3981. *
  3982. * http://www.apache.org/licenses/LICENSE-2.0
  3983. *
  3984. * Unless required by applicable law or agreed to in writing, software
  3985. * distributed under the License is distributed on an "AS IS" BASIS,
  3986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3987. * See the License for the specific language governing permissions and
  3988. * limitations under the License.
  3989. */
  3990. class NamedNode {
  3991. constructor(name, node) {
  3992. this.name = name;
  3993. this.node = node;
  3994. }
  3995. static Wrap(name, node) {
  3996. return new NamedNode(name, node);
  3997. }
  3998. }
  3999. /**
  4000. * @license
  4001. * Copyright 2017 Google LLC
  4002. *
  4003. * Licensed under the Apache License, Version 2.0 (the "License");
  4004. * you may not use this file except in compliance with the License.
  4005. * You may obtain a copy of the License at
  4006. *
  4007. * http://www.apache.org/licenses/LICENSE-2.0
  4008. *
  4009. * Unless required by applicable law or agreed to in writing, software
  4010. * distributed under the License is distributed on an "AS IS" BASIS,
  4011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4012. * See the License for the specific language governing permissions and
  4013. * limitations under the License.
  4014. */
  4015. class Index {
  4016. /**
  4017. * @returns A standalone comparison function for
  4018. * this index
  4019. */
  4020. getCompare() {
  4021. return this.compare.bind(this);
  4022. }
  4023. /**
  4024. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4025. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4026. *
  4027. *
  4028. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4029. */
  4030. indexedValueChanged(oldNode, newNode) {
  4031. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4032. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4033. return this.compare(oldWrapped, newWrapped) !== 0;
  4034. }
  4035. /**
  4036. * @returns a node wrapper that will sort equal to or less than
  4037. * any other node wrapper, using this index
  4038. */
  4039. minPost() {
  4040. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4041. return NamedNode.MIN;
  4042. }
  4043. }
  4044. /**
  4045. * @license
  4046. * Copyright 2017 Google LLC
  4047. *
  4048. * Licensed under the Apache License, Version 2.0 (the "License");
  4049. * you may not use this file except in compliance with the License.
  4050. * You may obtain a copy of the License at
  4051. *
  4052. * http://www.apache.org/licenses/LICENSE-2.0
  4053. *
  4054. * Unless required by applicable law or agreed to in writing, software
  4055. * distributed under the License is distributed on an "AS IS" BASIS,
  4056. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4057. * See the License for the specific language governing permissions and
  4058. * limitations under the License.
  4059. */
  4060. let __EMPTY_NODE;
  4061. class KeyIndex extends Index {
  4062. static get __EMPTY_NODE() {
  4063. return __EMPTY_NODE;
  4064. }
  4065. static set __EMPTY_NODE(val) {
  4066. __EMPTY_NODE = val;
  4067. }
  4068. compare(a, b) {
  4069. return nameCompare(a.name, b.name);
  4070. }
  4071. isDefinedOn(node) {
  4072. // We could probably return true here (since every node has a key), but it's never called
  4073. // so just leaving unimplemented for now.
  4074. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4075. }
  4076. indexedValueChanged(oldNode, newNode) {
  4077. return false; // The key for a node never changes.
  4078. }
  4079. minPost() {
  4080. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4081. return NamedNode.MIN;
  4082. }
  4083. maxPost() {
  4084. // TODO: This should really be created once and cached in a static property, but
  4085. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4086. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4087. }
  4088. makePost(indexValue, name) {
  4089. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4090. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4091. return new NamedNode(indexValue, __EMPTY_NODE);
  4092. }
  4093. /**
  4094. * @returns String representation for inclusion in a query spec
  4095. */
  4096. toString() {
  4097. return '.key';
  4098. }
  4099. }
  4100. const KEY_INDEX = new KeyIndex();
  4101. /**
  4102. * @license
  4103. * Copyright 2017 Google LLC
  4104. *
  4105. * Licensed under the Apache License, Version 2.0 (the "License");
  4106. * you may not use this file except in compliance with the License.
  4107. * You may obtain a copy of the License at
  4108. *
  4109. * http://www.apache.org/licenses/LICENSE-2.0
  4110. *
  4111. * Unless required by applicable law or agreed to in writing, software
  4112. * distributed under the License is distributed on an "AS IS" BASIS,
  4113. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4114. * See the License for the specific language governing permissions and
  4115. * limitations under the License.
  4116. */
  4117. /**
  4118. * An iterator over an LLRBNode.
  4119. */
  4120. class SortedMapIterator {
  4121. /**
  4122. * @param node - Node to iterate.
  4123. * @param isReverse_ - Whether or not to iterate in reverse
  4124. */
  4125. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4126. this.isReverse_ = isReverse_;
  4127. this.resultGenerator_ = resultGenerator_;
  4128. this.nodeStack_ = [];
  4129. let cmp = 1;
  4130. while (!node.isEmpty()) {
  4131. node = node;
  4132. cmp = startKey ? comparator(node.key, startKey) : 1;
  4133. // flip the comparison if we're going in reverse
  4134. if (isReverse_) {
  4135. cmp *= -1;
  4136. }
  4137. if (cmp < 0) {
  4138. // This node is less than our start key. ignore it
  4139. if (this.isReverse_) {
  4140. node = node.left;
  4141. }
  4142. else {
  4143. node = node.right;
  4144. }
  4145. }
  4146. else if (cmp === 0) {
  4147. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4148. this.nodeStack_.push(node);
  4149. break;
  4150. }
  4151. else {
  4152. // This node is greater than our start key, add it to the stack and move to the next one
  4153. this.nodeStack_.push(node);
  4154. if (this.isReverse_) {
  4155. node = node.right;
  4156. }
  4157. else {
  4158. node = node.left;
  4159. }
  4160. }
  4161. }
  4162. }
  4163. getNext() {
  4164. if (this.nodeStack_.length === 0) {
  4165. return null;
  4166. }
  4167. let node = this.nodeStack_.pop();
  4168. let result;
  4169. if (this.resultGenerator_) {
  4170. result = this.resultGenerator_(node.key, node.value);
  4171. }
  4172. else {
  4173. result = { key: node.key, value: node.value };
  4174. }
  4175. if (this.isReverse_) {
  4176. node = node.left;
  4177. while (!node.isEmpty()) {
  4178. this.nodeStack_.push(node);
  4179. node = node.right;
  4180. }
  4181. }
  4182. else {
  4183. node = node.right;
  4184. while (!node.isEmpty()) {
  4185. this.nodeStack_.push(node);
  4186. node = node.left;
  4187. }
  4188. }
  4189. return result;
  4190. }
  4191. hasNext() {
  4192. return this.nodeStack_.length > 0;
  4193. }
  4194. peek() {
  4195. if (this.nodeStack_.length === 0) {
  4196. return null;
  4197. }
  4198. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4199. if (this.resultGenerator_) {
  4200. return this.resultGenerator_(node.key, node.value);
  4201. }
  4202. else {
  4203. return { key: node.key, value: node.value };
  4204. }
  4205. }
  4206. }
  4207. /**
  4208. * Represents a node in a Left-leaning Red-Black tree.
  4209. */
  4210. class LLRBNode {
  4211. /**
  4212. * @param key - Key associated with this node.
  4213. * @param value - Value associated with this node.
  4214. * @param color - Whether this node is red.
  4215. * @param left - Left child.
  4216. * @param right - Right child.
  4217. */
  4218. constructor(key, value, color, left, right) {
  4219. this.key = key;
  4220. this.value = value;
  4221. this.color = color != null ? color : LLRBNode.RED;
  4222. this.left =
  4223. left != null ? left : SortedMap.EMPTY_NODE;
  4224. this.right =
  4225. right != null ? right : SortedMap.EMPTY_NODE;
  4226. }
  4227. /**
  4228. * Returns a copy of the current node, optionally replacing pieces of it.
  4229. *
  4230. * @param key - New key for the node, or null.
  4231. * @param value - New value for the node, or null.
  4232. * @param color - New color for the node, or null.
  4233. * @param left - New left child for the node, or null.
  4234. * @param right - New right child for the node, or null.
  4235. * @returns The node copy.
  4236. */
  4237. copy(key, value, color, left, right) {
  4238. 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);
  4239. }
  4240. /**
  4241. * @returns The total number of nodes in the tree.
  4242. */
  4243. count() {
  4244. return this.left.count() + 1 + this.right.count();
  4245. }
  4246. /**
  4247. * @returns True if the tree is empty.
  4248. */
  4249. isEmpty() {
  4250. return false;
  4251. }
  4252. /**
  4253. * Traverses the tree in key order and calls the specified action function
  4254. * for each node.
  4255. *
  4256. * @param action - Callback function to be called for each
  4257. * node. If it returns true, traversal is aborted.
  4258. * @returns The first truthy value returned by action, or the last falsey
  4259. * value returned by action
  4260. */
  4261. inorderTraversal(action) {
  4262. return (this.left.inorderTraversal(action) ||
  4263. !!action(this.key, this.value) ||
  4264. this.right.inorderTraversal(action));
  4265. }
  4266. /**
  4267. * Traverses the tree in reverse key order and calls the specified action function
  4268. * for each node.
  4269. *
  4270. * @param action - Callback function to be called for each
  4271. * node. If it returns true, traversal is aborted.
  4272. * @returns True if traversal was aborted.
  4273. */
  4274. reverseTraversal(action) {
  4275. return (this.right.reverseTraversal(action) ||
  4276. action(this.key, this.value) ||
  4277. this.left.reverseTraversal(action));
  4278. }
  4279. /**
  4280. * @returns The minimum node in the tree.
  4281. */
  4282. min_() {
  4283. if (this.left.isEmpty()) {
  4284. return this;
  4285. }
  4286. else {
  4287. return this.left.min_();
  4288. }
  4289. }
  4290. /**
  4291. * @returns The maximum key in the tree.
  4292. */
  4293. minKey() {
  4294. return this.min_().key;
  4295. }
  4296. /**
  4297. * @returns The maximum key in the tree.
  4298. */
  4299. maxKey() {
  4300. if (this.right.isEmpty()) {
  4301. return this.key;
  4302. }
  4303. else {
  4304. return this.right.maxKey();
  4305. }
  4306. }
  4307. /**
  4308. * @param key - Key to insert.
  4309. * @param value - Value to insert.
  4310. * @param comparator - Comparator.
  4311. * @returns New tree, with the key/value added.
  4312. */
  4313. insert(key, value, comparator) {
  4314. let n = this;
  4315. const cmp = comparator(key, n.key);
  4316. if (cmp < 0) {
  4317. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4318. }
  4319. else if (cmp === 0) {
  4320. n = n.copy(null, value, null, null, null);
  4321. }
  4322. else {
  4323. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4324. }
  4325. return n.fixUp_();
  4326. }
  4327. /**
  4328. * @returns New tree, with the minimum key removed.
  4329. */
  4330. removeMin_() {
  4331. if (this.left.isEmpty()) {
  4332. return SortedMap.EMPTY_NODE;
  4333. }
  4334. let n = this;
  4335. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4336. n = n.moveRedLeft_();
  4337. }
  4338. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4339. return n.fixUp_();
  4340. }
  4341. /**
  4342. * @param key - The key of the item to remove.
  4343. * @param comparator - Comparator.
  4344. * @returns New tree, with the specified item removed.
  4345. */
  4346. remove(key, comparator) {
  4347. let n, smallest;
  4348. n = this;
  4349. if (comparator(key, n.key) < 0) {
  4350. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4351. n = n.moveRedLeft_();
  4352. }
  4353. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4354. }
  4355. else {
  4356. if (n.left.isRed_()) {
  4357. n = n.rotateRight_();
  4358. }
  4359. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4360. n = n.moveRedRight_();
  4361. }
  4362. if (comparator(key, n.key) === 0) {
  4363. if (n.right.isEmpty()) {
  4364. return SortedMap.EMPTY_NODE;
  4365. }
  4366. else {
  4367. smallest = n.right.min_();
  4368. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4369. }
  4370. }
  4371. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4372. }
  4373. return n.fixUp_();
  4374. }
  4375. /**
  4376. * @returns Whether this is a RED node.
  4377. */
  4378. isRed_() {
  4379. return this.color;
  4380. }
  4381. /**
  4382. * @returns New tree after performing any needed rotations.
  4383. */
  4384. fixUp_() {
  4385. let n = this;
  4386. if (n.right.isRed_() && !n.left.isRed_()) {
  4387. n = n.rotateLeft_();
  4388. }
  4389. if (n.left.isRed_() && n.left.left.isRed_()) {
  4390. n = n.rotateRight_();
  4391. }
  4392. if (n.left.isRed_() && n.right.isRed_()) {
  4393. n = n.colorFlip_();
  4394. }
  4395. return n;
  4396. }
  4397. /**
  4398. * @returns New tree, after moveRedLeft.
  4399. */
  4400. moveRedLeft_() {
  4401. let n = this.colorFlip_();
  4402. if (n.right.left.isRed_()) {
  4403. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4404. n = n.rotateLeft_();
  4405. n = n.colorFlip_();
  4406. }
  4407. return n;
  4408. }
  4409. /**
  4410. * @returns New tree, after moveRedRight.
  4411. */
  4412. moveRedRight_() {
  4413. let n = this.colorFlip_();
  4414. if (n.left.left.isRed_()) {
  4415. n = n.rotateRight_();
  4416. n = n.colorFlip_();
  4417. }
  4418. return n;
  4419. }
  4420. /**
  4421. * @returns New tree, after rotateLeft.
  4422. */
  4423. rotateLeft_() {
  4424. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4425. return this.right.copy(null, null, this.color, nl, null);
  4426. }
  4427. /**
  4428. * @returns New tree, after rotateRight.
  4429. */
  4430. rotateRight_() {
  4431. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4432. return this.left.copy(null, null, this.color, null, nr);
  4433. }
  4434. /**
  4435. * @returns Newt ree, after colorFlip.
  4436. */
  4437. colorFlip_() {
  4438. const left = this.left.copy(null, null, !this.left.color, null, null);
  4439. const right = this.right.copy(null, null, !this.right.color, null, null);
  4440. return this.copy(null, null, !this.color, left, right);
  4441. }
  4442. /**
  4443. * For testing.
  4444. *
  4445. * @returns True if all is well.
  4446. */
  4447. checkMaxDepth_() {
  4448. const blackDepth = this.check_();
  4449. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4450. }
  4451. check_() {
  4452. if (this.isRed_() && this.left.isRed_()) {
  4453. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4454. }
  4455. if (this.right.isRed_()) {
  4456. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4457. }
  4458. const blackDepth = this.left.check_();
  4459. if (blackDepth !== this.right.check_()) {
  4460. throw new Error('Black depths differ');
  4461. }
  4462. else {
  4463. return blackDepth + (this.isRed_() ? 0 : 1);
  4464. }
  4465. }
  4466. }
  4467. LLRBNode.RED = true;
  4468. LLRBNode.BLACK = false;
  4469. /**
  4470. * Represents an empty node (a leaf node in the Red-Black Tree).
  4471. */
  4472. class LLRBEmptyNode {
  4473. /**
  4474. * Returns a copy of the current node.
  4475. *
  4476. * @returns The node copy.
  4477. */
  4478. copy(key, value, color, left, right) {
  4479. return this;
  4480. }
  4481. /**
  4482. * Returns a copy of the tree, with the specified key/value added.
  4483. *
  4484. * @param key - Key to be added.
  4485. * @param value - Value to be added.
  4486. * @param comparator - Comparator.
  4487. * @returns New tree, with item added.
  4488. */
  4489. insert(key, value, comparator) {
  4490. return new LLRBNode(key, value, null);
  4491. }
  4492. /**
  4493. * Returns a copy of the tree, with the specified key removed.
  4494. *
  4495. * @param key - The key to remove.
  4496. * @param comparator - Comparator.
  4497. * @returns New tree, with item removed.
  4498. */
  4499. remove(key, comparator) {
  4500. return this;
  4501. }
  4502. /**
  4503. * @returns The total number of nodes in the tree.
  4504. */
  4505. count() {
  4506. return 0;
  4507. }
  4508. /**
  4509. * @returns True if the tree is empty.
  4510. */
  4511. isEmpty() {
  4512. return true;
  4513. }
  4514. /**
  4515. * Traverses the tree in key order and calls the specified action function
  4516. * for each node.
  4517. *
  4518. * @param action - Callback function to be called for each
  4519. * node. If it returns true, traversal is aborted.
  4520. * @returns True if traversal was aborted.
  4521. */
  4522. inorderTraversal(action) {
  4523. return false;
  4524. }
  4525. /**
  4526. * Traverses the tree in reverse key order and calls the specified action function
  4527. * for each node.
  4528. *
  4529. * @param action - Callback function to be called for each
  4530. * node. If it returns true, traversal is aborted.
  4531. * @returns True if traversal was aborted.
  4532. */
  4533. reverseTraversal(action) {
  4534. return false;
  4535. }
  4536. minKey() {
  4537. return null;
  4538. }
  4539. maxKey() {
  4540. return null;
  4541. }
  4542. check_() {
  4543. return 0;
  4544. }
  4545. /**
  4546. * @returns Whether this node is red.
  4547. */
  4548. isRed_() {
  4549. return false;
  4550. }
  4551. }
  4552. /**
  4553. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4554. * tree.
  4555. */
  4556. class SortedMap {
  4557. /**
  4558. * @param comparator_ - Key comparator.
  4559. * @param root_ - Optional root node for the map.
  4560. */
  4561. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4562. this.comparator_ = comparator_;
  4563. this.root_ = root_;
  4564. }
  4565. /**
  4566. * Returns a copy of the map, with the specified key/value added or replaced.
  4567. * (TODO: We should perhaps rename this method to 'put')
  4568. *
  4569. * @param key - Key to be added.
  4570. * @param value - Value to be added.
  4571. * @returns New map, with item added.
  4572. */
  4573. insert(key, value) {
  4574. return new SortedMap(this.comparator_, this.root_
  4575. .insert(key, value, this.comparator_)
  4576. .copy(null, null, LLRBNode.BLACK, null, null));
  4577. }
  4578. /**
  4579. * Returns a copy of the map, with the specified key removed.
  4580. *
  4581. * @param key - The key to remove.
  4582. * @returns New map, with item removed.
  4583. */
  4584. remove(key) {
  4585. return new SortedMap(this.comparator_, this.root_
  4586. .remove(key, this.comparator_)
  4587. .copy(null, null, LLRBNode.BLACK, null, null));
  4588. }
  4589. /**
  4590. * Returns the value of the node with the given key, or null.
  4591. *
  4592. * @param key - The key to look up.
  4593. * @returns The value of the node with the given key, or null if the
  4594. * key doesn't exist.
  4595. */
  4596. get(key) {
  4597. let cmp;
  4598. let node = this.root_;
  4599. while (!node.isEmpty()) {
  4600. cmp = this.comparator_(key, node.key);
  4601. if (cmp === 0) {
  4602. return node.value;
  4603. }
  4604. else if (cmp < 0) {
  4605. node = node.left;
  4606. }
  4607. else if (cmp > 0) {
  4608. node = node.right;
  4609. }
  4610. }
  4611. return null;
  4612. }
  4613. /**
  4614. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4615. * @param key - The key to find the predecessor of
  4616. * @returns The predecessor key.
  4617. */
  4618. getPredecessorKey(key) {
  4619. let cmp, node = this.root_, rightParent = null;
  4620. while (!node.isEmpty()) {
  4621. cmp = this.comparator_(key, node.key);
  4622. if (cmp === 0) {
  4623. if (!node.left.isEmpty()) {
  4624. node = node.left;
  4625. while (!node.right.isEmpty()) {
  4626. node = node.right;
  4627. }
  4628. return node.key;
  4629. }
  4630. else if (rightParent) {
  4631. return rightParent.key;
  4632. }
  4633. else {
  4634. return null; // first item.
  4635. }
  4636. }
  4637. else if (cmp < 0) {
  4638. node = node.left;
  4639. }
  4640. else if (cmp > 0) {
  4641. rightParent = node;
  4642. node = node.right;
  4643. }
  4644. }
  4645. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4646. }
  4647. /**
  4648. * @returns True if the map is empty.
  4649. */
  4650. isEmpty() {
  4651. return this.root_.isEmpty();
  4652. }
  4653. /**
  4654. * @returns The total number of nodes in the map.
  4655. */
  4656. count() {
  4657. return this.root_.count();
  4658. }
  4659. /**
  4660. * @returns The minimum key in the map.
  4661. */
  4662. minKey() {
  4663. return this.root_.minKey();
  4664. }
  4665. /**
  4666. * @returns The maximum key in the map.
  4667. */
  4668. maxKey() {
  4669. return this.root_.maxKey();
  4670. }
  4671. /**
  4672. * Traverses the map in key order and calls the specified action function
  4673. * for each key/value pair.
  4674. *
  4675. * @param action - Callback function to be called
  4676. * for each key/value pair. If action returns true, traversal is aborted.
  4677. * @returns The first truthy value returned by action, or the last falsey
  4678. * value returned by action
  4679. */
  4680. inorderTraversal(action) {
  4681. return this.root_.inorderTraversal(action);
  4682. }
  4683. /**
  4684. * Traverses the map in reverse key order and calls the specified action function
  4685. * for each key/value pair.
  4686. *
  4687. * @param action - Callback function to be called
  4688. * for each key/value pair. If action returns true, traversal is aborted.
  4689. * @returns True if the traversal was aborted.
  4690. */
  4691. reverseTraversal(action) {
  4692. return this.root_.reverseTraversal(action);
  4693. }
  4694. /**
  4695. * Returns an iterator over the SortedMap.
  4696. * @returns The iterator.
  4697. */
  4698. getIterator(resultGenerator) {
  4699. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4700. }
  4701. getIteratorFrom(key, resultGenerator) {
  4702. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4703. }
  4704. getReverseIteratorFrom(key, resultGenerator) {
  4705. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4706. }
  4707. getReverseIterator(resultGenerator) {
  4708. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4709. }
  4710. }
  4711. /**
  4712. * Always use the same empty node, to reduce memory.
  4713. */
  4714. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4715. /**
  4716. * @license
  4717. * Copyright 2017 Google LLC
  4718. *
  4719. * Licensed under the Apache License, Version 2.0 (the "License");
  4720. * you may not use this file except in compliance with the License.
  4721. * You may obtain a copy of the License at
  4722. *
  4723. * http://www.apache.org/licenses/LICENSE-2.0
  4724. *
  4725. * Unless required by applicable law or agreed to in writing, software
  4726. * distributed under the License is distributed on an "AS IS" BASIS,
  4727. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4728. * See the License for the specific language governing permissions and
  4729. * limitations under the License.
  4730. */
  4731. function NAME_ONLY_COMPARATOR(left, right) {
  4732. return nameCompare(left.name, right.name);
  4733. }
  4734. function NAME_COMPARATOR(left, right) {
  4735. return nameCompare(left, right);
  4736. }
  4737. /**
  4738. * @license
  4739. * Copyright 2017 Google LLC
  4740. *
  4741. * Licensed under the Apache License, Version 2.0 (the "License");
  4742. * you may not use this file except in compliance with the License.
  4743. * You may obtain a copy of the License at
  4744. *
  4745. * http://www.apache.org/licenses/LICENSE-2.0
  4746. *
  4747. * Unless required by applicable law or agreed to in writing, software
  4748. * distributed under the License is distributed on an "AS IS" BASIS,
  4749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4750. * See the License for the specific language governing permissions and
  4751. * limitations under the License.
  4752. */
  4753. let MAX_NODE$2;
  4754. function setMaxNode$1(val) {
  4755. MAX_NODE$2 = val;
  4756. }
  4757. const priorityHashText = function (priority) {
  4758. if (typeof priority === 'number') {
  4759. return 'number:' + doubleToIEEE754String(priority);
  4760. }
  4761. else {
  4762. return 'string:' + priority;
  4763. }
  4764. };
  4765. /**
  4766. * Validates that a priority snapshot Node is valid.
  4767. */
  4768. const validatePriorityNode = function (priorityNode) {
  4769. if (priorityNode.isLeafNode()) {
  4770. const val = priorityNode.val();
  4771. util.assert(typeof val === 'string' ||
  4772. typeof val === 'number' ||
  4773. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  4774. }
  4775. else {
  4776. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4777. }
  4778. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4779. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4780. };
  4781. /**
  4782. * @license
  4783. * Copyright 2017 Google LLC
  4784. *
  4785. * Licensed under the Apache License, Version 2.0 (the "License");
  4786. * you may not use this file except in compliance with the License.
  4787. * You may obtain a copy of the License at
  4788. *
  4789. * http://www.apache.org/licenses/LICENSE-2.0
  4790. *
  4791. * Unless required by applicable law or agreed to in writing, software
  4792. * distributed under the License is distributed on an "AS IS" BASIS,
  4793. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4794. * See the License for the specific language governing permissions and
  4795. * limitations under the License.
  4796. */
  4797. let __childrenNodeConstructor;
  4798. /**
  4799. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4800. * implements Node and stores the value of the node (a string,
  4801. * number, or boolean) accessible via getValue().
  4802. */
  4803. class LeafNode {
  4804. /**
  4805. * @param value_ - The value to store in this leaf node. The object type is
  4806. * possible in the event of a deferred value
  4807. * @param priorityNode_ - The priority of this node.
  4808. */
  4809. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4810. this.value_ = value_;
  4811. this.priorityNode_ = priorityNode_;
  4812. this.lazyHash_ = null;
  4813. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4814. validatePriorityNode(this.priorityNode_);
  4815. }
  4816. static set __childrenNodeConstructor(val) {
  4817. __childrenNodeConstructor = val;
  4818. }
  4819. static get __childrenNodeConstructor() {
  4820. return __childrenNodeConstructor;
  4821. }
  4822. /** @inheritDoc */
  4823. isLeafNode() {
  4824. return true;
  4825. }
  4826. /** @inheritDoc */
  4827. getPriority() {
  4828. return this.priorityNode_;
  4829. }
  4830. /** @inheritDoc */
  4831. updatePriority(newPriorityNode) {
  4832. return new LeafNode(this.value_, newPriorityNode);
  4833. }
  4834. /** @inheritDoc */
  4835. getImmediateChild(childName) {
  4836. // Hack to treat priority as a regular child
  4837. if (childName === '.priority') {
  4838. return this.priorityNode_;
  4839. }
  4840. else {
  4841. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4842. }
  4843. }
  4844. /** @inheritDoc */
  4845. getChild(path) {
  4846. if (pathIsEmpty(path)) {
  4847. return this;
  4848. }
  4849. else if (pathGetFront(path) === '.priority') {
  4850. return this.priorityNode_;
  4851. }
  4852. else {
  4853. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4854. }
  4855. }
  4856. hasChild() {
  4857. return false;
  4858. }
  4859. /** @inheritDoc */
  4860. getPredecessorChildName(childName, childNode) {
  4861. return null;
  4862. }
  4863. /** @inheritDoc */
  4864. updateImmediateChild(childName, newChildNode) {
  4865. if (childName === '.priority') {
  4866. return this.updatePriority(newChildNode);
  4867. }
  4868. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4869. return this;
  4870. }
  4871. else {
  4872. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4873. }
  4874. }
  4875. /** @inheritDoc */
  4876. updateChild(path, newChildNode) {
  4877. const front = pathGetFront(path);
  4878. if (front === null) {
  4879. return newChildNode;
  4880. }
  4881. else if (newChildNode.isEmpty() && front !== '.priority') {
  4882. return this;
  4883. }
  4884. else {
  4885. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4886. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4887. }
  4888. }
  4889. /** @inheritDoc */
  4890. isEmpty() {
  4891. return false;
  4892. }
  4893. /** @inheritDoc */
  4894. numChildren() {
  4895. return 0;
  4896. }
  4897. /** @inheritDoc */
  4898. forEachChild(index, action) {
  4899. return false;
  4900. }
  4901. val(exportFormat) {
  4902. if (exportFormat && !this.getPriority().isEmpty()) {
  4903. return {
  4904. '.value': this.getValue(),
  4905. '.priority': this.getPriority().val()
  4906. };
  4907. }
  4908. else {
  4909. return this.getValue();
  4910. }
  4911. }
  4912. /** @inheritDoc */
  4913. hash() {
  4914. if (this.lazyHash_ === null) {
  4915. let toHash = '';
  4916. if (!this.priorityNode_.isEmpty()) {
  4917. toHash +=
  4918. 'priority:' +
  4919. priorityHashText(this.priorityNode_.val()) +
  4920. ':';
  4921. }
  4922. const type = typeof this.value_;
  4923. toHash += type + ':';
  4924. if (type === 'number') {
  4925. toHash += doubleToIEEE754String(this.value_);
  4926. }
  4927. else {
  4928. toHash += this.value_;
  4929. }
  4930. this.lazyHash_ = sha1(toHash);
  4931. }
  4932. return this.lazyHash_;
  4933. }
  4934. /**
  4935. * Returns the value of the leaf node.
  4936. * @returns The value of the node.
  4937. */
  4938. getValue() {
  4939. return this.value_;
  4940. }
  4941. compareTo(other) {
  4942. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4943. return 1;
  4944. }
  4945. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4946. return -1;
  4947. }
  4948. else {
  4949. util.assert(other.isLeafNode(), 'Unknown node type');
  4950. return this.compareToLeafNode_(other);
  4951. }
  4952. }
  4953. /**
  4954. * Comparison specifically for two leaf nodes
  4955. */
  4956. compareToLeafNode_(otherLeaf) {
  4957. const otherLeafType = typeof otherLeaf.value_;
  4958. const thisLeafType = typeof this.value_;
  4959. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4960. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4961. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4962. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4963. if (otherIndex === thisIndex) {
  4964. // Same type, compare values
  4965. if (thisLeafType === 'object') {
  4966. // Deferred value nodes are all equal, but we should also never get to this point...
  4967. return 0;
  4968. }
  4969. else {
  4970. // Note that this works because true > false, all others are number or string comparisons
  4971. if (this.value_ < otherLeaf.value_) {
  4972. return -1;
  4973. }
  4974. else if (this.value_ === otherLeaf.value_) {
  4975. return 0;
  4976. }
  4977. else {
  4978. return 1;
  4979. }
  4980. }
  4981. }
  4982. else {
  4983. return thisIndex - otherIndex;
  4984. }
  4985. }
  4986. withIndex() {
  4987. return this;
  4988. }
  4989. isIndexed() {
  4990. return true;
  4991. }
  4992. equals(other) {
  4993. if (other === this) {
  4994. return true;
  4995. }
  4996. else if (other.isLeafNode()) {
  4997. const otherLeaf = other;
  4998. return (this.value_ === otherLeaf.value_ &&
  4999. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5000. }
  5001. else {
  5002. return false;
  5003. }
  5004. }
  5005. }
  5006. /**
  5007. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5008. * the same type, the comparison falls back to their value
  5009. */
  5010. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5011. /**
  5012. * @license
  5013. * Copyright 2017 Google LLC
  5014. *
  5015. * Licensed under the Apache License, Version 2.0 (the "License");
  5016. * you may not use this file except in compliance with the License.
  5017. * You may obtain a copy of the License at
  5018. *
  5019. * http://www.apache.org/licenses/LICENSE-2.0
  5020. *
  5021. * Unless required by applicable law or agreed to in writing, software
  5022. * distributed under the License is distributed on an "AS IS" BASIS,
  5023. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5024. * See the License for the specific language governing permissions and
  5025. * limitations under the License.
  5026. */
  5027. let nodeFromJSON$1;
  5028. let MAX_NODE$1;
  5029. function setNodeFromJSON(val) {
  5030. nodeFromJSON$1 = val;
  5031. }
  5032. function setMaxNode(val) {
  5033. MAX_NODE$1 = val;
  5034. }
  5035. class PriorityIndex extends Index {
  5036. compare(a, b) {
  5037. const aPriority = a.node.getPriority();
  5038. const bPriority = b.node.getPriority();
  5039. const indexCmp = aPriority.compareTo(bPriority);
  5040. if (indexCmp === 0) {
  5041. return nameCompare(a.name, b.name);
  5042. }
  5043. else {
  5044. return indexCmp;
  5045. }
  5046. }
  5047. isDefinedOn(node) {
  5048. return !node.getPriority().isEmpty();
  5049. }
  5050. indexedValueChanged(oldNode, newNode) {
  5051. return !oldNode.getPriority().equals(newNode.getPriority());
  5052. }
  5053. minPost() {
  5054. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5055. return NamedNode.MIN;
  5056. }
  5057. maxPost() {
  5058. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5059. }
  5060. makePost(indexValue, name) {
  5061. const priorityNode = nodeFromJSON$1(indexValue);
  5062. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5063. }
  5064. /**
  5065. * @returns String representation for inclusion in a query spec
  5066. */
  5067. toString() {
  5068. return '.priority';
  5069. }
  5070. }
  5071. const PRIORITY_INDEX = new PriorityIndex();
  5072. /**
  5073. * @license
  5074. * Copyright 2017 Google LLC
  5075. *
  5076. * Licensed under the Apache License, Version 2.0 (the "License");
  5077. * you may not use this file except in compliance with the License.
  5078. * You may obtain a copy of the License at
  5079. *
  5080. * http://www.apache.org/licenses/LICENSE-2.0
  5081. *
  5082. * Unless required by applicable law or agreed to in writing, software
  5083. * distributed under the License is distributed on an "AS IS" BASIS,
  5084. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5085. * See the License for the specific language governing permissions and
  5086. * limitations under the License.
  5087. */
  5088. const LOG_2 = Math.log(2);
  5089. class Base12Num {
  5090. constructor(length) {
  5091. const logBase2 = (num) =>
  5092. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5093. parseInt((Math.log(num) / LOG_2), 10);
  5094. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5095. this.count = logBase2(length + 1);
  5096. this.current_ = this.count - 1;
  5097. const mask = bitMask(this.count);
  5098. this.bits_ = (length + 1) & mask;
  5099. }
  5100. nextBitIsOne() {
  5101. //noinspection JSBitwiseOperatorUsage
  5102. const result = !(this.bits_ & (0x1 << this.current_));
  5103. this.current_--;
  5104. return result;
  5105. }
  5106. }
  5107. /**
  5108. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5109. * function
  5110. *
  5111. * Uses the algorithm described in the paper linked here:
  5112. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5113. *
  5114. * @param childList - Unsorted list of children
  5115. * @param cmp - The comparison method to be used
  5116. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5117. * type is not NamedNode
  5118. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5119. */
  5120. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5121. childList.sort(cmp);
  5122. const buildBalancedTree = function (low, high) {
  5123. const length = high - low;
  5124. let namedNode;
  5125. let key;
  5126. if (length === 0) {
  5127. return null;
  5128. }
  5129. else if (length === 1) {
  5130. namedNode = childList[low];
  5131. key = keyFn ? keyFn(namedNode) : namedNode;
  5132. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5133. }
  5134. else {
  5135. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5136. const middle = parseInt((length / 2), 10) + low;
  5137. const left = buildBalancedTree(low, middle);
  5138. const right = buildBalancedTree(middle + 1, high);
  5139. namedNode = childList[middle];
  5140. key = keyFn ? keyFn(namedNode) : namedNode;
  5141. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5142. }
  5143. };
  5144. const buildFrom12Array = function (base12) {
  5145. let node = null;
  5146. let root = null;
  5147. let index = childList.length;
  5148. const buildPennant = function (chunkSize, color) {
  5149. const low = index - chunkSize;
  5150. const high = index;
  5151. index -= chunkSize;
  5152. const childTree = buildBalancedTree(low + 1, high);
  5153. const namedNode = childList[low];
  5154. const key = keyFn ? keyFn(namedNode) : namedNode;
  5155. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5156. };
  5157. const attachPennant = function (pennant) {
  5158. if (node) {
  5159. node.left = pennant;
  5160. node = pennant;
  5161. }
  5162. else {
  5163. root = pennant;
  5164. node = pennant;
  5165. }
  5166. };
  5167. for (let i = 0; i < base12.count; ++i) {
  5168. const isOne = base12.nextBitIsOne();
  5169. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5170. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5171. if (isOne) {
  5172. buildPennant(chunkSize, LLRBNode.BLACK);
  5173. }
  5174. else {
  5175. // current == 2
  5176. buildPennant(chunkSize, LLRBNode.BLACK);
  5177. buildPennant(chunkSize, LLRBNode.RED);
  5178. }
  5179. }
  5180. return root;
  5181. };
  5182. const base12 = new Base12Num(childList.length);
  5183. const root = buildFrom12Array(base12);
  5184. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5185. return new SortedMap(mapSortFn || cmp, root);
  5186. };
  5187. /**
  5188. * @license
  5189. * Copyright 2017 Google LLC
  5190. *
  5191. * Licensed under the Apache License, Version 2.0 (the "License");
  5192. * you may not use this file except in compliance with the License.
  5193. * You may obtain a copy of the License at
  5194. *
  5195. * http://www.apache.org/licenses/LICENSE-2.0
  5196. *
  5197. * Unless required by applicable law or agreed to in writing, software
  5198. * distributed under the License is distributed on an "AS IS" BASIS,
  5199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5200. * See the License for the specific language governing permissions and
  5201. * limitations under the License.
  5202. */
  5203. let _defaultIndexMap;
  5204. const fallbackObject = {};
  5205. class IndexMap {
  5206. constructor(indexes_, indexSet_) {
  5207. this.indexes_ = indexes_;
  5208. this.indexSet_ = indexSet_;
  5209. }
  5210. /**
  5211. * The default IndexMap for nodes without a priority
  5212. */
  5213. static get Default() {
  5214. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5215. _defaultIndexMap =
  5216. _defaultIndexMap ||
  5217. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5218. return _defaultIndexMap;
  5219. }
  5220. get(indexKey) {
  5221. const sortedMap = util.safeGet(this.indexes_, indexKey);
  5222. if (!sortedMap) {
  5223. throw new Error('No index defined for ' + indexKey);
  5224. }
  5225. if (sortedMap instanceof SortedMap) {
  5226. return sortedMap;
  5227. }
  5228. else {
  5229. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5230. // regular child map
  5231. return null;
  5232. }
  5233. }
  5234. hasIndex(indexDefinition) {
  5235. return util.contains(this.indexSet_, indexDefinition.toString());
  5236. }
  5237. addIndex(indexDefinition, existingChildren) {
  5238. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5239. const childList = [];
  5240. let sawIndexedValue = false;
  5241. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5242. let next = iter.getNext();
  5243. while (next) {
  5244. sawIndexedValue =
  5245. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5246. childList.push(next);
  5247. next = iter.getNext();
  5248. }
  5249. let newIndex;
  5250. if (sawIndexedValue) {
  5251. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5252. }
  5253. else {
  5254. newIndex = fallbackObject;
  5255. }
  5256. const indexName = indexDefinition.toString();
  5257. const newIndexSet = Object.assign({}, this.indexSet_);
  5258. newIndexSet[indexName] = indexDefinition;
  5259. const newIndexes = Object.assign({}, this.indexes_);
  5260. newIndexes[indexName] = newIndex;
  5261. return new IndexMap(newIndexes, newIndexSet);
  5262. }
  5263. /**
  5264. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5265. */
  5266. addToIndexes(namedNode, existingChildren) {
  5267. const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => {
  5268. const index = util.safeGet(this.indexSet_, indexName);
  5269. util.assert(index, 'Missing index implementation for ' + indexName);
  5270. if (indexedChildren === fallbackObject) {
  5271. // Check to see if we need to index everything
  5272. if (index.isDefinedOn(namedNode.node)) {
  5273. // We need to build this index
  5274. const childList = [];
  5275. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5276. let next = iter.getNext();
  5277. while (next) {
  5278. if (next.name !== namedNode.name) {
  5279. childList.push(next);
  5280. }
  5281. next = iter.getNext();
  5282. }
  5283. childList.push(namedNode);
  5284. return buildChildSet(childList, index.getCompare());
  5285. }
  5286. else {
  5287. // No change, this remains a fallback
  5288. return fallbackObject;
  5289. }
  5290. }
  5291. else {
  5292. const existingSnap = existingChildren.get(namedNode.name);
  5293. let newChildren = indexedChildren;
  5294. if (existingSnap) {
  5295. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5296. }
  5297. return newChildren.insert(namedNode, namedNode.node);
  5298. }
  5299. });
  5300. return new IndexMap(newIndexes, this.indexSet_);
  5301. }
  5302. /**
  5303. * Create a new IndexMap instance with the given value removed
  5304. */
  5305. removeFromIndexes(namedNode, existingChildren) {
  5306. const newIndexes = util.map(this.indexes_, (indexedChildren) => {
  5307. if (indexedChildren === fallbackObject) {
  5308. // This is the fallback. Just return it, nothing to do in this case
  5309. return indexedChildren;
  5310. }
  5311. else {
  5312. const existingSnap = existingChildren.get(namedNode.name);
  5313. if (existingSnap) {
  5314. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5315. }
  5316. else {
  5317. // No record of this child
  5318. return indexedChildren;
  5319. }
  5320. }
  5321. });
  5322. return new IndexMap(newIndexes, this.indexSet_);
  5323. }
  5324. }
  5325. /**
  5326. * @license
  5327. * Copyright 2017 Google LLC
  5328. *
  5329. * Licensed under the Apache License, Version 2.0 (the "License");
  5330. * you may not use this file except in compliance with the License.
  5331. * You may obtain a copy of the License at
  5332. *
  5333. * http://www.apache.org/licenses/LICENSE-2.0
  5334. *
  5335. * Unless required by applicable law or agreed to in writing, software
  5336. * distributed under the License is distributed on an "AS IS" BASIS,
  5337. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5338. * See the License for the specific language governing permissions and
  5339. * limitations under the License.
  5340. */
  5341. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5342. let EMPTY_NODE;
  5343. /**
  5344. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5345. * (i.e. nodes with children). It implements Node and stores the
  5346. * list of children in the children property, sorted by child name.
  5347. */
  5348. class ChildrenNode {
  5349. /**
  5350. * @param children_ - List of children of this node..
  5351. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5352. */
  5353. constructor(children_, priorityNode_, indexMap_) {
  5354. this.children_ = children_;
  5355. this.priorityNode_ = priorityNode_;
  5356. this.indexMap_ = indexMap_;
  5357. this.lazyHash_ = null;
  5358. /**
  5359. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5360. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5361. * class instead of an empty ChildrenNode.
  5362. */
  5363. if (this.priorityNode_) {
  5364. validatePriorityNode(this.priorityNode_);
  5365. }
  5366. if (this.children_.isEmpty()) {
  5367. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5368. }
  5369. }
  5370. static get EMPTY_NODE() {
  5371. return (EMPTY_NODE ||
  5372. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5373. }
  5374. /** @inheritDoc */
  5375. isLeafNode() {
  5376. return false;
  5377. }
  5378. /** @inheritDoc */
  5379. getPriority() {
  5380. return this.priorityNode_ || EMPTY_NODE;
  5381. }
  5382. /** @inheritDoc */
  5383. updatePriority(newPriorityNode) {
  5384. if (this.children_.isEmpty()) {
  5385. // Don't allow priorities on empty nodes
  5386. return this;
  5387. }
  5388. else {
  5389. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5390. }
  5391. }
  5392. /** @inheritDoc */
  5393. getImmediateChild(childName) {
  5394. // Hack to treat priority as a regular child
  5395. if (childName === '.priority') {
  5396. return this.getPriority();
  5397. }
  5398. else {
  5399. const child = this.children_.get(childName);
  5400. return child === null ? EMPTY_NODE : child;
  5401. }
  5402. }
  5403. /** @inheritDoc */
  5404. getChild(path) {
  5405. const front = pathGetFront(path);
  5406. if (front === null) {
  5407. return this;
  5408. }
  5409. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5410. }
  5411. /** @inheritDoc */
  5412. hasChild(childName) {
  5413. return this.children_.get(childName) !== null;
  5414. }
  5415. /** @inheritDoc */
  5416. updateImmediateChild(childName, newChildNode) {
  5417. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  5418. if (childName === '.priority') {
  5419. return this.updatePriority(newChildNode);
  5420. }
  5421. else {
  5422. const namedNode = new NamedNode(childName, newChildNode);
  5423. let newChildren, newIndexMap;
  5424. if (newChildNode.isEmpty()) {
  5425. newChildren = this.children_.remove(childName);
  5426. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5427. }
  5428. else {
  5429. newChildren = this.children_.insert(childName, newChildNode);
  5430. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5431. }
  5432. const newPriority = newChildren.isEmpty()
  5433. ? EMPTY_NODE
  5434. : this.priorityNode_;
  5435. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5436. }
  5437. }
  5438. /** @inheritDoc */
  5439. updateChild(path, newChildNode) {
  5440. const front = pathGetFront(path);
  5441. if (front === null) {
  5442. return newChildNode;
  5443. }
  5444. else {
  5445. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5446. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5447. return this.updateImmediateChild(front, newImmediateChild);
  5448. }
  5449. }
  5450. /** @inheritDoc */
  5451. isEmpty() {
  5452. return this.children_.isEmpty();
  5453. }
  5454. /** @inheritDoc */
  5455. numChildren() {
  5456. return this.children_.count();
  5457. }
  5458. /** @inheritDoc */
  5459. val(exportFormat) {
  5460. if (this.isEmpty()) {
  5461. return null;
  5462. }
  5463. const obj = {};
  5464. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5465. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5466. obj[key] = childNode.val(exportFormat);
  5467. numKeys++;
  5468. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5469. maxKey = Math.max(maxKey, Number(key));
  5470. }
  5471. else {
  5472. allIntegerKeys = false;
  5473. }
  5474. });
  5475. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5476. // convert to array.
  5477. const array = [];
  5478. // eslint-disable-next-line guard-for-in
  5479. for (const key in obj) {
  5480. array[key] = obj[key];
  5481. }
  5482. return array;
  5483. }
  5484. else {
  5485. if (exportFormat && !this.getPriority().isEmpty()) {
  5486. obj['.priority'] = this.getPriority().val();
  5487. }
  5488. return obj;
  5489. }
  5490. }
  5491. /** @inheritDoc */
  5492. hash() {
  5493. if (this.lazyHash_ === null) {
  5494. let toHash = '';
  5495. if (!this.getPriority().isEmpty()) {
  5496. toHash +=
  5497. 'priority:' +
  5498. priorityHashText(this.getPriority().val()) +
  5499. ':';
  5500. }
  5501. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5502. const childHash = childNode.hash();
  5503. if (childHash !== '') {
  5504. toHash += ':' + key + ':' + childHash;
  5505. }
  5506. });
  5507. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5508. }
  5509. return this.lazyHash_;
  5510. }
  5511. /** @inheritDoc */
  5512. getPredecessorChildName(childName, childNode, index) {
  5513. const idx = this.resolveIndex_(index);
  5514. if (idx) {
  5515. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5516. return predecessor ? predecessor.name : null;
  5517. }
  5518. else {
  5519. return this.children_.getPredecessorKey(childName);
  5520. }
  5521. }
  5522. getFirstChildName(indexDefinition) {
  5523. const idx = this.resolveIndex_(indexDefinition);
  5524. if (idx) {
  5525. const minKey = idx.minKey();
  5526. return minKey && minKey.name;
  5527. }
  5528. else {
  5529. return this.children_.minKey();
  5530. }
  5531. }
  5532. getFirstChild(indexDefinition) {
  5533. const minKey = this.getFirstChildName(indexDefinition);
  5534. if (minKey) {
  5535. return new NamedNode(minKey, this.children_.get(minKey));
  5536. }
  5537. else {
  5538. return null;
  5539. }
  5540. }
  5541. /**
  5542. * Given an index, return the key name of the largest value we have, according to that index
  5543. */
  5544. getLastChildName(indexDefinition) {
  5545. const idx = this.resolveIndex_(indexDefinition);
  5546. if (idx) {
  5547. const maxKey = idx.maxKey();
  5548. return maxKey && maxKey.name;
  5549. }
  5550. else {
  5551. return this.children_.maxKey();
  5552. }
  5553. }
  5554. getLastChild(indexDefinition) {
  5555. const maxKey = this.getLastChildName(indexDefinition);
  5556. if (maxKey) {
  5557. return new NamedNode(maxKey, this.children_.get(maxKey));
  5558. }
  5559. else {
  5560. return null;
  5561. }
  5562. }
  5563. forEachChild(index, action) {
  5564. const idx = this.resolveIndex_(index);
  5565. if (idx) {
  5566. return idx.inorderTraversal(wrappedNode => {
  5567. return action(wrappedNode.name, wrappedNode.node);
  5568. });
  5569. }
  5570. else {
  5571. return this.children_.inorderTraversal(action);
  5572. }
  5573. }
  5574. getIterator(indexDefinition) {
  5575. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5576. }
  5577. getIteratorFrom(startPost, indexDefinition) {
  5578. const idx = this.resolveIndex_(indexDefinition);
  5579. if (idx) {
  5580. return idx.getIteratorFrom(startPost, key => key);
  5581. }
  5582. else {
  5583. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5584. let next = iterator.peek();
  5585. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5586. iterator.getNext();
  5587. next = iterator.peek();
  5588. }
  5589. return iterator;
  5590. }
  5591. }
  5592. getReverseIterator(indexDefinition) {
  5593. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5594. }
  5595. getReverseIteratorFrom(endPost, indexDefinition) {
  5596. const idx = this.resolveIndex_(indexDefinition);
  5597. if (idx) {
  5598. return idx.getReverseIteratorFrom(endPost, key => {
  5599. return key;
  5600. });
  5601. }
  5602. else {
  5603. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5604. let next = iterator.peek();
  5605. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5606. iterator.getNext();
  5607. next = iterator.peek();
  5608. }
  5609. return iterator;
  5610. }
  5611. }
  5612. compareTo(other) {
  5613. if (this.isEmpty()) {
  5614. if (other.isEmpty()) {
  5615. return 0;
  5616. }
  5617. else {
  5618. return -1;
  5619. }
  5620. }
  5621. else if (other.isLeafNode() || other.isEmpty()) {
  5622. return 1;
  5623. }
  5624. else if (other === MAX_NODE) {
  5625. return -1;
  5626. }
  5627. else {
  5628. // Must be another node with children.
  5629. return 0;
  5630. }
  5631. }
  5632. withIndex(indexDefinition) {
  5633. if (indexDefinition === KEY_INDEX ||
  5634. this.indexMap_.hasIndex(indexDefinition)) {
  5635. return this;
  5636. }
  5637. else {
  5638. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5639. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5640. }
  5641. }
  5642. isIndexed(index) {
  5643. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5644. }
  5645. equals(other) {
  5646. if (other === this) {
  5647. return true;
  5648. }
  5649. else if (other.isLeafNode()) {
  5650. return false;
  5651. }
  5652. else {
  5653. const otherChildrenNode = other;
  5654. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5655. return false;
  5656. }
  5657. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5658. const thisIter = this.getIterator(PRIORITY_INDEX);
  5659. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5660. let thisCurrent = thisIter.getNext();
  5661. let otherCurrent = otherIter.getNext();
  5662. while (thisCurrent && otherCurrent) {
  5663. if (thisCurrent.name !== otherCurrent.name ||
  5664. !thisCurrent.node.equals(otherCurrent.node)) {
  5665. return false;
  5666. }
  5667. thisCurrent = thisIter.getNext();
  5668. otherCurrent = otherIter.getNext();
  5669. }
  5670. return thisCurrent === null && otherCurrent === null;
  5671. }
  5672. else {
  5673. return false;
  5674. }
  5675. }
  5676. }
  5677. /**
  5678. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5679. * instead.
  5680. *
  5681. */
  5682. resolveIndex_(indexDefinition) {
  5683. if (indexDefinition === KEY_INDEX) {
  5684. return null;
  5685. }
  5686. else {
  5687. return this.indexMap_.get(indexDefinition.toString());
  5688. }
  5689. }
  5690. }
  5691. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5692. class MaxNode extends ChildrenNode {
  5693. constructor() {
  5694. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5695. }
  5696. compareTo(other) {
  5697. if (other === this) {
  5698. return 0;
  5699. }
  5700. else {
  5701. return 1;
  5702. }
  5703. }
  5704. equals(other) {
  5705. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5706. return other === this;
  5707. }
  5708. getPriority() {
  5709. return this;
  5710. }
  5711. getImmediateChild(childName) {
  5712. return ChildrenNode.EMPTY_NODE;
  5713. }
  5714. isEmpty() {
  5715. return false;
  5716. }
  5717. }
  5718. /**
  5719. * Marker that will sort higher than any other snapshot.
  5720. */
  5721. const MAX_NODE = new MaxNode();
  5722. Object.defineProperties(NamedNode, {
  5723. MIN: {
  5724. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5725. },
  5726. MAX: {
  5727. value: new NamedNode(MAX_NAME, MAX_NODE)
  5728. }
  5729. });
  5730. /**
  5731. * Reference Extensions
  5732. */
  5733. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5734. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5735. setMaxNode$1(MAX_NODE);
  5736. setMaxNode(MAX_NODE);
  5737. /**
  5738. * @license
  5739. * Copyright 2017 Google LLC
  5740. *
  5741. * Licensed under the Apache License, Version 2.0 (the "License");
  5742. * you may not use this file except in compliance with the License.
  5743. * You may obtain a copy of the License at
  5744. *
  5745. * http://www.apache.org/licenses/LICENSE-2.0
  5746. *
  5747. * Unless required by applicable law or agreed to in writing, software
  5748. * distributed under the License is distributed on an "AS IS" BASIS,
  5749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5750. * See the License for the specific language governing permissions and
  5751. * limitations under the License.
  5752. */
  5753. const USE_HINZE = true;
  5754. /**
  5755. * Constructs a snapshot node representing the passed JSON and returns it.
  5756. * @param json - JSON to create a node for.
  5757. * @param priority - Optional priority to use. This will be ignored if the
  5758. * passed JSON contains a .priority property.
  5759. */
  5760. function nodeFromJSON(json, priority = null) {
  5761. if (json === null) {
  5762. return ChildrenNode.EMPTY_NODE;
  5763. }
  5764. if (typeof json === 'object' && '.priority' in json) {
  5765. priority = json['.priority'];
  5766. }
  5767. util.assert(priority === null ||
  5768. typeof priority === 'string' ||
  5769. typeof priority === 'number' ||
  5770. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5771. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5772. json = json['.value'];
  5773. }
  5774. // Valid leaf nodes include non-objects or server-value wrapper objects
  5775. if (typeof json !== 'object' || '.sv' in json) {
  5776. const jsonLeaf = json;
  5777. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5778. }
  5779. if (!(json instanceof Array) && USE_HINZE) {
  5780. const children = [];
  5781. let childrenHavePriority = false;
  5782. const hinzeJsonObj = json;
  5783. each(hinzeJsonObj, (key, child) => {
  5784. if (key.substring(0, 1) !== '.') {
  5785. // Ignore metadata nodes
  5786. const childNode = nodeFromJSON(child);
  5787. if (!childNode.isEmpty()) {
  5788. childrenHavePriority =
  5789. childrenHavePriority || !childNode.getPriority().isEmpty();
  5790. children.push(new NamedNode(key, childNode));
  5791. }
  5792. }
  5793. });
  5794. if (children.length === 0) {
  5795. return ChildrenNode.EMPTY_NODE;
  5796. }
  5797. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5798. if (childrenHavePriority) {
  5799. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5800. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5801. }
  5802. else {
  5803. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5804. }
  5805. }
  5806. else {
  5807. let node = ChildrenNode.EMPTY_NODE;
  5808. each(json, (key, childData) => {
  5809. if (util.contains(json, key)) {
  5810. if (key.substring(0, 1) !== '.') {
  5811. // ignore metadata nodes.
  5812. const childNode = nodeFromJSON(childData);
  5813. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5814. node = node.updateImmediateChild(key, childNode);
  5815. }
  5816. }
  5817. }
  5818. });
  5819. return node.updatePriority(nodeFromJSON(priority));
  5820. }
  5821. }
  5822. setNodeFromJSON(nodeFromJSON);
  5823. /**
  5824. * @license
  5825. * Copyright 2017 Google LLC
  5826. *
  5827. * Licensed under the Apache License, Version 2.0 (the "License");
  5828. * you may not use this file except in compliance with the License.
  5829. * You may obtain a copy of the License at
  5830. *
  5831. * http://www.apache.org/licenses/LICENSE-2.0
  5832. *
  5833. * Unless required by applicable law or agreed to in writing, software
  5834. * distributed under the License is distributed on an "AS IS" BASIS,
  5835. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5836. * See the License for the specific language governing permissions and
  5837. * limitations under the License.
  5838. */
  5839. class PathIndex extends Index {
  5840. constructor(indexPath_) {
  5841. super();
  5842. this.indexPath_ = indexPath_;
  5843. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5844. }
  5845. extractChild(snap) {
  5846. return snap.getChild(this.indexPath_);
  5847. }
  5848. isDefinedOn(node) {
  5849. return !node.getChild(this.indexPath_).isEmpty();
  5850. }
  5851. compare(a, b) {
  5852. const aChild = this.extractChild(a.node);
  5853. const bChild = this.extractChild(b.node);
  5854. const indexCmp = aChild.compareTo(bChild);
  5855. if (indexCmp === 0) {
  5856. return nameCompare(a.name, b.name);
  5857. }
  5858. else {
  5859. return indexCmp;
  5860. }
  5861. }
  5862. makePost(indexValue, name) {
  5863. const valueNode = nodeFromJSON(indexValue);
  5864. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5865. return new NamedNode(name, node);
  5866. }
  5867. maxPost() {
  5868. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5869. return new NamedNode(MAX_NAME, node);
  5870. }
  5871. toString() {
  5872. return pathSlice(this.indexPath_, 0).join('/');
  5873. }
  5874. }
  5875. /**
  5876. * @license
  5877. * Copyright 2017 Google LLC
  5878. *
  5879. * Licensed under the Apache License, Version 2.0 (the "License");
  5880. * you may not use this file except in compliance with the License.
  5881. * You may obtain a copy of the License at
  5882. *
  5883. * http://www.apache.org/licenses/LICENSE-2.0
  5884. *
  5885. * Unless required by applicable law or agreed to in writing, software
  5886. * distributed under the License is distributed on an "AS IS" BASIS,
  5887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5888. * See the License for the specific language governing permissions and
  5889. * limitations under the License.
  5890. */
  5891. class ValueIndex extends Index {
  5892. compare(a, b) {
  5893. const indexCmp = a.node.compareTo(b.node);
  5894. if (indexCmp === 0) {
  5895. return nameCompare(a.name, b.name);
  5896. }
  5897. else {
  5898. return indexCmp;
  5899. }
  5900. }
  5901. isDefinedOn(node) {
  5902. return true;
  5903. }
  5904. indexedValueChanged(oldNode, newNode) {
  5905. return !oldNode.equals(newNode);
  5906. }
  5907. minPost() {
  5908. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5909. return NamedNode.MIN;
  5910. }
  5911. maxPost() {
  5912. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5913. return NamedNode.MAX;
  5914. }
  5915. makePost(indexValue, name) {
  5916. const valueNode = nodeFromJSON(indexValue);
  5917. return new NamedNode(name, valueNode);
  5918. }
  5919. /**
  5920. * @returns String representation for inclusion in a query spec
  5921. */
  5922. toString() {
  5923. return '.value';
  5924. }
  5925. }
  5926. const VALUE_INDEX = new ValueIndex();
  5927. /**
  5928. * @license
  5929. * Copyright 2017 Google LLC
  5930. *
  5931. * Licensed under the Apache License, Version 2.0 (the "License");
  5932. * you may not use this file except in compliance with the License.
  5933. * You may obtain a copy of the License at
  5934. *
  5935. * http://www.apache.org/licenses/LICENSE-2.0
  5936. *
  5937. * Unless required by applicable law or agreed to in writing, software
  5938. * distributed under the License is distributed on an "AS IS" BASIS,
  5939. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5940. * See the License for the specific language governing permissions and
  5941. * limitations under the License.
  5942. */
  5943. function changeValue(snapshotNode) {
  5944. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5945. }
  5946. function changeChildAdded(childName, snapshotNode) {
  5947. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5948. }
  5949. function changeChildRemoved(childName, snapshotNode) {
  5950. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5951. }
  5952. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5953. return {
  5954. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5955. snapshotNode,
  5956. childName,
  5957. oldSnap
  5958. };
  5959. }
  5960. function changeChildMoved(childName, snapshotNode) {
  5961. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5962. }
  5963. /**
  5964. * @license
  5965. * Copyright 2017 Google LLC
  5966. *
  5967. * Licensed under the Apache License, Version 2.0 (the "License");
  5968. * you may not use this file except in compliance with the License.
  5969. * You may obtain a copy of the License at
  5970. *
  5971. * http://www.apache.org/licenses/LICENSE-2.0
  5972. *
  5973. * Unless required by applicable law or agreed to in writing, software
  5974. * distributed under the License is distributed on an "AS IS" BASIS,
  5975. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5976. * See the License for the specific language governing permissions and
  5977. * limitations under the License.
  5978. */
  5979. /**
  5980. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5981. */
  5982. class IndexedFilter {
  5983. constructor(index_) {
  5984. this.index_ = index_;
  5985. }
  5986. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5987. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5988. const oldChild = snap.getImmediateChild(key);
  5989. // Check if anything actually changed.
  5990. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5991. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5992. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5993. // to avoid treating these cases as "nothing changed."
  5994. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5995. // Nothing changed.
  5996. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  5997. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  5998. return snap;
  5999. }
  6000. }
  6001. if (optChangeAccumulator != null) {
  6002. if (newChild.isEmpty()) {
  6003. if (snap.hasChild(key)) {
  6004. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6005. }
  6006. else {
  6007. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6008. }
  6009. }
  6010. else if (oldChild.isEmpty()) {
  6011. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6012. }
  6013. else {
  6014. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6015. }
  6016. }
  6017. if (snap.isLeafNode() && newChild.isEmpty()) {
  6018. return snap;
  6019. }
  6020. else {
  6021. // Make sure the node is indexed
  6022. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6023. }
  6024. }
  6025. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6026. if (optChangeAccumulator != null) {
  6027. if (!oldSnap.isLeafNode()) {
  6028. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6029. if (!newSnap.hasChild(key)) {
  6030. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6031. }
  6032. });
  6033. }
  6034. if (!newSnap.isLeafNode()) {
  6035. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6036. if (oldSnap.hasChild(key)) {
  6037. const oldChild = oldSnap.getImmediateChild(key);
  6038. if (!oldChild.equals(childNode)) {
  6039. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6040. }
  6041. }
  6042. else {
  6043. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6044. }
  6045. });
  6046. }
  6047. }
  6048. return newSnap.withIndex(this.index_);
  6049. }
  6050. updatePriority(oldSnap, newPriority) {
  6051. if (oldSnap.isEmpty()) {
  6052. return ChildrenNode.EMPTY_NODE;
  6053. }
  6054. else {
  6055. return oldSnap.updatePriority(newPriority);
  6056. }
  6057. }
  6058. filtersNodes() {
  6059. return false;
  6060. }
  6061. getIndexedFilter() {
  6062. return this;
  6063. }
  6064. getIndex() {
  6065. return this.index_;
  6066. }
  6067. }
  6068. /**
  6069. * @license
  6070. * Copyright 2017 Google LLC
  6071. *
  6072. * Licensed under the Apache License, Version 2.0 (the "License");
  6073. * you may not use this file except in compliance with the License.
  6074. * You may obtain a copy of the License at
  6075. *
  6076. * http://www.apache.org/licenses/LICENSE-2.0
  6077. *
  6078. * Unless required by applicable law or agreed to in writing, software
  6079. * distributed under the License is distributed on an "AS IS" BASIS,
  6080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6081. * See the License for the specific language governing permissions and
  6082. * limitations under the License.
  6083. */
  6084. /**
  6085. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6086. */
  6087. class RangedFilter {
  6088. constructor(params) {
  6089. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6090. this.index_ = params.getIndex();
  6091. this.startPost_ = RangedFilter.getStartPost_(params);
  6092. this.endPost_ = RangedFilter.getEndPost_(params);
  6093. this.startIsInclusive_ = !params.startAfterSet_;
  6094. this.endIsInclusive_ = !params.endBeforeSet_;
  6095. }
  6096. getStartPost() {
  6097. return this.startPost_;
  6098. }
  6099. getEndPost() {
  6100. return this.endPost_;
  6101. }
  6102. matches(node) {
  6103. const isWithinStart = this.startIsInclusive_
  6104. ? this.index_.compare(this.getStartPost(), node) <= 0
  6105. : this.index_.compare(this.getStartPost(), node) < 0;
  6106. const isWithinEnd = this.endIsInclusive_
  6107. ? this.index_.compare(node, this.getEndPost()) <= 0
  6108. : this.index_.compare(node, this.getEndPost()) < 0;
  6109. return isWithinStart && isWithinEnd;
  6110. }
  6111. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6112. if (!this.matches(new NamedNode(key, newChild))) {
  6113. newChild = ChildrenNode.EMPTY_NODE;
  6114. }
  6115. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6116. }
  6117. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6118. if (newSnap.isLeafNode()) {
  6119. // Make sure we have a children node with the correct index, not a leaf node;
  6120. newSnap = ChildrenNode.EMPTY_NODE;
  6121. }
  6122. let filtered = newSnap.withIndex(this.index_);
  6123. // Don't support priorities on queries
  6124. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6125. const self = this;
  6126. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6127. if (!self.matches(new NamedNode(key, childNode))) {
  6128. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6129. }
  6130. });
  6131. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6132. }
  6133. updatePriority(oldSnap, newPriority) {
  6134. // Don't support priorities on queries
  6135. return oldSnap;
  6136. }
  6137. filtersNodes() {
  6138. return true;
  6139. }
  6140. getIndexedFilter() {
  6141. return this.indexedFilter_;
  6142. }
  6143. getIndex() {
  6144. return this.index_;
  6145. }
  6146. static getStartPost_(params) {
  6147. if (params.hasStart()) {
  6148. const startName = params.getIndexStartName();
  6149. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6150. }
  6151. else {
  6152. return params.getIndex().minPost();
  6153. }
  6154. }
  6155. static getEndPost_(params) {
  6156. if (params.hasEnd()) {
  6157. const endName = params.getIndexEndName();
  6158. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6159. }
  6160. else {
  6161. return params.getIndex().maxPost();
  6162. }
  6163. }
  6164. }
  6165. /**
  6166. * @license
  6167. * Copyright 2017 Google LLC
  6168. *
  6169. * Licensed under the Apache License, Version 2.0 (the "License");
  6170. * you may not use this file except in compliance with the License.
  6171. * You may obtain a copy of the License at
  6172. *
  6173. * http://www.apache.org/licenses/LICENSE-2.0
  6174. *
  6175. * Unless required by applicable law or agreed to in writing, software
  6176. * distributed under the License is distributed on an "AS IS" BASIS,
  6177. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6178. * See the License for the specific language governing permissions and
  6179. * limitations under the License.
  6180. */
  6181. /**
  6182. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6183. */
  6184. class LimitedFilter {
  6185. constructor(params) {
  6186. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6187. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6188. this.withinStartPost = (node) => {
  6189. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6190. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6191. };
  6192. this.withinEndPost = (node) => {
  6193. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6194. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6195. };
  6196. this.rangedFilter_ = new RangedFilter(params);
  6197. this.index_ = params.getIndex();
  6198. this.limit_ = params.getLimit();
  6199. this.reverse_ = !params.isViewFromLeft();
  6200. this.startIsInclusive_ = !params.startAfterSet_;
  6201. this.endIsInclusive_ = !params.endBeforeSet_;
  6202. }
  6203. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6204. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6205. newChild = ChildrenNode.EMPTY_NODE;
  6206. }
  6207. if (snap.getImmediateChild(key).equals(newChild)) {
  6208. // No change
  6209. return snap;
  6210. }
  6211. else if (snap.numChildren() < this.limit_) {
  6212. return this.rangedFilter_
  6213. .getIndexedFilter()
  6214. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6215. }
  6216. else {
  6217. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6218. }
  6219. }
  6220. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6221. let filtered;
  6222. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6223. // Make sure we have a children node with the correct index, not a leaf node;
  6224. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6225. }
  6226. else {
  6227. if (this.limit_ * 2 < newSnap.numChildren() &&
  6228. newSnap.isIndexed(this.index_)) {
  6229. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6230. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6231. // anchor to the startPost, endPost, or last element as appropriate
  6232. let iterator;
  6233. if (this.reverse_) {
  6234. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6235. }
  6236. else {
  6237. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6238. }
  6239. let count = 0;
  6240. while (iterator.hasNext() && count < this.limit_) {
  6241. const next = iterator.getNext();
  6242. if (!this.withinDirectionalStart(next)) {
  6243. // if we have not reached the start, skip to the next element
  6244. continue;
  6245. }
  6246. else if (!this.withinDirectionalEnd(next)) {
  6247. // if we have reached the end, stop adding elements
  6248. break;
  6249. }
  6250. else {
  6251. filtered = filtered.updateImmediateChild(next.name, next.node);
  6252. count++;
  6253. }
  6254. }
  6255. }
  6256. else {
  6257. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6258. filtered = newSnap.withIndex(this.index_);
  6259. // Don't support priorities on queries
  6260. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6261. let iterator;
  6262. if (this.reverse_) {
  6263. iterator = filtered.getReverseIterator(this.index_);
  6264. }
  6265. else {
  6266. iterator = filtered.getIterator(this.index_);
  6267. }
  6268. let count = 0;
  6269. while (iterator.hasNext()) {
  6270. const next = iterator.getNext();
  6271. const inRange = count < this.limit_ &&
  6272. this.withinDirectionalStart(next) &&
  6273. this.withinDirectionalEnd(next);
  6274. if (inRange) {
  6275. count++;
  6276. }
  6277. else {
  6278. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6279. }
  6280. }
  6281. }
  6282. }
  6283. return this.rangedFilter_
  6284. .getIndexedFilter()
  6285. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6286. }
  6287. updatePriority(oldSnap, newPriority) {
  6288. // Don't support priorities on queries
  6289. return oldSnap;
  6290. }
  6291. filtersNodes() {
  6292. return true;
  6293. }
  6294. getIndexedFilter() {
  6295. return this.rangedFilter_.getIndexedFilter();
  6296. }
  6297. getIndex() {
  6298. return this.index_;
  6299. }
  6300. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6301. // TODO: rename all cache stuff etc to general snap terminology
  6302. let cmp;
  6303. if (this.reverse_) {
  6304. const indexCmp = this.index_.getCompare();
  6305. cmp = (a, b) => indexCmp(b, a);
  6306. }
  6307. else {
  6308. cmp = this.index_.getCompare();
  6309. }
  6310. const oldEventCache = snap;
  6311. util.assert(oldEventCache.numChildren() === this.limit_, '');
  6312. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6313. const windowBoundary = this.reverse_
  6314. ? oldEventCache.getFirstChild(this.index_)
  6315. : oldEventCache.getLastChild(this.index_);
  6316. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6317. if (oldEventCache.hasChild(childKey)) {
  6318. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6319. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6320. while (nextChild != null &&
  6321. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6322. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6323. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6324. // the limited filter...
  6325. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6326. }
  6327. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6328. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6329. if (remainsInWindow) {
  6330. if (changeAccumulator != null) {
  6331. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6332. }
  6333. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6334. }
  6335. else {
  6336. if (changeAccumulator != null) {
  6337. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6338. }
  6339. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6340. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6341. if (nextChildInRange) {
  6342. if (changeAccumulator != null) {
  6343. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6344. }
  6345. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6346. }
  6347. else {
  6348. return newEventCache;
  6349. }
  6350. }
  6351. }
  6352. else if (childSnap.isEmpty()) {
  6353. // we're deleting a node, but it was not in the window, so ignore it
  6354. return snap;
  6355. }
  6356. else if (inRange) {
  6357. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6358. if (changeAccumulator != null) {
  6359. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6360. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6361. }
  6362. return oldEventCache
  6363. .updateImmediateChild(childKey, childSnap)
  6364. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6365. }
  6366. else {
  6367. return snap;
  6368. }
  6369. }
  6370. else {
  6371. return snap;
  6372. }
  6373. }
  6374. }
  6375. /**
  6376. * @license
  6377. * Copyright 2017 Google LLC
  6378. *
  6379. * Licensed under the Apache License, Version 2.0 (the "License");
  6380. * you may not use this file except in compliance with the License.
  6381. * You may obtain a copy of the License at
  6382. *
  6383. * http://www.apache.org/licenses/LICENSE-2.0
  6384. *
  6385. * Unless required by applicable law or agreed to in writing, software
  6386. * distributed under the License is distributed on an "AS IS" BASIS,
  6387. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6388. * See the License for the specific language governing permissions and
  6389. * limitations under the License.
  6390. */
  6391. /**
  6392. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6393. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6394. * user-facing API level, so it is not done here.
  6395. *
  6396. * @internal
  6397. */
  6398. class QueryParams {
  6399. constructor() {
  6400. this.limitSet_ = false;
  6401. this.startSet_ = false;
  6402. this.startNameSet_ = false;
  6403. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6404. this.endSet_ = false;
  6405. this.endNameSet_ = false;
  6406. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6407. this.limit_ = 0;
  6408. this.viewFrom_ = '';
  6409. this.indexStartValue_ = null;
  6410. this.indexStartName_ = '';
  6411. this.indexEndValue_ = null;
  6412. this.indexEndName_ = '';
  6413. this.index_ = PRIORITY_INDEX;
  6414. }
  6415. hasStart() {
  6416. return this.startSet_;
  6417. }
  6418. /**
  6419. * @returns True if it would return from left.
  6420. */
  6421. isViewFromLeft() {
  6422. if (this.viewFrom_ === '') {
  6423. // limit(), rather than limitToFirst or limitToLast was called.
  6424. // This means that only one of startSet_ and endSet_ is true. Use them
  6425. // to calculate which side of the view to anchor to. If neither is set,
  6426. // anchor to the end.
  6427. return this.startSet_;
  6428. }
  6429. else {
  6430. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6431. }
  6432. }
  6433. /**
  6434. * Only valid to call if hasStart() returns true
  6435. */
  6436. getIndexStartValue() {
  6437. util.assert(this.startSet_, 'Only valid if start has been set');
  6438. return this.indexStartValue_;
  6439. }
  6440. /**
  6441. * Only valid to call if hasStart() returns true.
  6442. * Returns the starting key name for the range defined by these query parameters
  6443. */
  6444. getIndexStartName() {
  6445. util.assert(this.startSet_, 'Only valid if start has been set');
  6446. if (this.startNameSet_) {
  6447. return this.indexStartName_;
  6448. }
  6449. else {
  6450. return MIN_NAME;
  6451. }
  6452. }
  6453. hasEnd() {
  6454. return this.endSet_;
  6455. }
  6456. /**
  6457. * Only valid to call if hasEnd() returns true.
  6458. */
  6459. getIndexEndValue() {
  6460. util.assert(this.endSet_, 'Only valid if end has been set');
  6461. return this.indexEndValue_;
  6462. }
  6463. /**
  6464. * Only valid to call if hasEnd() returns true.
  6465. * Returns the end key name for the range defined by these query parameters
  6466. */
  6467. getIndexEndName() {
  6468. util.assert(this.endSet_, 'Only valid if end has been set');
  6469. if (this.endNameSet_) {
  6470. return this.indexEndName_;
  6471. }
  6472. else {
  6473. return MAX_NAME;
  6474. }
  6475. }
  6476. hasLimit() {
  6477. return this.limitSet_;
  6478. }
  6479. /**
  6480. * @returns True if a limit has been set and it has been explicitly anchored
  6481. */
  6482. hasAnchoredLimit() {
  6483. return this.limitSet_ && this.viewFrom_ !== '';
  6484. }
  6485. /**
  6486. * Only valid to call if hasLimit() returns true
  6487. */
  6488. getLimit() {
  6489. util.assert(this.limitSet_, 'Only valid if limit has been set');
  6490. return this.limit_;
  6491. }
  6492. getIndex() {
  6493. return this.index_;
  6494. }
  6495. loadsAllData() {
  6496. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6497. }
  6498. isDefault() {
  6499. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6500. }
  6501. copy() {
  6502. const copy = new QueryParams();
  6503. copy.limitSet_ = this.limitSet_;
  6504. copy.limit_ = this.limit_;
  6505. copy.startSet_ = this.startSet_;
  6506. copy.startAfterSet_ = this.startAfterSet_;
  6507. copy.indexStartValue_ = this.indexStartValue_;
  6508. copy.startNameSet_ = this.startNameSet_;
  6509. copy.indexStartName_ = this.indexStartName_;
  6510. copy.endSet_ = this.endSet_;
  6511. copy.endBeforeSet_ = this.endBeforeSet_;
  6512. copy.indexEndValue_ = this.indexEndValue_;
  6513. copy.endNameSet_ = this.endNameSet_;
  6514. copy.indexEndName_ = this.indexEndName_;
  6515. copy.index_ = this.index_;
  6516. copy.viewFrom_ = this.viewFrom_;
  6517. return copy;
  6518. }
  6519. }
  6520. function queryParamsGetNodeFilter(queryParams) {
  6521. if (queryParams.loadsAllData()) {
  6522. return new IndexedFilter(queryParams.getIndex());
  6523. }
  6524. else if (queryParams.hasLimit()) {
  6525. return new LimitedFilter(queryParams);
  6526. }
  6527. else {
  6528. return new RangedFilter(queryParams);
  6529. }
  6530. }
  6531. function queryParamsLimitToFirst(queryParams, newLimit) {
  6532. const newParams = queryParams.copy();
  6533. newParams.limitSet_ = true;
  6534. newParams.limit_ = newLimit;
  6535. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6536. return newParams;
  6537. }
  6538. function queryParamsLimitToLast(queryParams, newLimit) {
  6539. const newParams = queryParams.copy();
  6540. newParams.limitSet_ = true;
  6541. newParams.limit_ = newLimit;
  6542. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6543. return newParams;
  6544. }
  6545. function queryParamsStartAt(queryParams, indexValue, key) {
  6546. const newParams = queryParams.copy();
  6547. newParams.startSet_ = true;
  6548. if (indexValue === undefined) {
  6549. indexValue = null;
  6550. }
  6551. newParams.indexStartValue_ = indexValue;
  6552. if (key != null) {
  6553. newParams.startNameSet_ = true;
  6554. newParams.indexStartName_ = key;
  6555. }
  6556. else {
  6557. newParams.startNameSet_ = false;
  6558. newParams.indexStartName_ = '';
  6559. }
  6560. return newParams;
  6561. }
  6562. function queryParamsStartAfter(queryParams, indexValue, key) {
  6563. let params;
  6564. if (queryParams.index_ === KEY_INDEX || !!key) {
  6565. params = queryParamsStartAt(queryParams, indexValue, key);
  6566. }
  6567. else {
  6568. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6569. }
  6570. params.startAfterSet_ = true;
  6571. return params;
  6572. }
  6573. function queryParamsEndAt(queryParams, indexValue, key) {
  6574. const newParams = queryParams.copy();
  6575. newParams.endSet_ = true;
  6576. if (indexValue === undefined) {
  6577. indexValue = null;
  6578. }
  6579. newParams.indexEndValue_ = indexValue;
  6580. if (key !== undefined) {
  6581. newParams.endNameSet_ = true;
  6582. newParams.indexEndName_ = key;
  6583. }
  6584. else {
  6585. newParams.endNameSet_ = false;
  6586. newParams.indexEndName_ = '';
  6587. }
  6588. return newParams;
  6589. }
  6590. function queryParamsEndBefore(queryParams, indexValue, key) {
  6591. let params;
  6592. if (queryParams.index_ === KEY_INDEX || !!key) {
  6593. params = queryParamsEndAt(queryParams, indexValue, key);
  6594. }
  6595. else {
  6596. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6597. }
  6598. params.endBeforeSet_ = true;
  6599. return params;
  6600. }
  6601. function queryParamsOrderBy(queryParams, index) {
  6602. const newParams = queryParams.copy();
  6603. newParams.index_ = index;
  6604. return newParams;
  6605. }
  6606. /**
  6607. * Returns a set of REST query string parameters representing this query.
  6608. *
  6609. * @returns query string parameters
  6610. */
  6611. function queryParamsToRestQueryStringParameters(queryParams) {
  6612. const qs = {};
  6613. if (queryParams.isDefault()) {
  6614. return qs;
  6615. }
  6616. let orderBy;
  6617. if (queryParams.index_ === PRIORITY_INDEX) {
  6618. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6619. }
  6620. else if (queryParams.index_ === VALUE_INDEX) {
  6621. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6622. }
  6623. else if (queryParams.index_ === KEY_INDEX) {
  6624. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6625. }
  6626. else {
  6627. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6628. orderBy = queryParams.index_.toString();
  6629. }
  6630. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  6631. if (queryParams.startSet_) {
  6632. const startParam = queryParams.startAfterSet_
  6633. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6634. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6635. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  6636. if (queryParams.startNameSet_) {
  6637. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  6638. }
  6639. }
  6640. if (queryParams.endSet_) {
  6641. const endParam = queryParams.endBeforeSet_
  6642. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6643. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6644. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  6645. if (queryParams.endNameSet_) {
  6646. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  6647. }
  6648. }
  6649. if (queryParams.limitSet_) {
  6650. if (queryParams.isViewFromLeft()) {
  6651. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6652. }
  6653. else {
  6654. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6655. }
  6656. }
  6657. return qs;
  6658. }
  6659. function queryParamsGetQueryObject(queryParams) {
  6660. const obj = {};
  6661. if (queryParams.startSet_) {
  6662. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6663. queryParams.indexStartValue_;
  6664. if (queryParams.startNameSet_) {
  6665. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6666. queryParams.indexStartName_;
  6667. }
  6668. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6669. !queryParams.startAfterSet_;
  6670. }
  6671. if (queryParams.endSet_) {
  6672. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6673. if (queryParams.endNameSet_) {
  6674. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6675. }
  6676. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6677. !queryParams.endBeforeSet_;
  6678. }
  6679. if (queryParams.limitSet_) {
  6680. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6681. let viewFrom = queryParams.viewFrom_;
  6682. if (viewFrom === '') {
  6683. if (queryParams.isViewFromLeft()) {
  6684. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6685. }
  6686. else {
  6687. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6688. }
  6689. }
  6690. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6691. }
  6692. // For now, priority index is the default, so we only specify if it's some other index
  6693. if (queryParams.index_ !== PRIORITY_INDEX) {
  6694. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6695. }
  6696. return obj;
  6697. }
  6698. /**
  6699. * @license
  6700. * Copyright 2017 Google LLC
  6701. *
  6702. * Licensed under the Apache License, Version 2.0 (the "License");
  6703. * you may not use this file except in compliance with the License.
  6704. * You may obtain a copy of the License at
  6705. *
  6706. * http://www.apache.org/licenses/LICENSE-2.0
  6707. *
  6708. * Unless required by applicable law or agreed to in writing, software
  6709. * distributed under the License is distributed on an "AS IS" BASIS,
  6710. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6711. * See the License for the specific language governing permissions and
  6712. * limitations under the License.
  6713. */
  6714. /**
  6715. * An implementation of ServerActions that communicates with the server via REST requests.
  6716. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6717. * persistent connection (using WebSockets or long-polling)
  6718. */
  6719. class ReadonlyRestClient extends ServerActions {
  6720. /**
  6721. * @param repoInfo_ - Data about the namespace we are connecting to
  6722. * @param onDataUpdate_ - A callback for new data from the server
  6723. */
  6724. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6725. super();
  6726. this.repoInfo_ = repoInfo_;
  6727. this.onDataUpdate_ = onDataUpdate_;
  6728. this.authTokenProvider_ = authTokenProvider_;
  6729. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6730. /** @private {function(...[*])} */
  6731. this.log_ = logWrapper('p:rest:');
  6732. /**
  6733. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6734. * that's been removed. :-/
  6735. */
  6736. this.listens_ = {};
  6737. }
  6738. reportStats(stats) {
  6739. throw new Error('Method not implemented.');
  6740. }
  6741. static getListenId_(query, tag) {
  6742. if (tag !== undefined) {
  6743. return 'tag$' + tag;
  6744. }
  6745. else {
  6746. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6747. return query._path.toString();
  6748. }
  6749. }
  6750. /** @inheritDoc */
  6751. listen(query, currentHashFn, tag, onComplete) {
  6752. const pathString = query._path.toString();
  6753. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6754. // Mark this listener so we can tell if it's removed.
  6755. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6756. const thisListen = {};
  6757. this.listens_[listenId] = thisListen;
  6758. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6759. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6760. let data = result;
  6761. if (error === 404) {
  6762. data = null;
  6763. error = null;
  6764. }
  6765. if (error === null) {
  6766. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6767. }
  6768. if (util.safeGet(this.listens_, listenId) === thisListen) {
  6769. let status;
  6770. if (!error) {
  6771. status = 'ok';
  6772. }
  6773. else if (error === 401) {
  6774. status = 'permission_denied';
  6775. }
  6776. else {
  6777. status = 'rest_error:' + error;
  6778. }
  6779. onComplete(status, null);
  6780. }
  6781. });
  6782. }
  6783. /** @inheritDoc */
  6784. unlisten(query, tag) {
  6785. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6786. delete this.listens_[listenId];
  6787. }
  6788. get(query) {
  6789. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6790. const pathString = query._path.toString();
  6791. const deferred = new util.Deferred();
  6792. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6793. let data = result;
  6794. if (error === 404) {
  6795. data = null;
  6796. error = null;
  6797. }
  6798. if (error === null) {
  6799. this.onDataUpdate_(pathString, data,
  6800. /*isMerge=*/ false,
  6801. /*tag=*/ null);
  6802. deferred.resolve(data);
  6803. }
  6804. else {
  6805. deferred.reject(new Error(data));
  6806. }
  6807. });
  6808. return deferred.promise;
  6809. }
  6810. /** @inheritDoc */
  6811. refreshAuthToken(token) {
  6812. // no-op since we just always call getToken.
  6813. }
  6814. /**
  6815. * Performs a REST request to the given path, with the provided query string parameters,
  6816. * and any auth credentials we have.
  6817. */
  6818. restRequest_(pathString, queryStringParameters = {}, callback) {
  6819. queryStringParameters['format'] = 'export';
  6820. return Promise.all([
  6821. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6822. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6823. ]).then(([authToken, appCheckToken]) => {
  6824. if (authToken && authToken.accessToken) {
  6825. queryStringParameters['auth'] = authToken.accessToken;
  6826. }
  6827. if (appCheckToken && appCheckToken.token) {
  6828. queryStringParameters['ac'] = appCheckToken.token;
  6829. }
  6830. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6831. this.repoInfo_.host +
  6832. pathString +
  6833. '?' +
  6834. 'ns=' +
  6835. this.repoInfo_.namespace +
  6836. util.querystring(queryStringParameters);
  6837. this.log_('Sending REST request for ' + url);
  6838. const xhr = new XMLHttpRequest();
  6839. xhr.onreadystatechange = () => {
  6840. if (callback && xhr.readyState === 4) {
  6841. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6842. let res = null;
  6843. if (xhr.status >= 200 && xhr.status < 300) {
  6844. try {
  6845. res = util.jsonEval(xhr.responseText);
  6846. }
  6847. catch (e) {
  6848. warn('Failed to parse JSON response for ' +
  6849. url +
  6850. ': ' +
  6851. xhr.responseText);
  6852. }
  6853. callback(null, res);
  6854. }
  6855. else {
  6856. // 401 and 404 are expected.
  6857. if (xhr.status !== 401 && xhr.status !== 404) {
  6858. warn('Got unsuccessful REST response for ' +
  6859. url +
  6860. ' Status: ' +
  6861. xhr.status);
  6862. }
  6863. callback(xhr.status);
  6864. }
  6865. callback = null;
  6866. }
  6867. };
  6868. xhr.open('GET', url, /*asynchronous=*/ true);
  6869. xhr.send();
  6870. });
  6871. }
  6872. }
  6873. /**
  6874. * @license
  6875. * Copyright 2017 Google LLC
  6876. *
  6877. * Licensed under the Apache License, Version 2.0 (the "License");
  6878. * you may not use this file except in compliance with the License.
  6879. * You may obtain a copy of the License at
  6880. *
  6881. * http://www.apache.org/licenses/LICENSE-2.0
  6882. *
  6883. * Unless required by applicable law or agreed to in writing, software
  6884. * distributed under the License is distributed on an "AS IS" BASIS,
  6885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6886. * See the License for the specific language governing permissions and
  6887. * limitations under the License.
  6888. */
  6889. /**
  6890. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6891. */
  6892. class SnapshotHolder {
  6893. constructor() {
  6894. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6895. }
  6896. getNode(path) {
  6897. return this.rootNode_.getChild(path);
  6898. }
  6899. updateSnapshot(path, newSnapshotNode) {
  6900. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6901. }
  6902. }
  6903. /**
  6904. * @license
  6905. * Copyright 2017 Google LLC
  6906. *
  6907. * Licensed under the Apache License, Version 2.0 (the "License");
  6908. * you may not use this file except in compliance with the License.
  6909. * You may obtain a copy of the License at
  6910. *
  6911. * http://www.apache.org/licenses/LICENSE-2.0
  6912. *
  6913. * Unless required by applicable law or agreed to in writing, software
  6914. * distributed under the License is distributed on an "AS IS" BASIS,
  6915. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6916. * See the License for the specific language governing permissions and
  6917. * limitations under the License.
  6918. */
  6919. function newSparseSnapshotTree() {
  6920. return {
  6921. value: null,
  6922. children: new Map()
  6923. };
  6924. }
  6925. /**
  6926. * Stores the given node at the specified path. If there is already a node
  6927. * at a shallower path, it merges the new data into that snapshot node.
  6928. *
  6929. * @param path - Path to look up snapshot for.
  6930. * @param data - The new data, or null.
  6931. */
  6932. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6933. if (pathIsEmpty(path)) {
  6934. sparseSnapshotTree.value = data;
  6935. sparseSnapshotTree.children.clear();
  6936. }
  6937. else if (sparseSnapshotTree.value !== null) {
  6938. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6939. }
  6940. else {
  6941. const childKey = pathGetFront(path);
  6942. if (!sparseSnapshotTree.children.has(childKey)) {
  6943. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6944. }
  6945. const child = sparseSnapshotTree.children.get(childKey);
  6946. path = pathPopFront(path);
  6947. sparseSnapshotTreeRemember(child, path, data);
  6948. }
  6949. }
  6950. /**
  6951. * Purge the data at path from the cache.
  6952. *
  6953. * @param path - Path to look up snapshot for.
  6954. * @returns True if this node should now be removed.
  6955. */
  6956. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6957. if (pathIsEmpty(path)) {
  6958. sparseSnapshotTree.value = null;
  6959. sparseSnapshotTree.children.clear();
  6960. return true;
  6961. }
  6962. else {
  6963. if (sparseSnapshotTree.value !== null) {
  6964. if (sparseSnapshotTree.value.isLeafNode()) {
  6965. // We're trying to forget a node that doesn't exist
  6966. return false;
  6967. }
  6968. else {
  6969. const value = sparseSnapshotTree.value;
  6970. sparseSnapshotTree.value = null;
  6971. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6972. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6973. });
  6974. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6975. }
  6976. }
  6977. else if (sparseSnapshotTree.children.size > 0) {
  6978. const childKey = pathGetFront(path);
  6979. path = pathPopFront(path);
  6980. if (sparseSnapshotTree.children.has(childKey)) {
  6981. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6982. if (safeToRemove) {
  6983. sparseSnapshotTree.children.delete(childKey);
  6984. }
  6985. }
  6986. return sparseSnapshotTree.children.size === 0;
  6987. }
  6988. else {
  6989. return true;
  6990. }
  6991. }
  6992. }
  6993. /**
  6994. * Recursively iterates through all of the stored tree and calls the
  6995. * callback on each one.
  6996. *
  6997. * @param prefixPath - Path to look up node for.
  6998. * @param func - The function to invoke for each tree.
  6999. */
  7000. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7001. if (sparseSnapshotTree.value !== null) {
  7002. func(prefixPath, sparseSnapshotTree.value);
  7003. }
  7004. else {
  7005. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  7006. const path = new Path(prefixPath.toString() + '/' + key);
  7007. sparseSnapshotTreeForEachTree(tree, path, func);
  7008. });
  7009. }
  7010. }
  7011. /**
  7012. * Iterates through each immediate child and triggers the callback.
  7013. * Only seems to be used in tests.
  7014. *
  7015. * @param func - The function to invoke for each child.
  7016. */
  7017. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7018. sparseSnapshotTree.children.forEach((tree, key) => {
  7019. func(key, tree);
  7020. });
  7021. }
  7022. /**
  7023. * @license
  7024. * Copyright 2017 Google LLC
  7025. *
  7026. * Licensed under the Apache License, Version 2.0 (the "License");
  7027. * you may not use this file except in compliance with the License.
  7028. * You may obtain a copy of the License at
  7029. *
  7030. * http://www.apache.org/licenses/LICENSE-2.0
  7031. *
  7032. * Unless required by applicable law or agreed to in writing, software
  7033. * distributed under the License is distributed on an "AS IS" BASIS,
  7034. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7035. * See the License for the specific language governing permissions and
  7036. * limitations under the License.
  7037. */
  7038. /**
  7039. * Returns the delta from the previous call to get stats.
  7040. *
  7041. * @param collection_ - The collection to "listen" to.
  7042. */
  7043. class StatsListener {
  7044. constructor(collection_) {
  7045. this.collection_ = collection_;
  7046. this.last_ = null;
  7047. }
  7048. get() {
  7049. const newStats = this.collection_.get();
  7050. const delta = Object.assign({}, newStats);
  7051. if (this.last_) {
  7052. each(this.last_, (stat, value) => {
  7053. delta[stat] = delta[stat] - value;
  7054. });
  7055. }
  7056. this.last_ = newStats;
  7057. return delta;
  7058. }
  7059. }
  7060. /**
  7061. * @license
  7062. * Copyright 2017 Google LLC
  7063. *
  7064. * Licensed under the Apache License, Version 2.0 (the "License");
  7065. * you may not use this file except in compliance with the License.
  7066. * You may obtain a copy of the License at
  7067. *
  7068. * http://www.apache.org/licenses/LICENSE-2.0
  7069. *
  7070. * Unless required by applicable law or agreed to in writing, software
  7071. * distributed under the License is distributed on an "AS IS" BASIS,
  7072. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7073. * See the License for the specific language governing permissions and
  7074. * limitations under the License.
  7075. */
  7076. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7077. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7078. // seconds to try to ensure the Firebase connection is established / settled.
  7079. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7080. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7081. // We'll continue to report stats on average every 5 minutes.
  7082. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7083. class StatsReporter {
  7084. constructor(collection, server_) {
  7085. this.server_ = server_;
  7086. this.statsToReport_ = {};
  7087. this.statsListener_ = new StatsListener(collection);
  7088. const timeout = FIRST_STATS_MIN_TIME +
  7089. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7090. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7091. }
  7092. reportStats_() {
  7093. const stats = this.statsListener_.get();
  7094. const reportedStats = {};
  7095. let haveStatsToReport = false;
  7096. each(stats, (stat, value) => {
  7097. if (value > 0 && util.contains(this.statsToReport_, stat)) {
  7098. reportedStats[stat] = value;
  7099. haveStatsToReport = true;
  7100. }
  7101. });
  7102. if (haveStatsToReport) {
  7103. this.server_.reportStats(reportedStats);
  7104. }
  7105. // queue our next run.
  7106. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7107. }
  7108. }
  7109. /**
  7110. * @license
  7111. * Copyright 2017 Google LLC
  7112. *
  7113. * Licensed under the Apache License, Version 2.0 (the "License");
  7114. * you may not use this file except in compliance with the License.
  7115. * You may obtain a copy of the License at
  7116. *
  7117. * http://www.apache.org/licenses/LICENSE-2.0
  7118. *
  7119. * Unless required by applicable law or agreed to in writing, software
  7120. * distributed under the License is distributed on an "AS IS" BASIS,
  7121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7122. * See the License for the specific language governing permissions and
  7123. * limitations under the License.
  7124. */
  7125. /**
  7126. *
  7127. * @enum
  7128. */
  7129. var OperationType;
  7130. (function (OperationType) {
  7131. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7132. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7133. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7134. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7135. })(OperationType || (OperationType = {}));
  7136. function newOperationSourceUser() {
  7137. return {
  7138. fromUser: true,
  7139. fromServer: false,
  7140. queryId: null,
  7141. tagged: false
  7142. };
  7143. }
  7144. function newOperationSourceServer() {
  7145. return {
  7146. fromUser: false,
  7147. fromServer: true,
  7148. queryId: null,
  7149. tagged: false
  7150. };
  7151. }
  7152. function newOperationSourceServerTaggedQuery(queryId) {
  7153. return {
  7154. fromUser: false,
  7155. fromServer: true,
  7156. queryId,
  7157. tagged: true
  7158. };
  7159. }
  7160. /**
  7161. * @license
  7162. * Copyright 2017 Google LLC
  7163. *
  7164. * Licensed under the Apache License, Version 2.0 (the "License");
  7165. * you may not use this file except in compliance with the License.
  7166. * You may obtain a copy of the License at
  7167. *
  7168. * http://www.apache.org/licenses/LICENSE-2.0
  7169. *
  7170. * Unless required by applicable law or agreed to in writing, software
  7171. * distributed under the License is distributed on an "AS IS" BASIS,
  7172. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7173. * See the License for the specific language governing permissions and
  7174. * limitations under the License.
  7175. */
  7176. class AckUserWrite {
  7177. /**
  7178. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7179. */
  7180. constructor(
  7181. /** @inheritDoc */ path,
  7182. /** @inheritDoc */ affectedTree,
  7183. /** @inheritDoc */ revert) {
  7184. this.path = path;
  7185. this.affectedTree = affectedTree;
  7186. this.revert = revert;
  7187. /** @inheritDoc */
  7188. this.type = OperationType.ACK_USER_WRITE;
  7189. /** @inheritDoc */
  7190. this.source = newOperationSourceUser();
  7191. }
  7192. operationForChild(childName) {
  7193. if (!pathIsEmpty(this.path)) {
  7194. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7195. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7196. }
  7197. else if (this.affectedTree.value != null) {
  7198. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7199. // All child locations are affected as well; just return same operation.
  7200. return this;
  7201. }
  7202. else {
  7203. const childTree = this.affectedTree.subtree(new Path(childName));
  7204. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7205. }
  7206. }
  7207. }
  7208. /**
  7209. * @license
  7210. * Copyright 2017 Google LLC
  7211. *
  7212. * Licensed under the Apache License, Version 2.0 (the "License");
  7213. * you may not use this file except in compliance with the License.
  7214. * You may obtain a copy of the License at
  7215. *
  7216. * http://www.apache.org/licenses/LICENSE-2.0
  7217. *
  7218. * Unless required by applicable law or agreed to in writing, software
  7219. * distributed under the License is distributed on an "AS IS" BASIS,
  7220. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7221. * See the License for the specific language governing permissions and
  7222. * limitations under the License.
  7223. */
  7224. class ListenComplete {
  7225. constructor(source, path) {
  7226. this.source = source;
  7227. this.path = path;
  7228. /** @inheritDoc */
  7229. this.type = OperationType.LISTEN_COMPLETE;
  7230. }
  7231. operationForChild(childName) {
  7232. if (pathIsEmpty(this.path)) {
  7233. return new ListenComplete(this.source, newEmptyPath());
  7234. }
  7235. else {
  7236. return new ListenComplete(this.source, pathPopFront(this.path));
  7237. }
  7238. }
  7239. }
  7240. /**
  7241. * @license
  7242. * Copyright 2017 Google LLC
  7243. *
  7244. * Licensed under the Apache License, Version 2.0 (the "License");
  7245. * you may not use this file except in compliance with the License.
  7246. * You may obtain a copy of the License at
  7247. *
  7248. * http://www.apache.org/licenses/LICENSE-2.0
  7249. *
  7250. * Unless required by applicable law or agreed to in writing, software
  7251. * distributed under the License is distributed on an "AS IS" BASIS,
  7252. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7253. * See the License for the specific language governing permissions and
  7254. * limitations under the License.
  7255. */
  7256. class Overwrite {
  7257. constructor(source, path, snap) {
  7258. this.source = source;
  7259. this.path = path;
  7260. this.snap = snap;
  7261. /** @inheritDoc */
  7262. this.type = OperationType.OVERWRITE;
  7263. }
  7264. operationForChild(childName) {
  7265. if (pathIsEmpty(this.path)) {
  7266. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7267. }
  7268. else {
  7269. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7270. }
  7271. }
  7272. }
  7273. /**
  7274. * @license
  7275. * Copyright 2017 Google LLC
  7276. *
  7277. * Licensed under the Apache License, Version 2.0 (the "License");
  7278. * you may not use this file except in compliance with the License.
  7279. * You may obtain a copy of the License at
  7280. *
  7281. * http://www.apache.org/licenses/LICENSE-2.0
  7282. *
  7283. * Unless required by applicable law or agreed to in writing, software
  7284. * distributed under the License is distributed on an "AS IS" BASIS,
  7285. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7286. * See the License for the specific language governing permissions and
  7287. * limitations under the License.
  7288. */
  7289. class Merge {
  7290. constructor(
  7291. /** @inheritDoc */ source,
  7292. /** @inheritDoc */ path,
  7293. /** @inheritDoc */ children) {
  7294. this.source = source;
  7295. this.path = path;
  7296. this.children = children;
  7297. /** @inheritDoc */
  7298. this.type = OperationType.MERGE;
  7299. }
  7300. operationForChild(childName) {
  7301. if (pathIsEmpty(this.path)) {
  7302. const childTree = this.children.subtree(new Path(childName));
  7303. if (childTree.isEmpty()) {
  7304. // This child is unaffected
  7305. return null;
  7306. }
  7307. else if (childTree.value) {
  7308. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7309. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7310. }
  7311. else {
  7312. // This is a merge at a deeper level
  7313. return new Merge(this.source, newEmptyPath(), childTree);
  7314. }
  7315. }
  7316. else {
  7317. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7318. return new Merge(this.source, pathPopFront(this.path), this.children);
  7319. }
  7320. }
  7321. toString() {
  7322. return ('Operation(' +
  7323. this.path +
  7324. ': ' +
  7325. this.source.toString() +
  7326. ' merge: ' +
  7327. this.children.toString() +
  7328. ')');
  7329. }
  7330. }
  7331. /**
  7332. * @license
  7333. * Copyright 2017 Google LLC
  7334. *
  7335. * Licensed under the Apache License, Version 2.0 (the "License");
  7336. * you may not use this file except in compliance with the License.
  7337. * You may obtain a copy of the License at
  7338. *
  7339. * http://www.apache.org/licenses/LICENSE-2.0
  7340. *
  7341. * Unless required by applicable law or agreed to in writing, software
  7342. * distributed under the License is distributed on an "AS IS" BASIS,
  7343. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7344. * See the License for the specific language governing permissions and
  7345. * limitations under the License.
  7346. */
  7347. /**
  7348. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7349. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7350. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7351. * whether a node potentially had children removed due to a filter.
  7352. */
  7353. class CacheNode {
  7354. constructor(node_, fullyInitialized_, filtered_) {
  7355. this.node_ = node_;
  7356. this.fullyInitialized_ = fullyInitialized_;
  7357. this.filtered_ = filtered_;
  7358. }
  7359. /**
  7360. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7361. */
  7362. isFullyInitialized() {
  7363. return this.fullyInitialized_;
  7364. }
  7365. /**
  7366. * Returns whether this node is potentially missing children due to a filter applied to the node
  7367. */
  7368. isFiltered() {
  7369. return this.filtered_;
  7370. }
  7371. isCompleteForPath(path) {
  7372. if (pathIsEmpty(path)) {
  7373. return this.isFullyInitialized() && !this.filtered_;
  7374. }
  7375. const childKey = pathGetFront(path);
  7376. return this.isCompleteForChild(childKey);
  7377. }
  7378. isCompleteForChild(key) {
  7379. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7380. }
  7381. getNode() {
  7382. return this.node_;
  7383. }
  7384. }
  7385. /**
  7386. * @license
  7387. * Copyright 2017 Google LLC
  7388. *
  7389. * Licensed under the Apache License, Version 2.0 (the "License");
  7390. * you may not use this file except in compliance with the License.
  7391. * You may obtain a copy of the License at
  7392. *
  7393. * http://www.apache.org/licenses/LICENSE-2.0
  7394. *
  7395. * Unless required by applicable law or agreed to in writing, software
  7396. * distributed under the License is distributed on an "AS IS" BASIS,
  7397. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7398. * See the License for the specific language governing permissions and
  7399. * limitations under the License.
  7400. */
  7401. /**
  7402. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7403. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7404. * for details.
  7405. *
  7406. */
  7407. class EventGenerator {
  7408. constructor(query_) {
  7409. this.query_ = query_;
  7410. this.index_ = this.query_._queryParams.getIndex();
  7411. }
  7412. }
  7413. /**
  7414. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7415. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7416. *
  7417. * Notes:
  7418. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7419. * our index.
  7420. * - prevName will be calculated based on the index ordering.
  7421. */
  7422. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7423. const events = [];
  7424. const moves = [];
  7425. changes.forEach(change => {
  7426. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7427. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7428. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7429. }
  7430. });
  7431. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7432. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7433. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7434. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7435. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7436. return events;
  7437. }
  7438. /**
  7439. * Given changes of a single change type, generate the corresponding events.
  7440. */
  7441. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7442. const filteredChanges = changes.filter(change => change.type === eventType);
  7443. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7444. filteredChanges.forEach(change => {
  7445. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7446. registrations.forEach(registration => {
  7447. if (registration.respondsTo(change.type)) {
  7448. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7449. }
  7450. });
  7451. });
  7452. }
  7453. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7454. if (change.type === 'value' || change.type === 'child_removed') {
  7455. return change;
  7456. }
  7457. else {
  7458. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7459. return change;
  7460. }
  7461. }
  7462. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7463. if (a.childName == null || b.childName == null) {
  7464. throw util.assertionError('Should only compare child_ events.');
  7465. }
  7466. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7467. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7468. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7469. }
  7470. /**
  7471. * @license
  7472. * Copyright 2017 Google LLC
  7473. *
  7474. * Licensed under the Apache License, Version 2.0 (the "License");
  7475. * you may not use this file except in compliance with the License.
  7476. * You may obtain a copy of the License at
  7477. *
  7478. * http://www.apache.org/licenses/LICENSE-2.0
  7479. *
  7480. * Unless required by applicable law or agreed to in writing, software
  7481. * distributed under the License is distributed on an "AS IS" BASIS,
  7482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7483. * See the License for the specific language governing permissions and
  7484. * limitations under the License.
  7485. */
  7486. function newViewCache(eventCache, serverCache) {
  7487. return { eventCache, serverCache };
  7488. }
  7489. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7490. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7491. }
  7492. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7493. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7494. }
  7495. function viewCacheGetCompleteEventSnap(viewCache) {
  7496. return viewCache.eventCache.isFullyInitialized()
  7497. ? viewCache.eventCache.getNode()
  7498. : null;
  7499. }
  7500. function viewCacheGetCompleteServerSnap(viewCache) {
  7501. return viewCache.serverCache.isFullyInitialized()
  7502. ? viewCache.serverCache.getNode()
  7503. : null;
  7504. }
  7505. /**
  7506. * @license
  7507. * Copyright 2017 Google LLC
  7508. *
  7509. * Licensed under the Apache License, Version 2.0 (the "License");
  7510. * you may not use this file except in compliance with the License.
  7511. * You may obtain a copy of the License at
  7512. *
  7513. * http://www.apache.org/licenses/LICENSE-2.0
  7514. *
  7515. * Unless required by applicable law or agreed to in writing, software
  7516. * distributed under the License is distributed on an "AS IS" BASIS,
  7517. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7518. * See the License for the specific language governing permissions and
  7519. * limitations under the License.
  7520. */
  7521. let emptyChildrenSingleton;
  7522. /**
  7523. * Singleton empty children collection.
  7524. *
  7525. */
  7526. const EmptyChildren = () => {
  7527. if (!emptyChildrenSingleton) {
  7528. emptyChildrenSingleton = new SortedMap(stringCompare);
  7529. }
  7530. return emptyChildrenSingleton;
  7531. };
  7532. /**
  7533. * A tree with immutable elements.
  7534. */
  7535. class ImmutableTree {
  7536. constructor(value, children = EmptyChildren()) {
  7537. this.value = value;
  7538. this.children = children;
  7539. }
  7540. static fromObject(obj) {
  7541. let tree = new ImmutableTree(null);
  7542. each(obj, (childPath, childSnap) => {
  7543. tree = tree.set(new Path(childPath), childSnap);
  7544. });
  7545. return tree;
  7546. }
  7547. /**
  7548. * True if the value is empty and there are no children
  7549. */
  7550. isEmpty() {
  7551. return this.value === null && this.children.isEmpty();
  7552. }
  7553. /**
  7554. * Given a path and predicate, return the first node and the path to that node
  7555. * where the predicate returns true.
  7556. *
  7557. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7558. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7559. *
  7560. * @param relativePath - The remainder of the path
  7561. * @param predicate - The predicate to satisfy to return a node
  7562. */
  7563. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7564. if (this.value != null && predicate(this.value)) {
  7565. return { path: newEmptyPath(), value: this.value };
  7566. }
  7567. else {
  7568. if (pathIsEmpty(relativePath)) {
  7569. return null;
  7570. }
  7571. else {
  7572. const front = pathGetFront(relativePath);
  7573. const child = this.children.get(front);
  7574. if (child !== null) {
  7575. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7576. if (childExistingPathAndValue != null) {
  7577. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7578. return { path: fullPath, value: childExistingPathAndValue.value };
  7579. }
  7580. else {
  7581. return null;
  7582. }
  7583. }
  7584. else {
  7585. return null;
  7586. }
  7587. }
  7588. }
  7589. }
  7590. /**
  7591. * Find, if it exists, the shortest subpath of the given path that points a defined
  7592. * value in the tree
  7593. */
  7594. findRootMostValueAndPath(relativePath) {
  7595. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7596. }
  7597. /**
  7598. * @returns The subtree at the given path
  7599. */
  7600. subtree(relativePath) {
  7601. if (pathIsEmpty(relativePath)) {
  7602. return this;
  7603. }
  7604. else {
  7605. const front = pathGetFront(relativePath);
  7606. const childTree = this.children.get(front);
  7607. if (childTree !== null) {
  7608. return childTree.subtree(pathPopFront(relativePath));
  7609. }
  7610. else {
  7611. return new ImmutableTree(null);
  7612. }
  7613. }
  7614. }
  7615. /**
  7616. * Sets a value at the specified path.
  7617. *
  7618. * @param relativePath - Path to set value at.
  7619. * @param toSet - Value to set.
  7620. * @returns Resulting tree.
  7621. */
  7622. set(relativePath, toSet) {
  7623. if (pathIsEmpty(relativePath)) {
  7624. return new ImmutableTree(toSet, this.children);
  7625. }
  7626. else {
  7627. const front = pathGetFront(relativePath);
  7628. const child = this.children.get(front) || new ImmutableTree(null);
  7629. const newChild = child.set(pathPopFront(relativePath), toSet);
  7630. const newChildren = this.children.insert(front, newChild);
  7631. return new ImmutableTree(this.value, newChildren);
  7632. }
  7633. }
  7634. /**
  7635. * Removes the value at the specified path.
  7636. *
  7637. * @param relativePath - Path to value to remove.
  7638. * @returns Resulting tree.
  7639. */
  7640. remove(relativePath) {
  7641. if (pathIsEmpty(relativePath)) {
  7642. if (this.children.isEmpty()) {
  7643. return new ImmutableTree(null);
  7644. }
  7645. else {
  7646. return new ImmutableTree(null, this.children);
  7647. }
  7648. }
  7649. else {
  7650. const front = pathGetFront(relativePath);
  7651. const child = this.children.get(front);
  7652. if (child) {
  7653. const newChild = child.remove(pathPopFront(relativePath));
  7654. let newChildren;
  7655. if (newChild.isEmpty()) {
  7656. newChildren = this.children.remove(front);
  7657. }
  7658. else {
  7659. newChildren = this.children.insert(front, newChild);
  7660. }
  7661. if (this.value === null && newChildren.isEmpty()) {
  7662. return new ImmutableTree(null);
  7663. }
  7664. else {
  7665. return new ImmutableTree(this.value, newChildren);
  7666. }
  7667. }
  7668. else {
  7669. return this;
  7670. }
  7671. }
  7672. }
  7673. /**
  7674. * Gets a value from the tree.
  7675. *
  7676. * @param relativePath - Path to get value for.
  7677. * @returns Value at path, or null.
  7678. */
  7679. get(relativePath) {
  7680. if (pathIsEmpty(relativePath)) {
  7681. return this.value;
  7682. }
  7683. else {
  7684. const front = pathGetFront(relativePath);
  7685. const child = this.children.get(front);
  7686. if (child) {
  7687. return child.get(pathPopFront(relativePath));
  7688. }
  7689. else {
  7690. return null;
  7691. }
  7692. }
  7693. }
  7694. /**
  7695. * Replace the subtree at the specified path with the given new tree.
  7696. *
  7697. * @param relativePath - Path to replace subtree for.
  7698. * @param newTree - New tree.
  7699. * @returns Resulting tree.
  7700. */
  7701. setTree(relativePath, newTree) {
  7702. if (pathIsEmpty(relativePath)) {
  7703. return newTree;
  7704. }
  7705. else {
  7706. const front = pathGetFront(relativePath);
  7707. const child = this.children.get(front) || new ImmutableTree(null);
  7708. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7709. let newChildren;
  7710. if (newChild.isEmpty()) {
  7711. newChildren = this.children.remove(front);
  7712. }
  7713. else {
  7714. newChildren = this.children.insert(front, newChild);
  7715. }
  7716. return new ImmutableTree(this.value, newChildren);
  7717. }
  7718. }
  7719. /**
  7720. * Performs a depth first fold on this tree. Transforms a tree into a single
  7721. * value, given a function that operates on the path to a node, an optional
  7722. * current value, and a map of child names to folded subtrees
  7723. */
  7724. fold(fn) {
  7725. return this.fold_(newEmptyPath(), fn);
  7726. }
  7727. /**
  7728. * Recursive helper for public-facing fold() method
  7729. */
  7730. fold_(pathSoFar, fn) {
  7731. const accum = {};
  7732. this.children.inorderTraversal((childKey, childTree) => {
  7733. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7734. });
  7735. return fn(pathSoFar, this.value, accum);
  7736. }
  7737. /**
  7738. * Find the first matching value on the given path. Return the result of applying f to it.
  7739. */
  7740. findOnPath(path, f) {
  7741. return this.findOnPath_(path, newEmptyPath(), f);
  7742. }
  7743. findOnPath_(pathToFollow, pathSoFar, f) {
  7744. const result = this.value ? f(pathSoFar, this.value) : false;
  7745. if (result) {
  7746. return result;
  7747. }
  7748. else {
  7749. if (pathIsEmpty(pathToFollow)) {
  7750. return null;
  7751. }
  7752. else {
  7753. const front = pathGetFront(pathToFollow);
  7754. const nextChild = this.children.get(front);
  7755. if (nextChild) {
  7756. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7757. }
  7758. else {
  7759. return null;
  7760. }
  7761. }
  7762. }
  7763. }
  7764. foreachOnPath(path, f) {
  7765. return this.foreachOnPath_(path, newEmptyPath(), f);
  7766. }
  7767. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7768. if (pathIsEmpty(pathToFollow)) {
  7769. return this;
  7770. }
  7771. else {
  7772. if (this.value) {
  7773. f(currentRelativePath, this.value);
  7774. }
  7775. const front = pathGetFront(pathToFollow);
  7776. const nextChild = this.children.get(front);
  7777. if (nextChild) {
  7778. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7779. }
  7780. else {
  7781. return new ImmutableTree(null);
  7782. }
  7783. }
  7784. }
  7785. /**
  7786. * Calls the given function for each node in the tree that has a value.
  7787. *
  7788. * @param f - A function to be called with the path from the root of the tree to
  7789. * a node, and the value at that node. Called in depth-first order.
  7790. */
  7791. foreach(f) {
  7792. this.foreach_(newEmptyPath(), f);
  7793. }
  7794. foreach_(currentRelativePath, f) {
  7795. this.children.inorderTraversal((childName, childTree) => {
  7796. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7797. });
  7798. if (this.value) {
  7799. f(currentRelativePath, this.value);
  7800. }
  7801. }
  7802. foreachChild(f) {
  7803. this.children.inorderTraversal((childName, childTree) => {
  7804. if (childTree.value) {
  7805. f(childName, childTree.value);
  7806. }
  7807. });
  7808. }
  7809. }
  7810. /**
  7811. * @license
  7812. * Copyright 2017 Google LLC
  7813. *
  7814. * Licensed under the Apache License, Version 2.0 (the "License");
  7815. * you may not use this file except in compliance with the License.
  7816. * You may obtain a copy of the License at
  7817. *
  7818. * http://www.apache.org/licenses/LICENSE-2.0
  7819. *
  7820. * Unless required by applicable law or agreed to in writing, software
  7821. * distributed under the License is distributed on an "AS IS" BASIS,
  7822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7823. * See the License for the specific language governing permissions and
  7824. * limitations under the License.
  7825. */
  7826. /**
  7827. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7828. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7829. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7830. * to reflect the write added.
  7831. */
  7832. class CompoundWrite {
  7833. constructor(writeTree_) {
  7834. this.writeTree_ = writeTree_;
  7835. }
  7836. static empty() {
  7837. return new CompoundWrite(new ImmutableTree(null));
  7838. }
  7839. }
  7840. function compoundWriteAddWrite(compoundWrite, path, node) {
  7841. if (pathIsEmpty(path)) {
  7842. return new CompoundWrite(new ImmutableTree(node));
  7843. }
  7844. else {
  7845. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7846. if (rootmost != null) {
  7847. const rootMostPath = rootmost.path;
  7848. let value = rootmost.value;
  7849. const relativePath = newRelativePath(rootMostPath, path);
  7850. value = value.updateChild(relativePath, node);
  7851. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7852. }
  7853. else {
  7854. const subtree = new ImmutableTree(node);
  7855. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7856. return new CompoundWrite(newWriteTree);
  7857. }
  7858. }
  7859. }
  7860. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7861. let newWrite = compoundWrite;
  7862. each(updates, (childKey, node) => {
  7863. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7864. });
  7865. return newWrite;
  7866. }
  7867. /**
  7868. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7869. * location, which must be removed by calling this method with that path.
  7870. *
  7871. * @param compoundWrite - The CompoundWrite to remove.
  7872. * @param path - The path at which a write and all deeper writes should be removed
  7873. * @returns The new CompoundWrite with the removed path
  7874. */
  7875. function compoundWriteRemoveWrite(compoundWrite, path) {
  7876. if (pathIsEmpty(path)) {
  7877. return CompoundWrite.empty();
  7878. }
  7879. else {
  7880. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7881. return new CompoundWrite(newWriteTree);
  7882. }
  7883. }
  7884. /**
  7885. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7886. * considered "complete".
  7887. *
  7888. * @param compoundWrite - The CompoundWrite to check.
  7889. * @param path - The path to check for
  7890. * @returns Whether there is a complete write at that path
  7891. */
  7892. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7893. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7894. }
  7895. /**
  7896. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7897. * writes from deeper paths, but will return child nodes from a more shallow path.
  7898. *
  7899. * @param compoundWrite - The CompoundWrite to get the node from.
  7900. * @param path - The path to get a complete write
  7901. * @returns The node if complete at that path, or null otherwise.
  7902. */
  7903. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7904. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7905. if (rootmost != null) {
  7906. return compoundWrite.writeTree_
  7907. .get(rootmost.path)
  7908. .getChild(newRelativePath(rootmost.path, path));
  7909. }
  7910. else {
  7911. return null;
  7912. }
  7913. }
  7914. /**
  7915. * Returns all children that are guaranteed to be a complete overwrite.
  7916. *
  7917. * @param compoundWrite - The CompoundWrite to get children from.
  7918. * @returns A list of all complete children.
  7919. */
  7920. function compoundWriteGetCompleteChildren(compoundWrite) {
  7921. const children = [];
  7922. const node = compoundWrite.writeTree_.value;
  7923. if (node != null) {
  7924. // If it's a leaf node, it has no children; so nothing to do.
  7925. if (!node.isLeafNode()) {
  7926. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7927. children.push(new NamedNode(childName, childNode));
  7928. });
  7929. }
  7930. }
  7931. else {
  7932. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7933. if (childTree.value != null) {
  7934. children.push(new NamedNode(childName, childTree.value));
  7935. }
  7936. });
  7937. }
  7938. return children;
  7939. }
  7940. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7941. if (pathIsEmpty(path)) {
  7942. return compoundWrite;
  7943. }
  7944. else {
  7945. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7946. if (shadowingNode != null) {
  7947. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7948. }
  7949. else {
  7950. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7951. }
  7952. }
  7953. }
  7954. /**
  7955. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7956. * @returns Whether this CompoundWrite is empty
  7957. */
  7958. function compoundWriteIsEmpty(compoundWrite) {
  7959. return compoundWrite.writeTree_.isEmpty();
  7960. }
  7961. /**
  7962. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7963. * node
  7964. * @param node - The node to apply this CompoundWrite to
  7965. * @returns The node with all writes applied
  7966. */
  7967. function compoundWriteApply(compoundWrite, node) {
  7968. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7969. }
  7970. function applySubtreeWrite(relativePath, writeTree, node) {
  7971. if (writeTree.value != null) {
  7972. // Since there a write is always a leaf, we're done here
  7973. return node.updateChild(relativePath, writeTree.value);
  7974. }
  7975. else {
  7976. let priorityWrite = null;
  7977. writeTree.children.inorderTraversal((childKey, childTree) => {
  7978. if (childKey === '.priority') {
  7979. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7980. // to apply priorities to empty nodes that are later filled
  7981. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7982. priorityWrite = childTree.value;
  7983. }
  7984. else {
  7985. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7986. }
  7987. });
  7988. // If there was a priority write, we only apply it if the node is not empty
  7989. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7990. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7991. }
  7992. return node;
  7993. }
  7994. }
  7995. /**
  7996. * @license
  7997. * Copyright 2017 Google LLC
  7998. *
  7999. * Licensed under the Apache License, Version 2.0 (the "License");
  8000. * you may not use this file except in compliance with the License.
  8001. * You may obtain a copy of the License at
  8002. *
  8003. * http://www.apache.org/licenses/LICENSE-2.0
  8004. *
  8005. * Unless required by applicable law or agreed to in writing, software
  8006. * distributed under the License is distributed on an "AS IS" BASIS,
  8007. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8008. * See the License for the specific language governing permissions and
  8009. * limitations under the License.
  8010. */
  8011. /**
  8012. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8013. *
  8014. */
  8015. function writeTreeChildWrites(writeTree, path) {
  8016. return newWriteTreeRef(path, writeTree);
  8017. }
  8018. /**
  8019. * Record a new overwrite from user code.
  8020. *
  8021. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8022. */
  8023. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8024. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8025. if (visible === undefined) {
  8026. visible = true;
  8027. }
  8028. writeTree.allWrites.push({
  8029. path,
  8030. snap,
  8031. writeId,
  8032. visible
  8033. });
  8034. if (visible) {
  8035. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8036. }
  8037. writeTree.lastWriteId = writeId;
  8038. }
  8039. /**
  8040. * Record a new merge from user code.
  8041. */
  8042. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8043. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8044. writeTree.allWrites.push({
  8045. path,
  8046. children: changedChildren,
  8047. writeId,
  8048. visible: true
  8049. });
  8050. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8051. writeTree.lastWriteId = writeId;
  8052. }
  8053. function writeTreeGetWrite(writeTree, writeId) {
  8054. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8055. const record = writeTree.allWrites[i];
  8056. if (record.writeId === writeId) {
  8057. return record;
  8058. }
  8059. }
  8060. return null;
  8061. }
  8062. /**
  8063. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8064. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8065. *
  8066. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8067. * events as a result).
  8068. */
  8069. function writeTreeRemoveWrite(writeTree, writeId) {
  8070. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8071. // out of order.
  8072. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8073. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8074. const idx = writeTree.allWrites.findIndex(s => {
  8075. return s.writeId === writeId;
  8076. });
  8077. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8078. const writeToRemove = writeTree.allWrites[idx];
  8079. writeTree.allWrites.splice(idx, 1);
  8080. let removedWriteWasVisible = writeToRemove.visible;
  8081. let removedWriteOverlapsWithOtherWrites = false;
  8082. let i = writeTree.allWrites.length - 1;
  8083. while (removedWriteWasVisible && i >= 0) {
  8084. const currentWrite = writeTree.allWrites[i];
  8085. if (currentWrite.visible) {
  8086. if (i >= idx &&
  8087. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8088. // The removed write was completely shadowed by a subsequent write.
  8089. removedWriteWasVisible = false;
  8090. }
  8091. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8092. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8093. removedWriteOverlapsWithOtherWrites = true;
  8094. }
  8095. }
  8096. i--;
  8097. }
  8098. if (!removedWriteWasVisible) {
  8099. return false;
  8100. }
  8101. else if (removedWriteOverlapsWithOtherWrites) {
  8102. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8103. writeTreeResetTree_(writeTree);
  8104. return true;
  8105. }
  8106. else {
  8107. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8108. if (writeToRemove.snap) {
  8109. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8110. }
  8111. else {
  8112. const children = writeToRemove.children;
  8113. each(children, (childName) => {
  8114. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8115. });
  8116. }
  8117. return true;
  8118. }
  8119. }
  8120. function writeTreeRecordContainsPath_(writeRecord, path) {
  8121. if (writeRecord.snap) {
  8122. return pathContains(writeRecord.path, path);
  8123. }
  8124. else {
  8125. for (const childName in writeRecord.children) {
  8126. if (writeRecord.children.hasOwnProperty(childName) &&
  8127. pathContains(pathChild(writeRecord.path, childName), path)) {
  8128. return true;
  8129. }
  8130. }
  8131. return false;
  8132. }
  8133. }
  8134. /**
  8135. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8136. */
  8137. function writeTreeResetTree_(writeTree) {
  8138. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8139. if (writeTree.allWrites.length > 0) {
  8140. writeTree.lastWriteId =
  8141. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8142. }
  8143. else {
  8144. writeTree.lastWriteId = -1;
  8145. }
  8146. }
  8147. /**
  8148. * The default filter used when constructing the tree. Keep everything that's visible.
  8149. */
  8150. function writeTreeDefaultFilter_(write) {
  8151. return write.visible;
  8152. }
  8153. /**
  8154. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8155. * event data at that path.
  8156. */
  8157. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8158. let compoundWrite = CompoundWrite.empty();
  8159. for (let i = 0; i < writes.length; ++i) {
  8160. const write = writes[i];
  8161. // Theory, a later set will either:
  8162. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8163. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8164. if (filter(write)) {
  8165. const writePath = write.path;
  8166. let relativePath;
  8167. if (write.snap) {
  8168. if (pathContains(treeRoot, writePath)) {
  8169. relativePath = newRelativePath(treeRoot, writePath);
  8170. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8171. }
  8172. else if (pathContains(writePath, treeRoot)) {
  8173. relativePath = newRelativePath(writePath, treeRoot);
  8174. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8175. }
  8176. else ;
  8177. }
  8178. else if (write.children) {
  8179. if (pathContains(treeRoot, writePath)) {
  8180. relativePath = newRelativePath(treeRoot, writePath);
  8181. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8182. }
  8183. else if (pathContains(writePath, treeRoot)) {
  8184. relativePath = newRelativePath(writePath, treeRoot);
  8185. if (pathIsEmpty(relativePath)) {
  8186. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8187. }
  8188. else {
  8189. const child = util.safeGet(write.children, pathGetFront(relativePath));
  8190. if (child) {
  8191. // There exists a child in this node that matches the root path
  8192. const deepNode = child.getChild(pathPopFront(relativePath));
  8193. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8194. }
  8195. }
  8196. }
  8197. else ;
  8198. }
  8199. else {
  8200. throw util.assertionError('WriteRecord should have .snap or .children');
  8201. }
  8202. }
  8203. }
  8204. return compoundWrite;
  8205. }
  8206. /**
  8207. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8208. * writes), attempt to calculate a complete snapshot for the given path
  8209. *
  8210. * @param writeIdsToExclude - An optional set to be excluded
  8211. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8212. */
  8213. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8214. if (!writeIdsToExclude && !includeHiddenWrites) {
  8215. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8216. if (shadowingNode != null) {
  8217. return shadowingNode;
  8218. }
  8219. else {
  8220. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8221. if (compoundWriteIsEmpty(subMerge)) {
  8222. return completeServerCache;
  8223. }
  8224. else if (completeServerCache == null &&
  8225. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8226. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8227. return null;
  8228. }
  8229. else {
  8230. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8231. return compoundWriteApply(subMerge, layeredCache);
  8232. }
  8233. }
  8234. }
  8235. else {
  8236. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8237. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8238. return completeServerCache;
  8239. }
  8240. else {
  8241. // If the server cache is null, and we don't have a complete cache, we need to return null
  8242. if (!includeHiddenWrites &&
  8243. completeServerCache == null &&
  8244. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8245. return null;
  8246. }
  8247. else {
  8248. const filter = function (write) {
  8249. return ((write.visible || includeHiddenWrites) &&
  8250. (!writeIdsToExclude ||
  8251. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8252. (pathContains(write.path, treePath) ||
  8253. pathContains(treePath, write.path)));
  8254. };
  8255. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8256. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8257. return compoundWriteApply(mergeAtPath, layeredCache);
  8258. }
  8259. }
  8260. }
  8261. }
  8262. /**
  8263. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8264. * Used when creating new views, to pre-fill their complete event children snapshot.
  8265. */
  8266. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8267. let completeChildren = ChildrenNode.EMPTY_NODE;
  8268. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8269. if (topLevelSet) {
  8270. if (!topLevelSet.isLeafNode()) {
  8271. // we're shadowing everything. Return the children.
  8272. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8273. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8274. });
  8275. }
  8276. return completeChildren;
  8277. }
  8278. else if (completeServerChildren) {
  8279. // Layer any children we have on top of this
  8280. // We know we don't have a top-level set, so just enumerate existing children
  8281. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8282. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8283. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8284. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8285. });
  8286. // Add any complete children we have from the set
  8287. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8288. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8289. });
  8290. return completeChildren;
  8291. }
  8292. else {
  8293. // We don't have anything to layer on top of. Layer on any children we have
  8294. // Note that we can return an empty snap if we have a defined delete
  8295. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8296. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8297. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8298. });
  8299. return completeChildren;
  8300. }
  8301. }
  8302. /**
  8303. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8304. * applied to the event cache.
  8305. *
  8306. * Possibilities:
  8307. *
  8308. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8309. *
  8310. * 2. Some write is completely shadowing. No events to be raised
  8311. *
  8312. * 3. Is partially shadowed. Events
  8313. *
  8314. * Either existingEventSnap or existingServerSnap must exist
  8315. */
  8316. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8317. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8318. const path = pathChild(treePath, childPath);
  8319. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8320. // At this point we can probably guarantee that we're in case 2, meaning no events
  8321. // May need to check visibility while doing the findRootMostValueAndPath call
  8322. return null;
  8323. }
  8324. else {
  8325. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8326. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8327. if (compoundWriteIsEmpty(childMerge)) {
  8328. // We're not shadowing at all. Case 1
  8329. return existingServerSnap.getChild(childPath);
  8330. }
  8331. else {
  8332. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8333. // However this is tricky to find out, since user updates don't necessary change the server
  8334. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8335. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8336. // only check if the updates change the serverNode.
  8337. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8338. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8339. }
  8340. }
  8341. }
  8342. /**
  8343. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8344. * complete child for this ChildKey.
  8345. */
  8346. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8347. const path = pathChild(treePath, childKey);
  8348. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8349. if (shadowingNode != null) {
  8350. return shadowingNode;
  8351. }
  8352. else {
  8353. if (existingServerSnap.isCompleteForChild(childKey)) {
  8354. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8355. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8356. }
  8357. else {
  8358. return null;
  8359. }
  8360. }
  8361. }
  8362. /**
  8363. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8364. * a higher path, this will return the child of that write relative to the write and this path.
  8365. * Returns null if there is no write at this path.
  8366. */
  8367. function writeTreeShadowingWrite(writeTree, path) {
  8368. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8369. }
  8370. /**
  8371. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8372. * the window, but may now be in the window.
  8373. */
  8374. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8375. let toIterate;
  8376. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8377. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8378. if (shadowingNode != null) {
  8379. toIterate = shadowingNode;
  8380. }
  8381. else if (completeServerData != null) {
  8382. toIterate = compoundWriteApply(merge, completeServerData);
  8383. }
  8384. else {
  8385. // no children to iterate on
  8386. return [];
  8387. }
  8388. toIterate = toIterate.withIndex(index);
  8389. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8390. const nodes = [];
  8391. const cmp = index.getCompare();
  8392. const iter = reverse
  8393. ? toIterate.getReverseIteratorFrom(startPost, index)
  8394. : toIterate.getIteratorFrom(startPost, index);
  8395. let next = iter.getNext();
  8396. while (next && nodes.length < count) {
  8397. if (cmp(next, startPost) !== 0) {
  8398. nodes.push(next);
  8399. }
  8400. next = iter.getNext();
  8401. }
  8402. return nodes;
  8403. }
  8404. else {
  8405. return [];
  8406. }
  8407. }
  8408. function newWriteTree() {
  8409. return {
  8410. visibleWrites: CompoundWrite.empty(),
  8411. allWrites: [],
  8412. lastWriteId: -1
  8413. };
  8414. }
  8415. /**
  8416. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8417. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8418. * can lead to a more expensive calculation.
  8419. *
  8420. * @param writeIdsToExclude - Optional writes to exclude.
  8421. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8422. */
  8423. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8424. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8425. }
  8426. /**
  8427. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8428. * mix of the given server data and write data.
  8429. *
  8430. */
  8431. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8432. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8433. }
  8434. /**
  8435. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8436. * if anything, needs to be applied to the event cache.
  8437. *
  8438. * Possibilities:
  8439. *
  8440. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8441. *
  8442. * 2. Some write is completely shadowing. No events to be raised
  8443. *
  8444. * 3. Is partially shadowed. Events should be raised
  8445. *
  8446. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8447. *
  8448. *
  8449. */
  8450. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8451. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8452. }
  8453. /**
  8454. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8455. * a higher path, this will return the child of that write relative to the write and this path.
  8456. * Returns null if there is no write at this path.
  8457. *
  8458. */
  8459. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8460. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8461. }
  8462. /**
  8463. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8464. * the window, but may now be in the window
  8465. */
  8466. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8467. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8468. }
  8469. /**
  8470. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8471. * complete child for this ChildKey.
  8472. */
  8473. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8474. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8475. }
  8476. /**
  8477. * Return a WriteTreeRef for a child.
  8478. */
  8479. function writeTreeRefChild(writeTreeRef, childName) {
  8480. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8481. }
  8482. function newWriteTreeRef(path, writeTree) {
  8483. return {
  8484. treePath: path,
  8485. writeTree
  8486. };
  8487. }
  8488. /**
  8489. * @license
  8490. * Copyright 2017 Google LLC
  8491. *
  8492. * Licensed under the Apache License, Version 2.0 (the "License");
  8493. * you may not use this file except in compliance with the License.
  8494. * You may obtain a copy of the License at
  8495. *
  8496. * http://www.apache.org/licenses/LICENSE-2.0
  8497. *
  8498. * Unless required by applicable law or agreed to in writing, software
  8499. * distributed under the License is distributed on an "AS IS" BASIS,
  8500. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8501. * See the License for the specific language governing permissions and
  8502. * limitations under the License.
  8503. */
  8504. class ChildChangeAccumulator {
  8505. constructor() {
  8506. this.changeMap = new Map();
  8507. }
  8508. trackChildChange(change) {
  8509. const type = change.type;
  8510. const childKey = change.childName;
  8511. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8512. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8513. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8514. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8515. const oldChange = this.changeMap.get(childKey);
  8516. if (oldChange) {
  8517. const oldType = oldChange.type;
  8518. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8519. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8520. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8521. }
  8522. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8523. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8524. this.changeMap.delete(childKey);
  8525. }
  8526. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8527. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8528. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8529. }
  8530. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8531. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8532. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8533. }
  8534. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8535. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8536. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8537. }
  8538. else {
  8539. throw util.assertionError('Illegal combination of changes: ' +
  8540. change +
  8541. ' occurred after ' +
  8542. oldChange);
  8543. }
  8544. }
  8545. else {
  8546. this.changeMap.set(childKey, change);
  8547. }
  8548. }
  8549. getChanges() {
  8550. return Array.from(this.changeMap.values());
  8551. }
  8552. }
  8553. /**
  8554. * @license
  8555. * Copyright 2017 Google LLC
  8556. *
  8557. * Licensed under the Apache License, Version 2.0 (the "License");
  8558. * you may not use this file except in compliance with the License.
  8559. * You may obtain a copy of the License at
  8560. *
  8561. * http://www.apache.org/licenses/LICENSE-2.0
  8562. *
  8563. * Unless required by applicable law or agreed to in writing, software
  8564. * distributed under the License is distributed on an "AS IS" BASIS,
  8565. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8566. * See the License for the specific language governing permissions and
  8567. * limitations under the License.
  8568. */
  8569. /**
  8570. * An implementation of CompleteChildSource that never returns any additional children
  8571. */
  8572. // eslint-disable-next-line @typescript-eslint/naming-convention
  8573. class NoCompleteChildSource_ {
  8574. getCompleteChild(childKey) {
  8575. return null;
  8576. }
  8577. getChildAfterChild(index, child, reverse) {
  8578. return null;
  8579. }
  8580. }
  8581. /**
  8582. * Singleton instance.
  8583. */
  8584. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8585. /**
  8586. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8587. * old event caches available to calculate complete children.
  8588. */
  8589. class WriteTreeCompleteChildSource {
  8590. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8591. this.writes_ = writes_;
  8592. this.viewCache_ = viewCache_;
  8593. this.optCompleteServerCache_ = optCompleteServerCache_;
  8594. }
  8595. getCompleteChild(childKey) {
  8596. const node = this.viewCache_.eventCache;
  8597. if (node.isCompleteForChild(childKey)) {
  8598. return node.getNode().getImmediateChild(childKey);
  8599. }
  8600. else {
  8601. const serverNode = this.optCompleteServerCache_ != null
  8602. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8603. : this.viewCache_.serverCache;
  8604. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8605. }
  8606. }
  8607. getChildAfterChild(index, child, reverse) {
  8608. const completeServerData = this.optCompleteServerCache_ != null
  8609. ? this.optCompleteServerCache_
  8610. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8611. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8612. if (nodes.length === 0) {
  8613. return null;
  8614. }
  8615. else {
  8616. return nodes[0];
  8617. }
  8618. }
  8619. }
  8620. /**
  8621. * @license
  8622. * Copyright 2017 Google LLC
  8623. *
  8624. * Licensed under the Apache License, Version 2.0 (the "License");
  8625. * you may not use this file except in compliance with the License.
  8626. * You may obtain a copy of the License at
  8627. *
  8628. * http://www.apache.org/licenses/LICENSE-2.0
  8629. *
  8630. * Unless required by applicable law or agreed to in writing, software
  8631. * distributed under the License is distributed on an "AS IS" BASIS,
  8632. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8633. * See the License for the specific language governing permissions and
  8634. * limitations under the License.
  8635. */
  8636. function newViewProcessor(filter) {
  8637. return { filter };
  8638. }
  8639. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8640. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8641. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8642. }
  8643. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8644. const accumulator = new ChildChangeAccumulator();
  8645. let newViewCache, filterServerNode;
  8646. if (operation.type === OperationType.OVERWRITE) {
  8647. const overwrite = operation;
  8648. if (overwrite.source.fromUser) {
  8649. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8650. }
  8651. else {
  8652. util.assert(overwrite.source.fromServer, 'Unknown source.');
  8653. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8654. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8655. // again
  8656. filterServerNode =
  8657. overwrite.source.tagged ||
  8658. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8659. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8660. }
  8661. }
  8662. else if (operation.type === OperationType.MERGE) {
  8663. const merge = operation;
  8664. if (merge.source.fromUser) {
  8665. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8666. }
  8667. else {
  8668. util.assert(merge.source.fromServer, 'Unknown source.');
  8669. // We filter the node if it's a tagged update or the node has been previously filtered
  8670. filterServerNode =
  8671. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8672. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8673. }
  8674. }
  8675. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8676. const ackUserWrite = operation;
  8677. if (!ackUserWrite.revert) {
  8678. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8679. }
  8680. else {
  8681. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8682. }
  8683. }
  8684. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8685. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8686. }
  8687. else {
  8688. throw util.assertionError('Unknown operation type: ' + operation.type);
  8689. }
  8690. const changes = accumulator.getChanges();
  8691. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8692. return { viewCache: newViewCache, changes };
  8693. }
  8694. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8695. const eventSnap = newViewCache.eventCache;
  8696. if (eventSnap.isFullyInitialized()) {
  8697. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8698. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8699. if (accumulator.length > 0 ||
  8700. !oldViewCache.eventCache.isFullyInitialized() ||
  8701. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8702. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8703. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8704. }
  8705. }
  8706. }
  8707. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8708. const oldEventSnap = viewCache.eventCache;
  8709. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8710. // we have a shadowing write, ignore changes
  8711. return viewCache;
  8712. }
  8713. else {
  8714. let newEventCache, serverNode;
  8715. if (pathIsEmpty(changePath)) {
  8716. // TODO: figure out how this plays with "sliding ack windows"
  8717. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8718. if (viewCache.serverCache.isFiltered()) {
  8719. // We need to special case this, because we need to only apply writes to complete children, or
  8720. // we might end up raising events for incomplete children. If the server data is filtered deep
  8721. // writes cannot be guaranteed to be complete
  8722. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8723. const completeChildren = serverCache instanceof ChildrenNode
  8724. ? serverCache
  8725. : ChildrenNode.EMPTY_NODE;
  8726. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8727. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8728. }
  8729. else {
  8730. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8731. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8732. }
  8733. }
  8734. else {
  8735. const childKey = pathGetFront(changePath);
  8736. if (childKey === '.priority') {
  8737. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8738. const oldEventNode = oldEventSnap.getNode();
  8739. serverNode = viewCache.serverCache.getNode();
  8740. // we might have overwrites for this priority
  8741. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8742. if (updatedPriority != null) {
  8743. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8744. }
  8745. else {
  8746. // priority didn't change, keep old node
  8747. newEventCache = oldEventSnap.getNode();
  8748. }
  8749. }
  8750. else {
  8751. const childChangePath = pathPopFront(changePath);
  8752. // update child
  8753. let newEventChild;
  8754. if (oldEventSnap.isCompleteForChild(childKey)) {
  8755. serverNode = viewCache.serverCache.getNode();
  8756. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8757. if (eventChildUpdate != null) {
  8758. newEventChild = oldEventSnap
  8759. .getNode()
  8760. .getImmediateChild(childKey)
  8761. .updateChild(childChangePath, eventChildUpdate);
  8762. }
  8763. else {
  8764. // Nothing changed, just keep the old child
  8765. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8766. }
  8767. }
  8768. else {
  8769. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8770. }
  8771. if (newEventChild != null) {
  8772. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8773. }
  8774. else {
  8775. // no complete child available or no change
  8776. newEventCache = oldEventSnap.getNode();
  8777. }
  8778. }
  8779. }
  8780. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8781. }
  8782. }
  8783. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8784. const oldServerSnap = oldViewCache.serverCache;
  8785. let newServerCache;
  8786. const serverFilter = filterServerNode
  8787. ? viewProcessor.filter
  8788. : viewProcessor.filter.getIndexedFilter();
  8789. if (pathIsEmpty(changePath)) {
  8790. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8791. }
  8792. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8793. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8794. const newServerNode = oldServerSnap
  8795. .getNode()
  8796. .updateChild(changePath, changedSnap);
  8797. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8798. }
  8799. else {
  8800. const childKey = pathGetFront(changePath);
  8801. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8802. pathGetLength(changePath) > 1) {
  8803. // We don't update incomplete nodes with updates intended for other listeners
  8804. return oldViewCache;
  8805. }
  8806. const childChangePath = pathPopFront(changePath);
  8807. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8808. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8809. if (childKey === '.priority') {
  8810. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8811. }
  8812. else {
  8813. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8814. }
  8815. }
  8816. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8817. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8818. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8819. }
  8820. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8821. const oldEventSnap = oldViewCache.eventCache;
  8822. let newViewCache, newEventCache;
  8823. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8824. if (pathIsEmpty(changePath)) {
  8825. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8826. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8827. }
  8828. else {
  8829. const childKey = pathGetFront(changePath);
  8830. if (childKey === '.priority') {
  8831. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8832. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8833. }
  8834. else {
  8835. const childChangePath = pathPopFront(changePath);
  8836. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8837. let newChild;
  8838. if (pathIsEmpty(childChangePath)) {
  8839. // Child overwrite, we can replace the child
  8840. newChild = changedSnap;
  8841. }
  8842. else {
  8843. const childNode = source.getCompleteChild(childKey);
  8844. if (childNode != null) {
  8845. if (pathGetBack(childChangePath) === '.priority' &&
  8846. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8847. // This is a priority update on an empty node. If this node exists on the server, the
  8848. // server will send down the priority in the update, so ignore for now
  8849. newChild = childNode;
  8850. }
  8851. else {
  8852. newChild = childNode.updateChild(childChangePath, changedSnap);
  8853. }
  8854. }
  8855. else {
  8856. // There is no complete child node available
  8857. newChild = ChildrenNode.EMPTY_NODE;
  8858. }
  8859. }
  8860. if (!oldChild.equals(newChild)) {
  8861. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8862. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8863. }
  8864. else {
  8865. newViewCache = oldViewCache;
  8866. }
  8867. }
  8868. }
  8869. return newViewCache;
  8870. }
  8871. function viewProcessorCacheHasChild(viewCache, childKey) {
  8872. return viewCache.eventCache.isCompleteForChild(childKey);
  8873. }
  8874. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8875. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8876. // window leaving room for new items. It's important we process these changes first, so we
  8877. // iterate the changes twice, first processing any that affect items currently in view.
  8878. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8879. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8880. // not the other.
  8881. let curViewCache = viewCache;
  8882. changedChildren.foreach((relativePath, childNode) => {
  8883. const writePath = pathChild(path, relativePath);
  8884. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8885. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8886. }
  8887. });
  8888. changedChildren.foreach((relativePath, childNode) => {
  8889. const writePath = pathChild(path, relativePath);
  8890. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8891. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8892. }
  8893. });
  8894. return curViewCache;
  8895. }
  8896. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8897. merge.foreach((relativePath, childNode) => {
  8898. node = node.updateChild(relativePath, childNode);
  8899. });
  8900. return node;
  8901. }
  8902. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8903. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8904. // wait for the complete data update coming soon.
  8905. if (viewCache.serverCache.getNode().isEmpty() &&
  8906. !viewCache.serverCache.isFullyInitialized()) {
  8907. return viewCache;
  8908. }
  8909. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8910. // window leaving room for new items. It's important we process these changes first, so we
  8911. // iterate the changes twice, first processing any that affect items currently in view.
  8912. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8913. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8914. // not the other.
  8915. let curViewCache = viewCache;
  8916. let viewMergeTree;
  8917. if (pathIsEmpty(path)) {
  8918. viewMergeTree = changedChildren;
  8919. }
  8920. else {
  8921. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8922. }
  8923. const serverNode = viewCache.serverCache.getNode();
  8924. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8925. if (serverNode.hasChild(childKey)) {
  8926. const serverChild = viewCache.serverCache
  8927. .getNode()
  8928. .getImmediateChild(childKey);
  8929. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8930. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8931. }
  8932. });
  8933. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8934. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8935. childMergeTree.value === null;
  8936. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8937. const serverChild = viewCache.serverCache
  8938. .getNode()
  8939. .getImmediateChild(childKey);
  8940. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8941. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8942. }
  8943. });
  8944. return curViewCache;
  8945. }
  8946. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8947. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8948. return viewCache;
  8949. }
  8950. // Only filter server node if it is currently filtered
  8951. const filterServerNode = viewCache.serverCache.isFiltered();
  8952. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8953. // now that it won't be shadowed.
  8954. const serverCache = viewCache.serverCache;
  8955. if (affectedTree.value != null) {
  8956. // This is an overwrite.
  8957. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8958. serverCache.isCompleteForPath(ackPath)) {
  8959. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8960. }
  8961. else if (pathIsEmpty(ackPath)) {
  8962. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8963. // should just re-apply whatever we have in our cache as a merge.
  8964. let changedChildren = new ImmutableTree(null);
  8965. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8966. changedChildren = changedChildren.set(new Path(name), node);
  8967. });
  8968. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8969. }
  8970. else {
  8971. return viewCache;
  8972. }
  8973. }
  8974. else {
  8975. // This is a merge.
  8976. let changedChildren = new ImmutableTree(null);
  8977. affectedTree.foreach((mergePath, value) => {
  8978. const serverCachePath = pathChild(ackPath, mergePath);
  8979. if (serverCache.isCompleteForPath(serverCachePath)) {
  8980. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8981. }
  8982. });
  8983. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8984. }
  8985. }
  8986. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8987. const oldServerNode = viewCache.serverCache;
  8988. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8989. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8990. }
  8991. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8992. let complete;
  8993. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8994. return viewCache;
  8995. }
  8996. else {
  8997. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  8998. const oldEventCache = viewCache.eventCache.getNode();
  8999. let newEventCache;
  9000. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9001. let newNode;
  9002. if (viewCache.serverCache.isFullyInitialized()) {
  9003. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9004. }
  9005. else {
  9006. const serverChildren = viewCache.serverCache.getNode();
  9007. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9008. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9009. }
  9010. newNode = newNode;
  9011. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9012. }
  9013. else {
  9014. const childKey = pathGetFront(path);
  9015. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9016. if (newChild == null &&
  9017. viewCache.serverCache.isCompleteForChild(childKey)) {
  9018. newChild = oldEventCache.getImmediateChild(childKey);
  9019. }
  9020. if (newChild != null) {
  9021. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9022. }
  9023. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9024. // No complete child available, delete the existing one, if any
  9025. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9026. }
  9027. else {
  9028. newEventCache = oldEventCache;
  9029. }
  9030. if (newEventCache.isEmpty() &&
  9031. viewCache.serverCache.isFullyInitialized()) {
  9032. // We might have reverted all child writes. Maybe the old event was a leaf node
  9033. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9034. if (complete.isLeafNode()) {
  9035. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9036. }
  9037. }
  9038. }
  9039. complete =
  9040. viewCache.serverCache.isFullyInitialized() ||
  9041. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9042. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9043. }
  9044. }
  9045. /**
  9046. * @license
  9047. * Copyright 2017 Google LLC
  9048. *
  9049. * Licensed under the Apache License, Version 2.0 (the "License");
  9050. * you may not use this file except in compliance with the License.
  9051. * You may obtain a copy of the License at
  9052. *
  9053. * http://www.apache.org/licenses/LICENSE-2.0
  9054. *
  9055. * Unless required by applicable law or agreed to in writing, software
  9056. * distributed under the License is distributed on an "AS IS" BASIS,
  9057. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9058. * See the License for the specific language governing permissions and
  9059. * limitations under the License.
  9060. */
  9061. /**
  9062. * A view represents a specific location and query that has 1 or more event registrations.
  9063. *
  9064. * It does several things:
  9065. * - Maintains the list of event registrations for this location/query.
  9066. * - Maintains a cache of the data visible for this location/query.
  9067. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9068. * registrations returns the set of events to be raised.
  9069. */
  9070. class View {
  9071. constructor(query_, initialViewCache) {
  9072. this.query_ = query_;
  9073. this.eventRegistrations_ = [];
  9074. const params = this.query_._queryParams;
  9075. const indexFilter = new IndexedFilter(params.getIndex());
  9076. const filter = queryParamsGetNodeFilter(params);
  9077. this.processor_ = newViewProcessor(filter);
  9078. const initialServerCache = initialViewCache.serverCache;
  9079. const initialEventCache = initialViewCache.eventCache;
  9080. // Don't filter server node with other filter than index, wait for tagged listen
  9081. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9082. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9083. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9084. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9085. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9086. this.eventGenerator_ = new EventGenerator(this.query_);
  9087. }
  9088. get query() {
  9089. return this.query_;
  9090. }
  9091. }
  9092. function viewGetServerCache(view) {
  9093. return view.viewCache_.serverCache.getNode();
  9094. }
  9095. function viewGetCompleteNode(view) {
  9096. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9097. }
  9098. function viewGetCompleteServerCache(view, path) {
  9099. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9100. if (cache) {
  9101. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9102. // we need to see if it contains the child we're interested in.
  9103. if (view.query._queryParams.loadsAllData() ||
  9104. (!pathIsEmpty(path) &&
  9105. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9106. return cache.getChild(path);
  9107. }
  9108. }
  9109. return null;
  9110. }
  9111. function viewIsEmpty(view) {
  9112. return view.eventRegistrations_.length === 0;
  9113. }
  9114. function viewAddEventRegistration(view, eventRegistration) {
  9115. view.eventRegistrations_.push(eventRegistration);
  9116. }
  9117. /**
  9118. * @param eventRegistration - If null, remove all callbacks.
  9119. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9120. * @returns Cancel events, if cancelError was provided.
  9121. */
  9122. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9123. const cancelEvents = [];
  9124. if (cancelError) {
  9125. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9126. const path = view.query._path;
  9127. view.eventRegistrations_.forEach(registration => {
  9128. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9129. if (maybeEvent) {
  9130. cancelEvents.push(maybeEvent);
  9131. }
  9132. });
  9133. }
  9134. if (eventRegistration) {
  9135. let remaining = [];
  9136. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9137. const existing = view.eventRegistrations_[i];
  9138. if (!existing.matches(eventRegistration)) {
  9139. remaining.push(existing);
  9140. }
  9141. else if (eventRegistration.hasAnyCallback()) {
  9142. // We're removing just this one
  9143. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9144. break;
  9145. }
  9146. }
  9147. view.eventRegistrations_ = remaining;
  9148. }
  9149. else {
  9150. view.eventRegistrations_ = [];
  9151. }
  9152. return cancelEvents;
  9153. }
  9154. /**
  9155. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9156. */
  9157. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9158. if (operation.type === OperationType.MERGE &&
  9159. operation.source.queryId !== null) {
  9160. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9161. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9162. }
  9163. const oldViewCache = view.viewCache_;
  9164. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9165. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9166. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  9167. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9168. view.viewCache_ = result.viewCache;
  9169. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9170. }
  9171. function viewGetInitialEvents(view, registration) {
  9172. const eventSnap = view.viewCache_.eventCache;
  9173. const initialChanges = [];
  9174. if (!eventSnap.getNode().isLeafNode()) {
  9175. const eventNode = eventSnap.getNode();
  9176. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9177. initialChanges.push(changeChildAdded(key, childNode));
  9178. });
  9179. }
  9180. if (eventSnap.isFullyInitialized()) {
  9181. initialChanges.push(changeValue(eventSnap.getNode()));
  9182. }
  9183. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9184. }
  9185. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9186. const registrations = eventRegistration
  9187. ? [eventRegistration]
  9188. : view.eventRegistrations_;
  9189. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9190. }
  9191. /**
  9192. * @license
  9193. * Copyright 2017 Google LLC
  9194. *
  9195. * Licensed under the Apache License, Version 2.0 (the "License");
  9196. * you may not use this file except in compliance with the License.
  9197. * You may obtain a copy of the License at
  9198. *
  9199. * http://www.apache.org/licenses/LICENSE-2.0
  9200. *
  9201. * Unless required by applicable law or agreed to in writing, software
  9202. * distributed under the License is distributed on an "AS IS" BASIS,
  9203. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9204. * See the License for the specific language governing permissions and
  9205. * limitations under the License.
  9206. */
  9207. let referenceConstructor$1;
  9208. /**
  9209. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9210. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9211. * and user writes (set, transaction, update).
  9212. *
  9213. * It's responsible for:
  9214. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9215. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9216. * applyUserOverwrite, etc.)
  9217. */
  9218. class SyncPoint {
  9219. constructor() {
  9220. /**
  9221. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9222. * queryId and the value is the View for that query.
  9223. *
  9224. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9225. */
  9226. this.views = new Map();
  9227. }
  9228. }
  9229. function syncPointSetReferenceConstructor(val) {
  9230. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9231. referenceConstructor$1 = val;
  9232. }
  9233. function syncPointGetReferenceConstructor() {
  9234. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9235. return referenceConstructor$1;
  9236. }
  9237. function syncPointIsEmpty(syncPoint) {
  9238. return syncPoint.views.size === 0;
  9239. }
  9240. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9241. const queryId = operation.source.queryId;
  9242. if (queryId !== null) {
  9243. const view = syncPoint.views.get(queryId);
  9244. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9245. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9246. }
  9247. else {
  9248. let events = [];
  9249. for (const view of syncPoint.views.values()) {
  9250. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9251. }
  9252. return events;
  9253. }
  9254. }
  9255. /**
  9256. * Get a view for the specified query.
  9257. *
  9258. * @param query - The query to return a view for
  9259. * @param writesCache
  9260. * @param serverCache
  9261. * @param serverCacheComplete
  9262. * @returns Events to raise.
  9263. */
  9264. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9265. const queryId = query._queryIdentifier;
  9266. const view = syncPoint.views.get(queryId);
  9267. if (!view) {
  9268. // TODO: make writesCache take flag for complete server node
  9269. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9270. let eventCacheComplete = false;
  9271. if (eventCache) {
  9272. eventCacheComplete = true;
  9273. }
  9274. else if (serverCache instanceof ChildrenNode) {
  9275. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9276. eventCacheComplete = false;
  9277. }
  9278. else {
  9279. eventCache = ChildrenNode.EMPTY_NODE;
  9280. eventCacheComplete = false;
  9281. }
  9282. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9283. return new View(query, viewCache);
  9284. }
  9285. return view;
  9286. }
  9287. /**
  9288. * Add an event callback for the specified query.
  9289. *
  9290. * @param query
  9291. * @param eventRegistration
  9292. * @param writesCache
  9293. * @param serverCache - Complete server cache, if we have it.
  9294. * @param serverCacheComplete
  9295. * @returns Events to raise.
  9296. */
  9297. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9298. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9299. if (!syncPoint.views.has(query._queryIdentifier)) {
  9300. syncPoint.views.set(query._queryIdentifier, view);
  9301. }
  9302. // This is guaranteed to exist now, we just created anything that was missing
  9303. viewAddEventRegistration(view, eventRegistration);
  9304. return viewGetInitialEvents(view, eventRegistration);
  9305. }
  9306. /**
  9307. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9308. *
  9309. * If query is the default query, we'll check all views for the specified eventRegistration.
  9310. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9311. *
  9312. * @param eventRegistration - If null, remove all callbacks.
  9313. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9314. * @returns removed queries and any cancel events
  9315. */
  9316. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9317. const queryId = query._queryIdentifier;
  9318. const removed = [];
  9319. let cancelEvents = [];
  9320. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9321. if (queryId === 'default') {
  9322. // When you do ref.off(...), we search all views for the registration to remove.
  9323. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9324. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9325. if (viewIsEmpty(view)) {
  9326. syncPoint.views.delete(viewQueryId);
  9327. // We'll deal with complete views later.
  9328. if (!view.query._queryParams.loadsAllData()) {
  9329. removed.push(view.query);
  9330. }
  9331. }
  9332. }
  9333. }
  9334. else {
  9335. // remove the callback from the specific view.
  9336. const view = syncPoint.views.get(queryId);
  9337. if (view) {
  9338. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9339. if (viewIsEmpty(view)) {
  9340. syncPoint.views.delete(queryId);
  9341. // We'll deal with complete views later.
  9342. if (!view.query._queryParams.loadsAllData()) {
  9343. removed.push(view.query);
  9344. }
  9345. }
  9346. }
  9347. }
  9348. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9349. // We removed our last complete view.
  9350. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9351. }
  9352. return { removed, events: cancelEvents };
  9353. }
  9354. function syncPointGetQueryViews(syncPoint) {
  9355. const result = [];
  9356. for (const view of syncPoint.views.values()) {
  9357. if (!view.query._queryParams.loadsAllData()) {
  9358. result.push(view);
  9359. }
  9360. }
  9361. return result;
  9362. }
  9363. /**
  9364. * @param path - The path to the desired complete snapshot
  9365. * @returns A complete cache, if it exists
  9366. */
  9367. function syncPointGetCompleteServerCache(syncPoint, path) {
  9368. let serverCache = null;
  9369. for (const view of syncPoint.views.values()) {
  9370. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9371. }
  9372. return serverCache;
  9373. }
  9374. function syncPointViewForQuery(syncPoint, query) {
  9375. const params = query._queryParams;
  9376. if (params.loadsAllData()) {
  9377. return syncPointGetCompleteView(syncPoint);
  9378. }
  9379. else {
  9380. const queryId = query._queryIdentifier;
  9381. return syncPoint.views.get(queryId);
  9382. }
  9383. }
  9384. function syncPointViewExistsForQuery(syncPoint, query) {
  9385. return syncPointViewForQuery(syncPoint, query) != null;
  9386. }
  9387. function syncPointHasCompleteView(syncPoint) {
  9388. return syncPointGetCompleteView(syncPoint) != null;
  9389. }
  9390. function syncPointGetCompleteView(syncPoint) {
  9391. for (const view of syncPoint.views.values()) {
  9392. if (view.query._queryParams.loadsAllData()) {
  9393. return view;
  9394. }
  9395. }
  9396. return null;
  9397. }
  9398. /**
  9399. * @license
  9400. * Copyright 2017 Google LLC
  9401. *
  9402. * Licensed under the Apache License, Version 2.0 (the "License");
  9403. * you may not use this file except in compliance with the License.
  9404. * You may obtain a copy of the License at
  9405. *
  9406. * http://www.apache.org/licenses/LICENSE-2.0
  9407. *
  9408. * Unless required by applicable law or agreed to in writing, software
  9409. * distributed under the License is distributed on an "AS IS" BASIS,
  9410. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9411. * See the License for the specific language governing permissions and
  9412. * limitations under the License.
  9413. */
  9414. let referenceConstructor;
  9415. function syncTreeSetReferenceConstructor(val) {
  9416. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9417. referenceConstructor = val;
  9418. }
  9419. function syncTreeGetReferenceConstructor() {
  9420. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  9421. return referenceConstructor;
  9422. }
  9423. /**
  9424. * Static tracker for next query tag.
  9425. */
  9426. let syncTreeNextQueryTag_ = 1;
  9427. /**
  9428. * SyncTree is the central class for managing event callback registration, data caching, views
  9429. * (query processing), and event generation. There are typically two SyncTree instances for
  9430. * each Repo, one for the normal Firebase data, and one for the .info data.
  9431. *
  9432. * It has a number of responsibilities, including:
  9433. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9434. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9435. * (applyUserOverwrite(), applyUserMerge()).
  9436. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9437. * applyServerMerge()).
  9438. * - Generating user-facing events for server and user changes (all of the apply* methods
  9439. * return the set of events that need to be raised as a result).
  9440. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9441. * to the correct set of paths and queries to satisfy the current set of user event
  9442. * callbacks (listens are started/stopped using the provided listenProvider).
  9443. *
  9444. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9445. * events are returned to the caller rather than raised synchronously.
  9446. *
  9447. */
  9448. class SyncTree {
  9449. /**
  9450. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9451. * to server data.
  9452. */
  9453. constructor(listenProvider_) {
  9454. this.listenProvider_ = listenProvider_;
  9455. /**
  9456. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9457. */
  9458. this.syncPointTree_ = new ImmutableTree(null);
  9459. /**
  9460. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9461. */
  9462. this.pendingWriteTree_ = newWriteTree();
  9463. this.tagToQueryMap = new Map();
  9464. this.queryToTagMap = new Map();
  9465. }
  9466. }
  9467. /**
  9468. * Apply the data changes for a user-generated set() or transaction() call.
  9469. *
  9470. * @returns Events to raise.
  9471. */
  9472. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9473. // Record pending write.
  9474. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9475. if (!visible) {
  9476. return [];
  9477. }
  9478. else {
  9479. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9480. }
  9481. }
  9482. /**
  9483. * Apply the data from a user-generated update() call
  9484. *
  9485. * @returns Events to raise.
  9486. */
  9487. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9488. // Record pending merge.
  9489. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9490. const changeTree = ImmutableTree.fromObject(changedChildren);
  9491. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9492. }
  9493. /**
  9494. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9495. *
  9496. * @param revert - True if the given write failed and needs to be reverted
  9497. * @returns Events to raise.
  9498. */
  9499. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9500. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9501. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9502. if (!needToReevaluate) {
  9503. return [];
  9504. }
  9505. else {
  9506. let affectedTree = new ImmutableTree(null);
  9507. if (write.snap != null) {
  9508. // overwrite
  9509. affectedTree = affectedTree.set(newEmptyPath(), true);
  9510. }
  9511. else {
  9512. each(write.children, (pathString) => {
  9513. affectedTree = affectedTree.set(new Path(pathString), true);
  9514. });
  9515. }
  9516. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9517. }
  9518. }
  9519. /**
  9520. * Apply new server data for the specified path..
  9521. *
  9522. * @returns Events to raise.
  9523. */
  9524. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9525. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9526. }
  9527. /**
  9528. * Apply new server data to be merged in at the specified path.
  9529. *
  9530. * @returns Events to raise.
  9531. */
  9532. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9533. const changeTree = ImmutableTree.fromObject(changedChildren);
  9534. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9535. }
  9536. /**
  9537. * Apply a listen complete for a query
  9538. *
  9539. * @returns Events to raise.
  9540. */
  9541. function syncTreeApplyListenComplete(syncTree, path) {
  9542. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9543. }
  9544. /**
  9545. * Apply a listen complete for a tagged query
  9546. *
  9547. * @returns Events to raise.
  9548. */
  9549. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9550. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9551. if (queryKey) {
  9552. const r = syncTreeParseQueryKey_(queryKey);
  9553. const queryPath = r.path, queryId = r.queryId;
  9554. const relativePath = newRelativePath(queryPath, path);
  9555. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9556. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9557. }
  9558. else {
  9559. // We've already removed the query. No big deal, ignore the update
  9560. return [];
  9561. }
  9562. }
  9563. /**
  9564. * Remove event callback(s).
  9565. *
  9566. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9567. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9568. *
  9569. * @param eventRegistration - If null, all callbacks are removed.
  9570. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9571. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9572. * deduping needs to take place. This flag allows toggling of that behavior
  9573. * @returns Cancel events, if cancelError was provided.
  9574. */
  9575. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9576. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9577. const path = query._path;
  9578. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9579. let cancelEvents = [];
  9580. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9581. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9582. // not loadsAllData().
  9583. if (maybeSyncPoint &&
  9584. (query._queryIdentifier === 'default' ||
  9585. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9586. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9587. if (syncPointIsEmpty(maybeSyncPoint)) {
  9588. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9589. }
  9590. const removed = removedAndEvents.removed;
  9591. cancelEvents = removedAndEvents.events;
  9592. if (!skipListenerDedup) {
  9593. /**
  9594. * We may have just removed one of many listeners and can short-circuit this whole process
  9595. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9596. * properly set up.
  9597. */
  9598. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9599. // queryId === 'default'
  9600. const removingDefault = -1 !==
  9601. removed.findIndex(query => {
  9602. return query._queryParams.loadsAllData();
  9603. });
  9604. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9605. if (removingDefault && !covered) {
  9606. const subtree = syncTree.syncPointTree_.subtree(path);
  9607. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9608. // removal
  9609. if (!subtree.isEmpty()) {
  9610. // We need to fold over our subtree and collect the listeners to send
  9611. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9612. // Ok, we've collected all the listens we need. Set them up.
  9613. for (let i = 0; i < newViews.length; ++i) {
  9614. const view = newViews[i], newQuery = view.query;
  9615. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9616. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9617. }
  9618. }
  9619. // Otherwise there's nothing below us, so nothing we need to start listening on
  9620. }
  9621. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9622. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9623. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9624. if (!covered && removed.length > 0 && !cancelError) {
  9625. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9626. // default. Otherwise, we need to iterate through and cancel each individual query
  9627. if (removingDefault) {
  9628. // We don't tag default listeners
  9629. const defaultTag = null;
  9630. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9631. }
  9632. else {
  9633. removed.forEach((queryToRemove) => {
  9634. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9635. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9636. });
  9637. }
  9638. }
  9639. }
  9640. // Now, clear all of the tags we're tracking for the removed listens
  9641. syncTreeRemoveTags_(syncTree, removed);
  9642. }
  9643. return cancelEvents;
  9644. }
  9645. /**
  9646. * Apply new server data for the specified tagged query.
  9647. *
  9648. * @returns Events to raise.
  9649. */
  9650. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9651. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9652. if (queryKey != null) {
  9653. const r = syncTreeParseQueryKey_(queryKey);
  9654. const queryPath = r.path, queryId = r.queryId;
  9655. const relativePath = newRelativePath(queryPath, path);
  9656. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9657. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9658. }
  9659. else {
  9660. // Query must have been removed already
  9661. return [];
  9662. }
  9663. }
  9664. /**
  9665. * Apply server data to be merged in for the specified tagged query.
  9666. *
  9667. * @returns Events to raise.
  9668. */
  9669. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9670. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9671. if (queryKey) {
  9672. const r = syncTreeParseQueryKey_(queryKey);
  9673. const queryPath = r.path, queryId = r.queryId;
  9674. const relativePath = newRelativePath(queryPath, path);
  9675. const changeTree = ImmutableTree.fromObject(changedChildren);
  9676. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9677. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9678. }
  9679. else {
  9680. // We've already removed the query. No big deal, ignore the update
  9681. return [];
  9682. }
  9683. }
  9684. /**
  9685. * Add an event callback for the specified query.
  9686. *
  9687. * @returns Events to raise.
  9688. */
  9689. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9690. const path = query._path;
  9691. let serverCache = null;
  9692. let foundAncestorDefaultView = false;
  9693. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9694. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9695. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9696. const relativePath = newRelativePath(pathToSyncPoint, path);
  9697. serverCache =
  9698. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9699. foundAncestorDefaultView =
  9700. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9701. });
  9702. let syncPoint = syncTree.syncPointTree_.get(path);
  9703. if (!syncPoint) {
  9704. syncPoint = new SyncPoint();
  9705. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9706. }
  9707. else {
  9708. foundAncestorDefaultView =
  9709. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9710. serverCache =
  9711. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9712. }
  9713. let serverCacheComplete;
  9714. if (serverCache != null) {
  9715. serverCacheComplete = true;
  9716. }
  9717. else {
  9718. serverCacheComplete = false;
  9719. serverCache = ChildrenNode.EMPTY_NODE;
  9720. const subtree = syncTree.syncPointTree_.subtree(path);
  9721. subtree.foreachChild((childName, childSyncPoint) => {
  9722. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9723. if (completeCache) {
  9724. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9725. }
  9726. });
  9727. }
  9728. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9729. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9730. // We need to track a tag for this query
  9731. const queryKey = syncTreeMakeQueryKey_(query);
  9732. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9733. const tag = syncTreeGetNextQueryTag_();
  9734. syncTree.queryToTagMap.set(queryKey, tag);
  9735. syncTree.tagToQueryMap.set(tag, queryKey);
  9736. }
  9737. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9738. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9739. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9740. const view = syncPointViewForQuery(syncPoint, query);
  9741. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9742. }
  9743. return events;
  9744. }
  9745. /**
  9746. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9747. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9748. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9749. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9750. *
  9751. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9752. *
  9753. * @param path - The path to the data we want
  9754. * @param writeIdsToExclude - A specific set to be excluded
  9755. */
  9756. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9757. const includeHiddenSets = true;
  9758. const writeTree = syncTree.pendingWriteTree_;
  9759. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9760. const relativePath = newRelativePath(pathSoFar, path);
  9761. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9762. if (serverCache) {
  9763. return serverCache;
  9764. }
  9765. });
  9766. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9767. }
  9768. function syncTreeGetServerValue(syncTree, query) {
  9769. const path = query._path;
  9770. let serverCache = null;
  9771. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9772. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9773. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9774. const relativePath = newRelativePath(pathToSyncPoint, path);
  9775. serverCache =
  9776. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9777. });
  9778. let syncPoint = syncTree.syncPointTree_.get(path);
  9779. if (!syncPoint) {
  9780. syncPoint = new SyncPoint();
  9781. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9782. }
  9783. else {
  9784. serverCache =
  9785. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9786. }
  9787. const serverCacheComplete = serverCache != null;
  9788. const serverCacheNode = serverCacheComplete
  9789. ? new CacheNode(serverCache, true, false)
  9790. : null;
  9791. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9792. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9793. return viewGetCompleteNode(view);
  9794. }
  9795. /**
  9796. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9797. *
  9798. * NOTES:
  9799. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9800. *
  9801. * - We call applyOperation() on each SyncPoint passing three things:
  9802. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9803. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9804. * 3. A snapshot Node with cached server data, if we have it.
  9805. *
  9806. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9807. */
  9808. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9809. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9810. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9811. }
  9812. /**
  9813. * Recursive helper for applyOperationToSyncPoints_
  9814. */
  9815. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9816. if (pathIsEmpty(operation.path)) {
  9817. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9818. }
  9819. else {
  9820. const syncPoint = syncPointTree.get(newEmptyPath());
  9821. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9822. if (serverCache == null && syncPoint != null) {
  9823. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9824. }
  9825. let events = [];
  9826. const childName = pathGetFront(operation.path);
  9827. const childOperation = operation.operationForChild(childName);
  9828. const childTree = syncPointTree.children.get(childName);
  9829. if (childTree && childOperation) {
  9830. const childServerCache = serverCache
  9831. ? serverCache.getImmediateChild(childName)
  9832. : null;
  9833. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9834. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9835. }
  9836. if (syncPoint) {
  9837. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9838. }
  9839. return events;
  9840. }
  9841. }
  9842. /**
  9843. * Recursive helper for applyOperationToSyncPoints_
  9844. */
  9845. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9846. const syncPoint = syncPointTree.get(newEmptyPath());
  9847. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9848. if (serverCache == null && syncPoint != null) {
  9849. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9850. }
  9851. let events = [];
  9852. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9853. const childServerCache = serverCache
  9854. ? serverCache.getImmediateChild(childName)
  9855. : null;
  9856. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9857. const childOperation = operation.operationForChild(childName);
  9858. if (childOperation) {
  9859. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9860. }
  9861. });
  9862. if (syncPoint) {
  9863. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9864. }
  9865. return events;
  9866. }
  9867. function syncTreeCreateListenerForView_(syncTree, view) {
  9868. const query = view.query;
  9869. const tag = syncTreeTagForQuery(syncTree, query);
  9870. return {
  9871. hashFn: () => {
  9872. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9873. return cache.hash();
  9874. },
  9875. onComplete: (status) => {
  9876. if (status === 'ok') {
  9877. if (tag) {
  9878. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9879. }
  9880. else {
  9881. return syncTreeApplyListenComplete(syncTree, query._path);
  9882. }
  9883. }
  9884. else {
  9885. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9886. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9887. const error = errorForServerCode(status, query);
  9888. return syncTreeRemoveEventRegistration(syncTree, query,
  9889. /*eventRegistration*/ null, error);
  9890. }
  9891. }
  9892. };
  9893. }
  9894. /**
  9895. * Return the tag associated with the given query.
  9896. */
  9897. function syncTreeTagForQuery(syncTree, query) {
  9898. const queryKey = syncTreeMakeQueryKey_(query);
  9899. return syncTree.queryToTagMap.get(queryKey);
  9900. }
  9901. /**
  9902. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9903. */
  9904. function syncTreeMakeQueryKey_(query) {
  9905. return query._path.toString() + '$' + query._queryIdentifier;
  9906. }
  9907. /**
  9908. * Return the query associated with the given tag, if we have one
  9909. */
  9910. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9911. return syncTree.tagToQueryMap.get(tag);
  9912. }
  9913. /**
  9914. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9915. */
  9916. function syncTreeParseQueryKey_(queryKey) {
  9917. const splitIndex = queryKey.indexOf('$');
  9918. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9919. return {
  9920. queryId: queryKey.substr(splitIndex + 1),
  9921. path: new Path(queryKey.substr(0, splitIndex))
  9922. };
  9923. }
  9924. /**
  9925. * A helper method to apply tagged operations
  9926. */
  9927. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9928. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9929. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9930. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9931. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9932. }
  9933. /**
  9934. * This collapses multiple unfiltered views into a single view, since we only need a single
  9935. * listener for them.
  9936. */
  9937. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9938. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9939. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9940. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9941. return [completeView];
  9942. }
  9943. else {
  9944. // No complete view here, flatten any deeper listens into an array
  9945. let views = [];
  9946. if (maybeChildSyncPoint) {
  9947. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9948. }
  9949. each(childMap, (_key, childViews) => {
  9950. views = views.concat(childViews);
  9951. });
  9952. return views;
  9953. }
  9954. });
  9955. }
  9956. /**
  9957. * Normalizes a query to a query we send the server for listening
  9958. *
  9959. * @returns The normalized query
  9960. */
  9961. function syncTreeQueryForListening_(query) {
  9962. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9963. // We treat queries that load all data as default queries
  9964. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9965. // from Query
  9966. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9967. }
  9968. else {
  9969. return query;
  9970. }
  9971. }
  9972. function syncTreeRemoveTags_(syncTree, queries) {
  9973. for (let j = 0; j < queries.length; ++j) {
  9974. const removedQuery = queries[j];
  9975. if (!removedQuery._queryParams.loadsAllData()) {
  9976. // We should have a tag for this
  9977. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9978. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9979. syncTree.queryToTagMap.delete(removedQueryKey);
  9980. syncTree.tagToQueryMap.delete(removedQueryTag);
  9981. }
  9982. }
  9983. }
  9984. /**
  9985. * Static accessor for query tags.
  9986. */
  9987. function syncTreeGetNextQueryTag_() {
  9988. return syncTreeNextQueryTag_++;
  9989. }
  9990. /**
  9991. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9992. *
  9993. * @returns This method can return events to support synchronous data sources
  9994. */
  9995. function syncTreeSetupListener_(syncTree, query, view) {
  9996. const path = query._path;
  9997. const tag = syncTreeTagForQuery(syncTree, query);
  9998. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9999. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10000. const subtree = syncTree.syncPointTree_.subtree(path);
  10001. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10002. // may need to shadow other listens as well.
  10003. if (tag) {
  10004. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10005. }
  10006. else {
  10007. // Shadow everything at or below this location, this is a default listener.
  10008. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  10009. if (!pathIsEmpty(relativePath) &&
  10010. maybeChildSyncPoint &&
  10011. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10012. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10013. }
  10014. else {
  10015. // No default listener here, flatten any deeper queries into an array
  10016. let queries = [];
  10017. if (maybeChildSyncPoint) {
  10018. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10019. }
  10020. each(childMap, (_key, childQueries) => {
  10021. queries = queries.concat(childQueries);
  10022. });
  10023. return queries;
  10024. }
  10025. });
  10026. for (let i = 0; i < queriesToStop.length; ++i) {
  10027. const queryToStop = queriesToStop[i];
  10028. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10029. }
  10030. }
  10031. return events;
  10032. }
  10033. /**
  10034. * @license
  10035. * Copyright 2017 Google LLC
  10036. *
  10037. * Licensed under the Apache License, Version 2.0 (the "License");
  10038. * you may not use this file except in compliance with the License.
  10039. * You may obtain a copy of the License at
  10040. *
  10041. * http://www.apache.org/licenses/LICENSE-2.0
  10042. *
  10043. * Unless required by applicable law or agreed to in writing, software
  10044. * distributed under the License is distributed on an "AS IS" BASIS,
  10045. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10046. * See the License for the specific language governing permissions and
  10047. * limitations under the License.
  10048. */
  10049. class ExistingValueProvider {
  10050. constructor(node_) {
  10051. this.node_ = node_;
  10052. }
  10053. getImmediateChild(childName) {
  10054. const child = this.node_.getImmediateChild(childName);
  10055. return new ExistingValueProvider(child);
  10056. }
  10057. node() {
  10058. return this.node_;
  10059. }
  10060. }
  10061. class DeferredValueProvider {
  10062. constructor(syncTree, path) {
  10063. this.syncTree_ = syncTree;
  10064. this.path_ = path;
  10065. }
  10066. getImmediateChild(childName) {
  10067. const childPath = pathChild(this.path_, childName);
  10068. return new DeferredValueProvider(this.syncTree_, childPath);
  10069. }
  10070. node() {
  10071. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10072. }
  10073. }
  10074. /**
  10075. * Generate placeholders for deferred values.
  10076. */
  10077. const generateWithValues = function (values) {
  10078. values = values || {};
  10079. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10080. return values;
  10081. };
  10082. /**
  10083. * Value to use when firing local events. When writing server values, fire
  10084. * local events with an approximate value, otherwise return value as-is.
  10085. */
  10086. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10087. if (!value || typeof value !== 'object') {
  10088. return value;
  10089. }
  10090. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10091. if (typeof value['.sv'] === 'string') {
  10092. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10093. }
  10094. else if (typeof value['.sv'] === 'object') {
  10095. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10096. }
  10097. else {
  10098. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10099. }
  10100. };
  10101. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10102. switch (op) {
  10103. case 'timestamp':
  10104. return serverValues['timestamp'];
  10105. default:
  10106. util.assert(false, 'Unexpected server value: ' + op);
  10107. }
  10108. };
  10109. const resolveComplexDeferredValue = function (op, existing, unused) {
  10110. if (!op.hasOwnProperty('increment')) {
  10111. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10112. }
  10113. const delta = op['increment'];
  10114. if (typeof delta !== 'number') {
  10115. util.assert(false, 'Unexpected increment value: ' + delta);
  10116. }
  10117. const existingNode = existing.node();
  10118. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10119. // Incrementing a non-number sets the value to the incremented amount
  10120. if (!existingNode.isLeafNode()) {
  10121. return delta;
  10122. }
  10123. const leaf = existingNode;
  10124. const existingVal = leaf.getValue();
  10125. if (typeof existingVal !== 'number') {
  10126. return delta;
  10127. }
  10128. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10129. return existingVal + delta;
  10130. };
  10131. /**
  10132. * Recursively replace all deferred values and priorities in the tree with the
  10133. * specified generated replacement values.
  10134. * @param path - path to which write is relative
  10135. * @param node - new data written at path
  10136. * @param syncTree - current data
  10137. */
  10138. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10139. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10140. };
  10141. /**
  10142. * Recursively replace all deferred values and priorities in the node with the
  10143. * specified generated replacement values. If there are no server values in the node,
  10144. * it'll be returned as-is.
  10145. */
  10146. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10147. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10148. };
  10149. function resolveDeferredValue(node, existingVal, serverValues) {
  10150. const rawPri = node.getPriority().val();
  10151. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10152. let newNode;
  10153. if (node.isLeafNode()) {
  10154. const leafNode = node;
  10155. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10156. if (value !== leafNode.getValue() ||
  10157. priority !== leafNode.getPriority().val()) {
  10158. return new LeafNode(value, nodeFromJSON(priority));
  10159. }
  10160. else {
  10161. return node;
  10162. }
  10163. }
  10164. else {
  10165. const childrenNode = node;
  10166. newNode = childrenNode;
  10167. if (priority !== childrenNode.getPriority().val()) {
  10168. newNode = newNode.updatePriority(new LeafNode(priority));
  10169. }
  10170. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10171. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10172. if (newChildNode !== childNode) {
  10173. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10174. }
  10175. });
  10176. return newNode;
  10177. }
  10178. }
  10179. /**
  10180. * @license
  10181. * Copyright 2017 Google LLC
  10182. *
  10183. * Licensed under the Apache License, Version 2.0 (the "License");
  10184. * you may not use this file except in compliance with the License.
  10185. * You may obtain a copy of the License at
  10186. *
  10187. * http://www.apache.org/licenses/LICENSE-2.0
  10188. *
  10189. * Unless required by applicable law or agreed to in writing, software
  10190. * distributed under the License is distributed on an "AS IS" BASIS,
  10191. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10192. * See the License for the specific language governing permissions and
  10193. * limitations under the License.
  10194. */
  10195. /**
  10196. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10197. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10198. * children.
  10199. */
  10200. class Tree {
  10201. /**
  10202. * @param name - Optional name of the node.
  10203. * @param parent - Optional parent node.
  10204. * @param node - Optional node to wrap.
  10205. */
  10206. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10207. this.name = name;
  10208. this.parent = parent;
  10209. this.node = node;
  10210. }
  10211. }
  10212. /**
  10213. * Returns a sub-Tree for the given path.
  10214. *
  10215. * @param pathObj - Path to look up.
  10216. * @returns Tree for path.
  10217. */
  10218. function treeSubTree(tree, pathObj) {
  10219. // TODO: Require pathObj to be Path?
  10220. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10221. let child = tree, next = pathGetFront(path);
  10222. while (next !== null) {
  10223. const childNode = util.safeGet(child.node.children, next) || {
  10224. children: {},
  10225. childCount: 0
  10226. };
  10227. child = new Tree(next, child, childNode);
  10228. path = pathPopFront(path);
  10229. next = pathGetFront(path);
  10230. }
  10231. return child;
  10232. }
  10233. /**
  10234. * Returns the data associated with this tree node.
  10235. *
  10236. * @returns The data or null if no data exists.
  10237. */
  10238. function treeGetValue(tree) {
  10239. return tree.node.value;
  10240. }
  10241. /**
  10242. * Sets data to this tree node.
  10243. *
  10244. * @param value - Value to set.
  10245. */
  10246. function treeSetValue(tree, value) {
  10247. tree.node.value = value;
  10248. treeUpdateParents(tree);
  10249. }
  10250. /**
  10251. * @returns Whether the tree has any children.
  10252. */
  10253. function treeHasChildren(tree) {
  10254. return tree.node.childCount > 0;
  10255. }
  10256. /**
  10257. * @returns Whether the tree is empty (no value or children).
  10258. */
  10259. function treeIsEmpty(tree) {
  10260. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10261. }
  10262. /**
  10263. * Calls action for each child of this tree node.
  10264. *
  10265. * @param action - Action to be called for each child.
  10266. */
  10267. function treeForEachChild(tree, action) {
  10268. each(tree.node.children, (child, childTree) => {
  10269. action(new Tree(child, tree, childTree));
  10270. });
  10271. }
  10272. /**
  10273. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10274. *
  10275. * @param action - Action to be called for each child.
  10276. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10277. * false.
  10278. * @param childrenFirst - Whether to call action on children before calling it on
  10279. * parent.
  10280. */
  10281. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10282. if (includeSelf && !childrenFirst) {
  10283. action(tree);
  10284. }
  10285. treeForEachChild(tree, child => {
  10286. treeForEachDescendant(child, action, true, childrenFirst);
  10287. });
  10288. if (includeSelf && childrenFirst) {
  10289. action(tree);
  10290. }
  10291. }
  10292. /**
  10293. * Calls action on each ancestor node.
  10294. *
  10295. * @param action - Action to be called on each parent; return
  10296. * true to abort.
  10297. * @param includeSelf - Whether to call action on this node as well.
  10298. * @returns true if the action callback returned true.
  10299. */
  10300. function treeForEachAncestor(tree, action, includeSelf) {
  10301. let node = includeSelf ? tree : tree.parent;
  10302. while (node !== null) {
  10303. if (action(node)) {
  10304. return true;
  10305. }
  10306. node = node.parent;
  10307. }
  10308. return false;
  10309. }
  10310. /**
  10311. * @returns The path of this tree node, as a Path.
  10312. */
  10313. function treeGetPath(tree) {
  10314. return new Path(tree.parent === null
  10315. ? tree.name
  10316. : treeGetPath(tree.parent) + '/' + tree.name);
  10317. }
  10318. /**
  10319. * Adds or removes this child from its parent based on whether it's empty or not.
  10320. */
  10321. function treeUpdateParents(tree) {
  10322. if (tree.parent !== null) {
  10323. treeUpdateChild(tree.parent, tree.name, tree);
  10324. }
  10325. }
  10326. /**
  10327. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10328. *
  10329. * @param childName - The name of the child to update.
  10330. * @param child - The child to update.
  10331. */
  10332. function treeUpdateChild(tree, childName, child) {
  10333. const childEmpty = treeIsEmpty(child);
  10334. const childExists = util.contains(tree.node.children, childName);
  10335. if (childEmpty && childExists) {
  10336. delete tree.node.children[childName];
  10337. tree.node.childCount--;
  10338. treeUpdateParents(tree);
  10339. }
  10340. else if (!childEmpty && !childExists) {
  10341. tree.node.children[childName] = child.node;
  10342. tree.node.childCount++;
  10343. treeUpdateParents(tree);
  10344. }
  10345. }
  10346. /**
  10347. * @license
  10348. * Copyright 2017 Google LLC
  10349. *
  10350. * Licensed under the Apache License, Version 2.0 (the "License");
  10351. * you may not use this file except in compliance with the License.
  10352. * You may obtain a copy of the License at
  10353. *
  10354. * http://www.apache.org/licenses/LICENSE-2.0
  10355. *
  10356. * Unless required by applicable law or agreed to in writing, software
  10357. * distributed under the License is distributed on an "AS IS" BASIS,
  10358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10359. * See the License for the specific language governing permissions and
  10360. * limitations under the License.
  10361. */
  10362. /**
  10363. * True for invalid Firebase keys
  10364. */
  10365. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10366. /**
  10367. * True for invalid Firebase paths.
  10368. * Allows '/' in paths.
  10369. */
  10370. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10371. /**
  10372. * Maximum number of characters to allow in leaf value
  10373. */
  10374. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10375. const isValidKey = function (key) {
  10376. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10377. };
  10378. const isValidPathString = function (pathString) {
  10379. return (typeof pathString === 'string' &&
  10380. pathString.length !== 0 &&
  10381. !INVALID_PATH_REGEX_.test(pathString));
  10382. };
  10383. const isValidRootPathString = function (pathString) {
  10384. if (pathString) {
  10385. // Allow '/.info/' at the beginning.
  10386. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10387. }
  10388. return isValidPathString(pathString);
  10389. };
  10390. const isValidPriority = function (priority) {
  10391. return (priority === null ||
  10392. typeof priority === 'string' ||
  10393. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10394. (priority &&
  10395. typeof priority === 'object' &&
  10396. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10397. util.contains(priority, '.sv')));
  10398. };
  10399. /**
  10400. * Pre-validate a datum passed as an argument to Firebase function.
  10401. */
  10402. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10403. if (optional && value === undefined) {
  10404. return;
  10405. }
  10406. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  10407. };
  10408. /**
  10409. * Validate a data object client-side before sending to server.
  10410. */
  10411. const validateFirebaseData = function (errorPrefix, data, path_) {
  10412. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10413. if (data === undefined) {
  10414. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10415. }
  10416. if (typeof data === 'function') {
  10417. throw new Error(errorPrefix +
  10418. 'contains a function ' +
  10419. validationPathToErrorString(path) +
  10420. ' with contents = ' +
  10421. data.toString());
  10422. }
  10423. if (isInvalidJSONNumber(data)) {
  10424. throw new Error(errorPrefix +
  10425. 'contains ' +
  10426. data.toString() +
  10427. ' ' +
  10428. validationPathToErrorString(path));
  10429. }
  10430. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10431. if (typeof data === 'string' &&
  10432. data.length > MAX_LEAF_SIZE_ / 3 &&
  10433. util.stringLength(data) > MAX_LEAF_SIZE_) {
  10434. throw new Error(errorPrefix +
  10435. 'contains a string greater than ' +
  10436. MAX_LEAF_SIZE_ +
  10437. ' utf8 bytes ' +
  10438. validationPathToErrorString(path) +
  10439. " ('" +
  10440. data.substring(0, 50) +
  10441. "...')");
  10442. }
  10443. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10444. // to save extra walking of large objects.
  10445. if (data && typeof data === 'object') {
  10446. let hasDotValue = false;
  10447. let hasActualChild = false;
  10448. each(data, (key, value) => {
  10449. if (key === '.value') {
  10450. hasDotValue = true;
  10451. }
  10452. else if (key !== '.priority' && key !== '.sv') {
  10453. hasActualChild = true;
  10454. if (!isValidKey(key)) {
  10455. throw new Error(errorPrefix +
  10456. ' contains an invalid key (' +
  10457. key +
  10458. ') ' +
  10459. validationPathToErrorString(path) +
  10460. '. Keys must be non-empty strings ' +
  10461. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10462. }
  10463. }
  10464. validationPathPush(path, key);
  10465. validateFirebaseData(errorPrefix, value, path);
  10466. validationPathPop(path);
  10467. });
  10468. if (hasDotValue && hasActualChild) {
  10469. throw new Error(errorPrefix +
  10470. ' contains ".value" child ' +
  10471. validationPathToErrorString(path) +
  10472. ' in addition to actual children.');
  10473. }
  10474. }
  10475. };
  10476. /**
  10477. * Pre-validate paths passed in the firebase function.
  10478. */
  10479. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10480. let i, curPath;
  10481. for (i = 0; i < mergePaths.length; i++) {
  10482. curPath = mergePaths[i];
  10483. const keys = pathSlice(curPath);
  10484. for (let j = 0; j < keys.length; j++) {
  10485. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10486. else if (!isValidKey(keys[j])) {
  10487. throw new Error(errorPrefix +
  10488. 'contains an invalid key (' +
  10489. keys[j] +
  10490. ') in path ' +
  10491. curPath.toString() +
  10492. '. Keys must be non-empty strings ' +
  10493. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10494. }
  10495. }
  10496. }
  10497. // Check that update keys are not descendants of each other.
  10498. // We rely on the property that sorting guarantees that ancestors come
  10499. // right before descendants.
  10500. mergePaths.sort(pathCompare);
  10501. let prevPath = null;
  10502. for (i = 0; i < mergePaths.length; i++) {
  10503. curPath = mergePaths[i];
  10504. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10505. throw new Error(errorPrefix +
  10506. 'contains a path ' +
  10507. prevPath.toString() +
  10508. ' that is ancestor of another path ' +
  10509. curPath.toString());
  10510. }
  10511. prevPath = curPath;
  10512. }
  10513. };
  10514. /**
  10515. * pre-validate an object passed as an argument to firebase function (
  10516. * must be an object - e.g. for firebase.update()).
  10517. */
  10518. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10519. if (optional && data === undefined) {
  10520. return;
  10521. }
  10522. const errorPrefix = util.errorPrefix(fnName, 'values');
  10523. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10524. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  10525. }
  10526. const mergePaths = [];
  10527. each(data, (key, value) => {
  10528. const curPath = new Path(key);
  10529. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  10530. if (pathGetBack(curPath) === '.priority') {
  10531. if (!isValidPriority(value)) {
  10532. throw new Error(errorPrefix +
  10533. "contains an invalid value for '" +
  10534. curPath.toString() +
  10535. "', which must be a valid " +
  10536. 'Firebase priority (a string, finite number, server value, or null).');
  10537. }
  10538. }
  10539. mergePaths.push(curPath);
  10540. });
  10541. validateFirebaseMergePaths(errorPrefix, mergePaths);
  10542. };
  10543. const validatePriority = function (fnName, priority, optional) {
  10544. if (optional && priority === undefined) {
  10545. return;
  10546. }
  10547. if (isInvalidJSONNumber(priority)) {
  10548. throw new Error(util.errorPrefix(fnName, 'priority') +
  10549. 'is ' +
  10550. priority.toString() +
  10551. ', but must be a valid Firebase priority (a string, finite number, ' +
  10552. 'server value, or null).');
  10553. }
  10554. // Special case to allow importing data with a .sv.
  10555. if (!isValidPriority(priority)) {
  10556. throw new Error(util.errorPrefix(fnName, 'priority') +
  10557. 'must be a valid Firebase priority ' +
  10558. '(a string, finite number, server value, or null).');
  10559. }
  10560. };
  10561. const validateKey = function (fnName, argumentName, key, optional) {
  10562. if (optional && key === undefined) {
  10563. return;
  10564. }
  10565. if (!isValidKey(key)) {
  10566. throw new Error(util.errorPrefix(fnName, argumentName) +
  10567. 'was an invalid key = "' +
  10568. key +
  10569. '". Firebase keys must be non-empty strings and ' +
  10570. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10571. }
  10572. };
  10573. /**
  10574. * @internal
  10575. */
  10576. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10577. if (optional && pathString === undefined) {
  10578. return;
  10579. }
  10580. if (!isValidPathString(pathString)) {
  10581. throw new Error(util.errorPrefix(fnName, argumentName) +
  10582. 'was an invalid path = "' +
  10583. pathString +
  10584. '". Paths must be non-empty strings and ' +
  10585. 'can\'t contain ".", "#", "$", "[", or "]"');
  10586. }
  10587. };
  10588. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10589. if (pathString) {
  10590. // Allow '/.info/' at the beginning.
  10591. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10592. }
  10593. validatePathString(fnName, argumentName, pathString, optional);
  10594. };
  10595. /**
  10596. * @internal
  10597. */
  10598. const validateWritablePath = function (fnName, path) {
  10599. if (pathGetFront(path) === '.info') {
  10600. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10601. }
  10602. };
  10603. const validateUrl = function (fnName, parsedUrl) {
  10604. // TODO = Validate server better.
  10605. const pathString = parsedUrl.path.toString();
  10606. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10607. parsedUrl.repoInfo.host.length === 0 ||
  10608. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10609. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10610. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10611. throw new Error(util.errorPrefix(fnName, 'url') +
  10612. 'must be a valid firebase URL and ' +
  10613. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10614. }
  10615. };
  10616. /**
  10617. * @license
  10618. * Copyright 2017 Google LLC
  10619. *
  10620. * Licensed under the Apache License, Version 2.0 (the "License");
  10621. * you may not use this file except in compliance with the License.
  10622. * You may obtain a copy of the License at
  10623. *
  10624. * http://www.apache.org/licenses/LICENSE-2.0
  10625. *
  10626. * Unless required by applicable law or agreed to in writing, software
  10627. * distributed under the License is distributed on an "AS IS" BASIS,
  10628. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10629. * See the License for the specific language governing permissions and
  10630. * limitations under the License.
  10631. */
  10632. /**
  10633. * The event queue serves a few purposes:
  10634. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10635. * events being queued.
  10636. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10637. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10638. * left off, ensuring that the events are still raised synchronously and in order.
  10639. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10640. * events are raised synchronously.
  10641. *
  10642. * NOTE: This can all go away if/when we move to async events.
  10643. *
  10644. */
  10645. class EventQueue {
  10646. constructor() {
  10647. this.eventLists_ = [];
  10648. /**
  10649. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10650. */
  10651. this.recursionDepth_ = 0;
  10652. }
  10653. }
  10654. /**
  10655. * @param eventDataList - The new events to queue.
  10656. */
  10657. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10658. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10659. let currList = null;
  10660. for (let i = 0; i < eventDataList.length; i++) {
  10661. const data = eventDataList[i];
  10662. const path = data.getPath();
  10663. if (currList !== null && !pathEquals(path, currList.path)) {
  10664. eventQueue.eventLists_.push(currList);
  10665. currList = null;
  10666. }
  10667. if (currList === null) {
  10668. currList = { events: [], path };
  10669. }
  10670. currList.events.push(data);
  10671. }
  10672. if (currList) {
  10673. eventQueue.eventLists_.push(currList);
  10674. }
  10675. }
  10676. /**
  10677. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10678. * for the specified path.
  10679. *
  10680. * It is assumed that the new events are all for the specified path.
  10681. *
  10682. * @param path - The path to raise events for.
  10683. * @param eventDataList - The new events to raise.
  10684. */
  10685. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10686. eventQueueQueueEvents(eventQueue, eventDataList);
  10687. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10688. }
  10689. /**
  10690. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10691. * locations related to the specified change path (i.e. all ancestors and descendants).
  10692. *
  10693. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10694. *
  10695. * @param changedPath - The path to raise events for.
  10696. * @param eventDataList - The events to raise
  10697. */
  10698. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10699. eventQueueQueueEvents(eventQueue, eventDataList);
  10700. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10701. pathContains(changedPath, eventPath));
  10702. }
  10703. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10704. eventQueue.recursionDepth_++;
  10705. let sentAll = true;
  10706. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10707. const eventList = eventQueue.eventLists_[i];
  10708. if (eventList) {
  10709. const eventPath = eventList.path;
  10710. if (predicate(eventPath)) {
  10711. eventListRaise(eventQueue.eventLists_[i]);
  10712. eventQueue.eventLists_[i] = null;
  10713. }
  10714. else {
  10715. sentAll = false;
  10716. }
  10717. }
  10718. }
  10719. if (sentAll) {
  10720. eventQueue.eventLists_ = [];
  10721. }
  10722. eventQueue.recursionDepth_--;
  10723. }
  10724. /**
  10725. * Iterates through the list and raises each event
  10726. */
  10727. function eventListRaise(eventList) {
  10728. for (let i = 0; i < eventList.events.length; i++) {
  10729. const eventData = eventList.events[i];
  10730. if (eventData !== null) {
  10731. eventList.events[i] = null;
  10732. const eventFn = eventData.getEventRunner();
  10733. if (logger) {
  10734. log('event: ' + eventData.toString());
  10735. }
  10736. exceptionGuard(eventFn);
  10737. }
  10738. }
  10739. }
  10740. /**
  10741. * @license
  10742. * Copyright 2017 Google LLC
  10743. *
  10744. * Licensed under the Apache License, Version 2.0 (the "License");
  10745. * you may not use this file except in compliance with the License.
  10746. * You may obtain a copy of the License at
  10747. *
  10748. * http://www.apache.org/licenses/LICENSE-2.0
  10749. *
  10750. * Unless required by applicable law or agreed to in writing, software
  10751. * distributed under the License is distributed on an "AS IS" BASIS,
  10752. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10753. * See the License for the specific language governing permissions and
  10754. * limitations under the License.
  10755. */
  10756. const INTERRUPT_REASON = 'repo_interrupt';
  10757. /**
  10758. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10759. * things this ensure that if there's ever a bug causing a mismatch between
  10760. * client / server hashes for some data, we won't retry indefinitely.
  10761. */
  10762. const MAX_TRANSACTION_RETRIES = 25;
  10763. /**
  10764. * A connection to a single data repository.
  10765. */
  10766. class Repo {
  10767. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10768. this.repoInfo_ = repoInfo_;
  10769. this.forceRestClient_ = forceRestClient_;
  10770. this.authTokenProvider_ = authTokenProvider_;
  10771. this.appCheckProvider_ = appCheckProvider_;
  10772. this.dataUpdateCount = 0;
  10773. this.statsListener_ = null;
  10774. this.eventQueue_ = new EventQueue();
  10775. this.nextWriteId_ = 1;
  10776. this.interceptServerDataCallback_ = null;
  10777. /** A list of data pieces and paths to be set when this client disconnects. */
  10778. this.onDisconnect_ = newSparseSnapshotTree();
  10779. /** Stores queues of outstanding transactions for Firebase locations. */
  10780. this.transactionQueueTree_ = new Tree();
  10781. // TODO: This should be @private but it's used by test_access.js and internal.js
  10782. this.persistentConnection_ = null;
  10783. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10784. this.key = this.repoInfo_.toURLString();
  10785. }
  10786. /**
  10787. * @returns The URL corresponding to the root of this Firebase.
  10788. */
  10789. toString() {
  10790. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10791. }
  10792. }
  10793. function repoStart(repo, appId, authOverride) {
  10794. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10795. if (repo.forceRestClient_ || beingCrawled()) {
  10796. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10797. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10798. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10799. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10800. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10801. }
  10802. else {
  10803. // Validate authOverride
  10804. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10805. if (typeof authOverride !== 'object') {
  10806. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10807. }
  10808. try {
  10809. util.stringify(authOverride);
  10810. }
  10811. catch (e) {
  10812. throw new Error('Invalid authOverride provided: ' + e);
  10813. }
  10814. }
  10815. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10816. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10817. }, (connectStatus) => {
  10818. repoOnConnectStatus(repo, connectStatus);
  10819. }, (updates) => {
  10820. repoOnServerInfoUpdate(repo, updates);
  10821. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10822. repo.server_ = repo.persistentConnection_;
  10823. }
  10824. repo.authTokenProvider_.addTokenChangeListener(token => {
  10825. repo.server_.refreshAuthToken(token);
  10826. });
  10827. repo.appCheckProvider_.addTokenChangeListener(result => {
  10828. repo.server_.refreshAppCheckToken(result.token);
  10829. });
  10830. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10831. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10832. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10833. // Used for .info.
  10834. repo.infoData_ = new SnapshotHolder();
  10835. repo.infoSyncTree_ = new SyncTree({
  10836. startListening: (query, tag, currentHashFn, onComplete) => {
  10837. let infoEvents = [];
  10838. const node = repo.infoData_.getNode(query._path);
  10839. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10840. // on initial data...
  10841. if (!node.isEmpty()) {
  10842. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10843. setTimeout(() => {
  10844. onComplete('ok');
  10845. }, 0);
  10846. }
  10847. return infoEvents;
  10848. },
  10849. stopListening: () => { }
  10850. });
  10851. repoUpdateInfo(repo, 'connected', false);
  10852. repo.serverSyncTree_ = new SyncTree({
  10853. startListening: (query, tag, currentHashFn, onComplete) => {
  10854. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10855. const events = onComplete(status, data);
  10856. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10857. });
  10858. // No synchronous events for network-backed sync trees
  10859. return [];
  10860. },
  10861. stopListening: (query, tag) => {
  10862. repo.server_.unlisten(query, tag);
  10863. }
  10864. });
  10865. }
  10866. /**
  10867. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10868. */
  10869. function repoServerTime(repo) {
  10870. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10871. const offset = offsetNode.val() || 0;
  10872. return new Date().getTime() + offset;
  10873. }
  10874. /**
  10875. * Generate ServerValues using some variables from the repo object.
  10876. */
  10877. function repoGenerateServerValues(repo) {
  10878. return generateWithValues({
  10879. timestamp: repoServerTime(repo)
  10880. });
  10881. }
  10882. /**
  10883. * Called by realtime when we get new messages from the server.
  10884. */
  10885. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10886. // For testing.
  10887. repo.dataUpdateCount++;
  10888. const path = new Path(pathString);
  10889. data = repo.interceptServerDataCallback_
  10890. ? repo.interceptServerDataCallback_(pathString, data)
  10891. : data;
  10892. let events = [];
  10893. if (tag) {
  10894. if (isMerge) {
  10895. const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  10896. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10897. }
  10898. else {
  10899. const taggedSnap = nodeFromJSON(data);
  10900. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10901. }
  10902. }
  10903. else if (isMerge) {
  10904. const changedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  10905. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10906. }
  10907. else {
  10908. const snap = nodeFromJSON(data);
  10909. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10910. }
  10911. let affectedPath = path;
  10912. if (events.length > 0) {
  10913. // Since we have a listener outstanding for each transaction, receiving any events
  10914. // is a proxy for some change having occurred.
  10915. affectedPath = repoRerunTransactions(repo, path);
  10916. }
  10917. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10918. }
  10919. function repoOnConnectStatus(repo, connectStatus) {
  10920. repoUpdateInfo(repo, 'connected', connectStatus);
  10921. if (connectStatus === false) {
  10922. repoRunOnDisconnectEvents(repo);
  10923. }
  10924. }
  10925. function repoOnServerInfoUpdate(repo, updates) {
  10926. each(updates, (key, value) => {
  10927. repoUpdateInfo(repo, key, value);
  10928. });
  10929. }
  10930. function repoUpdateInfo(repo, pathString, value) {
  10931. const path = new Path('/.info/' + pathString);
  10932. const newNode = nodeFromJSON(value);
  10933. repo.infoData_.updateSnapshot(path, newNode);
  10934. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10935. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10936. }
  10937. function repoGetNextWriteId(repo) {
  10938. return repo.nextWriteId_++;
  10939. }
  10940. /**
  10941. * The purpose of `getValue` is to return the latest known value
  10942. * satisfying `query`.
  10943. *
  10944. * This method will first check for in-memory cached values
  10945. * belonging to active listeners. If they are found, such values
  10946. * are considered to be the most up-to-date.
  10947. *
  10948. * If the client is not connected, this method will wait until the
  10949. * repo has established a connection and then request the value for `query`.
  10950. * If the client is not able to retrieve the query result for another reason,
  10951. * it reports an error.
  10952. *
  10953. * @param query - The query to surface a value for.
  10954. */
  10955. function repoGetValue(repo, query, eventRegistration) {
  10956. // Only active queries are cached. There is no persisted cache.
  10957. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10958. if (cached != null) {
  10959. return Promise.resolve(cached);
  10960. }
  10961. return repo.server_.get(query).then(payload => {
  10962. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10963. /**
  10964. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10965. * Add an event registration,
  10966. * Update data at the path,
  10967. * Raise any events,
  10968. * Cleanup the SyncTree
  10969. */
  10970. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10971. let events;
  10972. if (query._queryParams.loadsAllData()) {
  10973. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10974. }
  10975. else {
  10976. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10977. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10978. }
  10979. /*
  10980. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10981. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10982. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10983. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10984. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10985. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10986. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10987. * ensure the corresponding child events will get fired.
  10988. */
  10989. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10990. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10991. return node;
  10992. }, err => {
  10993. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  10994. return Promise.reject(new Error(err));
  10995. });
  10996. }
  10997. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  10998. repoLog(repo, 'set', {
  10999. path: path.toString(),
  11000. value: newVal,
  11001. priority: newPriority
  11002. });
  11003. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11004. // (b) store unresolved paths on JSON parse
  11005. const serverValues = repoGenerateServerValues(repo);
  11006. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11007. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11008. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11009. const writeId = repoGetNextWriteId(repo);
  11010. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11011. eventQueueQueueEvents(repo.eventQueue_, events);
  11012. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11013. const success = status === 'ok';
  11014. if (!success) {
  11015. warn('set at ' + path + ' failed: ' + status);
  11016. }
  11017. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11018. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11019. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11020. });
  11021. const affectedPath = repoAbortTransactions(repo, path);
  11022. repoRerunTransactions(repo, affectedPath);
  11023. // We queued the events above, so just flush the queue here
  11024. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11025. }
  11026. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11027. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11028. // Start with our existing data and merge each child into it.
  11029. let empty = true;
  11030. const serverValues = repoGenerateServerValues(repo);
  11031. const changedChildren = {};
  11032. each(childrenToMerge, (changedKey, changedValue) => {
  11033. empty = false;
  11034. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11035. });
  11036. if (!empty) {
  11037. const writeId = repoGetNextWriteId(repo);
  11038. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11039. eventQueueQueueEvents(repo.eventQueue_, events);
  11040. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11041. const success = status === 'ok';
  11042. if (!success) {
  11043. warn('update at ' + path + ' failed: ' + status);
  11044. }
  11045. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11046. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11047. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11048. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11049. });
  11050. each(childrenToMerge, (changedPath) => {
  11051. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11052. repoRerunTransactions(repo, affectedPath);
  11053. });
  11054. // We queued the events above, so just flush the queue here
  11055. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11056. }
  11057. else {
  11058. log("update() called with empty data. Don't do anything.");
  11059. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11060. }
  11061. }
  11062. /**
  11063. * Applies all of the changes stored up in the onDisconnect_ tree.
  11064. */
  11065. function repoRunOnDisconnectEvents(repo) {
  11066. repoLog(repo, 'onDisconnectEvents');
  11067. const serverValues = repoGenerateServerValues(repo);
  11068. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11069. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11070. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11071. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11072. });
  11073. let events = [];
  11074. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11075. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11076. const affectedPath = repoAbortTransactions(repo, path);
  11077. repoRerunTransactions(repo, affectedPath);
  11078. });
  11079. repo.onDisconnect_ = newSparseSnapshotTree();
  11080. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11081. }
  11082. function repoOnDisconnectCancel(repo, path, onComplete) {
  11083. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11084. if (status === 'ok') {
  11085. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11086. }
  11087. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11088. });
  11089. }
  11090. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11091. const newNode = nodeFromJSON(value);
  11092. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11093. if (status === 'ok') {
  11094. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11095. }
  11096. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11097. });
  11098. }
  11099. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11100. const newNode = nodeFromJSON(value, priority);
  11101. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11102. if (status === 'ok') {
  11103. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11104. }
  11105. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11106. });
  11107. }
  11108. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11109. if (util.isEmpty(childrenToMerge)) {
  11110. log("onDisconnect().update() called with empty data. Don't do anything.");
  11111. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11112. return;
  11113. }
  11114. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11115. if (status === 'ok') {
  11116. each(childrenToMerge, (childName, childNode) => {
  11117. const newChildNode = nodeFromJSON(childNode);
  11118. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11119. });
  11120. }
  11121. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11122. });
  11123. }
  11124. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11125. let events;
  11126. if (pathGetFront(query._path) === '.info') {
  11127. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11128. }
  11129. else {
  11130. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11131. }
  11132. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11133. }
  11134. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11135. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11136. // a little bit by handling the return values anyways.
  11137. let events;
  11138. if (pathGetFront(query._path) === '.info') {
  11139. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11140. }
  11141. else {
  11142. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11143. }
  11144. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11145. }
  11146. function repoInterrupt(repo) {
  11147. if (repo.persistentConnection_) {
  11148. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11149. }
  11150. }
  11151. function repoResume(repo) {
  11152. if (repo.persistentConnection_) {
  11153. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11154. }
  11155. }
  11156. function repoLog(repo, ...varArgs) {
  11157. let prefix = '';
  11158. if (repo.persistentConnection_) {
  11159. prefix = repo.persistentConnection_.id + ':';
  11160. }
  11161. log(prefix, ...varArgs);
  11162. }
  11163. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11164. if (callback) {
  11165. exceptionGuard(() => {
  11166. if (status === 'ok') {
  11167. callback(null);
  11168. }
  11169. else {
  11170. const code = (status || 'error').toUpperCase();
  11171. let message = code;
  11172. if (errorReason) {
  11173. message += ': ' + errorReason;
  11174. }
  11175. const error = new Error(message);
  11176. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11177. error.code = code;
  11178. callback(error);
  11179. }
  11180. });
  11181. }
  11182. }
  11183. /**
  11184. * Creates a new transaction, adds it to the transactions we're tracking, and
  11185. * sends it to the server if possible.
  11186. *
  11187. * @param path - Path at which to do transaction.
  11188. * @param transactionUpdate - Update callback.
  11189. * @param onComplete - Completion callback.
  11190. * @param unwatcher - Function that will be called when the transaction no longer
  11191. * need data updates for `path`.
  11192. * @param applyLocally - Whether or not to make intermediate results visible
  11193. */
  11194. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11195. repoLog(repo, 'transaction on ' + path);
  11196. // Initialize transaction.
  11197. const transaction = {
  11198. path,
  11199. update: transactionUpdate,
  11200. onComplete,
  11201. // One of TransactionStatus enums.
  11202. status: null,
  11203. // Used when combining transactions at different locations to figure out
  11204. // which one goes first.
  11205. order: LUIDGenerator(),
  11206. // Whether to raise local events for this transaction.
  11207. applyLocally,
  11208. // Count of how many times we've retried the transaction.
  11209. retryCount: 0,
  11210. // Function to call to clean up our .on() listener.
  11211. unwatcher,
  11212. // Stores why a transaction was aborted.
  11213. abortReason: null,
  11214. currentWriteId: null,
  11215. currentInputSnapshot: null,
  11216. currentOutputSnapshotRaw: null,
  11217. currentOutputSnapshotResolved: null
  11218. };
  11219. // Run transaction initially.
  11220. const currentState = repoGetLatestState(repo, path, undefined);
  11221. transaction.currentInputSnapshot = currentState;
  11222. const newVal = transaction.update(currentState.val());
  11223. if (newVal === undefined) {
  11224. // Abort transaction.
  11225. transaction.unwatcher();
  11226. transaction.currentOutputSnapshotRaw = null;
  11227. transaction.currentOutputSnapshotResolved = null;
  11228. if (transaction.onComplete) {
  11229. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11230. }
  11231. }
  11232. else {
  11233. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11234. // Mark as run and add to our queue.
  11235. transaction.status = 0 /* TransactionStatus.RUN */;
  11236. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11237. const nodeQueue = treeGetValue(queueNode) || [];
  11238. nodeQueue.push(transaction);
  11239. treeSetValue(queueNode, nodeQueue);
  11240. // Update visibleData and raise events
  11241. // Note: We intentionally raise events after updating all of our
  11242. // transaction state, since the user could start new transactions from the
  11243. // event callbacks.
  11244. let priorityForNode;
  11245. if (typeof newVal === 'object' &&
  11246. newVal !== null &&
  11247. util.contains(newVal, '.priority')) {
  11248. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11249. priorityForNode = util.safeGet(newVal, '.priority');
  11250. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11251. 'Priority must be a valid string, finite number, server value, or null.');
  11252. }
  11253. else {
  11254. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11255. ChildrenNode.EMPTY_NODE;
  11256. priorityForNode = currentNode.getPriority().val();
  11257. }
  11258. const serverValues = repoGenerateServerValues(repo);
  11259. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11260. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11261. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11262. transaction.currentOutputSnapshotResolved = newNode;
  11263. transaction.currentWriteId = repoGetNextWriteId(repo);
  11264. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11265. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11266. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11267. }
  11268. }
  11269. /**
  11270. * @param excludeSets - A specific set to exclude
  11271. */
  11272. function repoGetLatestState(repo, path, excludeSets) {
  11273. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11274. ChildrenNode.EMPTY_NODE);
  11275. }
  11276. /**
  11277. * Sends any already-run transactions that aren't waiting for outstanding
  11278. * transactions to complete.
  11279. *
  11280. * Externally it's called with no arguments, but it calls itself recursively
  11281. * with a particular transactionQueueTree node to recurse through the tree.
  11282. *
  11283. * @param node - transactionQueueTree node to start at.
  11284. */
  11285. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11286. // Before recursing, make sure any completed transactions are removed.
  11287. if (!node) {
  11288. repoPruneCompletedTransactionsBelowNode(repo, node);
  11289. }
  11290. if (treeGetValue(node)) {
  11291. const queue = repoBuildTransactionQueue(repo, node);
  11292. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  11293. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11294. // If they're all run (and not sent), we can send them. Else, we must wait.
  11295. if (allRun) {
  11296. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11297. }
  11298. }
  11299. else if (treeHasChildren(node)) {
  11300. treeForEachChild(node, childNode => {
  11301. repoSendReadyTransactions(repo, childNode);
  11302. });
  11303. }
  11304. }
  11305. /**
  11306. * Given a list of run transactions, send them to the server and then handle
  11307. * the result (success or failure).
  11308. *
  11309. * @param path - The location of the queue.
  11310. * @param queue - Queue of transactions under the specified location.
  11311. */
  11312. function repoSendTransactionQueue(repo, path, queue) {
  11313. // Mark transactions as sent and increment retry count!
  11314. const setsToIgnore = queue.map(txn => {
  11315. return txn.currentWriteId;
  11316. });
  11317. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11318. let snapToSend = latestState;
  11319. const latestHash = latestState.hash();
  11320. for (let i = 0; i < queue.length; i++) {
  11321. const txn = queue[i];
  11322. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11323. txn.status = 1 /* TransactionStatus.SENT */;
  11324. txn.retryCount++;
  11325. const relativePath = newRelativePath(path, txn.path);
  11326. // If we've gotten to this point, the output snapshot must be defined.
  11327. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11328. }
  11329. const dataToSend = snapToSend.val(true);
  11330. const pathToSend = path;
  11331. // Send the put.
  11332. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11333. repoLog(repo, 'transaction put response', {
  11334. path: pathToSend.toString(),
  11335. status
  11336. });
  11337. let events = [];
  11338. if (status === 'ok') {
  11339. // Queue up the callbacks and fire them after cleaning up all of our
  11340. // transaction state, since the callback could trigger more
  11341. // transactions or sets.
  11342. const callbacks = [];
  11343. for (let i = 0; i < queue.length; i++) {
  11344. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11345. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11346. if (queue[i].onComplete) {
  11347. // We never unset the output snapshot, and given that this
  11348. // transaction is complete, it should be set
  11349. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11350. }
  11351. queue[i].unwatcher();
  11352. }
  11353. // Now remove the completed transactions.
  11354. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11355. // There may be pending transactions that we can now send.
  11356. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11357. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11358. // Finally, trigger onComplete callbacks.
  11359. for (let i = 0; i < callbacks.length; i++) {
  11360. exceptionGuard(callbacks[i]);
  11361. }
  11362. }
  11363. else {
  11364. // transactions are no longer sent. Update their status appropriately.
  11365. if (status === 'datastale') {
  11366. for (let i = 0; i < queue.length; i++) {
  11367. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11368. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11369. }
  11370. else {
  11371. queue[i].status = 0 /* TransactionStatus.RUN */;
  11372. }
  11373. }
  11374. }
  11375. else {
  11376. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11377. for (let i = 0; i < queue.length; i++) {
  11378. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11379. queue[i].abortReason = status;
  11380. }
  11381. }
  11382. repoRerunTransactions(repo, path);
  11383. }
  11384. }, latestHash);
  11385. }
  11386. /**
  11387. * Finds all transactions dependent on the data at changedPath and reruns them.
  11388. *
  11389. * Should be called any time cached data changes.
  11390. *
  11391. * Return the highest path that was affected by rerunning transactions. This
  11392. * is the path at which events need to be raised for.
  11393. *
  11394. * @param changedPath - The path in mergedData that changed.
  11395. * @returns The rootmost path that was affected by rerunning transactions.
  11396. */
  11397. function repoRerunTransactions(repo, changedPath) {
  11398. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11399. const path = treeGetPath(rootMostTransactionNode);
  11400. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11401. repoRerunTransactionQueue(repo, queue, path);
  11402. return path;
  11403. }
  11404. /**
  11405. * Does all the work of rerunning transactions (as well as cleans up aborted
  11406. * transactions and whatnot).
  11407. *
  11408. * @param queue - The queue of transactions to run.
  11409. * @param path - The path the queue is for.
  11410. */
  11411. function repoRerunTransactionQueue(repo, queue, path) {
  11412. if (queue.length === 0) {
  11413. return; // Nothing to do!
  11414. }
  11415. // Queue up the callbacks and fire them after cleaning up all of our
  11416. // transaction state, since the callback could trigger more transactions or
  11417. // sets.
  11418. const callbacks = [];
  11419. let events = [];
  11420. // Ignore all of the sets we're going to re-run.
  11421. const txnsToRerun = queue.filter(q => {
  11422. return q.status === 0 /* TransactionStatus.RUN */;
  11423. });
  11424. const setsToIgnore = txnsToRerun.map(q => {
  11425. return q.currentWriteId;
  11426. });
  11427. for (let i = 0; i < queue.length; i++) {
  11428. const transaction = queue[i];
  11429. const relativePath = newRelativePath(path, transaction.path);
  11430. let abortTransaction = false, abortReason;
  11431. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11432. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11433. abortTransaction = true;
  11434. abortReason = transaction.abortReason;
  11435. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11436. }
  11437. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11438. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11439. abortTransaction = true;
  11440. abortReason = 'maxretry';
  11441. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11442. }
  11443. else {
  11444. // This code reruns a transaction
  11445. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11446. transaction.currentInputSnapshot = currentNode;
  11447. const newData = queue[i].update(currentNode.val());
  11448. if (newData !== undefined) {
  11449. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11450. let newDataNode = nodeFromJSON(newData);
  11451. const hasExplicitPriority = typeof newData === 'object' &&
  11452. newData != null &&
  11453. util.contains(newData, '.priority');
  11454. if (!hasExplicitPriority) {
  11455. // Keep the old priority if there wasn't a priority explicitly specified.
  11456. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11457. }
  11458. const oldWriteId = transaction.currentWriteId;
  11459. const serverValues = repoGenerateServerValues(repo);
  11460. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11461. transaction.currentOutputSnapshotRaw = newDataNode;
  11462. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11463. transaction.currentWriteId = repoGetNextWriteId(repo);
  11464. // Mutates setsToIgnore in place
  11465. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11466. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11467. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11468. }
  11469. else {
  11470. abortTransaction = true;
  11471. abortReason = 'nodata';
  11472. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11473. }
  11474. }
  11475. }
  11476. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11477. events = [];
  11478. if (abortTransaction) {
  11479. // Abort.
  11480. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11481. // Removing a listener can trigger pruning which can muck with
  11482. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11483. // until we're done.
  11484. (function (unwatcher) {
  11485. setTimeout(unwatcher, Math.floor(0));
  11486. })(queue[i].unwatcher);
  11487. if (queue[i].onComplete) {
  11488. if (abortReason === 'nodata') {
  11489. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11490. }
  11491. else {
  11492. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11493. }
  11494. }
  11495. }
  11496. }
  11497. // Clean up completed transactions.
  11498. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11499. // Now fire callbacks, now that we're in a good, known state.
  11500. for (let i = 0; i < callbacks.length; i++) {
  11501. exceptionGuard(callbacks[i]);
  11502. }
  11503. // Try to send the transaction result to the server.
  11504. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11505. }
  11506. /**
  11507. * Returns the rootmost ancestor node of the specified path that has a pending
  11508. * transaction on it, or just returns the node for the given path if there are
  11509. * no pending transactions on any ancestor.
  11510. *
  11511. * @param path - The location to start at.
  11512. * @returns The rootmost node with a transaction.
  11513. */
  11514. function repoGetAncestorTransactionNode(repo, path) {
  11515. let front;
  11516. // Start at the root and walk deeper into the tree towards path until we
  11517. // find a node with pending transactions.
  11518. let transactionNode = repo.transactionQueueTree_;
  11519. front = pathGetFront(path);
  11520. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11521. transactionNode = treeSubTree(transactionNode, front);
  11522. path = pathPopFront(path);
  11523. front = pathGetFront(path);
  11524. }
  11525. return transactionNode;
  11526. }
  11527. /**
  11528. * Builds the queue of all transactions at or below the specified
  11529. * transactionNode.
  11530. *
  11531. * @param transactionNode
  11532. * @returns The generated queue.
  11533. */
  11534. function repoBuildTransactionQueue(repo, transactionNode) {
  11535. // Walk any child transaction queues and aggregate them into a single queue.
  11536. const transactionQueue = [];
  11537. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11538. // Sort them by the order the transactions were created.
  11539. transactionQueue.sort((a, b) => a.order - b.order);
  11540. return transactionQueue;
  11541. }
  11542. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11543. const nodeQueue = treeGetValue(node);
  11544. if (nodeQueue) {
  11545. for (let i = 0; i < nodeQueue.length; i++) {
  11546. queue.push(nodeQueue[i]);
  11547. }
  11548. }
  11549. treeForEachChild(node, child => {
  11550. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11551. });
  11552. }
  11553. /**
  11554. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11555. */
  11556. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11557. const queue = treeGetValue(node);
  11558. if (queue) {
  11559. let to = 0;
  11560. for (let from = 0; from < queue.length; from++) {
  11561. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11562. queue[to] = queue[from];
  11563. to++;
  11564. }
  11565. }
  11566. queue.length = to;
  11567. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11568. }
  11569. treeForEachChild(node, childNode => {
  11570. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11571. });
  11572. }
  11573. /**
  11574. * Aborts all transactions on ancestors or descendants of the specified path.
  11575. * Called when doing a set() or update() since we consider them incompatible
  11576. * with transactions.
  11577. *
  11578. * @param path - Path for which we want to abort related transactions.
  11579. */
  11580. function repoAbortTransactions(repo, path) {
  11581. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11582. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11583. treeForEachAncestor(transactionNode, (node) => {
  11584. repoAbortTransactionsOnNode(repo, node);
  11585. });
  11586. repoAbortTransactionsOnNode(repo, transactionNode);
  11587. treeForEachDescendant(transactionNode, (node) => {
  11588. repoAbortTransactionsOnNode(repo, node);
  11589. });
  11590. return affectedPath;
  11591. }
  11592. /**
  11593. * Abort transactions stored in this transaction queue node.
  11594. *
  11595. * @param node - Node to abort transactions for.
  11596. */
  11597. function repoAbortTransactionsOnNode(repo, node) {
  11598. const queue = treeGetValue(node);
  11599. if (queue) {
  11600. // Queue up the callbacks and fire them after cleaning up all of our
  11601. // transaction state, since the callback could trigger more transactions
  11602. // or sets.
  11603. const callbacks = [];
  11604. // Go through queue. Any already-sent transactions must be marked for
  11605. // abort, while the unsent ones can be immediately aborted and removed.
  11606. let events = [];
  11607. let lastSent = -1;
  11608. for (let i = 0; i < queue.length; i++) {
  11609. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11610. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11611. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11612. lastSent = i;
  11613. // Mark transaction for abort when it comes back.
  11614. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11615. queue[i].abortReason = 'set';
  11616. }
  11617. else {
  11618. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11619. // We can abort it immediately.
  11620. queue[i].unwatcher();
  11621. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11622. if (queue[i].onComplete) {
  11623. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11624. }
  11625. }
  11626. }
  11627. if (lastSent === -1) {
  11628. // We're not waiting for any sent transactions. We can clear the queue.
  11629. treeSetValue(node, undefined);
  11630. }
  11631. else {
  11632. // Remove the transactions we aborted.
  11633. queue.length = lastSent + 1;
  11634. }
  11635. // Now fire the callbacks.
  11636. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11637. for (let i = 0; i < callbacks.length; i++) {
  11638. exceptionGuard(callbacks[i]);
  11639. }
  11640. }
  11641. }
  11642. /**
  11643. * @license
  11644. * Copyright 2017 Google LLC
  11645. *
  11646. * Licensed under the Apache License, Version 2.0 (the "License");
  11647. * you may not use this file except in compliance with the License.
  11648. * You may obtain a copy of the License at
  11649. *
  11650. * http://www.apache.org/licenses/LICENSE-2.0
  11651. *
  11652. * Unless required by applicable law or agreed to in writing, software
  11653. * distributed under the License is distributed on an "AS IS" BASIS,
  11654. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11655. * See the License for the specific language governing permissions and
  11656. * limitations under the License.
  11657. */
  11658. function decodePath(pathString) {
  11659. let pathStringDecoded = '';
  11660. const pieces = pathString.split('/');
  11661. for (let i = 0; i < pieces.length; i++) {
  11662. if (pieces[i].length > 0) {
  11663. let piece = pieces[i];
  11664. try {
  11665. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11666. }
  11667. catch (e) { }
  11668. pathStringDecoded += '/' + piece;
  11669. }
  11670. }
  11671. return pathStringDecoded;
  11672. }
  11673. /**
  11674. * @returns key value hash
  11675. */
  11676. function decodeQuery(queryString) {
  11677. const results = {};
  11678. if (queryString.charAt(0) === '?') {
  11679. queryString = queryString.substring(1);
  11680. }
  11681. for (const segment of queryString.split('&')) {
  11682. if (segment.length === 0) {
  11683. continue;
  11684. }
  11685. const kv = segment.split('=');
  11686. if (kv.length === 2) {
  11687. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11688. }
  11689. else {
  11690. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11691. }
  11692. }
  11693. return results;
  11694. }
  11695. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11696. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11697. if (parsedUrl.domain === 'firebase.com') {
  11698. fatal(parsedUrl.host +
  11699. ' is no longer supported. ' +
  11700. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11701. }
  11702. // Catch common error of uninitialized namespace value.
  11703. if ((!namespace || namespace === 'undefined') &&
  11704. parsedUrl.domain !== 'localhost') {
  11705. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11706. }
  11707. if (!parsedUrl.secure) {
  11708. warnIfPageIsSecure();
  11709. }
  11710. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11711. return {
  11712. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11713. /*persistenceKey=*/ '',
  11714. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11715. path: new Path(parsedUrl.pathString)
  11716. };
  11717. };
  11718. const parseDatabaseURL = function (dataURL) {
  11719. // Default to empty strings in the event of a malformed string.
  11720. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11721. // Always default to SSL, unless otherwise specified.
  11722. let secure = true, scheme = 'https', port = 443;
  11723. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11724. if (typeof dataURL === 'string') {
  11725. // Parse scheme.
  11726. let colonInd = dataURL.indexOf('//');
  11727. if (colonInd >= 0) {
  11728. scheme = dataURL.substring(0, colonInd - 1);
  11729. dataURL = dataURL.substring(colonInd + 2);
  11730. }
  11731. // Parse host, path, and query string.
  11732. let slashInd = dataURL.indexOf('/');
  11733. if (slashInd === -1) {
  11734. slashInd = dataURL.length;
  11735. }
  11736. let questionMarkInd = dataURL.indexOf('?');
  11737. if (questionMarkInd === -1) {
  11738. questionMarkInd = dataURL.length;
  11739. }
  11740. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11741. if (slashInd < questionMarkInd) {
  11742. // For pathString, questionMarkInd will always come after slashInd
  11743. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11744. }
  11745. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11746. // If we have a port, use scheme for determining if it's secure.
  11747. colonInd = host.indexOf(':');
  11748. if (colonInd >= 0) {
  11749. secure = scheme === 'https' || scheme === 'wss';
  11750. port = parseInt(host.substring(colonInd + 1), 10);
  11751. }
  11752. else {
  11753. colonInd = host.length;
  11754. }
  11755. const hostWithoutPort = host.slice(0, colonInd);
  11756. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11757. domain = 'localhost';
  11758. }
  11759. else if (hostWithoutPort.split('.').length <= 2) {
  11760. domain = hostWithoutPort;
  11761. }
  11762. else {
  11763. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11764. const dotInd = host.indexOf('.');
  11765. subdomain = host.substring(0, dotInd).toLowerCase();
  11766. domain = host.substring(dotInd + 1);
  11767. // Normalize namespaces to lowercase to share storage / connection.
  11768. namespace = subdomain;
  11769. }
  11770. // Always treat the value of the `ns` as the namespace name if it is present.
  11771. if ('ns' in queryParams) {
  11772. namespace = queryParams['ns'];
  11773. }
  11774. }
  11775. return {
  11776. host,
  11777. port,
  11778. domain,
  11779. subdomain,
  11780. secure,
  11781. scheme,
  11782. pathString,
  11783. namespace
  11784. };
  11785. };
  11786. /**
  11787. * @license
  11788. * Copyright 2017 Google LLC
  11789. *
  11790. * Licensed under the Apache License, Version 2.0 (the "License");
  11791. * you may not use this file except in compliance with the License.
  11792. * You may obtain a copy of the License at
  11793. *
  11794. * http://www.apache.org/licenses/LICENSE-2.0
  11795. *
  11796. * Unless required by applicable law or agreed to in writing, software
  11797. * distributed under the License is distributed on an "AS IS" BASIS,
  11798. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11799. * See the License for the specific language governing permissions and
  11800. * limitations under the License.
  11801. */
  11802. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11803. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11804. /**
  11805. * Fancy ID generator that creates 20-character string identifiers with the
  11806. * following properties:
  11807. *
  11808. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11809. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11810. * collide with other clients' IDs.
  11811. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11812. * that will sort properly).
  11813. * 4. They're monotonically increasing. Even if you generate more than one in
  11814. * the same timestamp, the latter ones will sort after the former ones. We do
  11815. * this by using the previous random bits but "incrementing" them by 1 (only
  11816. * in the case of a timestamp collision).
  11817. */
  11818. const nextPushId = (function () {
  11819. // Timestamp of last push, used to prevent local collisions if you push twice
  11820. // in one ms.
  11821. let lastPushTime = 0;
  11822. // We generate 72-bits of randomness which get turned into 12 characters and
  11823. // appended to the timestamp to prevent collisions with other clients. We
  11824. // store the last characters we generated because in the event of a collision,
  11825. // we'll use those same characters except "incremented" by one.
  11826. const lastRandChars = [];
  11827. return function (now) {
  11828. const duplicateTime = now === lastPushTime;
  11829. lastPushTime = now;
  11830. let i;
  11831. const timeStampChars = new Array(8);
  11832. for (i = 7; i >= 0; i--) {
  11833. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11834. // NOTE: Can't use << here because javascript will convert to int and lose
  11835. // the upper bits.
  11836. now = Math.floor(now / 64);
  11837. }
  11838. util.assert(now === 0, 'Cannot push at time == 0');
  11839. let id = timeStampChars.join('');
  11840. if (!duplicateTime) {
  11841. for (i = 0; i < 12; i++) {
  11842. lastRandChars[i] = Math.floor(Math.random() * 64);
  11843. }
  11844. }
  11845. else {
  11846. // If the timestamp hasn't changed since last push, use the same random
  11847. // number, except incremented by 1.
  11848. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11849. lastRandChars[i] = 0;
  11850. }
  11851. lastRandChars[i]++;
  11852. }
  11853. for (i = 0; i < 12; i++) {
  11854. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11855. }
  11856. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  11857. return id;
  11858. };
  11859. })();
  11860. /**
  11861. * @license
  11862. * Copyright 2017 Google LLC
  11863. *
  11864. * Licensed under the Apache License, Version 2.0 (the "License");
  11865. * you may not use this file except in compliance with the License.
  11866. * You may obtain a copy of the License at
  11867. *
  11868. * http://www.apache.org/licenses/LICENSE-2.0
  11869. *
  11870. * Unless required by applicable law or agreed to in writing, software
  11871. * distributed under the License is distributed on an "AS IS" BASIS,
  11872. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11873. * See the License for the specific language governing permissions and
  11874. * limitations under the License.
  11875. */
  11876. /**
  11877. * Encapsulates the data needed to raise an event
  11878. */
  11879. class DataEvent {
  11880. /**
  11881. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11882. * @param eventRegistration - The function to call to with the event data. User provided
  11883. * @param snapshot - The data backing the event
  11884. * @param prevName - Optional, the name of the previous child for child_* events.
  11885. */
  11886. constructor(eventType, eventRegistration, snapshot, prevName) {
  11887. this.eventType = eventType;
  11888. this.eventRegistration = eventRegistration;
  11889. this.snapshot = snapshot;
  11890. this.prevName = prevName;
  11891. }
  11892. getPath() {
  11893. const ref = this.snapshot.ref;
  11894. if (this.eventType === 'value') {
  11895. return ref._path;
  11896. }
  11897. else {
  11898. return ref.parent._path;
  11899. }
  11900. }
  11901. getEventType() {
  11902. return this.eventType;
  11903. }
  11904. getEventRunner() {
  11905. return this.eventRegistration.getEventRunner(this);
  11906. }
  11907. toString() {
  11908. return (this.getPath().toString() +
  11909. ':' +
  11910. this.eventType +
  11911. ':' +
  11912. util.stringify(this.snapshot.exportVal()));
  11913. }
  11914. }
  11915. class CancelEvent {
  11916. constructor(eventRegistration, error, path) {
  11917. this.eventRegistration = eventRegistration;
  11918. this.error = error;
  11919. this.path = path;
  11920. }
  11921. getPath() {
  11922. return this.path;
  11923. }
  11924. getEventType() {
  11925. return 'cancel';
  11926. }
  11927. getEventRunner() {
  11928. return this.eventRegistration.getEventRunner(this);
  11929. }
  11930. toString() {
  11931. return this.path.toString() + ':cancel';
  11932. }
  11933. }
  11934. /**
  11935. * @license
  11936. * Copyright 2017 Google LLC
  11937. *
  11938. * Licensed under the Apache License, Version 2.0 (the "License");
  11939. * you may not use this file except in compliance with the License.
  11940. * You may obtain a copy of the License at
  11941. *
  11942. * http://www.apache.org/licenses/LICENSE-2.0
  11943. *
  11944. * Unless required by applicable law or agreed to in writing, software
  11945. * distributed under the License is distributed on an "AS IS" BASIS,
  11946. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11947. * See the License for the specific language governing permissions and
  11948. * limitations under the License.
  11949. */
  11950. /**
  11951. * A wrapper class that converts events from the database@exp SDK to the legacy
  11952. * Database SDK. Events are not converted directly as event registration relies
  11953. * on reference comparison of the original user callback (see `matches()`) and
  11954. * relies on equality of the legacy SDK's `context` object.
  11955. */
  11956. class CallbackContext {
  11957. constructor(snapshotCallback, cancelCallback) {
  11958. this.snapshotCallback = snapshotCallback;
  11959. this.cancelCallback = cancelCallback;
  11960. }
  11961. onValue(expDataSnapshot, previousChildName) {
  11962. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11963. }
  11964. onCancel(error) {
  11965. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11966. return this.cancelCallback.call(null, error);
  11967. }
  11968. get hasCancelCallback() {
  11969. return !!this.cancelCallback;
  11970. }
  11971. matches(other) {
  11972. return (this.snapshotCallback === other.snapshotCallback ||
  11973. (this.snapshotCallback.userCallback !== undefined &&
  11974. this.snapshotCallback.userCallback ===
  11975. other.snapshotCallback.userCallback &&
  11976. this.snapshotCallback.context === other.snapshotCallback.context));
  11977. }
  11978. }
  11979. /**
  11980. * @license
  11981. * Copyright 2021 Google LLC
  11982. *
  11983. * Licensed under the Apache License, Version 2.0 (the "License");
  11984. * you may not use this file except in compliance with the License.
  11985. * You may obtain a copy of the License at
  11986. *
  11987. * http://www.apache.org/licenses/LICENSE-2.0
  11988. *
  11989. * Unless required by applicable law or agreed to in writing, software
  11990. * distributed under the License is distributed on an "AS IS" BASIS,
  11991. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11992. * See the License for the specific language governing permissions and
  11993. * limitations under the License.
  11994. */
  11995. /**
  11996. * The `onDisconnect` class allows you to write or clear data when your client
  11997. * disconnects from the Database server. These updates occur whether your
  11998. * client disconnects cleanly or not, so you can rely on them to clean up data
  11999. * even if a connection is dropped or a client crashes.
  12000. *
  12001. * The `onDisconnect` class is most commonly used to manage presence in
  12002. * applications where it is useful to detect how many clients are connected and
  12003. * when other clients disconnect. See
  12004. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12005. * for more information.
  12006. *
  12007. * To avoid problems when a connection is dropped before the requests can be
  12008. * transferred to the Database server, these functions should be called before
  12009. * writing any data.
  12010. *
  12011. * Note that `onDisconnect` operations are only triggered once. If you want an
  12012. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12013. * the `onDisconnect` operations each time you reconnect.
  12014. */
  12015. class OnDisconnect {
  12016. /** @hideconstructor */
  12017. constructor(_repo, _path) {
  12018. this._repo = _repo;
  12019. this._path = _path;
  12020. }
  12021. /**
  12022. * Cancels all previously queued `onDisconnect()` set or update events for this
  12023. * location and all children.
  12024. *
  12025. * If a write has been queued for this location via a `set()` or `update()` at a
  12026. * parent location, the write at this location will be canceled, though writes
  12027. * to sibling locations will still occur.
  12028. *
  12029. * @returns Resolves when synchronization to the server is complete.
  12030. */
  12031. cancel() {
  12032. const deferred = new util.Deferred();
  12033. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12034. return deferred.promise;
  12035. }
  12036. /**
  12037. * Ensures the data at this location is deleted when the client is disconnected
  12038. * (due to closing the browser, navigating to a new page, or network issues).
  12039. *
  12040. * @returns Resolves when synchronization to the server is complete.
  12041. */
  12042. remove() {
  12043. validateWritablePath('OnDisconnect.remove', this._path);
  12044. const deferred = new util.Deferred();
  12045. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12046. return deferred.promise;
  12047. }
  12048. /**
  12049. * Ensures the data at this location is set to the specified value when the
  12050. * client is disconnected (due to closing the browser, navigating to a new page,
  12051. * or network issues).
  12052. *
  12053. * `set()` is especially useful for implementing "presence" systems, where a
  12054. * value should be changed or cleared when a user disconnects so that they
  12055. * appear "offline" to other users. See
  12056. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12057. * for more information.
  12058. *
  12059. * Note that `onDisconnect` operations are only triggered once. If you want an
  12060. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12061. * the `onDisconnect` operations each time.
  12062. *
  12063. * @param value - The value to be written to this location on disconnect (can
  12064. * be an object, array, string, number, boolean, or null).
  12065. * @returns Resolves when synchronization to the Database is complete.
  12066. */
  12067. set(value) {
  12068. validateWritablePath('OnDisconnect.set', this._path);
  12069. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12070. const deferred = new util.Deferred();
  12071. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12072. return deferred.promise;
  12073. }
  12074. /**
  12075. * Ensures the data at this location is set to the specified value and priority
  12076. * when the client is disconnected (due to closing the browser, navigating to a
  12077. * new page, or network issues).
  12078. *
  12079. * @param value - The value to be written to this location on disconnect (can
  12080. * be an object, array, string, number, boolean, or null).
  12081. * @param priority - The priority to be written (string, number, or null).
  12082. * @returns Resolves when synchronization to the Database is complete.
  12083. */
  12084. setWithPriority(value, priority) {
  12085. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12086. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12087. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12088. const deferred = new util.Deferred();
  12089. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12090. return deferred.promise;
  12091. }
  12092. /**
  12093. * Writes multiple values at this location when the client is disconnected (due
  12094. * to closing the browser, navigating to a new page, or network issues).
  12095. *
  12096. * The `values` argument contains multiple property-value pairs that will be
  12097. * written to the Database together. Each child property can either be a simple
  12098. * property (for example, "name") or a relative path (for example, "name/first")
  12099. * from the current location to the data to update.
  12100. *
  12101. * As opposed to the `set()` method, `update()` can be use to selectively update
  12102. * only the referenced properties at the current location (instead of replacing
  12103. * all the child properties at the current location).
  12104. *
  12105. * @param values - Object containing multiple values.
  12106. * @returns Resolves when synchronization to the Database is complete.
  12107. */
  12108. update(values) {
  12109. validateWritablePath('OnDisconnect.update', this._path);
  12110. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12111. const deferred = new util.Deferred();
  12112. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12113. return deferred.promise;
  12114. }
  12115. }
  12116. /**
  12117. * @license
  12118. * Copyright 2020 Google LLC
  12119. *
  12120. * Licensed under the Apache License, Version 2.0 (the "License");
  12121. * you may not use this file except in compliance with the License.
  12122. * You may obtain a copy of the License at
  12123. *
  12124. * http://www.apache.org/licenses/LICENSE-2.0
  12125. *
  12126. * Unless required by applicable law or agreed to in writing, software
  12127. * distributed under the License is distributed on an "AS IS" BASIS,
  12128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12129. * See the License for the specific language governing permissions and
  12130. * limitations under the License.
  12131. */
  12132. /**
  12133. * @internal
  12134. */
  12135. class QueryImpl {
  12136. /**
  12137. * @hideconstructor
  12138. */
  12139. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12140. this._repo = _repo;
  12141. this._path = _path;
  12142. this._queryParams = _queryParams;
  12143. this._orderByCalled = _orderByCalled;
  12144. }
  12145. get key() {
  12146. if (pathIsEmpty(this._path)) {
  12147. return null;
  12148. }
  12149. else {
  12150. return pathGetBack(this._path);
  12151. }
  12152. }
  12153. get ref() {
  12154. return new ReferenceImpl(this._repo, this._path);
  12155. }
  12156. get _queryIdentifier() {
  12157. const obj = queryParamsGetQueryObject(this._queryParams);
  12158. const id = ObjectToUniqueKey(obj);
  12159. return id === '{}' ? 'default' : id;
  12160. }
  12161. /**
  12162. * An object representation of the query parameters used by this Query.
  12163. */
  12164. get _queryObject() {
  12165. return queryParamsGetQueryObject(this._queryParams);
  12166. }
  12167. isEqual(other) {
  12168. other = util.getModularInstance(other);
  12169. if (!(other instanceof QueryImpl)) {
  12170. return false;
  12171. }
  12172. const sameRepo = this._repo === other._repo;
  12173. const samePath = pathEquals(this._path, other._path);
  12174. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12175. return sameRepo && samePath && sameQueryIdentifier;
  12176. }
  12177. toJSON() {
  12178. return this.toString();
  12179. }
  12180. toString() {
  12181. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12182. }
  12183. }
  12184. /**
  12185. * Validates that no other order by call has been made
  12186. */
  12187. function validateNoPreviousOrderByCall(query, fnName) {
  12188. if (query._orderByCalled === true) {
  12189. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12190. }
  12191. }
  12192. /**
  12193. * Validates start/end values for queries.
  12194. */
  12195. function validateQueryEndpoints(params) {
  12196. let startNode = null;
  12197. let endNode = null;
  12198. if (params.hasStart()) {
  12199. startNode = params.getIndexStartValue();
  12200. }
  12201. if (params.hasEnd()) {
  12202. endNode = params.getIndexEndValue();
  12203. }
  12204. if (params.getIndex() === KEY_INDEX) {
  12205. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12206. 'startAt(), endAt(), or equalTo().';
  12207. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12208. 'endAt(), endBefore(), or equalTo() must be a string.';
  12209. if (params.hasStart()) {
  12210. const startName = params.getIndexStartName();
  12211. if (startName !== MIN_NAME) {
  12212. throw new Error(tooManyArgsError);
  12213. }
  12214. else if (typeof startNode !== 'string') {
  12215. throw new Error(wrongArgTypeError);
  12216. }
  12217. }
  12218. if (params.hasEnd()) {
  12219. const endName = params.getIndexEndName();
  12220. if (endName !== MAX_NAME) {
  12221. throw new Error(tooManyArgsError);
  12222. }
  12223. else if (typeof endNode !== 'string') {
  12224. throw new Error(wrongArgTypeError);
  12225. }
  12226. }
  12227. }
  12228. else if (params.getIndex() === PRIORITY_INDEX) {
  12229. if ((startNode != null && !isValidPriority(startNode)) ||
  12230. (endNode != null && !isValidPriority(endNode))) {
  12231. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12232. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12233. '(null, a number, or a string).');
  12234. }
  12235. }
  12236. else {
  12237. util.assert(params.getIndex() instanceof PathIndex ||
  12238. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12239. if ((startNode != null && typeof startNode === 'object') ||
  12240. (endNode != null && typeof endNode === 'object')) {
  12241. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12242. 'equalTo() cannot be an object.');
  12243. }
  12244. }
  12245. }
  12246. /**
  12247. * Validates that limit* has been called with the correct combination of parameters
  12248. */
  12249. function validateLimit(params) {
  12250. if (params.hasStart() &&
  12251. params.hasEnd() &&
  12252. params.hasLimit() &&
  12253. !params.hasAnchoredLimit()) {
  12254. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12255. 'limitToFirst() or limitToLast() instead.');
  12256. }
  12257. }
  12258. /**
  12259. * @internal
  12260. */
  12261. class ReferenceImpl extends QueryImpl {
  12262. /** @hideconstructor */
  12263. constructor(repo, path) {
  12264. super(repo, path, new QueryParams(), false);
  12265. }
  12266. get parent() {
  12267. const parentPath = pathParent(this._path);
  12268. return parentPath === null
  12269. ? null
  12270. : new ReferenceImpl(this._repo, parentPath);
  12271. }
  12272. get root() {
  12273. let ref = this;
  12274. while (ref.parent !== null) {
  12275. ref = ref.parent;
  12276. }
  12277. return ref;
  12278. }
  12279. }
  12280. /**
  12281. * A `DataSnapshot` contains data from a Database location.
  12282. *
  12283. * Any time you read data from the Database, you receive the data as a
  12284. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12285. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12286. * JavaScript object by calling the `val()` method. Alternatively, you can
  12287. * traverse into the snapshot by calling `child()` to return child snapshots
  12288. * (which you could then call `val()` on).
  12289. *
  12290. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12291. * a Database location. It cannot be modified and will never change (to modify
  12292. * data, you always call the `set()` method on a `Reference` directly).
  12293. */
  12294. class DataSnapshot {
  12295. /**
  12296. * @param _node - A SnapshotNode to wrap.
  12297. * @param ref - The location this snapshot came from.
  12298. * @param _index - The iteration order for this snapshot
  12299. * @hideconstructor
  12300. */
  12301. constructor(_node,
  12302. /**
  12303. * The location of this DataSnapshot.
  12304. */
  12305. ref, _index) {
  12306. this._node = _node;
  12307. this.ref = ref;
  12308. this._index = _index;
  12309. }
  12310. /**
  12311. * Gets the priority value of the data in this `DataSnapshot`.
  12312. *
  12313. * Applications need not use priority but can order collections by
  12314. * ordinary properties (see
  12315. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12316. * ).
  12317. */
  12318. get priority() {
  12319. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12320. return this._node.getPriority().val();
  12321. }
  12322. /**
  12323. * The key (last part of the path) of the location of this `DataSnapshot`.
  12324. *
  12325. * The last token in a Database location is considered its key. For example,
  12326. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12327. * `DataSnapshot` will return the key for the location that generated it.
  12328. * However, accessing the key on the root URL of a Database will return
  12329. * `null`.
  12330. */
  12331. get key() {
  12332. return this.ref.key;
  12333. }
  12334. /** Returns the number of child properties of this `DataSnapshot`. */
  12335. get size() {
  12336. return this._node.numChildren();
  12337. }
  12338. /**
  12339. * Gets another `DataSnapshot` for the location at the specified relative path.
  12340. *
  12341. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12342. * another `DataSnapshot` for the location at the specified relative path. The
  12343. * relative path can either be a simple child name (for example, "ada") or a
  12344. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12345. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12346. * whose value is `null`) is returned.
  12347. *
  12348. * @param path - A relative path to the location of child data.
  12349. */
  12350. child(path) {
  12351. const childPath = new Path(path);
  12352. const childRef = child(this.ref, path);
  12353. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12354. }
  12355. /**
  12356. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12357. * efficient than using `snapshot.val() !== null`.
  12358. */
  12359. exists() {
  12360. return !this._node.isEmpty();
  12361. }
  12362. /**
  12363. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12364. *
  12365. * The `exportVal()` method is similar to `val()`, except priority information
  12366. * is included (if available), making it suitable for backing up your data.
  12367. *
  12368. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12369. * Array, string, number, boolean, or `null`).
  12370. */
  12371. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12372. exportVal() {
  12373. return this._node.val(true);
  12374. }
  12375. /**
  12376. * Enumerates the top-level children in the `IteratedDataSnapshot`.
  12377. *
  12378. * Because of the way JavaScript objects work, the ordering of data in the
  12379. * JavaScript object returned by `val()` is not guaranteed to match the
  12380. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12381. * where `forEach()` comes in handy. It guarantees the children of a
  12382. * `DataSnapshot` will be iterated in their query order.
  12383. *
  12384. * If no explicit `orderBy*()` method is used, results are returned
  12385. * ordered by key (unless priorities are used, in which case, results are
  12386. * returned by priority).
  12387. *
  12388. * @param action - A function that will be called for each child DataSnapshot.
  12389. * The callback can return true to cancel further enumeration.
  12390. * @returns true if enumeration was canceled due to your callback returning
  12391. * true.
  12392. */
  12393. forEach(action) {
  12394. if (this._node.isLeafNode()) {
  12395. return false;
  12396. }
  12397. const childrenNode = this._node;
  12398. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12399. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12400. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12401. });
  12402. }
  12403. /**
  12404. * Returns true if the specified child path has (non-null) data.
  12405. *
  12406. * @param path - A relative path to the location of a potential child.
  12407. * @returns `true` if data exists at the specified child path; else
  12408. * `false`.
  12409. */
  12410. hasChild(path) {
  12411. const childPath = new Path(path);
  12412. return !this._node.getChild(childPath).isEmpty();
  12413. }
  12414. /**
  12415. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12416. * properties.
  12417. *
  12418. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12419. * children. If it does, you can enumerate them using `forEach()`. If it
  12420. * doesn't, then either this snapshot contains a primitive value (which can be
  12421. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12422. * `null`).
  12423. *
  12424. * @returns true if this snapshot has any children; else false.
  12425. */
  12426. hasChildren() {
  12427. if (this._node.isLeafNode()) {
  12428. return false;
  12429. }
  12430. else {
  12431. return !this._node.isEmpty();
  12432. }
  12433. }
  12434. /**
  12435. * Returns a JSON-serializable representation of this object.
  12436. */
  12437. toJSON() {
  12438. return this.exportVal();
  12439. }
  12440. /**
  12441. * Extracts a JavaScript value from a `DataSnapshot`.
  12442. *
  12443. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12444. * scalar type (string, number, or boolean), an array, or an object. It may
  12445. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12446. * data).
  12447. *
  12448. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12449. * Array, string, number, boolean, or `null`).
  12450. */
  12451. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12452. val() {
  12453. return this._node.val();
  12454. }
  12455. }
  12456. /**
  12457. *
  12458. * Returns a `Reference` representing the location in the Database
  12459. * corresponding to the provided path. If no path is provided, the `Reference`
  12460. * will point to the root of the Database.
  12461. *
  12462. * @param db - The database instance to obtain a reference for.
  12463. * @param path - Optional path representing the location the returned
  12464. * `Reference` will point. If not provided, the returned `Reference` will
  12465. * point to the root of the Database.
  12466. * @returns If a path is provided, a `Reference`
  12467. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12468. * root of the Database.
  12469. */
  12470. function ref(db, path) {
  12471. db = util.getModularInstance(db);
  12472. db._checkNotDeleted('ref');
  12473. return path !== undefined ? child(db._root, path) : db._root;
  12474. }
  12475. /**
  12476. * Returns a `Reference` representing the location in the Database
  12477. * corresponding to the provided Firebase URL.
  12478. *
  12479. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12480. * has a different domain than the current `Database` instance.
  12481. *
  12482. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12483. * and are not applied to the returned `Reference`.
  12484. *
  12485. * @param db - The database instance to obtain a reference for.
  12486. * @param url - The Firebase URL at which the returned `Reference` will
  12487. * point.
  12488. * @returns A `Reference` pointing to the provided
  12489. * Firebase URL.
  12490. */
  12491. function refFromURL(db, url) {
  12492. db = util.getModularInstance(db);
  12493. db._checkNotDeleted('refFromURL');
  12494. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12495. validateUrl('refFromURL', parsedURL);
  12496. const repoInfo = parsedURL.repoInfo;
  12497. if (!db._repo.repoInfo_.isCustomHost() &&
  12498. repoInfo.host !== db._repo.repoInfo_.host) {
  12499. fatal('refFromURL' +
  12500. ': Host name does not match the current database: ' +
  12501. '(found ' +
  12502. repoInfo.host +
  12503. ' but expected ' +
  12504. db._repo.repoInfo_.host +
  12505. ')');
  12506. }
  12507. return ref(db, parsedURL.path.toString());
  12508. }
  12509. /**
  12510. * Gets a `Reference` for the location at the specified relative path.
  12511. *
  12512. * The relative path can either be a simple child name (for example, "ada") or
  12513. * a deeper slash-separated path (for example, "ada/name/first").
  12514. *
  12515. * @param parent - The parent location.
  12516. * @param path - A relative path from this location to the desired child
  12517. * location.
  12518. * @returns The specified child location.
  12519. */
  12520. function child(parent, path) {
  12521. parent = util.getModularInstance(parent);
  12522. if (pathGetFront(parent._path) === null) {
  12523. validateRootPathString('child', 'path', path, false);
  12524. }
  12525. else {
  12526. validatePathString('child', 'path', path, false);
  12527. }
  12528. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12529. }
  12530. /**
  12531. * Returns an `OnDisconnect` object - see
  12532. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12533. * for more information on how to use it.
  12534. *
  12535. * @param ref - The reference to add OnDisconnect triggers for.
  12536. */
  12537. function onDisconnect(ref) {
  12538. ref = util.getModularInstance(ref);
  12539. return new OnDisconnect(ref._repo, ref._path);
  12540. }
  12541. /**
  12542. * Generates a new child location using a unique key and returns its
  12543. * `Reference`.
  12544. *
  12545. * This is the most common pattern for adding data to a collection of items.
  12546. *
  12547. * If you provide a value to `push()`, the value is written to the
  12548. * generated location. If you don't pass a value, nothing is written to the
  12549. * database and the child remains empty (but you can use the `Reference`
  12550. * elsewhere).
  12551. *
  12552. * The unique keys generated by `push()` are ordered by the current time, so the
  12553. * resulting list of items is chronologically sorted. The keys are also
  12554. * designed to be unguessable (they contain 72 random bits of entropy).
  12555. *
  12556. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12557. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12558. *
  12559. * @param parent - The parent location.
  12560. * @param value - Optional value to be written at the generated location.
  12561. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12562. * but can be used immediately as the `Reference` to the child location.
  12563. */
  12564. function push(parent, value) {
  12565. parent = util.getModularInstance(parent);
  12566. validateWritablePath('push', parent._path);
  12567. validateFirebaseDataArg('push', value, parent._path, true);
  12568. const now = repoServerTime(parent._repo);
  12569. const name = nextPushId(now);
  12570. // push() returns a ThennableReference whose promise is fulfilled with a
  12571. // regular Reference. We use child() to create handles to two different
  12572. // references. The first is turned into a ThennableReference below by adding
  12573. // then() and catch() methods and is used as the return value of push(). The
  12574. // second remains a regular Reference and is used as the fulfilled value of
  12575. // the first ThennableReference.
  12576. const thenablePushRef = child(parent, name);
  12577. const pushRef = child(parent, name);
  12578. let promise;
  12579. if (value != null) {
  12580. promise = set(pushRef, value).then(() => pushRef);
  12581. }
  12582. else {
  12583. promise = Promise.resolve(pushRef);
  12584. }
  12585. thenablePushRef.then = promise.then.bind(promise);
  12586. thenablePushRef.catch = promise.then.bind(promise, undefined);
  12587. return thenablePushRef;
  12588. }
  12589. /**
  12590. * Removes the data at this Database location.
  12591. *
  12592. * Any data at child locations will also be deleted.
  12593. *
  12594. * The effect of the remove will be visible immediately and the corresponding
  12595. * event 'value' will be triggered. Synchronization of the remove to the
  12596. * Firebase servers will also be started, and the returned Promise will resolve
  12597. * when complete. If provided, the onComplete callback will be called
  12598. * asynchronously after synchronization has finished.
  12599. *
  12600. * @param ref - The location to remove.
  12601. * @returns Resolves when remove on server is complete.
  12602. */
  12603. function remove(ref) {
  12604. validateWritablePath('remove', ref._path);
  12605. return set(ref, null);
  12606. }
  12607. /**
  12608. * Writes data to this Database location.
  12609. *
  12610. * This will overwrite any data at this location and all child locations.
  12611. *
  12612. * The effect of the write will be visible immediately, and the corresponding
  12613. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12614. * the data to the Firebase servers will also be started, and the returned
  12615. * Promise will resolve when complete. If provided, the `onComplete` callback
  12616. * will be called asynchronously after synchronization has finished.
  12617. *
  12618. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12619. * all data at this location and all child locations will be deleted.
  12620. *
  12621. * `set()` will remove any priority stored at this location, so if priority is
  12622. * meant to be preserved, you need to use `setWithPriority()` instead.
  12623. *
  12624. * Note that modifying data with `set()` will cancel any pending transactions
  12625. * at that location, so extreme care should be taken if mixing `set()` and
  12626. * `transaction()` to modify the same data.
  12627. *
  12628. * A single `set()` will generate a single "value" event at the location where
  12629. * the `set()` was performed.
  12630. *
  12631. * @param ref - The location to write to.
  12632. * @param value - The value to be written (string, number, boolean, object,
  12633. * array, or null).
  12634. * @returns Resolves when write to server is complete.
  12635. */
  12636. function set(ref, value) {
  12637. ref = util.getModularInstance(ref);
  12638. validateWritablePath('set', ref._path);
  12639. validateFirebaseDataArg('set', value, ref._path, false);
  12640. const deferred = new util.Deferred();
  12641. repoSetWithPriority(ref._repo, ref._path, value,
  12642. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12643. return deferred.promise;
  12644. }
  12645. /**
  12646. * Sets a priority for the data at this Database location.
  12647. *
  12648. * Applications need not use priority but can order collections by
  12649. * ordinary properties (see
  12650. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12651. * ).
  12652. *
  12653. * @param ref - The location to write to.
  12654. * @param priority - The priority to be written (string, number, or null).
  12655. * @returns Resolves when write to server is complete.
  12656. */
  12657. function setPriority(ref, priority) {
  12658. ref = util.getModularInstance(ref);
  12659. validateWritablePath('setPriority', ref._path);
  12660. validatePriority('setPriority', priority, false);
  12661. const deferred = new util.Deferred();
  12662. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12663. return deferred.promise;
  12664. }
  12665. /**
  12666. * Writes data the Database location. Like `set()` but also specifies the
  12667. * priority for that data.
  12668. *
  12669. * Applications need not use priority but can order collections by
  12670. * ordinary properties (see
  12671. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12672. * ).
  12673. *
  12674. * @param ref - The location to write to.
  12675. * @param value - The value to be written (string, number, boolean, object,
  12676. * array, or null).
  12677. * @param priority - The priority to be written (string, number, or null).
  12678. * @returns Resolves when write to server is complete.
  12679. */
  12680. function setWithPriority(ref, value, priority) {
  12681. validateWritablePath('setWithPriority', ref._path);
  12682. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12683. validatePriority('setWithPriority', priority, false);
  12684. if (ref.key === '.length' || ref.key === '.keys') {
  12685. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12686. }
  12687. const deferred = new util.Deferred();
  12688. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12689. return deferred.promise;
  12690. }
  12691. /**
  12692. * Writes multiple values to the Database at once.
  12693. *
  12694. * The `values` argument contains multiple property-value pairs that will be
  12695. * written to the Database together. Each child property can either be a simple
  12696. * property (for example, "name") or a relative path (for example,
  12697. * "name/first") from the current location to the data to update.
  12698. *
  12699. * As opposed to the `set()` method, `update()` can be use to selectively update
  12700. * only the referenced properties at the current location (instead of replacing
  12701. * all the child properties at the current location).
  12702. *
  12703. * The effect of the write will be visible immediately, and the corresponding
  12704. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12705. * the data to the Firebase servers will also be started, and the returned
  12706. * Promise will resolve when complete. If provided, the `onComplete` callback
  12707. * will be called asynchronously after synchronization has finished.
  12708. *
  12709. * A single `update()` will generate a single "value" event at the location
  12710. * where the `update()` was performed, regardless of how many children were
  12711. * modified.
  12712. *
  12713. * Note that modifying data with `update()` will cancel any pending
  12714. * transactions at that location, so extreme care should be taken if mixing
  12715. * `update()` and `transaction()` to modify the same data.
  12716. *
  12717. * Passing `null` to `update()` will remove the data at this location.
  12718. *
  12719. * See
  12720. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12721. *
  12722. * @param ref - The location to write to.
  12723. * @param values - Object containing multiple values.
  12724. * @returns Resolves when update on server is complete.
  12725. */
  12726. function update(ref, values) {
  12727. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12728. const deferred = new util.Deferred();
  12729. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12730. return deferred.promise;
  12731. }
  12732. /**
  12733. * Gets the most up-to-date result for this query.
  12734. *
  12735. * @param query - The query to run.
  12736. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12737. * available, or rejects if the client is unable to return a value (e.g., if the
  12738. * server is unreachable and there is nothing cached).
  12739. */
  12740. function get(query) {
  12741. query = util.getModularInstance(query);
  12742. const callbackContext = new CallbackContext(() => { });
  12743. const container = new ValueEventRegistration(callbackContext);
  12744. return repoGetValue(query._repo, query, container).then(node => {
  12745. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12746. });
  12747. }
  12748. /**
  12749. * Represents registration for 'value' events.
  12750. */
  12751. class ValueEventRegistration {
  12752. constructor(callbackContext) {
  12753. this.callbackContext = callbackContext;
  12754. }
  12755. respondsTo(eventType) {
  12756. return eventType === 'value';
  12757. }
  12758. createEvent(change, query) {
  12759. const index = query._queryParams.getIndex();
  12760. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12761. }
  12762. getEventRunner(eventData) {
  12763. if (eventData.getEventType() === 'cancel') {
  12764. return () => this.callbackContext.onCancel(eventData.error);
  12765. }
  12766. else {
  12767. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12768. }
  12769. }
  12770. createCancelEvent(error, path) {
  12771. if (this.callbackContext.hasCancelCallback) {
  12772. return new CancelEvent(this, error, path);
  12773. }
  12774. else {
  12775. return null;
  12776. }
  12777. }
  12778. matches(other) {
  12779. if (!(other instanceof ValueEventRegistration)) {
  12780. return false;
  12781. }
  12782. else if (!other.callbackContext || !this.callbackContext) {
  12783. // If no callback specified, we consider it to match any callback.
  12784. return true;
  12785. }
  12786. else {
  12787. return other.callbackContext.matches(this.callbackContext);
  12788. }
  12789. }
  12790. hasAnyCallback() {
  12791. return this.callbackContext !== null;
  12792. }
  12793. }
  12794. /**
  12795. * Represents the registration of a child_x event.
  12796. */
  12797. class ChildEventRegistration {
  12798. constructor(eventType, callbackContext) {
  12799. this.eventType = eventType;
  12800. this.callbackContext = callbackContext;
  12801. }
  12802. respondsTo(eventType) {
  12803. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12804. eventToCheck =
  12805. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12806. return this.eventType === eventToCheck;
  12807. }
  12808. createCancelEvent(error, path) {
  12809. if (this.callbackContext.hasCancelCallback) {
  12810. return new CancelEvent(this, error, path);
  12811. }
  12812. else {
  12813. return null;
  12814. }
  12815. }
  12816. createEvent(change, query) {
  12817. util.assert(change.childName != null, 'Child events should have a childName.');
  12818. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12819. const index = query._queryParams.getIndex();
  12820. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12821. }
  12822. getEventRunner(eventData) {
  12823. if (eventData.getEventType() === 'cancel') {
  12824. return () => this.callbackContext.onCancel(eventData.error);
  12825. }
  12826. else {
  12827. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12828. }
  12829. }
  12830. matches(other) {
  12831. if (other instanceof ChildEventRegistration) {
  12832. return (this.eventType === other.eventType &&
  12833. (!this.callbackContext ||
  12834. !other.callbackContext ||
  12835. this.callbackContext.matches(other.callbackContext)));
  12836. }
  12837. return false;
  12838. }
  12839. hasAnyCallback() {
  12840. return !!this.callbackContext;
  12841. }
  12842. }
  12843. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12844. let cancelCallback;
  12845. if (typeof cancelCallbackOrListenOptions === 'object') {
  12846. cancelCallback = undefined;
  12847. options = cancelCallbackOrListenOptions;
  12848. }
  12849. if (typeof cancelCallbackOrListenOptions === 'function') {
  12850. cancelCallback = cancelCallbackOrListenOptions;
  12851. }
  12852. if (options && options.onlyOnce) {
  12853. const userCallback = callback;
  12854. const onceCallback = (dataSnapshot, previousChildName) => {
  12855. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12856. userCallback(dataSnapshot, previousChildName);
  12857. };
  12858. onceCallback.userCallback = callback.userCallback;
  12859. onceCallback.context = callback.context;
  12860. callback = onceCallback;
  12861. }
  12862. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12863. const container = eventType === 'value'
  12864. ? new ValueEventRegistration(callbackContext)
  12865. : new ChildEventRegistration(eventType, callbackContext);
  12866. repoAddEventCallbackForQuery(query._repo, query, container);
  12867. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12868. }
  12869. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12870. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12871. }
  12872. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12873. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12874. }
  12875. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12876. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12877. }
  12878. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12879. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12880. }
  12881. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12882. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12883. }
  12884. /**
  12885. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12886. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12887. * the respective `on*` callbacks.
  12888. *
  12889. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12890. * will not automatically remove listeners registered on child nodes, `off()`
  12891. * must also be called on any child listeners to remove the callback.
  12892. *
  12893. * If a callback is not specified, all callbacks for the specified eventType
  12894. * will be removed. Similarly, if no eventType is specified, all callbacks
  12895. * for the `Reference` will be removed.
  12896. *
  12897. * Individual listeners can also be removed by invoking their unsubscribe
  12898. * callbacks.
  12899. *
  12900. * @param query - The query that the listener was registered with.
  12901. * @param eventType - One of the following strings: "value", "child_added",
  12902. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12903. * for the `Reference` will be removed.
  12904. * @param callback - The callback function that was passed to `on()` or
  12905. * `undefined` to remove all callbacks.
  12906. */
  12907. function off(query, eventType, callback) {
  12908. let container = null;
  12909. const expCallback = callback ? new CallbackContext(callback) : null;
  12910. if (eventType === 'value') {
  12911. container = new ValueEventRegistration(expCallback);
  12912. }
  12913. else if (eventType) {
  12914. container = new ChildEventRegistration(eventType, expCallback);
  12915. }
  12916. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12917. }
  12918. /**
  12919. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12920. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12921. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12922. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12923. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12924. * {@link orderByValue} or {@link equalTo} and
  12925. * can then be passed to {@link query} to create a new query instance that
  12926. * also contains this `QueryConstraint`.
  12927. */
  12928. class QueryConstraint {
  12929. }
  12930. class QueryEndAtConstraint extends QueryConstraint {
  12931. constructor(_value, _key) {
  12932. super();
  12933. this._value = _value;
  12934. this._key = _key;
  12935. this.type = 'endAt';
  12936. }
  12937. _apply(query) {
  12938. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12939. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12940. validateLimit(newParams);
  12941. validateQueryEndpoints(newParams);
  12942. if (query._queryParams.hasEnd()) {
  12943. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12944. 'endBefore or equalTo).');
  12945. }
  12946. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12947. }
  12948. }
  12949. /**
  12950. * Creates a `QueryConstraint` with the specified ending point.
  12951. *
  12952. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12953. * allows you to choose arbitrary starting and ending points for your queries.
  12954. *
  12955. * The ending point is inclusive, so children with exactly the specified value
  12956. * will be included in the query. The optional key argument can be used to
  12957. * further limit the range of the query. If it is specified, then children that
  12958. * have exactly the specified value must also have a key name less than or equal
  12959. * to the specified key.
  12960. *
  12961. * You can read more about `endAt()` in
  12962. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12963. *
  12964. * @param value - The value to end at. The argument type depends on which
  12965. * `orderBy*()` function was used in this query. Specify a value that matches
  12966. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12967. * value must be a string.
  12968. * @param key - The child key to end at, among the children with the previously
  12969. * specified priority. This argument is only allowed if ordering by child,
  12970. * value, or priority.
  12971. */
  12972. function endAt(value, key) {
  12973. validateKey('endAt', 'key', key, true);
  12974. return new QueryEndAtConstraint(value, key);
  12975. }
  12976. class QueryEndBeforeConstraint extends QueryConstraint {
  12977. constructor(_value, _key) {
  12978. super();
  12979. this._value = _value;
  12980. this._key = _key;
  12981. this.type = 'endBefore';
  12982. }
  12983. _apply(query) {
  12984. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12985. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12986. validateLimit(newParams);
  12987. validateQueryEndpoints(newParams);
  12988. if (query._queryParams.hasEnd()) {
  12989. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12990. 'endBefore or equalTo).');
  12991. }
  12992. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12993. }
  12994. }
  12995. /**
  12996. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  12997. *
  12998. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12999. * allows you to choose arbitrary starting and ending points for your queries.
  13000. *
  13001. * The ending point is exclusive. If only a value is provided, children
  13002. * with a value less than the specified value will be included in the query.
  13003. * If a key is specified, then children must have a value less than or equal
  13004. * to the specified value and a key name less than the specified key.
  13005. *
  13006. * @param value - The value to end before. The argument type depends on which
  13007. * `orderBy*()` function was used in this query. Specify a value that matches
  13008. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13009. * value must be a string.
  13010. * @param key - The child key to end before, among the children with the
  13011. * previously specified priority. This argument is only allowed if ordering by
  13012. * child, value, or priority.
  13013. */
  13014. function endBefore(value, key) {
  13015. validateKey('endBefore', 'key', key, true);
  13016. return new QueryEndBeforeConstraint(value, key);
  13017. }
  13018. class QueryStartAtConstraint extends QueryConstraint {
  13019. constructor(_value, _key) {
  13020. super();
  13021. this._value = _value;
  13022. this._key = _key;
  13023. this.type = 'startAt';
  13024. }
  13025. _apply(query) {
  13026. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13027. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13028. validateLimit(newParams);
  13029. validateQueryEndpoints(newParams);
  13030. if (query._queryParams.hasStart()) {
  13031. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13032. 'startBefore or equalTo).');
  13033. }
  13034. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13035. }
  13036. }
  13037. /**
  13038. * Creates a `QueryConstraint` with the specified starting point.
  13039. *
  13040. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13041. * allows you to choose arbitrary starting and ending points for your queries.
  13042. *
  13043. * The starting point is inclusive, so children with exactly the specified value
  13044. * will be included in the query. The optional key argument can be used to
  13045. * further limit the range of the query. If it is specified, then children that
  13046. * have exactly the specified value must also have a key name greater than or
  13047. * equal to the specified key.
  13048. *
  13049. * You can read more about `startAt()` in
  13050. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13051. *
  13052. * @param value - The value to start at. The argument type depends on which
  13053. * `orderBy*()` function was used in this query. Specify a value that matches
  13054. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13055. * value must be a string.
  13056. * @param key - The child key to start at. This argument is only allowed if
  13057. * ordering by child, value, or priority.
  13058. */
  13059. function startAt(value = null, key) {
  13060. validateKey('startAt', 'key', key, true);
  13061. return new QueryStartAtConstraint(value, key);
  13062. }
  13063. class QueryStartAfterConstraint extends QueryConstraint {
  13064. constructor(_value, _key) {
  13065. super();
  13066. this._value = _value;
  13067. this._key = _key;
  13068. this.type = 'startAfter';
  13069. }
  13070. _apply(query) {
  13071. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13072. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13073. validateLimit(newParams);
  13074. validateQueryEndpoints(newParams);
  13075. if (query._queryParams.hasStart()) {
  13076. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13077. 'startAfter, or equalTo).');
  13078. }
  13079. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13080. }
  13081. }
  13082. /**
  13083. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13084. *
  13085. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13086. * allows you to choose arbitrary starting and ending points for your queries.
  13087. *
  13088. * The starting point is exclusive. If only a value is provided, children
  13089. * with a value greater than the specified value will be included in the query.
  13090. * If a key is specified, then children must have a value greater than or equal
  13091. * to the specified value and a a key name greater than the specified key.
  13092. *
  13093. * @param value - The value to start after. The argument type depends on which
  13094. * `orderBy*()` function was used in this query. Specify a value that matches
  13095. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13096. * value must be a string.
  13097. * @param key - The child key to start after. This argument is only allowed if
  13098. * ordering by child, value, or priority.
  13099. */
  13100. function startAfter(value, key) {
  13101. validateKey('startAfter', 'key', key, true);
  13102. return new QueryStartAfterConstraint(value, key);
  13103. }
  13104. class QueryLimitToFirstConstraint extends QueryConstraint {
  13105. constructor(_limit) {
  13106. super();
  13107. this._limit = _limit;
  13108. this.type = 'limitToFirst';
  13109. }
  13110. _apply(query) {
  13111. if (query._queryParams.hasLimit()) {
  13112. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13113. 'or limitToLast).');
  13114. }
  13115. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13116. }
  13117. }
  13118. /**
  13119. * Creates a new `QueryConstraint` that if limited to the first specific number
  13120. * of children.
  13121. *
  13122. * The `limitToFirst()` method is used to set a maximum number of children to be
  13123. * synced for a given callback. If we set a limit of 100, we will initially only
  13124. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13125. * stored in our Database, a `child_added` event will fire for each message.
  13126. * However, if we have over 100 messages, we will only receive a `child_added`
  13127. * event for the first 100 ordered messages. As items change, we will receive
  13128. * `child_removed` events for each item that drops out of the active list so
  13129. * that the total number stays at 100.
  13130. *
  13131. * You can read more about `limitToFirst()` in
  13132. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13133. *
  13134. * @param limit - The maximum number of nodes to include in this query.
  13135. */
  13136. function limitToFirst(limit) {
  13137. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13138. throw new Error('limitToFirst: First argument must be a positive integer.');
  13139. }
  13140. return new QueryLimitToFirstConstraint(limit);
  13141. }
  13142. class QueryLimitToLastConstraint extends QueryConstraint {
  13143. constructor(_limit) {
  13144. super();
  13145. this._limit = _limit;
  13146. this.type = 'limitToLast';
  13147. }
  13148. _apply(query) {
  13149. if (query._queryParams.hasLimit()) {
  13150. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13151. 'or limitToLast).');
  13152. }
  13153. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13154. }
  13155. }
  13156. /**
  13157. * Creates a new `QueryConstraint` that is limited to return only the last
  13158. * specified number of children.
  13159. *
  13160. * The `limitToLast()` method is used to set a maximum number of children to be
  13161. * synced for a given callback. If we set a limit of 100, we will initially only
  13162. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13163. * stored in our Database, a `child_added` event will fire for each message.
  13164. * However, if we have over 100 messages, we will only receive a `child_added`
  13165. * event for the last 100 ordered messages. As items change, we will receive
  13166. * `child_removed` events for each item that drops out of the active list so
  13167. * that the total number stays at 100.
  13168. *
  13169. * You can read more about `limitToLast()` in
  13170. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13171. *
  13172. * @param limit - The maximum number of nodes to include in this query.
  13173. */
  13174. function limitToLast(limit) {
  13175. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13176. throw new Error('limitToLast: First argument must be a positive integer.');
  13177. }
  13178. return new QueryLimitToLastConstraint(limit);
  13179. }
  13180. class QueryOrderByChildConstraint extends QueryConstraint {
  13181. constructor(_path) {
  13182. super();
  13183. this._path = _path;
  13184. this.type = 'orderByChild';
  13185. }
  13186. _apply(query) {
  13187. validateNoPreviousOrderByCall(query, 'orderByChild');
  13188. const parsedPath = new Path(this._path);
  13189. if (pathIsEmpty(parsedPath)) {
  13190. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13191. }
  13192. const index = new PathIndex(parsedPath);
  13193. const newParams = queryParamsOrderBy(query._queryParams, index);
  13194. validateQueryEndpoints(newParams);
  13195. return new QueryImpl(query._repo, query._path, newParams,
  13196. /*orderByCalled=*/ true);
  13197. }
  13198. }
  13199. /**
  13200. * Creates a new `QueryConstraint` that orders by the specified child key.
  13201. *
  13202. * Queries can only order by one key at a time. Calling `orderByChild()`
  13203. * multiple times on the same query is an error.
  13204. *
  13205. * Firebase queries allow you to order your data by any child key on the fly.
  13206. * However, if you know in advance what your indexes will be, you can define
  13207. * them via the .indexOn rule in your Security Rules for better performance. See
  13208. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13209. * rule for more information.
  13210. *
  13211. * You can read more about `orderByChild()` in
  13212. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13213. *
  13214. * @param path - The path to order by.
  13215. */
  13216. function orderByChild(path) {
  13217. if (path === '$key') {
  13218. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13219. }
  13220. else if (path === '$priority') {
  13221. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13222. }
  13223. else if (path === '$value') {
  13224. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13225. }
  13226. validatePathString('orderByChild', 'path', path, false);
  13227. return new QueryOrderByChildConstraint(path);
  13228. }
  13229. class QueryOrderByKeyConstraint extends QueryConstraint {
  13230. constructor() {
  13231. super(...arguments);
  13232. this.type = 'orderByKey';
  13233. }
  13234. _apply(query) {
  13235. validateNoPreviousOrderByCall(query, 'orderByKey');
  13236. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13237. validateQueryEndpoints(newParams);
  13238. return new QueryImpl(query._repo, query._path, newParams,
  13239. /*orderByCalled=*/ true);
  13240. }
  13241. }
  13242. /**
  13243. * Creates a new `QueryConstraint` that orders by the key.
  13244. *
  13245. * Sorts the results of a query by their (ascending) key values.
  13246. *
  13247. * You can read more about `orderByKey()` in
  13248. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13249. */
  13250. function orderByKey() {
  13251. return new QueryOrderByKeyConstraint();
  13252. }
  13253. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13254. constructor() {
  13255. super(...arguments);
  13256. this.type = 'orderByPriority';
  13257. }
  13258. _apply(query) {
  13259. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13260. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_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 priority.
  13268. *
  13269. * Applications need not use priority but can order collections by
  13270. * ordinary properties (see
  13271. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13272. * for alternatives to priority.
  13273. */
  13274. function orderByPriority() {
  13275. return new QueryOrderByPriorityConstraint();
  13276. }
  13277. class QueryOrderByValueConstraint extends QueryConstraint {
  13278. constructor() {
  13279. super(...arguments);
  13280. this.type = 'orderByValue';
  13281. }
  13282. _apply(query) {
  13283. validateNoPreviousOrderByCall(query, 'orderByValue');
  13284. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13285. validateQueryEndpoints(newParams);
  13286. return new QueryImpl(query._repo, query._path, newParams,
  13287. /*orderByCalled=*/ true);
  13288. }
  13289. }
  13290. /**
  13291. * Creates a new `QueryConstraint` that orders by value.
  13292. *
  13293. * If the children of a query are all scalar values (string, number, or
  13294. * boolean), you can order the results by their (ascending) values.
  13295. *
  13296. * You can read more about `orderByValue()` in
  13297. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13298. */
  13299. function orderByValue() {
  13300. return new QueryOrderByValueConstraint();
  13301. }
  13302. class QueryEqualToValueConstraint extends QueryConstraint {
  13303. constructor(_value, _key) {
  13304. super();
  13305. this._value = _value;
  13306. this._key = _key;
  13307. this.type = 'equalTo';
  13308. }
  13309. _apply(query) {
  13310. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13311. if (query._queryParams.hasStart()) {
  13312. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13313. 'equalTo).');
  13314. }
  13315. if (query._queryParams.hasEnd()) {
  13316. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13317. 'equalTo).');
  13318. }
  13319. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13320. }
  13321. }
  13322. /**
  13323. * Creates a `QueryConstraint` that includes children that match the specified
  13324. * value.
  13325. *
  13326. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13327. * allows you to choose arbitrary starting and ending points for your queries.
  13328. *
  13329. * The optional key argument can be used to further limit the range of the
  13330. * query. If it is specified, then children that have exactly the specified
  13331. * value must also have exactly the specified key as their key name. This can be
  13332. * used to filter result sets with many matches for the same value.
  13333. *
  13334. * You can read more about `equalTo()` in
  13335. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13336. *
  13337. * @param value - The value to match for. The argument type depends on which
  13338. * `orderBy*()` function was used in this query. Specify a value that matches
  13339. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13340. * value must be a string.
  13341. * @param key - The child key to start at, among the children with the
  13342. * previously specified priority. This argument is only allowed if ordering by
  13343. * child, value, or priority.
  13344. */
  13345. function equalTo(value, key) {
  13346. validateKey('equalTo', 'key', key, true);
  13347. return new QueryEqualToValueConstraint(value, key);
  13348. }
  13349. /**
  13350. * Creates a new immutable instance of `Query` that is extended to also include
  13351. * additional query constraints.
  13352. *
  13353. * @param query - The Query instance to use as a base for the new constraints.
  13354. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13355. * @throws if any of the provided query constraints cannot be combined with the
  13356. * existing or new constraints.
  13357. */
  13358. function query(query, ...queryConstraints) {
  13359. let queryImpl = util.getModularInstance(query);
  13360. for (const constraint of queryConstraints) {
  13361. queryImpl = constraint._apply(queryImpl);
  13362. }
  13363. return queryImpl;
  13364. }
  13365. /**
  13366. * Define reference constructor in various modules
  13367. *
  13368. * We are doing this here to avoid several circular
  13369. * dependency issues
  13370. */
  13371. syncPointSetReferenceConstructor(ReferenceImpl);
  13372. syncTreeSetReferenceConstructor(ReferenceImpl);
  13373. /**
  13374. * @license
  13375. * Copyright 2020 Google LLC
  13376. *
  13377. * Licensed under the Apache License, Version 2.0 (the "License");
  13378. * you may not use this file except in compliance with the License.
  13379. * You may obtain a copy of the License at
  13380. *
  13381. * http://www.apache.org/licenses/LICENSE-2.0
  13382. *
  13383. * Unless required by applicable law or agreed to in writing, software
  13384. * distributed under the License is distributed on an "AS IS" BASIS,
  13385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13386. * See the License for the specific language governing permissions and
  13387. * limitations under the License.
  13388. */
  13389. /**
  13390. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13391. * modifying this definition, consult the definition in:
  13392. *
  13393. * https://github.com/firebase/firebase-admin-node
  13394. *
  13395. * and make sure the two are consistent.
  13396. */
  13397. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13398. /**
  13399. * Creates and caches `Repo` instances.
  13400. */
  13401. const repos = {};
  13402. /**
  13403. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13404. */
  13405. let useRestClient = false;
  13406. /**
  13407. * Update an existing `Repo` in place to point to a new host/port.
  13408. */
  13409. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13410. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13411. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13412. /*isUsingEmulator=*/ true);
  13413. if (tokenProvider) {
  13414. repo.authTokenProvider_ = tokenProvider;
  13415. }
  13416. }
  13417. /**
  13418. * This function should only ever be called to CREATE a new database instance.
  13419. * @internal
  13420. */
  13421. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13422. let dbUrl = url || app.options.databaseURL;
  13423. if (dbUrl === undefined) {
  13424. if (!app.options.projectId) {
  13425. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13426. ' a Project ID when calling firebase.initializeApp().');
  13427. }
  13428. log('Using default host for project ', app.options.projectId);
  13429. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13430. }
  13431. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13432. let repoInfo = parsedUrl.repoInfo;
  13433. let isEmulator;
  13434. let dbEmulatorHost = undefined;
  13435. if (typeof process !== 'undefined' && process.env) {
  13436. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13437. }
  13438. if (dbEmulatorHost) {
  13439. isEmulator = true;
  13440. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13441. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13442. repoInfo = parsedUrl.repoInfo;
  13443. }
  13444. else {
  13445. isEmulator = !parsedUrl.repoInfo.secure;
  13446. }
  13447. const authTokenProvider = nodeAdmin && isEmulator
  13448. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13449. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13450. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13451. if (!pathIsEmpty(parsedUrl.path)) {
  13452. fatal('Database URL must point to the root of a Firebase Database ' +
  13453. '(not including a child path).');
  13454. }
  13455. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13456. return new Database(repo, app);
  13457. }
  13458. /**
  13459. * Remove the repo and make sure it is disconnected.
  13460. *
  13461. */
  13462. function repoManagerDeleteRepo(repo, appName) {
  13463. const appRepos = repos[appName];
  13464. // This should never happen...
  13465. if (!appRepos || appRepos[repo.key] !== repo) {
  13466. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13467. }
  13468. repoInterrupt(repo);
  13469. delete appRepos[repo.key];
  13470. }
  13471. /**
  13472. * Ensures a repo doesn't already exist and then creates one using the
  13473. * provided app.
  13474. *
  13475. * @param repoInfo - The metadata about the Repo
  13476. * @returns The Repo object for the specified server / repoName.
  13477. */
  13478. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13479. let appRepos = repos[app.name];
  13480. if (!appRepos) {
  13481. appRepos = {};
  13482. repos[app.name] = appRepos;
  13483. }
  13484. let repo = appRepos[repoInfo.toURLString()];
  13485. if (repo) {
  13486. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13487. }
  13488. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13489. appRepos[repoInfo.toURLString()] = repo;
  13490. return repo;
  13491. }
  13492. /**
  13493. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13494. */
  13495. function repoManagerForceRestClient(forceRestClient) {
  13496. useRestClient = forceRestClient;
  13497. }
  13498. /**
  13499. * Class representing a Firebase Realtime Database.
  13500. */
  13501. class Database {
  13502. /** @hideconstructor */
  13503. constructor(_repoInternal,
  13504. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13505. app) {
  13506. this._repoInternal = _repoInternal;
  13507. this.app = app;
  13508. /** Represents a `Database` instance. */
  13509. this['type'] = 'database';
  13510. /** Track if the instance has been used (root or repo accessed) */
  13511. this._instanceStarted = false;
  13512. }
  13513. get _repo() {
  13514. if (!this._instanceStarted) {
  13515. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13516. this._instanceStarted = true;
  13517. }
  13518. return this._repoInternal;
  13519. }
  13520. get _root() {
  13521. if (!this._rootInternal) {
  13522. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13523. }
  13524. return this._rootInternal;
  13525. }
  13526. _delete() {
  13527. if (this._rootInternal !== null) {
  13528. repoManagerDeleteRepo(this._repo, this.app.name);
  13529. this._repoInternal = null;
  13530. this._rootInternal = null;
  13531. }
  13532. return Promise.resolve();
  13533. }
  13534. _checkNotDeleted(apiName) {
  13535. if (this._rootInternal === null) {
  13536. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13537. }
  13538. }
  13539. }
  13540. function checkTransportInit() {
  13541. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13542. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13543. }
  13544. }
  13545. /**
  13546. * Force the use of websockets instead of longPolling.
  13547. */
  13548. function forceWebSockets() {
  13549. checkTransportInit();
  13550. BrowserPollConnection.forceDisallow();
  13551. }
  13552. /**
  13553. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13554. */
  13555. function forceLongPolling() {
  13556. checkTransportInit();
  13557. WebSocketConnection.forceDisallow();
  13558. BrowserPollConnection.forceAllow();
  13559. }
  13560. /**
  13561. * Modify the provided instance to communicate with the Realtime Database
  13562. * emulator.
  13563. *
  13564. * <p>Note: This method must be called before performing any other operation.
  13565. *
  13566. * @param db - The instance to modify.
  13567. * @param host - The emulator host (ex: localhost)
  13568. * @param port - The emulator port (ex: 8080)
  13569. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13570. */
  13571. function connectDatabaseEmulator(db, host, port, options = {}) {
  13572. db = util.getModularInstance(db);
  13573. db._checkNotDeleted('useEmulator');
  13574. if (db._instanceStarted) {
  13575. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13576. }
  13577. const repo = db._repoInternal;
  13578. let tokenProvider = undefined;
  13579. if (repo.repoInfo_.nodeAdmin) {
  13580. if (options.mockUserToken) {
  13581. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13582. }
  13583. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13584. }
  13585. else if (options.mockUserToken) {
  13586. const token = typeof options.mockUserToken === 'string'
  13587. ? options.mockUserToken
  13588. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13589. tokenProvider = new EmulatorTokenProvider(token);
  13590. }
  13591. // Modify the repo to apply emulator settings
  13592. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13593. }
  13594. /**
  13595. * Disconnects from the server (all Database operations will be completed
  13596. * offline).
  13597. *
  13598. * The client automatically maintains a persistent connection to the Database
  13599. * server, which will remain active indefinitely and reconnect when
  13600. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13601. * to control the client connection in cases where a persistent connection is
  13602. * undesirable.
  13603. *
  13604. * While offline, the client will no longer receive data updates from the
  13605. * Database. However, all Database operations performed locally will continue to
  13606. * immediately fire events, allowing your application to continue behaving
  13607. * normally. Additionally, each operation performed locally will automatically
  13608. * be queued and retried upon reconnection to the Database server.
  13609. *
  13610. * To reconnect to the Database and begin receiving remote events, see
  13611. * `goOnline()`.
  13612. *
  13613. * @param db - The instance to disconnect.
  13614. */
  13615. function goOffline(db) {
  13616. db = util.getModularInstance(db);
  13617. db._checkNotDeleted('goOffline');
  13618. repoInterrupt(db._repo);
  13619. }
  13620. /**
  13621. * Reconnects to the server and synchronizes the offline Database state
  13622. * with the server state.
  13623. *
  13624. * This method should be used after disabling the active connection with
  13625. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13626. * and fire the appropriate events so that your client "catches up"
  13627. * automatically.
  13628. *
  13629. * @param db - The instance to reconnect.
  13630. */
  13631. function goOnline(db) {
  13632. db = util.getModularInstance(db);
  13633. db._checkNotDeleted('goOnline');
  13634. repoResume(db._repo);
  13635. }
  13636. function enableLogging(logger, persistent) {
  13637. enableLogging$1(logger, persistent);
  13638. }
  13639. /**
  13640. * @license
  13641. * Copyright 2020 Google LLC
  13642. *
  13643. * Licensed under the Apache License, Version 2.0 (the "License");
  13644. * you may not use this file except in compliance with the License.
  13645. * You may obtain a copy of the License at
  13646. *
  13647. * http://www.apache.org/licenses/LICENSE-2.0
  13648. *
  13649. * Unless required by applicable law or agreed to in writing, software
  13650. * distributed under the License is distributed on an "AS IS" BASIS,
  13651. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13652. * See the License for the specific language governing permissions and
  13653. * limitations under the License.
  13654. */
  13655. const SERVER_TIMESTAMP = {
  13656. '.sv': 'timestamp'
  13657. };
  13658. /**
  13659. * Returns a placeholder value for auto-populating the current timestamp (time
  13660. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13661. * servers.
  13662. */
  13663. function serverTimestamp() {
  13664. return SERVER_TIMESTAMP;
  13665. }
  13666. /**
  13667. * Returns a placeholder value that can be used to atomically increment the
  13668. * current database value by the provided delta.
  13669. *
  13670. * @param delta - the amount to modify the current value atomically.
  13671. * @returns A placeholder value for modifying data atomically server-side.
  13672. */
  13673. function increment(delta) {
  13674. return {
  13675. '.sv': {
  13676. 'increment': delta
  13677. }
  13678. };
  13679. }
  13680. /**
  13681. * @license
  13682. * Copyright 2020 Google LLC
  13683. *
  13684. * Licensed under the Apache License, Version 2.0 (the "License");
  13685. * you may not use this file except in compliance with the License.
  13686. * You may obtain a copy of the License at
  13687. *
  13688. * http://www.apache.org/licenses/LICENSE-2.0
  13689. *
  13690. * Unless required by applicable law or agreed to in writing, software
  13691. * distributed under the License is distributed on an "AS IS" BASIS,
  13692. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13693. * See the License for the specific language governing permissions and
  13694. * limitations under the License.
  13695. */
  13696. /**
  13697. * A type for the resolve value of {@link runTransaction}.
  13698. */
  13699. class TransactionResult {
  13700. /** @hideconstructor */
  13701. constructor(
  13702. /** Whether the transaction was successfully committed. */
  13703. committed,
  13704. /** The resulting data snapshot. */
  13705. snapshot) {
  13706. this.committed = committed;
  13707. this.snapshot = snapshot;
  13708. }
  13709. /** Returns a JSON-serializable representation of this object. */
  13710. toJSON() {
  13711. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13712. }
  13713. }
  13714. /**
  13715. * Atomically modifies the data at this location.
  13716. *
  13717. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13718. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13719. * used to modify the existing value to a new value, ensuring there are no
  13720. * conflicts with other clients writing to the same location at the same time.
  13721. *
  13722. * To accomplish this, you pass `runTransaction()` an update function which is
  13723. * used to transform the current value into a new value. If another client
  13724. * writes to the location before your new value is successfully written, your
  13725. * update function will be called again with the new current value, and the
  13726. * write will be retried. This will happen repeatedly until your write succeeds
  13727. * without conflict or you abort the transaction by not returning a value from
  13728. * your update function.
  13729. *
  13730. * Note: Modifying data with `set()` will cancel any pending transactions at
  13731. * that location, so extreme care should be taken if mixing `set()` and
  13732. * `runTransaction()` to update the same data.
  13733. *
  13734. * Note: When using transactions with Security and Firebase Rules in place, be
  13735. * aware that a client needs `.read` access in addition to `.write` access in
  13736. * order to perform a transaction. This is because the client-side nature of
  13737. * transactions requires the client to read the data in order to transactionally
  13738. * update it.
  13739. *
  13740. * @param ref - The location to atomically modify.
  13741. * @param transactionUpdate - A developer-supplied function which will be passed
  13742. * the current data stored at this location (as a JavaScript object). The
  13743. * function should return the new value it would like written (as a JavaScript
  13744. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13745. * transaction will be aborted and the data at this location will not be
  13746. * modified.
  13747. * @param options - An options object to configure transactions.
  13748. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13749. * callback to handle success and failure.
  13750. */
  13751. function runTransaction(ref,
  13752. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13753. transactionUpdate, options) {
  13754. var _a;
  13755. ref = util.getModularInstance(ref);
  13756. validateWritablePath('Reference.transaction', ref._path);
  13757. if (ref.key === '.length' || ref.key === '.keys') {
  13758. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13759. }
  13760. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13761. const deferred = new util.Deferred();
  13762. const promiseComplete = (error, committed, node) => {
  13763. let dataSnapshot = null;
  13764. if (error) {
  13765. deferred.reject(error);
  13766. }
  13767. else {
  13768. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13769. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13770. }
  13771. };
  13772. // Add a watch to make sure we get server updates.
  13773. const unwatcher = onValue(ref, () => { });
  13774. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13775. return deferred.promise;
  13776. }
  13777. /**
  13778. * @license
  13779. * Copyright 2017 Google LLC
  13780. *
  13781. * Licensed under the Apache License, Version 2.0 (the "License");
  13782. * you may not use this file except in compliance with the License.
  13783. * You may obtain a copy of the License at
  13784. *
  13785. * http://www.apache.org/licenses/LICENSE-2.0
  13786. *
  13787. * Unless required by applicable law or agreed to in writing, software
  13788. * distributed under the License is distributed on an "AS IS" BASIS,
  13789. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13790. * See the License for the specific language governing permissions and
  13791. * limitations under the License.
  13792. */
  13793. PersistentConnection;
  13794. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13795. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13796. this.sendRequest('q', { p: pathString }, onComplete);
  13797. };
  13798. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13799. PersistentConnection.prototype.echo = function (data, onEcho) {
  13800. this.sendRequest('echo', { d: data }, onEcho);
  13801. };
  13802. // RealTimeConnection properties that we use in tests.
  13803. Connection;
  13804. /**
  13805. * @internal
  13806. */
  13807. const hijackHash = function (newHash) {
  13808. const oldPut = PersistentConnection.prototype.put;
  13809. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13810. if (hash !== undefined) {
  13811. hash = newHash();
  13812. }
  13813. oldPut.call(this, pathString, data, onComplete, hash);
  13814. };
  13815. return function () {
  13816. PersistentConnection.prototype.put = oldPut;
  13817. };
  13818. };
  13819. RepoInfo;
  13820. /**
  13821. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13822. * @internal
  13823. */
  13824. const forceRestClient = function (forceRestClient) {
  13825. repoManagerForceRestClient(forceRestClient);
  13826. };
  13827. /**
  13828. * @license
  13829. * Copyright 2023 Google LLC
  13830. *
  13831. * Licensed under the Apache License, Version 2.0 (the "License");
  13832. * you may not use this file except in compliance with the License.
  13833. * You may obtain a copy of the License at
  13834. *
  13835. * http://www.apache.org/licenses/LICENSE-2.0
  13836. *
  13837. * Unless required by applicable law or agreed to in writing, software
  13838. * distributed under the License is distributed on an "AS IS" BASIS,
  13839. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13840. * See the License for the specific language governing permissions and
  13841. * limitations under the License.
  13842. */
  13843. /**
  13844. * Used by console to create a database based on the app,
  13845. * passed database URL and a custom auth implementation.
  13846. * @internal
  13847. * @param app - A valid FirebaseApp-like object
  13848. * @param url - A valid Firebase databaseURL
  13849. * @param version - custom version e.g. firebase-admin version
  13850. * @param customAppCheckImpl - custom app check implementation
  13851. * @param customAuthImpl - custom auth implementation
  13852. */
  13853. function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {
  13854. setSDKVersion(version);
  13855. /**
  13856. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  13857. * any actual function.
  13858. */
  13859. const componentContainer = new component.ComponentContainer('database-standalone');
  13860. const authProvider = new component.Provider('auth-internal', componentContainer);
  13861. let appCheckProvider;
  13862. if (customAppCheckImpl) {
  13863. appCheckProvider = new component.Provider('app-check-internal', componentContainer);
  13864. appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13865. }
  13866. authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13867. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);
  13868. }
  13869. /**
  13870. * @license
  13871. * Copyright 2021 Google LLC
  13872. *
  13873. * Licensed under the Apache License, Version 2.0 (the "License");
  13874. * you may not use this file except in compliance with the License.
  13875. * You may obtain a copy of the License at
  13876. *
  13877. * http://www.apache.org/licenses/LICENSE-2.0
  13878. *
  13879. * Unless required by applicable law or agreed to in writing, software
  13880. * distributed under the License is distributed on an "AS IS" BASIS,
  13881. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13882. * See the License for the specific language governing permissions and
  13883. * limitations under the License.
  13884. */
  13885. setWebSocketImpl(Websocket__default["default"].Client);
  13886. exports.DataSnapshot = DataSnapshot;
  13887. exports.Database = Database;
  13888. exports.OnDisconnect = OnDisconnect;
  13889. exports.QueryConstraint = QueryConstraint;
  13890. exports.TransactionResult = TransactionResult;
  13891. exports._QueryImpl = QueryImpl;
  13892. exports._QueryParams = QueryParams;
  13893. exports._ReferenceImpl = ReferenceImpl;
  13894. exports._TEST_ACCESS_forceRestClient = forceRestClient;
  13895. exports._TEST_ACCESS_hijackHash = hijackHash;
  13896. exports._initStandalone = _initStandalone;
  13897. exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  13898. exports._setSDKVersion = setSDKVersion;
  13899. exports._validatePathString = validatePathString;
  13900. exports._validateWritablePath = validateWritablePath;
  13901. exports.child = child;
  13902. exports.connectDatabaseEmulator = connectDatabaseEmulator;
  13903. exports.enableLogging = enableLogging;
  13904. exports.endAt = endAt;
  13905. exports.endBefore = endBefore;
  13906. exports.equalTo = equalTo;
  13907. exports.forceLongPolling = forceLongPolling;
  13908. exports.forceWebSockets = forceWebSockets;
  13909. exports.get = get;
  13910. exports.goOffline = goOffline;
  13911. exports.goOnline = goOnline;
  13912. exports.increment = increment;
  13913. exports.limitToFirst = limitToFirst;
  13914. exports.limitToLast = limitToLast;
  13915. exports.off = off;
  13916. exports.onChildAdded = onChildAdded;
  13917. exports.onChildChanged = onChildChanged;
  13918. exports.onChildMoved = onChildMoved;
  13919. exports.onChildRemoved = onChildRemoved;
  13920. exports.onDisconnect = onDisconnect;
  13921. exports.onValue = onValue;
  13922. exports.orderByChild = orderByChild;
  13923. exports.orderByKey = orderByKey;
  13924. exports.orderByPriority = orderByPriority;
  13925. exports.orderByValue = orderByValue;
  13926. exports.push = push;
  13927. exports.query = query;
  13928. exports.ref = ref;
  13929. exports.refFromURL = refFromURL;
  13930. exports.remove = remove;
  13931. exports.runTransaction = runTransaction;
  13932. exports.serverTimestamp = serverTimestamp;
  13933. exports.set = set;
  13934. exports.setPriority = setPriority;
  13935. exports.setWithPriority = setWithPriority;
  13936. exports.startAfter = startAfter;
  13937. exports.startAt = startAt;
  13938. exports.update = update;
  13939. //# sourceMappingURL=index.standalone.js.map