1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408 |
- import { getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app';
- import { Component } from '@firebase/component';
- import { __spreadArray, __read, __values, __extends, __awaiter, __generator, __assign } from 'tslib';
- import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';
- import { Logger, LogLevel } from '@firebase/logger';
-
- var name = "@firebase/database";
- var version = "0.14.1";
-
-
-
- var SDK_VERSION = '';
-
- function setSDKVersion(version) {
- SDK_VERSION = version;
- }
-
-
-
- var DOMStorageWrapper = (function () {
-
-
- function DOMStorageWrapper(domStorage_) {
- this.domStorage_ = domStorage_;
-
- this.prefix_ = 'firebase:';
- }
-
-
- DOMStorageWrapper.prototype.set = function (key, value) {
- if (value == null) {
- this.domStorage_.removeItem(this.prefixedName_(key));
- }
- else {
- this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
- }
- };
-
-
- DOMStorageWrapper.prototype.get = function (key) {
- var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
- if (storedVal == null) {
- return null;
- }
- else {
- return jsonEval(storedVal);
- }
- };
- DOMStorageWrapper.prototype.remove = function (key) {
- this.domStorage_.removeItem(this.prefixedName_(key));
- };
- DOMStorageWrapper.prototype.prefixedName_ = function (name) {
- return this.prefix_ + name;
- };
- DOMStorageWrapper.prototype.toString = function () {
- return this.domStorage_.toString();
- };
- return DOMStorageWrapper;
- }());
-
-
-
- var MemoryStorage = (function () {
- function MemoryStorage() {
- this.cache_ = {};
- this.isInMemoryStorage = true;
- }
- MemoryStorage.prototype.set = function (key, value) {
- if (value == null) {
- delete this.cache_[key];
- }
- else {
- this.cache_[key] = value;
- }
- };
- MemoryStorage.prototype.get = function (key) {
- if (contains(this.cache_, key)) {
- return this.cache_[key];
- }
- return null;
- };
- MemoryStorage.prototype.remove = function (key) {
- delete this.cache_[key];
- };
- return MemoryStorage;
- }());
-
-
-
- var createStoragefor = function (domStorageName) {
- try {
-
-
- if (typeof window !== 'undefined' &&
- typeof window[domStorageName] !== 'undefined') {
-
- var domStorage = window[domStorageName];
- domStorage.setItem('firebase:sentinel', 'cache');
- domStorage.removeItem('firebase:sentinel');
- return new DOMStorageWrapper(domStorage);
- }
- }
- catch (e) { }
-
-
- return new MemoryStorage();
- };
-
- var PersistentStorage = createStoragefor('localStorage');
-
- var SessionStorage = createStoragefor('sessionStorage');
-
-
- var logClient = new Logger('@firebase/database');
-
- var LUIDGenerator = (function () {
- var id = 1;
- return function () {
- return id++;
- };
- })();
-
- var sha1 = function (str) {
- var utf8Bytes = stringToByteArray(str);
- var sha1 = new Sha1();
- sha1.update(utf8Bytes);
- var sha1Bytes = sha1.digest();
- return base64.encodeByteArray(sha1Bytes);
- };
- var buildLogMessage_ = function () {
- var varArgs = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- varArgs[_i] = arguments[_i];
- }
- var message = '';
- for (var i = 0; i < varArgs.length; i++) {
- var arg = varArgs[i];
- if (Array.isArray(arg) ||
- (arg &&
- typeof arg === 'object' &&
-
- typeof arg.length === 'number')) {
- message += buildLogMessage_.apply(null, arg);
- }
- else if (typeof arg === 'object') {
- message += stringify(arg);
- }
- else {
- message += arg;
- }
- message += ' ';
- }
- return message;
- };
-
- var logger = null;
-
- var firstLog_ = true;
-
- var enableLogging$1 = function (logger_, persistent) {
- assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
- if (logger_ === true) {
- logClient.logLevel = LogLevel.VERBOSE;
- logger = logClient.log.bind(logClient);
- if (persistent) {
- SessionStorage.set('logging_enabled', true);
- }
- }
- else if (typeof logger_ === 'function') {
- logger = logger_;
- }
- else {
- logger = null;
- SessionStorage.remove('logging_enabled');
- }
- };
- var log = function () {
- var varArgs = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- varArgs[_i] = arguments[_i];
- }
- if (firstLog_ === true) {
- firstLog_ = false;
- if (logger === null && SessionStorage.get('logging_enabled') === true) {
- enableLogging$1(true);
- }
- }
- if (logger) {
- var message = buildLogMessage_.apply(null, varArgs);
- logger(message);
- }
- };
- var logWrapper = function (prefix) {
- return function () {
- var varArgs = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- varArgs[_i] = arguments[_i];
- }
- log.apply(void 0, __spreadArray([prefix], __read(varArgs), false));
- };
- };
- var error = function () {
- var varArgs = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- varArgs[_i] = arguments[_i];
- }
- var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false));
- logClient.error(message);
- };
- var fatal = function () {
- var varArgs = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- varArgs[_i] = arguments[_i];
- }
- var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false)));
- logClient.error(message);
- throw new Error(message);
- };
- var warn = function () {
- var varArgs = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- varArgs[_i] = arguments[_i];
- }
- var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false));
- logClient.warn(message);
- };
-
- var warnIfPageIsSecure = function () {
-
- if (typeof window !== 'undefined' &&
- window.location &&
- window.location.protocol &&
- window.location.protocol.indexOf('https:') !== -1) {
- warn('Insecure Firebase access from a secure page. ' +
- 'Please use https in calls to new Firebase().');
- }
- };
-
- var isInvalidJSONNumber = function (data) {
- return (typeof data === 'number' &&
- (data !== data ||
- data === Number.POSITIVE_INFINITY ||
- data === Number.NEGATIVE_INFINITY));
- };
- var executeWhenDOMReady = function (fn) {
- if (isNodeSdk() || document.readyState === 'complete') {
- fn();
- }
- else {
-
-
- var called_1 = false;
- var wrappedFn_1 = function () {
- if (!document.body) {
- setTimeout(wrappedFn_1, Math.floor(10));
- return;
- }
- if (!called_1) {
- called_1 = true;
- fn();
- }
- };
- if (document.addEventListener) {
- document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
-
- window.addEventListener('load', wrappedFn_1, false);
-
- }
- else if (document.attachEvent) {
-
-
- document.attachEvent('onreadystatechange', function () {
- if (document.readyState === 'complete') {
- wrappedFn_1();
- }
- });
-
-
- window.attachEvent('onload', wrappedFn_1);
-
-
-
- }
- }
- };
-
- var MIN_NAME = '[MIN_NAME]';
-
- var MAX_NAME = '[MAX_NAME]';
-
- var nameCompare = function (a, b) {
- if (a === b) {
- return 0;
- }
- else if (a === MIN_NAME || b === MAX_NAME) {
- return -1;
- }
- else if (b === MIN_NAME || a === MAX_NAME) {
- return 1;
- }
- else {
- var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
- if (aAsInt !== null) {
- if (bAsInt !== null) {
- return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
- }
- else {
- return -1;
- }
- }
- else if (bAsInt !== null) {
- return 1;
- }
- else {
- return a < b ? -1 : 1;
- }
- }
- };
-
- var stringCompare = function (a, b) {
- if (a === b) {
- return 0;
- }
- else if (a < b) {
- return -1;
- }
- else {
- return 1;
- }
- };
- var requireKey = function (key, obj) {
- if (obj && key in obj) {
- return obj[key];
- }
- else {
- throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
- }
- };
- var ObjectToUniqueKey = function (obj) {
- if (typeof obj !== 'object' || obj === null) {
- return stringify(obj);
- }
- var keys = [];
-
- for (var k in obj) {
- keys.push(k);
- }
-
- keys.sort();
- var key = '{';
- for (var i = 0; i < keys.length; i++) {
- if (i !== 0) {
- key += ',';
- }
- key += stringify(keys[i]);
- key += ':';
- key += ObjectToUniqueKey(obj[keys[i]]);
- }
- key += '}';
- return key;
- };
-
- var splitStringBySize = function (str, segsize) {
- var len = str.length;
- if (len <= segsize) {
- return [str];
- }
- var dataSegs = [];
- for (var c = 0; c < len; c += segsize) {
- if (c + segsize > len) {
- dataSegs.push(str.substring(c, len));
- }
- else {
- dataSegs.push(str.substring(c, c + segsize));
- }
- }
- return dataSegs;
- };
-
- function each(obj, fn) {
- for (var key in obj) {
- if (obj.hasOwnProperty(key)) {
- fn(key, obj[key]);
- }
- }
- }
-
- var doubleToIEEE754String = function (v) {
- assert(!isInvalidJSONNumber(v), 'Invalid JSON number');
- var ebits = 11, fbits = 52;
- var bias = (1 << (ebits - 1)) - 1;
- var s, e, f, ln, i;
-
-
- if (v === 0) {
- e = 0;
- f = 0;
- s = 1 / v === -Infinity ? 1 : 0;
- }
- else {
- s = v < 0;
- v = Math.abs(v);
- if (v >= Math.pow(2, 1 - bias)) {
-
- ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
- e = ln + bias;
- f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
- }
- else {
-
- e = 0;
- f = Math.round(v / Math.pow(2, 1 - bias - fbits));
- }
- }
-
- var bits = [];
- for (i = fbits; i; i -= 1) {
- bits.push(f % 2 ? 1 : 0);
- f = Math.floor(f / 2);
- }
- for (i = ebits; i; i -= 1) {
- bits.push(e % 2 ? 1 : 0);
- e = Math.floor(e / 2);
- }
- bits.push(s ? 1 : 0);
- bits.reverse();
- var str = bits.join('');
-
- var hexByteString = '';
- for (i = 0; i < 64; i += 8) {
- var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
- if (hexByte.length === 1) {
- hexByte = '0' + hexByte;
- }
- hexByteString = hexByteString + hexByte;
- }
- return hexByteString.toLowerCase();
- };
-
- var isChromeExtensionContentScript = function () {
- return !!(typeof window === 'object' &&
- window['chrome'] &&
- window['chrome']['extension'] &&
- !/^chrome/.test(window.location.href));
- };
-
- var isWindowsStoreApp = function () {
-
- return typeof Windows === 'object' && typeof Windows.UI === 'object';
- };
-
- function errorForServerCode(code, query) {
- var reason = 'Unknown Error';
- if (code === 'too_big') {
- reason =
- 'The data requested exceeds the maximum size ' +
- 'that can be accessed with a single request.';
- }
- else if (code === 'permission_denied') {
- reason = "Client doesn't have permission to access the desired data.";
- }
- else if (code === 'unavailable') {
- reason = 'The service is unavailable';
- }
- var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
-
- error.code = code.toUpperCase();
- return error;
- }
-
- var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
-
- var INTEGER_32_MIN = -2147483648;
-
- var INTEGER_32_MAX = 2147483647;
-
- var tryParseInt = function (str) {
- if (INTEGER_REGEXP_.test(str)) {
- var intVal = Number(str);
- if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
- return intVal;
- }
- }
- return null;
- };
-
- var exceptionGuard = function (fn) {
- try {
- fn();
- }
- catch (e) {
-
- setTimeout(function () {
-
-
-
-
- var stack = e.stack || '';
- warn('Exception was thrown by user callback.', stack);
- throw e;
- }, Math.floor(0));
- }
- };
-
- var beingCrawled = function () {
- var userAgent = (typeof window === 'object' &&
- window['navigator'] &&
- window['navigator']['userAgent']) ||
- '';
-
-
-
-
- return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
- };
-
- var setTimeoutNonBlocking = function (fn, time) {
- var timeout = setTimeout(fn, time);
-
- if (typeof timeout === 'number' &&
-
- typeof Deno !== 'undefined' &&
-
- Deno['unrefTimer']) {
-
- Deno.unrefTimer(timeout);
-
- }
- else if (typeof timeout === 'object' && timeout['unref']) {
-
- timeout['unref']();
- }
- return timeout;
- };
-
-
-
- var AppCheckTokenProvider = (function () {
- function AppCheckTokenProvider(appName_, appCheckProvider) {
- var _this = this;
- this.appName_ = appName_;
- this.appCheckProvider = appCheckProvider;
- this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
- if (!this.appCheck) {
- appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
- }
- }
- AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
- var _this = this;
- if (!this.appCheck) {
- return new Promise(function (resolve, reject) {
-
-
-
-
- setTimeout(function () {
- if (_this.appCheck) {
- _this.getToken(forceRefresh).then(resolve, reject);
- }
- else {
- resolve(null);
- }
- }, 0);
- });
- }
- return this.appCheck.getToken(forceRefresh);
- };
- AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
- var _a;
- (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
- };
- AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
- warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
- 'are invalid. This usually indicates your app was not initialized correctly.');
- };
- return AppCheckTokenProvider;
- }());
-
-
-
- var FirebaseAuthTokenProvider = (function () {
- function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
- var _this = this;
- this.appName_ = appName_;
- this.firebaseOptions_ = firebaseOptions_;
- this.authProvider_ = authProvider_;
- this.auth_ = null;
- this.auth_ = authProvider_.getImmediate({ optional: true });
- if (!this.auth_) {
- authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
- }
- }
- FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
- var _this = this;
- if (!this.auth_) {
- return new Promise(function (resolve, reject) {
-
-
-
-
- setTimeout(function () {
- if (_this.auth_) {
- _this.getToken(forceRefresh).then(resolve, reject);
- }
- else {
- resolve(null);
- }
- }, 0);
- });
- }
- return this.auth_.getToken(forceRefresh).catch(function (error) {
-
-
- if (error && error.code === 'auth/token-not-initialized') {
- log('Got auth/token-not-initialized error. Treating as null token.');
- return null;
- }
- else {
- return Promise.reject(error);
- }
- });
- };
- FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
-
-
- if (this.auth_) {
- this.auth_.addAuthTokenListener(listener);
- }
- else {
- this.authProvider_
- .get()
- .then(function (auth) { return auth.addAuthTokenListener(listener); });
- }
- };
- FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
- this.authProvider_
- .get()
- .then(function (auth) { return auth.removeAuthTokenListener(listener); });
- };
- FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
- var errorMessage = 'Provided authentication credentials for the app named "' +
- this.appName_ +
- '" are invalid. This usually indicates your app was not ' +
- 'initialized correctly. ';
- if ('credential' in this.firebaseOptions_) {
- errorMessage +=
- 'Make sure the "credential" property provided to initializeApp() ' +
- 'is authorized to access the specified "databaseURL" and is from the correct ' +
- 'project.';
- }
- else if ('serviceAccount' in this.firebaseOptions_) {
- errorMessage +=
- 'Make sure the "serviceAccount" property provided to initializeApp() ' +
- 'is authorized to access the specified "databaseURL" and is from the correct ' +
- 'project.';
- }
- else {
- errorMessage +=
- 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
- 'initializeApp() match the values provided for your app at ' +
- 'https://console.firebase.google.com/.';
- }
- warn(errorMessage);
- };
- return FirebaseAuthTokenProvider;
- }());
-
- var EmulatorTokenProvider = (function () {
- function EmulatorTokenProvider(accessToken) {
- this.accessToken = accessToken;
- }
- EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
- return Promise.resolve({
- accessToken: this.accessToken
- });
- };
- EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
-
-
- listener(this.accessToken);
- };
- EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
- EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
-
- EmulatorTokenProvider.OWNER = 'owner';
- return EmulatorTokenProvider;
- }());
-
-
- var PROTOCOL_VERSION = '5';
- var VERSION_PARAM = 'v';
- var TRANSPORT_SESSION_PARAM = 's';
- var REFERER_PARAM = 'r';
- var FORGE_REF = 'f';
-
-
- var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
- var LAST_SESSION_PARAM = 'ls';
- var APPLICATION_ID_PARAM = 'p';
- var APP_CHECK_TOKEN_PARAM = 'ac';
- var WEBSOCKET = 'websocket';
- var LONG_POLLING = 'long_polling';
-
-
-
- var RepoInfo = (function () {
-
-
- function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams) {
- if (nodeAdmin === void 0) { nodeAdmin = false; }
- if (persistenceKey === void 0) { persistenceKey = ''; }
- if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
- this.secure = secure;
- this.namespace = namespace;
- this.webSocketOnly = webSocketOnly;
- this.nodeAdmin = nodeAdmin;
- this.persistenceKey = persistenceKey;
- this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
- this._host = host.toLowerCase();
- this._domain = this._host.substr(this._host.indexOf('.') + 1);
- this.internalHost =
- PersistentStorage.get('host:' + host) || this._host;
- }
- RepoInfo.prototype.isCacheableHost = function () {
- return this.internalHost.substr(0, 2) === 's-';
- };
- RepoInfo.prototype.isCustomHost = function () {
- return (this._domain !== 'firebaseio.com' &&
- this._domain !== 'firebaseio-demo.com');
- };
- Object.defineProperty(RepoInfo.prototype, "host", {
- get: function () {
- return this._host;
- },
- set: function (newHost) {
- if (newHost !== this.internalHost) {
- this.internalHost = newHost;
- if (this.isCacheableHost()) {
- PersistentStorage.set('host:' + this._host, this.internalHost);
- }
- }
- },
- enumerable: false,
- configurable: true
- });
- RepoInfo.prototype.toString = function () {
- var str = this.toURLString();
- if (this.persistenceKey) {
- str += '<' + this.persistenceKey + '>';
- }
- return str;
- };
- RepoInfo.prototype.toURLString = function () {
- var protocol = this.secure ? 'https://' : 'http://';
- var query = this.includeNamespaceInQueryParams
- ? "?ns=".concat(this.namespace)
- : '';
- return "".concat(protocol).concat(this.host, "/").concat(query);
- };
- return RepoInfo;
- }());
- function repoInfoNeedsQueryParam(repoInfo) {
- return (repoInfo.host !== repoInfo.internalHost ||
- repoInfo.isCustomHost() ||
- repoInfo.includeNamespaceInQueryParams);
- }
-
- function repoInfoConnectionURL(repoInfo, type, params) {
- assert(typeof type === 'string', 'typeof type must == string');
- assert(typeof params === 'object', 'typeof params must == object');
- var connURL;
- if (type === WEBSOCKET) {
- connURL =
- (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
- }
- else if (type === LONG_POLLING) {
- connURL =
- (repoInfo.secure ? 'https://' : 'http://') +
- repoInfo.internalHost +
- '/.lp?';
- }
- else {
- throw new Error('Unknown connection type: ' + type);
- }
- if (repoInfoNeedsQueryParam(repoInfo)) {
- params['ns'] = repoInfo.namespace;
- }
- var pairs = [];
- each(params, function (key, value) {
- pairs.push(key + '=' + value);
- });
- return connURL + pairs.join('&');
- }
-
-
-
- var StatsCollection = (function () {
- function StatsCollection() {
- this.counters_ = {};
- }
- StatsCollection.prototype.incrementCounter = function (name, amount) {
- if (amount === void 0) { amount = 1; }
- if (!contains(this.counters_, name)) {
- this.counters_[name] = 0;
- }
- this.counters_[name] += amount;
- };
- StatsCollection.prototype.get = function () {
- return deepCopy(this.counters_);
- };
- return StatsCollection;
- }());
-
-
- var collections = {};
- var reporters = {};
- function statsManagerGetCollection(repoInfo) {
- var hashString = repoInfo.toString();
- if (!collections[hashString]) {
- collections[hashString] = new StatsCollection();
- }
- return collections[hashString];
- }
- function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
- var hashString = repoInfo.toString();
- if (!reporters[hashString]) {
- reporters[hashString] = creatorFunction();
- }
- return reporters[hashString];
- }
-
-
-
- var PacketReceiver = (function () {
-
-
- function PacketReceiver(onMessage_) {
- this.onMessage_ = onMessage_;
- this.pendingResponses = [];
- this.currentResponseNum = 0;
- this.closeAfterResponse = -1;
- this.onClose = null;
- }
- PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
- this.closeAfterResponse = responseNum;
- this.onClose = callback;
- if (this.closeAfterResponse < this.currentResponseNum) {
- this.onClose();
- this.onClose = null;
- }
- };
-
-
- PacketReceiver.prototype.handleResponse = function (requestNum, data) {
- var _this = this;
- this.pendingResponses[requestNum] = data;
- var _loop_1 = function () {
- var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
- delete this_1.pendingResponses[this_1.currentResponseNum];
- var _loop_2 = function (i) {
- if (toProcess[i]) {
- exceptionGuard(function () {
- _this.onMessage_(toProcess[i]);
- });
- }
- };
- for (var i = 0; i < toProcess.length; ++i) {
- _loop_2(i);
- }
- if (this_1.currentResponseNum === this_1.closeAfterResponse) {
- if (this_1.onClose) {
- this_1.onClose();
- this_1.onClose = null;
- }
- return "break";
- }
- this_1.currentResponseNum++;
- };
- var this_1 = this;
- while (this.pendingResponses[this.currentResponseNum]) {
- var state_1 = _loop_1();
- if (state_1 === "break")
- break;
- }
- };
- return PacketReceiver;
- }());
-
-
-
- var FIREBASE_LONGPOLL_START_PARAM = 'start';
- var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
- var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
- var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
- var FIREBASE_LONGPOLL_ID_PARAM = 'id';
- var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
- var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
- var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
- var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
- var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
- var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
- var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
-
-
-
- var MAX_URL_DATA_SIZE = 1870;
- var SEG_HEADER_SIZE = 30;
- var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
-
- var KEEPALIVE_REQUEST_INTERVAL = 25000;
-
- var LP_CONNECT_TIMEOUT = 30000;
-
- var BrowserPollConnection = (function () {
-
-
- function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
- var _this = this;
- this.connId = connId;
- this.repoInfo = repoInfo;
- this.applicationId = applicationId;
- this.appCheckToken = appCheckToken;
- this.authToken = authToken;
- this.transportSessionId = transportSessionId;
- this.lastSessionId = lastSessionId;
- this.bytesSent = 0;
- this.bytesReceived = 0;
- this.everConnected_ = false;
- this.log_ = logWrapper(connId);
- this.stats_ = statsManagerGetCollection(repoInfo);
- this.urlFn = function (params) {
-
- if (_this.appCheckToken) {
- params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
- }
- return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
- };
- }
-
-
- BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
- var _this = this;
- this.curSegmentNum = 0;
- this.onDisconnect_ = onDisconnect;
- this.myPacketOrderer = new PacketReceiver(onMessage);
- this.isClosed_ = false;
- this.connectTimeoutTimer_ = setTimeout(function () {
- _this.log_('Timed out trying to connect.');
-
- _this.onClosed_();
- _this.connectTimeoutTimer_ = null;
-
- }, Math.floor(LP_CONNECT_TIMEOUT));
-
- executeWhenDOMReady(function () {
- if (_this.isClosed_) {
- return;
- }
-
- _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var _a = __read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
- _this.incrementIncomingBytes_(args);
- if (!_this.scriptTagHolder) {
- return;
- }
- if (_this.connectTimeoutTimer_) {
- clearTimeout(_this.connectTimeoutTimer_);
- _this.connectTimeoutTimer_ = null;
- }
- _this.everConnected_ = true;
- if (command === FIREBASE_LONGPOLL_START_PARAM) {
- _this.id = arg1;
- _this.password = arg2;
- }
- else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
-
- if (arg1) {
-
-
- _this.scriptTagHolder.sendNewPolls = false;
-
-
- _this.myPacketOrderer.closeAfter(arg1, function () {
- _this.onClosed_();
- });
- }
- else {
- _this.onClosed_();
- }
- }
- else {
- throw new Error('Unrecognized command received: ' + command);
- }
- }, function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var _a = __read(args, 2), pN = _a[0], data = _a[1];
- _this.incrementIncomingBytes_(args);
- _this.myPacketOrderer.handleResponse(pN, data);
- }, function () {
- _this.onClosed_();
- }, _this.urlFn);
-
-
- var urlParams = {};
- urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
- urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
- if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
- urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
- _this.scriptTagHolder.uniqueCallbackIdentifier;
- }
- urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
- if (_this.transportSessionId) {
- urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
- }
- if (_this.lastSessionId) {
- urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
- }
- if (_this.applicationId) {
- urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
- }
- if (_this.appCheckToken) {
- urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
- }
- if (typeof location !== 'undefined' &&
- location.hostname &&
- FORGE_DOMAIN_RE.test(location.hostname)) {
- urlParams[REFERER_PARAM] = FORGE_REF;
- }
- var connectURL = _this.urlFn(urlParams);
- _this.log_('Connecting via long-poll to ' + connectURL);
- _this.scriptTagHolder.addTag(connectURL, function () {
-
- });
- });
- };
-
-
- BrowserPollConnection.prototype.start = function () {
- this.scriptTagHolder.startLongPoll(this.id, this.password);
- this.addDisconnectPingFrame(this.id, this.password);
- };
-
-
- BrowserPollConnection.forceAllow = function () {
- BrowserPollConnection.forceAllow_ = true;
- };
-
-
- BrowserPollConnection.forceDisallow = function () {
- BrowserPollConnection.forceDisallow_ = true;
- };
-
- BrowserPollConnection.isAvailable = function () {
- if (isNodeSdk()) {
- return false;
- }
- else if (BrowserPollConnection.forceAllow_) {
- return true;
- }
- else {
-
-
- return (!BrowserPollConnection.forceDisallow_ &&
- typeof document !== 'undefined' &&
- document.createElement != null &&
- !isChromeExtensionContentScript() &&
- !isWindowsStoreApp());
- }
- };
-
-
- BrowserPollConnection.prototype.markConnectionHealthy = function () { };
-
-
- BrowserPollConnection.prototype.shutdown_ = function () {
- this.isClosed_ = true;
- if (this.scriptTagHolder) {
- this.scriptTagHolder.close();
- this.scriptTagHolder = null;
- }
-
- if (this.myDisconnFrame) {
- document.body.removeChild(this.myDisconnFrame);
- this.myDisconnFrame = null;
- }
- if (this.connectTimeoutTimer_) {
- clearTimeout(this.connectTimeoutTimer_);
- this.connectTimeoutTimer_ = null;
- }
- };
-
-
- BrowserPollConnection.prototype.onClosed_ = function () {
- if (!this.isClosed_) {
- this.log_('Longpoll is closing itself');
- this.shutdown_();
- if (this.onDisconnect_) {
- this.onDisconnect_(this.everConnected_);
- this.onDisconnect_ = null;
- }
- }
- };
-
-
- BrowserPollConnection.prototype.close = function () {
- if (!this.isClosed_) {
- this.log_('Longpoll is being closed.');
- this.shutdown_();
- }
- };
-
-
- BrowserPollConnection.prototype.send = function (data) {
- var dataStr = stringify(data);
- this.bytesSent += dataStr.length;
- this.stats_.incrementCounter('bytes_sent', dataStr.length);
-
- var base64data = base64Encode(dataStr);
-
-
- var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
-
-
- for (var i = 0; i < dataSegs.length; i++) {
- this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
- this.curSegmentNum++;
- }
- };
-
-
- BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
- if (isNodeSdk()) {
- return;
- }
- this.myDisconnFrame = document.createElement('iframe');
- var urlParams = {};
- urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
- urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
- urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
- this.myDisconnFrame.src = this.urlFn(urlParams);
- this.myDisconnFrame.style.display = 'none';
- document.body.appendChild(this.myDisconnFrame);
- };
-
-
- BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
-
- var bytesReceived = stringify(args).length;
- this.bytesReceived += bytesReceived;
- this.stats_.incrementCounter('bytes_received', bytesReceived);
- };
- return BrowserPollConnection;
- }());
-
- var FirebaseIFrameScriptHolder = (function () {
-
-
- function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
- this.onDisconnect = onDisconnect;
- this.urlFn = urlFn;
-
-
- this.outstandingRequests = new Set();
-
- this.pendingSegs = [];
-
-
-
-
-
- this.currentSerial = Math.floor(Math.random() * 100000000);
-
-
- this.sendNewPolls = true;
- if (!isNodeSdk()) {
-
-
-
-
- this.uniqueCallbackIdentifier = LUIDGenerator();
- window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
- window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
- onMessageCB;
-
- this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
-
- var script = '';
-
-
- if (this.myIFrame.src &&
- this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
- var currentDomain = document.domain;
- script = '<script>document.domain="' + currentDomain + '";</script>';
- }
- var iframeContents = '<html><body>' + script + '</body></html>';
- try {
- this.myIFrame.doc.open();
- this.myIFrame.doc.write(iframeContents);
- this.myIFrame.doc.close();
- }
- catch (e) {
- log('frame writing exception');
- if (e.stack) {
- log(e.stack);
- }
- log(e);
- }
- }
- else {
- this.commandCB = commandCB;
- this.onMessageCB = onMessageCB;
- }
- }
-
-
- FirebaseIFrameScriptHolder.createIFrame_ = function () {
- var iframe = document.createElement('iframe');
- iframe.style.display = 'none';
-
- if (document.body) {
- document.body.appendChild(iframe);
- try {
-
-
-
- var a = iframe.contentWindow.document;
- if (!a) {
-
- log('No IE domain setting required');
- }
- }
- catch (e) {
- var domain = document.domain;
- iframe.src =
- "javascript:void((function(){document.open();document.domain='" +
- domain +
- "';document.close();})())";
- }
- }
- else {
-
-
- throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
- }
-
- if (iframe.contentDocument) {
- iframe.doc = iframe.contentDocument;
- }
- else if (iframe.contentWindow) {
- iframe.doc = iframe.contentWindow.document;
-
- }
- else if (iframe.document) {
-
- iframe.doc = iframe.document;
- }
- return iframe;
- };
-
-
- FirebaseIFrameScriptHolder.prototype.close = function () {
- var _this = this;
-
- this.alive = false;
- if (this.myIFrame) {
-
-
-
- this.myIFrame.doc.body.textContent = '';
- setTimeout(function () {
- if (_this.myIFrame !== null) {
- document.body.removeChild(_this.myIFrame);
- _this.myIFrame = null;
- }
- }, Math.floor(0));
- }
-
- var onDisconnect = this.onDisconnect;
- if (onDisconnect) {
- this.onDisconnect = null;
- onDisconnect();
- }
- };
-
-
- FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
- this.myID = id;
- this.myPW = pw;
- this.alive = true;
-
- while (this.newRequest_()) { }
- };
-
-
- FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
-
-
-
- if (this.alive &&
- this.sendNewPolls &&
- this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
-
- this.currentSerial++;
- var urlParams = {};
- urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
- urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
- urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
- var theURL = this.urlFn(urlParams);
-
- var curDataString = '';
- var i = 0;
- while (this.pendingSegs.length > 0) {
-
- var nextSeg = this.pendingSegs[0];
- if (nextSeg.d.length +
- SEG_HEADER_SIZE +
- curDataString.length <=
- MAX_URL_DATA_SIZE) {
-
- var theSeg = this.pendingSegs.shift();
- curDataString =
- curDataString +
- '&' +
- FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
- i +
- '=' +
- theSeg.seg +
- '&' +
- FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
- i +
- '=' +
- theSeg.ts +
- '&' +
- FIREBASE_LONGPOLL_DATA_PARAM +
- i +
- '=' +
- theSeg.d;
- i++;
- }
- else {
- break;
- }
- }
- theURL = theURL + curDataString;
- this.addLongPollTag_(theURL, this.currentSerial);
- return true;
- }
- else {
- return false;
- }
- };
-
-
- FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
-
- this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
-
-
- if (this.alive) {
- this.newRequest_();
- }
- };
-
-
- FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
- var _this = this;
-
- this.outstandingRequests.add(serial);
- var doNewRequest = function () {
- _this.outstandingRequests.delete(serial);
- _this.newRequest_();
- };
-
-
- var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
- var readyStateCB = function () {
-
- clearTimeout(keepaliveTimeout);
-
- doNewRequest();
- };
- this.addTag(url, readyStateCB);
- };
-
-
- FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
- var _this = this;
- if (isNodeSdk()) {
-
- this.doNodeLongPoll(url, loadCB);
- }
- else {
- setTimeout(function () {
- try {
-
- if (!_this.sendNewPolls) {
- return;
- }
- var newScript_1 = _this.myIFrame.doc.createElement('script');
- newScript_1.type = 'text/javascript';
- newScript_1.async = true;
- newScript_1.src = url;
-
- newScript_1.onload = newScript_1.onreadystatechange =
- function () {
-
- var rstate = newScript_1.readyState;
- if (!rstate || rstate === 'loaded' || rstate === 'complete') {
-
- newScript_1.onload = newScript_1.onreadystatechange = null;
- if (newScript_1.parentNode) {
- newScript_1.parentNode.removeChild(newScript_1);
- }
- loadCB();
- }
- };
- newScript_1.onerror = function () {
- log('Long-poll script failed to load: ' + url);
- _this.sendNewPolls = false;
- _this.close();
- };
- _this.myIFrame.doc.body.appendChild(newScript_1);
- }
- catch (e) {
-
- }
- }, Math.floor(1));
- }
- };
- return FirebaseIFrameScriptHolder;
- }());
-
-
- var WEBSOCKET_MAX_FRAME_SIZE = 16384;
- var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
- var WebSocketImpl = null;
- if (typeof MozWebSocket !== 'undefined') {
- WebSocketImpl = MozWebSocket;
- }
- else if (typeof WebSocket !== 'undefined') {
- WebSocketImpl = WebSocket;
- }
-
- var WebSocketConnection = (function () {
-
-
- function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
- this.connId = connId;
- this.applicationId = applicationId;
- this.appCheckToken = appCheckToken;
- this.authToken = authToken;
- this.keepaliveTimer = null;
- this.frames = null;
- this.totalFrames = 0;
- this.bytesSent = 0;
- this.bytesReceived = 0;
- this.log_ = logWrapper(this.connId);
- this.stats_ = statsManagerGetCollection(repoInfo);
- this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
- this.nodeAdmin = repoInfo.nodeAdmin;
- }
-
-
- WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
- var urlParams = {};
- urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
- if (!isNodeSdk() &&
- typeof location !== 'undefined' &&
- location.hostname &&
- FORGE_DOMAIN_RE.test(location.hostname)) {
- urlParams[REFERER_PARAM] = FORGE_REF;
- }
- if (transportSessionId) {
- urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
- }
- if (lastSessionId) {
- urlParams[LAST_SESSION_PARAM] = lastSessionId;
- }
- if (appCheckToken) {
- urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
- }
- if (applicationId) {
- urlParams[APPLICATION_ID_PARAM] = applicationId;
- }
- return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
- };
-
-
- WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
- var _this = this;
- this.onDisconnect = onDisconnect;
- this.onMessage = onMessage;
- this.log_('Websocket connecting to ' + this.connURL);
- this.everConnected_ = false;
-
- PersistentStorage.set('previous_websocket_failure', true);
- try {
- var options = void 0;
- if (isNodeSdk()) {
- var device = this.nodeAdmin ? 'AdminNode' : 'Node';
-
- options = {
- headers: {
- 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
- 'X-Firebase-GMPID': this.applicationId || ''
- }
- };
-
-
-
-
-
- if (this.authToken) {
- options.headers['Authorization'] = "Bearer ".concat(this.authToken);
- }
- if (this.appCheckToken) {
- options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
- }
-
- var env = process['env'];
- var proxy = this.connURL.indexOf('wss://') === 0
- ? env['HTTPS_PROXY'] || env['https_proxy']
- : env['HTTP_PROXY'] || env['http_proxy'];
- if (proxy) {
- options['proxy'] = { origin: proxy };
- }
- }
- this.mySock = new WebSocketImpl(this.connURL, [], options);
- }
- catch (e) {
- this.log_('Error instantiating WebSocket.');
- var error = e.message || e.data;
- if (error) {
- this.log_(error);
- }
- this.onClosed_();
- return;
- }
- this.mySock.onopen = function () {
- _this.log_('Websocket connected.');
- _this.everConnected_ = true;
- };
- this.mySock.onclose = function () {
- _this.log_('Websocket connection was disconnected.');
- _this.mySock = null;
- _this.onClosed_();
- };
- this.mySock.onmessage = function (m) {
- _this.handleIncomingFrame(m);
- };
- this.mySock.onerror = function (e) {
- _this.log_('WebSocket error. Closing connection.');
-
- var error = e.message || e.data;
- if (error) {
- _this.log_(error);
- }
- _this.onClosed_();
- };
- };
-
-
- WebSocketConnection.prototype.start = function () { };
- WebSocketConnection.forceDisallow = function () {
- WebSocketConnection.forceDisallow_ = true;
- };
- WebSocketConnection.isAvailable = function () {
- var isOldAndroid = false;
- if (typeof navigator !== 'undefined' && navigator.userAgent) {
- var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
- var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
- if (oldAndroidMatch && oldAndroidMatch.length > 1) {
- if (parseFloat(oldAndroidMatch[1]) < 4.4) {
- isOldAndroid = true;
- }
- }
- }
- return (!isOldAndroid &&
- WebSocketImpl !== null &&
- !WebSocketConnection.forceDisallow_);
- };
-
-
- WebSocketConnection.previouslyFailed = function () {
-
-
- return (PersistentStorage.isInMemoryStorage ||
- PersistentStorage.get('previous_websocket_failure') === true);
- };
- WebSocketConnection.prototype.markConnectionHealthy = function () {
- PersistentStorage.remove('previous_websocket_failure');
- };
- WebSocketConnection.prototype.appendFrame_ = function (data) {
- this.frames.push(data);
- if (this.frames.length === this.totalFrames) {
- var fullMess = this.frames.join('');
- this.frames = null;
- var jsonMess = jsonEval(fullMess);
-
- this.onMessage(jsonMess);
- }
- };
-
-
- WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
- this.totalFrames = frameCount;
- this.frames = [];
- };
-
-
- WebSocketConnection.prototype.extractFrameCount_ = function (data) {
- assert(this.frames === null, 'We already have a frame buffer');
-
-
- if (data.length <= 6) {
- var frameCount = Number(data);
- if (!isNaN(frameCount)) {
- this.handleNewFrameCount_(frameCount);
- return null;
- }
- }
- this.handleNewFrameCount_(1);
- return data;
- };
-
-
- WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
- if (this.mySock === null) {
- return;
- }
- var data = mess['data'];
- this.bytesReceived += data.length;
- this.stats_.incrementCounter('bytes_received', data.length);
- this.resetKeepAlive();
- if (this.frames !== null) {
-
- this.appendFrame_(data);
- }
- else {
-
- var remainingData = this.extractFrameCount_(data);
- if (remainingData !== null) {
- this.appendFrame_(remainingData);
- }
- }
- };
-
-
- WebSocketConnection.prototype.send = function (data) {
- this.resetKeepAlive();
- var dataStr = stringify(data);
- this.bytesSent += dataStr.length;
- this.stats_.incrementCounter('bytes_sent', dataStr.length);
-
-
- var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
-
- if (dataSegs.length > 1) {
- this.sendString_(String(dataSegs.length));
- }
-
- for (var i = 0; i < dataSegs.length; i++) {
- this.sendString_(dataSegs[i]);
- }
- };
- WebSocketConnection.prototype.shutdown_ = function () {
- this.isClosed_ = true;
- if (this.keepaliveTimer) {
- clearInterval(this.keepaliveTimer);
- this.keepaliveTimer = null;
- }
- if (this.mySock) {
- this.mySock.close();
- this.mySock = null;
- }
- };
- WebSocketConnection.prototype.onClosed_ = function () {
- if (!this.isClosed_) {
- this.log_('WebSocket is closing itself');
- this.shutdown_();
-
- if (this.onDisconnect) {
- this.onDisconnect(this.everConnected_);
- this.onDisconnect = null;
- }
- }
- };
-
-
- WebSocketConnection.prototype.close = function () {
- if (!this.isClosed_) {
- this.log_('WebSocket is being closed');
- this.shutdown_();
- }
- };
-
-
- WebSocketConnection.prototype.resetKeepAlive = function () {
- var _this = this;
- clearInterval(this.keepaliveTimer);
- this.keepaliveTimer = setInterval(function () {
-
- if (_this.mySock) {
- _this.sendString_('0');
- }
- _this.resetKeepAlive();
-
- }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
- };
-
-
- WebSocketConnection.prototype.sendString_ = function (str) {
-
-
-
- try {
- this.mySock.send(str);
- }
- catch (e) {
- this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
- setTimeout(this.onClosed_.bind(this), 0);
- }
- };
-
-
- WebSocketConnection.responsesRequiredToBeHealthy = 2;
-
-
- WebSocketConnection.healthyTimeout = 30000;
- return WebSocketConnection;
- }());
-
-
-
- var TransportManager = (function () {
-
-
- function TransportManager(repoInfo) {
- this.initTransports_(repoInfo);
- }
- Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
- get: function () {
- return [BrowserPollConnection, WebSocketConnection];
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
-
-
- get: function () {
- return this.globalTransportInitialized_;
- },
- enumerable: false,
- configurable: true
- });
- TransportManager.prototype.initTransports_ = function (repoInfo) {
- var e_1, _a;
- var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
- var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
- if (repoInfo.webSocketOnly) {
- if (!isWebSocketsAvailable) {
- warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
- }
- isSkipPollConnection = true;
- }
- if (isSkipPollConnection) {
- this.transports_ = [WebSocketConnection];
- }
- else {
- var transports = (this.transports_ = []);
- try {
- for (var _b = __values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
- var transport = _c.value;
- if (transport && transport['isAvailable']()) {
- transports.push(transport);
- }
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
- }
- finally { if (e_1) throw e_1.error; }
- }
- TransportManager.globalTransportInitialized_ = true;
- }
- };
-
-
- TransportManager.prototype.initialTransport = function () {
- if (this.transports_.length > 0) {
- return this.transports_[0];
- }
- else {
- throw new Error('No transports available');
- }
- };
-
-
- TransportManager.prototype.upgradeTransport = function () {
- if (this.transports_.length > 1) {
- return this.transports_[1];
- }
- else {
- return null;
- }
- };
-
- TransportManager.globalTransportInitialized_ = false;
- return TransportManager;
- }());
-
-
-
- var UPGRADE_TIMEOUT = 60000;
-
-
- var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
-
-
-
- var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
- var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
- var MESSAGE_TYPE = 't';
- var MESSAGE_DATA = 'd';
- var CONTROL_SHUTDOWN = 's';
- var CONTROL_RESET = 'r';
- var CONTROL_ERROR = 'e';
- var CONTROL_PONG = 'o';
- var SWITCH_ACK = 'a';
- var END_TRANSMISSION = 'n';
- var PING = 'p';
- var SERVER_HELLO = 'h';
-
- var Connection = (function () {
-
-
- function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
- this.id = id;
- this.repoInfo_ = repoInfo_;
- this.applicationId_ = applicationId_;
- this.appCheckToken_ = appCheckToken_;
- this.authToken_ = authToken_;
- this.onMessage_ = onMessage_;
- this.onReady_ = onReady_;
- this.onDisconnect_ = onDisconnect_;
- this.onKill_ = onKill_;
- this.lastSessionId = lastSessionId;
- this.connectionCount = 0;
- this.pendingDataMessages = [];
- this.state_ = 0 ;
- this.log_ = logWrapper('c:' + this.id + ':');
- this.transportManager_ = new TransportManager(repoInfo_);
- this.log_('Connection created');
- this.start_();
- }
-
-
- Connection.prototype.start_ = function () {
- var _this = this;
- var conn = this.transportManager_.initialTransport();
- this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
-
-
- this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
- var onMessageReceived = this.connReceiver_(this.conn_);
- var onConnectionLost = this.disconnReceiver_(this.conn_);
- this.tx_ = this.conn_;
- this.rx_ = this.conn_;
- this.secondaryConn_ = null;
- this.isHealthy_ = false;
-
-
- setTimeout(function () {
-
- _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
- }, Math.floor(0));
- var healthyTimeoutMS = conn['healthyTimeout'] || 0;
- if (healthyTimeoutMS > 0) {
- this.healthyTimeout_ = setTimeoutNonBlocking(function () {
- _this.healthyTimeout_ = null;
- if (!_this.isHealthy_) {
- if (_this.conn_ &&
- _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
- _this.log_('Connection exceeded healthy timeout but has received ' +
- _this.conn_.bytesReceived +
- ' bytes. Marking connection healthy.');
- _this.isHealthy_ = true;
- _this.conn_.markConnectionHealthy();
- }
- else if (_this.conn_ &&
- _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
- _this.log_('Connection exceeded healthy timeout but has sent ' +
- _this.conn_.bytesSent +
- ' bytes. Leaving connection alive.');
-
-
- }
- else {
- _this.log_('Closing unhealthy connection after timeout.');
- _this.close();
- }
- }
-
- }, Math.floor(healthyTimeoutMS));
- }
- };
- Connection.prototype.nextTransportId_ = function () {
- return 'c:' + this.id + ':' + this.connectionCount++;
- };
- Connection.prototype.disconnReceiver_ = function (conn) {
- var _this = this;
- return function (everConnected) {
- if (conn === _this.conn_) {
- _this.onConnectionLost_(everConnected);
- }
- else if (conn === _this.secondaryConn_) {
- _this.log_('Secondary connection lost.');
- _this.onSecondaryConnectionLost_();
- }
- else {
- _this.log_('closing an old connection');
- }
- };
- };
- Connection.prototype.connReceiver_ = function (conn) {
- var _this = this;
- return function (message) {
- if (_this.state_ !== 2 ) {
- if (conn === _this.rx_) {
- _this.onPrimaryMessageReceived_(message);
- }
- else if (conn === _this.secondaryConn_) {
- _this.onSecondaryMessageReceived_(message);
- }
- else {
- _this.log_('message on old connection');
- }
- }
- };
- };
-
-
- Connection.prototype.sendRequest = function (dataMsg) {
-
- var msg = { t: 'd', d: dataMsg };
- this.sendData_(msg);
- };
- Connection.prototype.tryCleanupConnection = function () {
- if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
- this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
- this.conn_ = this.secondaryConn_;
- this.secondaryConn_ = null;
-
- }
- };
- Connection.prototype.onSecondaryControl_ = function (controlData) {
- if (MESSAGE_TYPE in controlData) {
- var cmd = controlData[MESSAGE_TYPE];
- if (cmd === SWITCH_ACK) {
- this.upgradeIfSecondaryHealthy_();
- }
- else if (cmd === CONTROL_RESET) {
-
- this.log_('Got a reset on secondary, closing it');
- this.secondaryConn_.close();
-
- if (this.tx_ === this.secondaryConn_ ||
- this.rx_ === this.secondaryConn_) {
- this.close();
- }
- }
- else if (cmd === CONTROL_PONG) {
- this.log_('got pong on secondary.');
- this.secondaryResponsesRequired_--;
- this.upgradeIfSecondaryHealthy_();
- }
- }
- };
- Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
- var layer = requireKey('t', parsedData);
- var data = requireKey('d', parsedData);
- if (layer === 'c') {
- this.onSecondaryControl_(data);
- }
- else if (layer === 'd') {
-
- this.pendingDataMessages.push(data);
- }
- else {
- throw new Error('Unknown protocol layer: ' + layer);
- }
- };
- Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
- if (this.secondaryResponsesRequired_ <= 0) {
- this.log_('Secondary connection is healthy.');
- this.isHealthy_ = true;
- this.secondaryConn_.markConnectionHealthy();
- this.proceedWithUpgrade_();
- }
- else {
-
- this.log_('sending ping on secondary.');
- this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
- }
- };
- Connection.prototype.proceedWithUpgrade_ = function () {
-
- this.secondaryConn_.start();
-
- this.log_('sending client ack on secondary');
- this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
-
-
- this.log_('Ending transmission on primary');
- this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
- this.tx_ = this.secondaryConn_;
- this.tryCleanupConnection();
- };
- Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
-
- var layer = requireKey('t', parsedData);
- var data = requireKey('d', parsedData);
- if (layer === 'c') {
- this.onControl_(data);
- }
- else if (layer === 'd') {
- this.onDataMessage_(data);
- }
- };
- Connection.prototype.onDataMessage_ = function (message) {
- this.onPrimaryResponse_();
-
- this.onMessage_(message);
- };
- Connection.prototype.onPrimaryResponse_ = function () {
- if (!this.isHealthy_) {
- this.primaryResponsesRequired_--;
- if (this.primaryResponsesRequired_ <= 0) {
- this.log_('Primary connection is healthy.');
- this.isHealthy_ = true;
- this.conn_.markConnectionHealthy();
- }
- }
- };
- Connection.prototype.onControl_ = function (controlData) {
- var cmd = requireKey(MESSAGE_TYPE, controlData);
- if (MESSAGE_DATA in controlData) {
- var payload = controlData[MESSAGE_DATA];
- if (cmd === SERVER_HELLO) {
- this.onHandshake_(payload);
- }
- else if (cmd === END_TRANSMISSION) {
- this.log_('recvd end transmission on primary');
- this.rx_ = this.secondaryConn_;
- for (var i = 0; i < this.pendingDataMessages.length; ++i) {
- this.onDataMessage_(this.pendingDataMessages[i]);
- }
- this.pendingDataMessages = [];
- this.tryCleanupConnection();
- }
- else if (cmd === CONTROL_SHUTDOWN) {
-
-
- this.onConnectionShutdown_(payload);
- }
- else if (cmd === CONTROL_RESET) {
-
- this.onReset_(payload);
- }
- else if (cmd === CONTROL_ERROR) {
- error('Server Error: ' + payload);
- }
- else if (cmd === CONTROL_PONG) {
- this.log_('got pong on primary.');
- this.onPrimaryResponse_();
- this.sendPingOnPrimaryIfNecessary_();
- }
- else {
- error('Unknown control packet command: ' + cmd);
- }
- }
- };
-
-
- Connection.prototype.onHandshake_ = function (handshake) {
- var timestamp = handshake.ts;
- var version = handshake.v;
- var host = handshake.h;
- this.sessionId = handshake.s;
- this.repoInfo_.host = host;
-
- if (this.state_ === 0 ) {
- this.conn_.start();
- this.onConnectionEstablished_(this.conn_, timestamp);
- if (PROTOCOL_VERSION !== version) {
- warn('Protocol version mismatch detected');
- }
-
- this.tryStartUpgrade_();
- }
- };
- Connection.prototype.tryStartUpgrade_ = function () {
- var conn = this.transportManager_.upgradeTransport();
- if (conn) {
- this.startUpgrade_(conn);
- }
- };
- Connection.prototype.startUpgrade_ = function (conn) {
- var _this = this;
- this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
-
-
- this.secondaryResponsesRequired_ =
- conn['responsesRequiredToBeHealthy'] || 0;
- var onMessage = this.connReceiver_(this.secondaryConn_);
- var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
- this.secondaryConn_.open(onMessage, onDisconnect);
-
- setTimeoutNonBlocking(function () {
- if (_this.secondaryConn_) {
- _this.log_('Timed out trying to upgrade.');
- _this.secondaryConn_.close();
- }
- }, Math.floor(UPGRADE_TIMEOUT));
- };
- Connection.prototype.onReset_ = function (host) {
- this.log_('Reset packet received. New host: ' + host);
- this.repoInfo_.host = host;
-
-
- if (this.state_ === 1 ) {
- this.close();
- }
- else {
-
- this.closeConnections_();
- this.start_();
- }
- };
- Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
- var _this = this;
- this.log_('Realtime connection established.');
- this.conn_ = conn;
- this.state_ = 1 ;
- if (this.onReady_) {
- this.onReady_(timestamp, this.sessionId);
- this.onReady_ = null;
- }
-
-
- if (this.primaryResponsesRequired_ === 0) {
- this.log_('Primary connection is healthy.');
- this.isHealthy_ = true;
- }
- else {
- setTimeoutNonBlocking(function () {
- _this.sendPingOnPrimaryIfNecessary_();
- }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
- }
- };
- Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
-
- if (!this.isHealthy_ && this.state_ === 1 ) {
- this.log_('sending ping on primary.');
- this.sendData_({ t: 'c', d: { t: PING, d: {} } });
- }
- };
- Connection.prototype.onSecondaryConnectionLost_ = function () {
- var conn = this.secondaryConn_;
- this.secondaryConn_ = null;
- if (this.tx_ === conn || this.rx_ === conn) {
-
- this.close();
- }
- };
-
-
- Connection.prototype.onConnectionLost_ = function (everConnected) {
- this.conn_ = null;
-
-
- if (!everConnected && this.state_ === 0 ) {
- this.log_('Realtime connection failed.');
-
- if (this.repoInfo_.isCacheableHost()) {
- PersistentStorage.remove('host:' + this.repoInfo_.host);
-
- this.repoInfo_.internalHost = this.repoInfo_.host;
- }
- }
- else if (this.state_ === 1 ) {
- this.log_('Realtime connection lost.');
- }
- this.close();
- };
- Connection.prototype.onConnectionShutdown_ = function (reason) {
- this.log_('Connection shutdown command received. Shutting down...');
- if (this.onKill_) {
- this.onKill_(reason);
- this.onKill_ = null;
- }
-
-
- this.onDisconnect_ = null;
- this.close();
- };
- Connection.prototype.sendData_ = function (data) {
- if (this.state_ !== 1 ) {
- throw 'Connection is not connected';
- }
- else {
- this.tx_.send(data);
- }
- };
-
-
- Connection.prototype.close = function () {
- if (this.state_ !== 2 ) {
- this.log_('Closing realtime connection.');
- this.state_ = 2 ;
- this.closeConnections_();
- if (this.onDisconnect_) {
- this.onDisconnect_();
- this.onDisconnect_ = null;
- }
- }
- };
- Connection.prototype.closeConnections_ = function () {
- this.log_('Shutting down all connections');
- if (this.conn_) {
- this.conn_.close();
- this.conn_ = null;
- }
- if (this.secondaryConn_) {
- this.secondaryConn_.close();
- this.secondaryConn_ = null;
- }
- if (this.healthyTimeout_) {
- clearTimeout(this.healthyTimeout_);
- this.healthyTimeout_ = null;
- }
- };
- return Connection;
- }());
-
-
-
- var ServerActions = (function () {
- function ServerActions() {
- }
- ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
- ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
-
-
- ServerActions.prototype.refreshAuthToken = function (token) { };
-
-
- ServerActions.prototype.refreshAppCheckToken = function (token) { };
- ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
- ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
- ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
- ServerActions.prototype.reportStats = function (stats) { };
- return ServerActions;
- }());
-
-
-
- var EventEmitter = (function () {
- function EventEmitter(allowedEvents_) {
- this.allowedEvents_ = allowedEvents_;
- this.listeners_ = {};
- assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
- }
-
-
- EventEmitter.prototype.trigger = function (eventType) {
- var varArgs = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- varArgs[_i - 1] = arguments[_i];
- }
- if (Array.isArray(this.listeners_[eventType])) {
-
- var listeners = __spreadArray([], __read(this.listeners_[eventType]), false);
- for (var i = 0; i < listeners.length; i++) {
- listeners[i].callback.apply(listeners[i].context, varArgs);
- }
- }
- };
- EventEmitter.prototype.on = function (eventType, callback, context) {
- this.validateEventType_(eventType);
- this.listeners_[eventType] = this.listeners_[eventType] || [];
- this.listeners_[eventType].push({ callback: callback, context: context });
- var eventData = this.getInitialEvent(eventType);
- if (eventData) {
- callback.apply(context, eventData);
- }
- };
- EventEmitter.prototype.off = function (eventType, callback, context) {
- this.validateEventType_(eventType);
- var listeners = this.listeners_[eventType] || [];
- for (var i = 0; i < listeners.length; i++) {
- if (listeners[i].callback === callback &&
- (!context || context === listeners[i].context)) {
- listeners.splice(i, 1);
- return;
- }
- }
- };
- EventEmitter.prototype.validateEventType_ = function (eventType) {
- assert(this.allowedEvents_.find(function (et) {
- return et === eventType;
- }), 'Unknown event: ' + eventType);
- };
- return EventEmitter;
- }());
-
-
-
- var OnlineMonitor = (function (_super) {
- __extends(OnlineMonitor, _super);
- function OnlineMonitor() {
- var _this = _super.call(this, ['online']) || this;
- _this.online_ = true;
-
-
-
-
- if (typeof window !== 'undefined' &&
- typeof window.addEventListener !== 'undefined' &&
- !isMobileCordova()) {
- window.addEventListener('online', function () {
- if (!_this.online_) {
- _this.online_ = true;
- _this.trigger('online', true);
- }
- }, false);
- window.addEventListener('offline', function () {
- if (_this.online_) {
- _this.online_ = false;
- _this.trigger('online', false);
- }
- }, false);
- }
- return _this;
- }
- OnlineMonitor.getInstance = function () {
- return new OnlineMonitor();
- };
- OnlineMonitor.prototype.getInitialEvent = function (eventType) {
- assert(eventType === 'online', 'Unknown event type: ' + eventType);
- return [this.online_];
- };
- OnlineMonitor.prototype.currentlyOnline = function () {
- return this.online_;
- };
- return OnlineMonitor;
- }(EventEmitter));
-
-
-
- var MAX_PATH_DEPTH = 32;
-
- var MAX_PATH_LENGTH_BYTES = 768;
-
- var Path = (function () {
-
-
- function Path(pathOrString, pieceNum) {
- if (pieceNum === void 0) {
- this.pieces_ = pathOrString.split('/');
-
- var copyTo = 0;
- for (var i = 0; i < this.pieces_.length; i++) {
- if (this.pieces_[i].length > 0) {
- this.pieces_[copyTo] = this.pieces_[i];
- copyTo++;
- }
- }
- this.pieces_.length = copyTo;
- this.pieceNum_ = 0;
- }
- else {
- this.pieces_ = pathOrString;
- this.pieceNum_ = pieceNum;
- }
- }
- Path.prototype.toString = function () {
- var pathString = '';
- for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
- if (this.pieces_[i] !== '') {
- pathString += '/' + this.pieces_[i];
- }
- }
- return pathString || '/';
- };
- return Path;
- }());
- function newEmptyPath() {
- return new Path('');
- }
- function pathGetFront(path) {
- if (path.pieceNum_ >= path.pieces_.length) {
- return null;
- }
- return path.pieces_[path.pieceNum_];
- }
-
- function pathGetLength(path) {
- return path.pieces_.length - path.pieceNum_;
- }
- function pathPopFront(path) {
- var pieceNum = path.pieceNum_;
- if (pieceNum < path.pieces_.length) {
- pieceNum++;
- }
- return new Path(path.pieces_, pieceNum);
- }
- function pathGetBack(path) {
- if (path.pieceNum_ < path.pieces_.length) {
- return path.pieces_[path.pieces_.length - 1];
- }
- return null;
- }
- function pathToUrlEncodedString(path) {
- var pathString = '';
- for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
- if (path.pieces_[i] !== '') {
- pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
- }
- }
- return pathString || '/';
- }
-
- function pathSlice(path, begin) {
- if (begin === void 0) { begin = 0; }
- return path.pieces_.slice(path.pieceNum_ + begin);
- }
- function pathParent(path) {
- if (path.pieceNum_ >= path.pieces_.length) {
- return null;
- }
- var pieces = [];
- for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
- pieces.push(path.pieces_[i]);
- }
- return new Path(pieces, 0);
- }
- function pathChild(path, childPathObj) {
- var pieces = [];
- for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
- pieces.push(path.pieces_[i]);
- }
- if (childPathObj instanceof Path) {
- for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
- pieces.push(childPathObj.pieces_[i]);
- }
- }
- else {
- var childPieces = childPathObj.split('/');
- for (var i = 0; i < childPieces.length; i++) {
- if (childPieces[i].length > 0) {
- pieces.push(childPieces[i]);
- }
- }
- }
- return new Path(pieces, 0);
- }
-
- function pathIsEmpty(path) {
- return path.pieceNum_ >= path.pieces_.length;
- }
-
- function newRelativePath(outerPath, innerPath) {
- var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
- if (outer === null) {
- return innerPath;
- }
- else if (outer === inner) {
- return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
- }
- else {
- throw new Error('INTERNAL ERROR: innerPath (' +
- innerPath +
- ') is not within ' +
- 'outerPath (' +
- outerPath +
- ')');
- }
- }
-
- function pathCompare(left, right) {
- var leftKeys = pathSlice(left, 0);
- var rightKeys = pathSlice(right, 0);
- for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
- var cmp = nameCompare(leftKeys[i], rightKeys[i]);
- if (cmp !== 0) {
- return cmp;
- }
- }
- if (leftKeys.length === rightKeys.length) {
- return 0;
- }
- return leftKeys.length < rightKeys.length ? -1 : 1;
- }
-
- function pathEquals(path, other) {
- if (pathGetLength(path) !== pathGetLength(other)) {
- return false;
- }
- for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
- if (path.pieces_[i] !== other.pieces_[j]) {
- return false;
- }
- }
- return true;
- }
-
- function pathContains(path, other) {
- var i = path.pieceNum_;
- var j = other.pieceNum_;
- if (pathGetLength(path) > pathGetLength(other)) {
- return false;
- }
- while (i < path.pieces_.length) {
- if (path.pieces_[i] !== other.pieces_[j]) {
- return false;
- }
- ++i;
- ++j;
- }
- return true;
- }
-
- var ValidationPath = (function () {
-
-
- function ValidationPath(path, errorPrefix_) {
- this.errorPrefix_ = errorPrefix_;
- this.parts_ = pathSlice(path, 0);
-
- this.byteLength_ = Math.max(1, this.parts_.length);
- for (var i = 0; i < this.parts_.length; i++) {
- this.byteLength_ += stringLength(this.parts_[i]);
- }
- validationPathCheckValid(this);
- }
- return ValidationPath;
- }());
- function validationPathPush(validationPath, child) {
-
- if (validationPath.parts_.length > 0) {
- validationPath.byteLength_ += 1;
- }
- validationPath.parts_.push(child);
- validationPath.byteLength_ += stringLength(child);
- validationPathCheckValid(validationPath);
- }
- function validationPathPop(validationPath) {
- var last = validationPath.parts_.pop();
- validationPath.byteLength_ -= stringLength(last);
-
- if (validationPath.parts_.length > 0) {
- validationPath.byteLength_ -= 1;
- }
- }
- function validationPathCheckValid(validationPath) {
- if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
- throw new Error(validationPath.errorPrefix_ +
- 'has a key path longer than ' +
- MAX_PATH_LENGTH_BYTES +
- ' bytes (' +
- validationPath.byteLength_ +
- ').');
- }
- if (validationPath.parts_.length > MAX_PATH_DEPTH) {
- throw new Error(validationPath.errorPrefix_ +
- 'path specified exceeds the maximum depth that can be written (' +
- MAX_PATH_DEPTH +
- ') or object contains a cycle ' +
- validationPathToErrorString(validationPath));
- }
- }
-
- function validationPathToErrorString(validationPath) {
- if (validationPath.parts_.length === 0) {
- return '';
- }
- return "in property '" + validationPath.parts_.join('.') + "'";
- }
-
-
- var VisibilityMonitor = (function (_super) {
- __extends(VisibilityMonitor, _super);
- function VisibilityMonitor() {
- var _this = _super.call(this, ['visible']) || this;
- var hidden;
- var visibilityChange;
- if (typeof document !== 'undefined' &&
- typeof document.addEventListener !== 'undefined') {
- if (typeof document['hidden'] !== 'undefined') {
-
- visibilityChange = 'visibilitychange';
- hidden = 'hidden';
- }
- else if (typeof document['mozHidden'] !== 'undefined') {
- visibilityChange = 'mozvisibilitychange';
- hidden = 'mozHidden';
- }
- else if (typeof document['msHidden'] !== 'undefined') {
- visibilityChange = 'msvisibilitychange';
- hidden = 'msHidden';
- }
- else if (typeof document['webkitHidden'] !== 'undefined') {
- visibilityChange = 'webkitvisibilitychange';
- hidden = 'webkitHidden';
- }
- }
-
-
-
-
- _this.visible_ = true;
- if (visibilityChange) {
- document.addEventListener(visibilityChange, function () {
- var visible = !document[hidden];
- if (visible !== _this.visible_) {
- _this.visible_ = visible;
- _this.trigger('visible', visible);
- }
- }, false);
- }
- return _this;
- }
- VisibilityMonitor.getInstance = function () {
- return new VisibilityMonitor();
- };
- VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
- assert(eventType === 'visible', 'Unknown event type: ' + eventType);
- return [this.visible_];
- };
- return VisibilityMonitor;
- }(EventEmitter));
-
-
- var RECONNECT_MIN_DELAY = 1000;
- var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000;
- var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000;
- var RECONNECT_DELAY_MULTIPLIER = 1.3;
- var RECONNECT_DELAY_RESET_TIMEOUT = 30000;
- var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
-
- var INVALID_TOKEN_THRESHOLD = 3;
-
- var PersistentConnection = (function (_super) {
- __extends(PersistentConnection, _super);
-
-
- function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
- var _this = _super.call(this) || this;
- _this.repoInfo_ = repoInfo_;
- _this.applicationId_ = applicationId_;
- _this.onDataUpdate_ = onDataUpdate_;
- _this.onConnectStatus_ = onConnectStatus_;
- _this.onServerInfoUpdate_ = onServerInfoUpdate_;
- _this.authTokenProvider_ = authTokenProvider_;
- _this.appCheckTokenProvider_ = appCheckTokenProvider_;
- _this.authOverride_ = authOverride_;
-
- _this.id = PersistentConnection.nextPersistentConnectionId_++;
- _this.log_ = logWrapper('p:' + _this.id + ':');
- _this.interruptReasons_ = {};
- _this.listens = new Map();
- _this.outstandingPuts_ = [];
- _this.outstandingGets_ = [];
- _this.outstandingPutCount_ = 0;
- _this.outstandingGetCount_ = 0;
- _this.onDisconnectRequestQueue_ = [];
- _this.connected_ = false;
- _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
- _this.securityDebugCallback_ = null;
- _this.lastSessionId = null;
- _this.establishConnectionTimer_ = null;
- _this.visible_ = false;
-
- _this.requestCBHash_ = {};
- _this.requestNumber_ = 0;
- _this.realtime_ = null;
- _this.authToken_ = null;
- _this.appCheckToken_ = null;
- _this.forceTokenRefresh_ = false;
- _this.invalidAuthTokenCount_ = 0;
- _this.invalidAppCheckTokenCount_ = 0;
- _this.firstConnection_ = true;
- _this.lastConnectionAttemptTime_ = null;
- _this.lastConnectionEstablishedTime_ = null;
- if (authOverride_ && !isNodeSdk()) {
- throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
- }
- VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
- if (repoInfo_.host.indexOf('fblocal') === -1) {
- OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
- }
- return _this;
- }
- PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
- var curReqNum = ++this.requestNumber_;
- var msg = { r: curReqNum, a: action, b: body };
- this.log_(stringify(msg));
- assert(this.connected_, "sendRequest call when we're not connected not allowed.");
- this.realtime_.sendRequest(msg);
- if (onResponse) {
- this.requestCBHash_[curReqNum] = onResponse;
- }
- };
- PersistentConnection.prototype.get = function (query) {
- this.initConnection_();
- var deferred = new Deferred();
- var request = {
- p: query._path.toString(),
- q: query._queryObject
- };
- var outstandingGet = {
- action: 'g',
- request: request,
- onComplete: function (message) {
- var payload = message['d'];
- if (message['s'] === 'ok') {
- deferred.resolve(payload);
- }
- else {
- deferred.reject(payload);
- }
- }
- };
- this.outstandingGets_.push(outstandingGet);
- this.outstandingGetCount_++;
- var index = this.outstandingGets_.length - 1;
- if (this.connected_) {
- this.sendGet_(index);
- }
- return deferred.promise;
- };
- PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
- this.initConnection_();
- var queryId = query._queryIdentifier;
- var pathString = query._path.toString();
- this.log_('Listen called for ' + pathString + ' ' + queryId);
- if (!this.listens.has(pathString)) {
- this.listens.set(pathString, new Map());
- }
- assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
- assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
- var listenSpec = {
- onComplete: onComplete,
- hashFn: currentHashFn,
- query: query,
- tag: tag
- };
- this.listens.get(pathString).set(queryId, listenSpec);
- if (this.connected_) {
- this.sendListen_(listenSpec);
- }
- };
- PersistentConnection.prototype.sendGet_ = function (index) {
- var _this = this;
- var get = this.outstandingGets_[index];
- this.sendRequest('g', get.request, function (message) {
- delete _this.outstandingGets_[index];
- _this.outstandingGetCount_--;
- if (_this.outstandingGetCount_ === 0) {
- _this.outstandingGets_ = [];
- }
- if (get.onComplete) {
- get.onComplete(message);
- }
- });
- };
- PersistentConnection.prototype.sendListen_ = function (listenSpec) {
- var _this = this;
- var query = listenSpec.query;
- var pathString = query._path.toString();
- var queryId = query._queryIdentifier;
- this.log_('Listen on ' + pathString + ' for ' + queryId);
- var req = { p: pathString };
- var action = 'q';
-
- if (listenSpec.tag) {
- req['q'] = query._queryObject;
- req['t'] = listenSpec.tag;
- }
- req[ 'h'] = listenSpec.hashFn();
- this.sendRequest(action, req, function (message) {
- var payload = message[ 'd'];
- var status = message[ 's'];
-
- PersistentConnection.warnOnListenWarnings_(payload, query);
- var currentListenSpec = _this.listens.get(pathString) &&
- _this.listens.get(pathString).get(queryId);
-
- if (currentListenSpec === listenSpec) {
- _this.log_('listen response', message);
- if (status !== 'ok') {
- _this.removeListen_(pathString, queryId);
- }
- if (listenSpec.onComplete) {
- listenSpec.onComplete(status, payload);
- }
- }
- });
- };
- PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
- if (payload && typeof payload === 'object' && contains(payload, 'w')) {
-
- var warnings = safeGet(payload, 'w');
- if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
- var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
- var indexPath = query._path.toString();
- warn("Using an unspecified index. Your data will be downloaded and " +
- "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
- "".concat(indexPath, " to your security rules for better performance."));
- }
- }
- };
- PersistentConnection.prototype.refreshAuthToken = function (token) {
- this.authToken_ = token;
- this.log_('Auth token refreshed');
- if (this.authToken_) {
- this.tryAuth();
- }
- else {
-
-
- if (this.connected_) {
- this.sendRequest('unauth', {}, function () { });
- }
- }
- this.reduceReconnectDelayIfAdminCredential_(token);
- };
- PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
-
-
- var isFirebaseSecret = credential && credential.length === 40;
- if (isFirebaseSecret || isAdmin(credential)) {
- this.log_('Admin auth credential detected. Reducing max reconnect time.');
- this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
- }
- };
- PersistentConnection.prototype.refreshAppCheckToken = function (token) {
- this.appCheckToken_ = token;
- this.log_('App check token refreshed');
- if (this.appCheckToken_) {
- this.tryAppCheck();
- }
- else {
-
-
-
- if (this.connected_) {
- this.sendRequest('unappeck', {}, function () { });
- }
- }
- };
-
-
- PersistentConnection.prototype.tryAuth = function () {
- var _this = this;
- if (this.connected_ && this.authToken_) {
- var token_1 = this.authToken_;
- var authMethod = isValidFormat(token_1) ? 'auth' : 'gauth';
- var requestData = { cred: token_1 };
- if (this.authOverride_ === null) {
- requestData['noauth'] = true;
- }
- else if (typeof this.authOverride_ === 'object') {
- requestData['authvar'] = this.authOverride_;
- }
- this.sendRequest(authMethod, requestData, function (res) {
- var status = res[ 's'];
- var data = res[ 'd'] || 'error';
- if (_this.authToken_ === token_1) {
- if (status === 'ok') {
- _this.invalidAuthTokenCount_ = 0;
- }
- else {
-
- _this.onAuthRevoked_(status, data);
- }
- }
- });
- }
- };
-
-
- PersistentConnection.prototype.tryAppCheck = function () {
- var _this = this;
- if (this.connected_ && this.appCheckToken_) {
- this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
- var status = res[ 's'];
- var data = res[ 'd'] || 'error';
- if (status === 'ok') {
- _this.invalidAppCheckTokenCount_ = 0;
- }
- else {
- _this.onAppCheckRevoked_(status, data);
- }
- });
- }
- };
-
-
- PersistentConnection.prototype.unlisten = function (query, tag) {
- var pathString = query._path.toString();
- var queryId = query._queryIdentifier;
- this.log_('Unlisten called for ' + pathString + ' ' + queryId);
- assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
- var listen = this.removeListen_(pathString, queryId);
- if (listen && this.connected_) {
- this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
- }
- };
- PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
- this.log_('Unlisten on ' + pathString + ' for ' + queryId);
- var req = { p: pathString };
- var action = 'n';
-
- if (tag) {
- req['q'] = queryObj;
- req['t'] = tag;
- }
- this.sendRequest(action, req);
- };
- PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
- this.initConnection_();
- if (this.connected_) {
- this.sendOnDisconnect_('o', pathString, data, onComplete);
- }
- else {
- this.onDisconnectRequestQueue_.push({
- pathString: pathString,
- action: 'o',
- data: data,
- onComplete: onComplete
- });
- }
- };
- PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
- this.initConnection_();
- if (this.connected_) {
- this.sendOnDisconnect_('om', pathString, data, onComplete);
- }
- else {
- this.onDisconnectRequestQueue_.push({
- pathString: pathString,
- action: 'om',
- data: data,
- onComplete: onComplete
- });
- }
- };
- PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
- this.initConnection_();
- if (this.connected_) {
- this.sendOnDisconnect_('oc', pathString, null, onComplete);
- }
- else {
- this.onDisconnectRequestQueue_.push({
- pathString: pathString,
- action: 'oc',
- data: null,
- onComplete: onComplete
- });
- }
- };
- PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
- var request = { p: pathString, d: data };
- this.log_('onDisconnect ' + action, request);
- this.sendRequest(action, request, function (response) {
- if (onComplete) {
- setTimeout(function () {
- onComplete(response[ 's'], response[ 'd']);
- }, Math.floor(0));
- }
- });
- };
- PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
- this.putInternal('p', pathString, data, onComplete, hash);
- };
- PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
- this.putInternal('m', pathString, data, onComplete, hash);
- };
- PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
- this.initConnection_();
- var request = {
- p: pathString,
- d: data
- };
- if (hash !== undefined) {
- request[ 'h'] = hash;
- }
-
- this.outstandingPuts_.push({
- action: action,
- request: request,
- onComplete: onComplete
- });
- this.outstandingPutCount_++;
- var index = this.outstandingPuts_.length - 1;
- if (this.connected_) {
- this.sendPut_(index);
- }
- else {
- this.log_('Buffering put: ' + pathString);
- }
- };
- PersistentConnection.prototype.sendPut_ = function (index) {
- var _this = this;
- var action = this.outstandingPuts_[index].action;
- var request = this.outstandingPuts_[index].request;
- var onComplete = this.outstandingPuts_[index].onComplete;
- this.outstandingPuts_[index].queued = this.connected_;
- this.sendRequest(action, request, function (message) {
- _this.log_(action + ' response', message);
- delete _this.outstandingPuts_[index];
- _this.outstandingPutCount_--;
-
- if (_this.outstandingPutCount_ === 0) {
- _this.outstandingPuts_ = [];
- }
- if (onComplete) {
- onComplete(message[ 's'], message[ 'd']);
- }
- });
- };
- PersistentConnection.prototype.reportStats = function (stats) {
- var _this = this;
-
- if (this.connected_) {
- var request = { c: stats };
- this.log_('reportStats', request);
- this.sendRequest( 's', request, function (result) {
- var status = result[ 's'];
- if (status !== 'ok') {
- var errorReason = result[ 'd'];
- _this.log_('reportStats', 'Error sending stats: ' + errorReason);
- }
- });
- }
- };
- PersistentConnection.prototype.onDataMessage_ = function (message) {
- if ('r' in message) {
-
- this.log_('from server: ' + stringify(message));
- var reqNum = message['r'];
- var onResponse = this.requestCBHash_[reqNum];
- if (onResponse) {
- delete this.requestCBHash_[reqNum];
- onResponse(message[ 'b']);
- }
- }
- else if ('error' in message) {
- throw 'A server-side error has occurred: ' + message['error'];
- }
- else if ('a' in message) {
-
- this.onDataPush_(message['a'], message['b']);
- }
- };
- PersistentConnection.prototype.onDataPush_ = function (action, body) {
- this.log_('handleServerMessage', action, body);
- if (action === 'd') {
- this.onDataUpdate_(body[ 'p'], body[ 'd'],
- false, body['t']);
- }
- else if (action === 'm') {
- this.onDataUpdate_(body[ 'p'], body[ 'd'],
- true, body['t']);
- }
- else if (action === 'c') {
- this.onListenRevoked_(body[ 'p'], body[ 'q']);
- }
- else if (action === 'ac') {
- this.onAuthRevoked_(body[ 's'], body[ 'd']);
- }
- else if (action === 'apc') {
- this.onAppCheckRevoked_(body[ 's'], body[ 'd']);
- }
- else if (action === 'sd') {
- this.onSecurityDebugPacket_(body);
- }
- else {
- error('Unrecognized action received from server: ' +
- stringify(action) +
- '\nAre you using the latest client?');
- }
- };
- PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
- this.log_('connection ready');
- this.connected_ = true;
- this.lastConnectionEstablishedTime_ = new Date().getTime();
- this.handleTimestamp_(timestamp);
- this.lastSessionId = sessionId;
- if (this.firstConnection_) {
- this.sendConnectStats_();
- }
- this.restoreState_();
- this.firstConnection_ = false;
- this.onConnectStatus_(true);
- };
- PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
- var _this = this;
- assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
- if (this.establishConnectionTimer_) {
- clearTimeout(this.establishConnectionTimer_);
- }
-
-
- this.establishConnectionTimer_ = setTimeout(function () {
- _this.establishConnectionTimer_ = null;
- _this.establishConnection_();
-
- }, Math.floor(timeout));
- };
- PersistentConnection.prototype.initConnection_ = function () {
- if (!this.realtime_ && this.firstConnection_) {
- this.scheduleConnect_(0);
- }
- };
- PersistentConnection.prototype.onVisible_ = function (visible) {
-
- if (visible &&
- !this.visible_ &&
- this.reconnectDelay_ === this.maxReconnectDelay_) {
- this.log_('Window became visible. Reducing delay.');
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- if (!this.realtime_) {
- this.scheduleConnect_(0);
- }
- }
- this.visible_ = visible;
- };
- PersistentConnection.prototype.onOnline_ = function (online) {
- if (online) {
- this.log_('Browser went online.');
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- if (!this.realtime_) {
- this.scheduleConnect_(0);
- }
- }
- else {
- this.log_('Browser went offline. Killing connection.');
- if (this.realtime_) {
- this.realtime_.close();
- }
- }
- };
- PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
- this.log_('data client disconnected');
- this.connected_ = false;
- this.realtime_ = null;
-
- this.cancelSentTransactions_();
-
- this.requestCBHash_ = {};
- if (this.shouldReconnect_()) {
- if (!this.visible_) {
- this.log_("Window isn't visible. Delaying reconnect.");
- this.reconnectDelay_ = this.maxReconnectDelay_;
- this.lastConnectionAttemptTime_ = new Date().getTime();
- }
- else if (this.lastConnectionEstablishedTime_) {
-
- var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
- if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- }
- this.lastConnectionEstablishedTime_ = null;
- }
- var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
- var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
- reconnectDelay = Math.random() * reconnectDelay;
- this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
- this.scheduleConnect_(reconnectDelay);
-
- this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
- }
- this.onConnectStatus_(false);
- };
- PersistentConnection.prototype.establishConnection_ = function () {
- return __awaiter(this, void 0, void 0, function () {
- var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
- var _this = this;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- if (!this.shouldReconnect_()) return [3 , 4];
- this.log_('Making a connection attempt');
- this.lastConnectionAttemptTime_ = new Date().getTime();
- this.lastConnectionEstablishedTime_ = null;
- onDataMessage = this.onDataMessage_.bind(this);
- onReady = this.onReady_.bind(this);
- onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
- connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
- lastSessionId = this.lastSessionId;
- canceled_1 = false;
- connection_1 = null;
- closeFn = function () {
- if (connection_1) {
- connection_1.close();
- }
- else {
- canceled_1 = true;
- onDisconnect_1();
- }
- };
- sendRequestFn = function (msg) {
- assert(connection_1, "sendRequest call when we're not connected not allowed.");
- connection_1.sendRequest(msg);
- };
- this.realtime_ = {
- close: closeFn,
- sendRequest: sendRequestFn
- };
- forceRefresh = this.forceTokenRefresh_;
- this.forceTokenRefresh_ = false;
- _b.label = 1;
- case 1:
- _b.trys.push([1, 3, , 4]);
- return [4 , Promise.all([
- this.authTokenProvider_.getToken(forceRefresh),
- this.appCheckTokenProvider_.getToken(forceRefresh)
- ])];
- case 2:
- _a = __read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
- if (!canceled_1) {
- log('getToken() completed. Creating connection.');
- this.authToken_ = authToken && authToken.accessToken;
- this.appCheckToken_ = appCheckToken && appCheckToken.token;
- connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
- function (reason) {
- warn(reason + ' (' + _this.repoInfo_.toString() + ')');
- _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
- }, lastSessionId);
- }
- else {
- log('getToken() completed but was canceled');
- }
- return [3 , 4];
- case 3:
- error_1 = _b.sent();
- this.log_('Failed to get token: ' + error_1);
- if (!canceled_1) {
- if (this.repoInfo_.nodeAdmin) {
-
-
-
- warn(error_1);
- }
- closeFn();
- }
- return [3 , 4];
- case 4: return [2 ];
- }
- });
- });
- };
- PersistentConnection.prototype.interrupt = function (reason) {
- log('Interrupting connection for reason: ' + reason);
- this.interruptReasons_[reason] = true;
- if (this.realtime_) {
- this.realtime_.close();
- }
- else {
- if (this.establishConnectionTimer_) {
- clearTimeout(this.establishConnectionTimer_);
- this.establishConnectionTimer_ = null;
- }
- if (this.connected_) {
- this.onRealtimeDisconnect_();
- }
- }
- };
- PersistentConnection.prototype.resume = function (reason) {
- log('Resuming connection for reason: ' + reason);
- delete this.interruptReasons_[reason];
- if (isEmpty(this.interruptReasons_)) {
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- if (!this.realtime_) {
- this.scheduleConnect_(0);
- }
- }
- };
- PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
- var delta = timestamp - new Date().getTime();
- this.onServerInfoUpdate_({ serverTimeOffset: delta });
- };
- PersistentConnection.prototype.cancelSentTransactions_ = function () {
- for (var i = 0; i < this.outstandingPuts_.length; i++) {
- var put = this.outstandingPuts_[i];
- if (put && 'h' in put.request && put.queued) {
- if (put.onComplete) {
- put.onComplete('disconnect');
- }
- delete this.outstandingPuts_[i];
- this.outstandingPutCount_--;
- }
- }
-
- if (this.outstandingPutCount_ === 0) {
- this.outstandingPuts_ = [];
- }
- };
- PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
-
- var queryId;
- if (!query) {
- queryId = 'default';
- }
- else {
- queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
- }
- var listen = this.removeListen_(pathString, queryId);
- if (listen && listen.onComplete) {
- listen.onComplete('permission_denied');
- }
- };
- PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
- var normalizedPathString = new Path(pathString).toString();
- var listen;
- if (this.listens.has(normalizedPathString)) {
- var map = this.listens.get(normalizedPathString);
- listen = map.get(queryId);
- map.delete(queryId);
- if (map.size === 0) {
- this.listens.delete(normalizedPathString);
- }
- }
- else {
-
- listen = undefined;
- }
- return listen;
- };
- PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
- log('Auth token revoked: ' + statusCode + '/' + explanation);
- this.authToken_ = null;
- this.forceTokenRefresh_ = true;
- this.realtime_.close();
- if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
-
-
-
- this.invalidAuthTokenCount_++;
- if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
-
- this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
-
-
- this.authTokenProvider_.notifyForInvalidToken();
- }
- }
- };
- PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
- log('App check token revoked: ' + statusCode + '/' + explanation);
- this.appCheckToken_ = null;
- this.forceTokenRefresh_ = true;
-
-
- if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
-
-
-
- this.invalidAppCheckTokenCount_++;
- if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
- this.appCheckTokenProvider_.notifyForInvalidToken();
- }
- }
- };
- PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
- if (this.securityDebugCallback_) {
- this.securityDebugCallback_(body);
- }
- else {
- if ('msg' in body) {
- console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
- }
- }
- };
- PersistentConnection.prototype.restoreState_ = function () {
- var e_1, _a, e_2, _b;
-
- this.tryAuth();
- this.tryAppCheck();
- try {
-
-
- for (var _c = __values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
- var queries = _d.value;
- try {
- for (var _e = (e_2 = void 0, __values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
- var listenSpec = _f.value;
- this.sendListen_(listenSpec);
- }
- }
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
- finally {
- try {
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
- }
- finally { if (e_2) throw e_2.error; }
- }
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
- }
- finally { if (e_1) throw e_1.error; }
- }
- for (var i = 0; i < this.outstandingPuts_.length; i++) {
- if (this.outstandingPuts_[i]) {
- this.sendPut_(i);
- }
- }
- while (this.onDisconnectRequestQueue_.length) {
- var request = this.onDisconnectRequestQueue_.shift();
- this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
- }
- for (var i = 0; i < this.outstandingGets_.length; i++) {
- if (this.outstandingGets_[i]) {
- this.sendGet_(i);
- }
- }
- };
-
-
- PersistentConnection.prototype.sendConnectStats_ = function () {
- var stats = {};
- var clientName = 'js';
- if (isNodeSdk()) {
- if (this.repoInfo_.nodeAdmin) {
- clientName = 'admin_node';
- }
- else {
- clientName = 'node';
- }
- }
- stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
- if (isMobileCordova()) {
- stats['framework.cordova'] = 1;
- }
- else if (isReactNative()) {
- stats['framework.reactnative'] = 1;
- }
- this.reportStats(stats);
- };
- PersistentConnection.prototype.shouldReconnect_ = function () {
- var online = OnlineMonitor.getInstance().currentlyOnline();
- return isEmpty(this.interruptReasons_) && online;
- };
- PersistentConnection.nextPersistentConnectionId_ = 0;
-
-
- PersistentConnection.nextConnectionId_ = 0;
- return PersistentConnection;
- }(ServerActions));
-
-
- var NamedNode = (function () {
- function NamedNode(name, node) {
- this.name = name;
- this.node = node;
- }
- NamedNode.Wrap = function (name, node) {
- return new NamedNode(name, node);
- };
- return NamedNode;
- }());
-
-
- var Index = (function () {
- function Index() {
- }
-
-
- Index.prototype.getCompare = function () {
- return this.compare.bind(this);
- };
-
-
- Index.prototype.indexedValueChanged = function (oldNode, newNode) {
- var oldWrapped = new NamedNode(MIN_NAME, oldNode);
- var newWrapped = new NamedNode(MIN_NAME, newNode);
- return this.compare(oldWrapped, newWrapped) !== 0;
- };
-
-
- Index.prototype.minPost = function () {
-
- return NamedNode.MIN;
- };
- return Index;
- }());
-
-
- var __EMPTY_NODE;
- var KeyIndex = (function (_super) {
- __extends(KeyIndex, _super);
- function KeyIndex() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
- get: function () {
- return __EMPTY_NODE;
- },
- set: function (val) {
- __EMPTY_NODE = val;
- },
- enumerable: false,
- configurable: true
- });
- KeyIndex.prototype.compare = function (a, b) {
- return nameCompare(a.name, b.name);
- };
- KeyIndex.prototype.isDefinedOn = function (node) {
-
-
- throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
- };
- KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
- return false;
- };
- KeyIndex.prototype.minPost = function () {
-
- return NamedNode.MIN;
- };
- KeyIndex.prototype.maxPost = function () {
-
-
- return new NamedNode(MAX_NAME, __EMPTY_NODE);
- };
- KeyIndex.prototype.makePost = function (indexValue, name) {
- assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
-
- return new NamedNode(indexValue, __EMPTY_NODE);
- };
-
-
- KeyIndex.prototype.toString = function () {
- return '.key';
- };
- return KeyIndex;
- }(Index));
- var KEY_INDEX = new KeyIndex();
-
-
-
- var SortedMapIterator = (function () {
-
-
- function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
- if (resultGenerator_ === void 0) { resultGenerator_ = null; }
- this.isReverse_ = isReverse_;
- this.resultGenerator_ = resultGenerator_;
- this.nodeStack_ = [];
- var cmp = 1;
- while (!node.isEmpty()) {
- node = node;
- cmp = startKey ? comparator(node.key, startKey) : 1;
-
- if (isReverse_) {
- cmp *= -1;
- }
- if (cmp < 0) {
-
- if (this.isReverse_) {
- node = node.left;
- }
- else {
- node = node.right;
- }
- }
- else if (cmp === 0) {
-
- this.nodeStack_.push(node);
- break;
- }
- else {
-
- this.nodeStack_.push(node);
- if (this.isReverse_) {
- node = node.right;
- }
- else {
- node = node.left;
- }
- }
- }
- }
- SortedMapIterator.prototype.getNext = function () {
- if (this.nodeStack_.length === 0) {
- return null;
- }
- var node = this.nodeStack_.pop();
- var result;
- if (this.resultGenerator_) {
- result = this.resultGenerator_(node.key, node.value);
- }
- else {
- result = { key: node.key, value: node.value };
- }
- if (this.isReverse_) {
- node = node.left;
- while (!node.isEmpty()) {
- this.nodeStack_.push(node);
- node = node.right;
- }
- }
- else {
- node = node.right;
- while (!node.isEmpty()) {
- this.nodeStack_.push(node);
- node = node.left;
- }
- }
- return result;
- };
- SortedMapIterator.prototype.hasNext = function () {
- return this.nodeStack_.length > 0;
- };
- SortedMapIterator.prototype.peek = function () {
- if (this.nodeStack_.length === 0) {
- return null;
- }
- var node = this.nodeStack_[this.nodeStack_.length - 1];
- if (this.resultGenerator_) {
- return this.resultGenerator_(node.key, node.value);
- }
- else {
- return { key: node.key, value: node.value };
- }
- };
- return SortedMapIterator;
- }());
-
- var LLRBNode = (function () {
-
-
- function LLRBNode(key, value, color, left, right) {
- this.key = key;
- this.value = value;
- this.color = color != null ? color : LLRBNode.RED;
- this.left =
- left != null ? left : SortedMap.EMPTY_NODE;
- this.right =
- right != null ? right : SortedMap.EMPTY_NODE;
- }
-
-
- LLRBNode.prototype.copy = function (key, value, color, left, right) {
- 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);
- };
-
-
- LLRBNode.prototype.count = function () {
- return this.left.count() + 1 + this.right.count();
- };
-
-
- LLRBNode.prototype.isEmpty = function () {
- return false;
- };
-
-
- LLRBNode.prototype.inorderTraversal = function (action) {
- return (this.left.inorderTraversal(action) ||
- !!action(this.key, this.value) ||
- this.right.inorderTraversal(action));
- };
-
-
- LLRBNode.prototype.reverseTraversal = function (action) {
- return (this.right.reverseTraversal(action) ||
- action(this.key, this.value) ||
- this.left.reverseTraversal(action));
- };
-
-
- LLRBNode.prototype.min_ = function () {
- if (this.left.isEmpty()) {
- return this;
- }
- else {
- return this.left.min_();
- }
- };
-
-
- LLRBNode.prototype.minKey = function () {
- return this.min_().key;
- };
-
-
- LLRBNode.prototype.maxKey = function () {
- if (this.right.isEmpty()) {
- return this.key;
- }
- else {
- return this.right.maxKey();
- }
- };
-
-
- LLRBNode.prototype.insert = function (key, value, comparator) {
- var n = this;
- var cmp = comparator(key, n.key);
- if (cmp < 0) {
- n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
- }
- else if (cmp === 0) {
- n = n.copy(null, value, null, null, null);
- }
- else {
- n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
- }
- return n.fixUp_();
- };
-
-
- LLRBNode.prototype.removeMin_ = function () {
- if (this.left.isEmpty()) {
- return SortedMap.EMPTY_NODE;
- }
- var n = this;
- if (!n.left.isRed_() && !n.left.left.isRed_()) {
- n = n.moveRedLeft_();
- }
- n = n.copy(null, null, null, n.left.removeMin_(), null);
- return n.fixUp_();
- };
-
-
- LLRBNode.prototype.remove = function (key, comparator) {
- var n, smallest;
- n = this;
- if (comparator(key, n.key) < 0) {
- if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
- n = n.moveRedLeft_();
- }
- n = n.copy(null, null, null, n.left.remove(key, comparator), null);
- }
- else {
- if (n.left.isRed_()) {
- n = n.rotateRight_();
- }
- if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
- n = n.moveRedRight_();
- }
- if (comparator(key, n.key) === 0) {
- if (n.right.isEmpty()) {
- return SortedMap.EMPTY_NODE;
- }
- else {
- smallest = n.right.min_();
- n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
- }
- }
- n = n.copy(null, null, null, null, n.right.remove(key, comparator));
- }
- return n.fixUp_();
- };
-
-
- LLRBNode.prototype.isRed_ = function () {
- return this.color;
- };
-
-
- LLRBNode.prototype.fixUp_ = function () {
- var n = this;
- if (n.right.isRed_() && !n.left.isRed_()) {
- n = n.rotateLeft_();
- }
- if (n.left.isRed_() && n.left.left.isRed_()) {
- n = n.rotateRight_();
- }
- if (n.left.isRed_() && n.right.isRed_()) {
- n = n.colorFlip_();
- }
- return n;
- };
-
-
- LLRBNode.prototype.moveRedLeft_ = function () {
- var n = this.colorFlip_();
- if (n.right.left.isRed_()) {
- n = n.copy(null, null, null, null, n.right.rotateRight_());
- n = n.rotateLeft_();
- n = n.colorFlip_();
- }
- return n;
- };
-
-
- LLRBNode.prototype.moveRedRight_ = function () {
- var n = this.colorFlip_();
- if (n.left.left.isRed_()) {
- n = n.rotateRight_();
- n = n.colorFlip_();
- }
- return n;
- };
-
-
- LLRBNode.prototype.rotateLeft_ = function () {
- var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
- return this.right.copy(null, null, this.color, nl, null);
- };
-
-
- LLRBNode.prototype.rotateRight_ = function () {
- var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
- return this.left.copy(null, null, this.color, null, nr);
- };
-
-
- LLRBNode.prototype.colorFlip_ = function () {
- var left = this.left.copy(null, null, !this.left.color, null, null);
- var right = this.right.copy(null, null, !this.right.color, null, null);
- return this.copy(null, null, !this.color, left, right);
- };
-
-
- LLRBNode.prototype.checkMaxDepth_ = function () {
- var blackDepth = this.check_();
- return Math.pow(2.0, blackDepth) <= this.count() + 1;
- };
- LLRBNode.prototype.check_ = function () {
- if (this.isRed_() && this.left.isRed_()) {
- throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
- }
- if (this.right.isRed_()) {
- throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
- }
- var blackDepth = this.left.check_();
- if (blackDepth !== this.right.check_()) {
- throw new Error('Black depths differ');
- }
- else {
- return blackDepth + (this.isRed_() ? 0 : 1);
- }
- };
- LLRBNode.RED = true;
- LLRBNode.BLACK = false;
- return LLRBNode;
- }());
-
- var LLRBEmptyNode = (function () {
- function LLRBEmptyNode() {
- }
-
-
- LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
- return this;
- };
-
-
- LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
- return new LLRBNode(key, value, null);
- };
-
-
- LLRBEmptyNode.prototype.remove = function (key, comparator) {
- return this;
- };
-
-
- LLRBEmptyNode.prototype.count = function () {
- return 0;
- };
-
-
- LLRBEmptyNode.prototype.isEmpty = function () {
- return true;
- };
-
-
- LLRBEmptyNode.prototype.inorderTraversal = function (action) {
- return false;
- };
-
-
- LLRBEmptyNode.prototype.reverseTraversal = function (action) {
- return false;
- };
- LLRBEmptyNode.prototype.minKey = function () {
- return null;
- };
- LLRBEmptyNode.prototype.maxKey = function () {
- return null;
- };
- LLRBEmptyNode.prototype.check_ = function () {
- return 0;
- };
-
-
- LLRBEmptyNode.prototype.isRed_ = function () {
- return false;
- };
- return LLRBEmptyNode;
- }());
-
- var SortedMap = (function () {
-
-
- function SortedMap(comparator_, root_) {
- if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
- this.comparator_ = comparator_;
- this.root_ = root_;
- }
-
-
- SortedMap.prototype.insert = function (key, value) {
- return new SortedMap(this.comparator_, this.root_
- .insert(key, value, this.comparator_)
- .copy(null, null, LLRBNode.BLACK, null, null));
- };
-
-
- SortedMap.prototype.remove = function (key) {
- return new SortedMap(this.comparator_, this.root_
- .remove(key, this.comparator_)
- .copy(null, null, LLRBNode.BLACK, null, null));
- };
-
-
- SortedMap.prototype.get = function (key) {
- var cmp;
- var node = this.root_;
- while (!node.isEmpty()) {
- cmp = this.comparator_(key, node.key);
- if (cmp === 0) {
- return node.value;
- }
- else if (cmp < 0) {
- node = node.left;
- }
- else if (cmp > 0) {
- node = node.right;
- }
- }
- return null;
- };
-
-
- SortedMap.prototype.getPredecessorKey = function (key) {
- var cmp, node = this.root_, rightParent = null;
- while (!node.isEmpty()) {
- cmp = this.comparator_(key, node.key);
- if (cmp === 0) {
- if (!node.left.isEmpty()) {
- node = node.left;
- while (!node.right.isEmpty()) {
- node = node.right;
- }
- return node.key;
- }
- else if (rightParent) {
- return rightParent.key;
- }
- else {
- return null;
- }
- }
- else if (cmp < 0) {
- node = node.left;
- }
- else if (cmp > 0) {
- rightParent = node;
- node = node.right;
- }
- }
- throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
- };
-
-
- SortedMap.prototype.isEmpty = function () {
- return this.root_.isEmpty();
- };
-
-
- SortedMap.prototype.count = function () {
- return this.root_.count();
- };
-
-
- SortedMap.prototype.minKey = function () {
- return this.root_.minKey();
- };
-
-
- SortedMap.prototype.maxKey = function () {
- return this.root_.maxKey();
- };
-
-
- SortedMap.prototype.inorderTraversal = function (action) {
- return this.root_.inorderTraversal(action);
- };
-
-
- SortedMap.prototype.reverseTraversal = function (action) {
- return this.root_.reverseTraversal(action);
- };
-
-
- SortedMap.prototype.getIterator = function (resultGenerator) {
- return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
- };
- SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
- return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
- };
- SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
- return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
- };
- SortedMap.prototype.getReverseIterator = function (resultGenerator) {
- return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
- };
-
-
- SortedMap.EMPTY_NODE = new LLRBEmptyNode();
- return SortedMap;
- }());
-
-
- function NAME_ONLY_COMPARATOR(left, right) {
- return nameCompare(left.name, right.name);
- }
- function NAME_COMPARATOR(left, right) {
- return nameCompare(left, right);
- }
-
-
- var MAX_NODE$2;
- function setMaxNode$1(val) {
- MAX_NODE$2 = val;
- }
- var priorityHashText = function (priority) {
- if (typeof priority === 'number') {
- return 'number:' + doubleToIEEE754String(priority);
- }
- else {
- return 'string:' + priority;
- }
- };
-
- var validatePriorityNode = function (priorityNode) {
- if (priorityNode.isLeafNode()) {
- var val = priorityNode.val();
- assert(typeof val === 'string' ||
- typeof val === 'number' ||
- (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
- }
- else {
- assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
- }
-
- assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
- };
-
-
- var __childrenNodeConstructor;
-
- var LeafNode = (function () {
-
-
- function LeafNode(value_, priorityNode_) {
- if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
- this.value_ = value_;
- this.priorityNode_ = priorityNode_;
- this.lazyHash_ = null;
- assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
- validatePriorityNode(this.priorityNode_);
- }
- Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
- get: function () {
- return __childrenNodeConstructor;
- },
- set: function (val) {
- __childrenNodeConstructor = val;
- },
- enumerable: false,
- configurable: true
- });
-
- LeafNode.prototype.isLeafNode = function () {
- return true;
- };
-
- LeafNode.prototype.getPriority = function () {
- return this.priorityNode_;
- };
-
- LeafNode.prototype.updatePriority = function (newPriorityNode) {
- return new LeafNode(this.value_, newPriorityNode);
- };
-
- LeafNode.prototype.getImmediateChild = function (childName) {
-
- if (childName === '.priority') {
- return this.priorityNode_;
- }
- else {
- return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
- }
- };
-
- LeafNode.prototype.getChild = function (path) {
- if (pathIsEmpty(path)) {
- return this;
- }
- else if (pathGetFront(path) === '.priority') {
- return this.priorityNode_;
- }
- else {
- return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
- }
- };
- LeafNode.prototype.hasChild = function () {
- return false;
- };
-
- LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
- return null;
- };
-
- LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
- if (childName === '.priority') {
- return this.updatePriority(newChildNode);
- }
- else if (newChildNode.isEmpty() && childName !== '.priority') {
- return this;
- }
- else {
- return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
- }
- };
-
- LeafNode.prototype.updateChild = function (path, newChildNode) {
- var front = pathGetFront(path);
- if (front === null) {
- return newChildNode;
- }
- else if (newChildNode.isEmpty() && front !== '.priority') {
- return this;
- }
- else {
- assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
- return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
- }
- };
-
- LeafNode.prototype.isEmpty = function () {
- return false;
- };
-
- LeafNode.prototype.numChildren = function () {
- return 0;
- };
-
- LeafNode.prototype.forEachChild = function (index, action) {
- return false;
- };
- LeafNode.prototype.val = function (exportFormat) {
- if (exportFormat && !this.getPriority().isEmpty()) {
- return {
- '.value': this.getValue(),
- '.priority': this.getPriority().val()
- };
- }
- else {
- return this.getValue();
- }
- };
-
- LeafNode.prototype.hash = function () {
- if (this.lazyHash_ === null) {
- var toHash = '';
- if (!this.priorityNode_.isEmpty()) {
- toHash +=
- 'priority:' +
- priorityHashText(this.priorityNode_.val()) +
- ':';
- }
- var type = typeof this.value_;
- toHash += type + ':';
- if (type === 'number') {
- toHash += doubleToIEEE754String(this.value_);
- }
- else {
- toHash += this.value_;
- }
- this.lazyHash_ = sha1(toHash);
- }
- return this.lazyHash_;
- };
-
-
- LeafNode.prototype.getValue = function () {
- return this.value_;
- };
- LeafNode.prototype.compareTo = function (other) {
- if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
- return 1;
- }
- else if (other instanceof LeafNode.__childrenNodeConstructor) {
- return -1;
- }
- else {
- assert(other.isLeafNode(), 'Unknown node type');
- return this.compareToLeafNode_(other);
- }
- };
-
-
- LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
- var otherLeafType = typeof otherLeaf.value_;
- var thisLeafType = typeof this.value_;
- var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
- var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
- assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
- assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
- if (otherIndex === thisIndex) {
-
- if (thisLeafType === 'object') {
-
- return 0;
- }
- else {
-
- if (this.value_ < otherLeaf.value_) {
- return -1;
- }
- else if (this.value_ === otherLeaf.value_) {
- return 0;
- }
- else {
- return 1;
- }
- }
- }
- else {
- return thisIndex - otherIndex;
- }
- };
- LeafNode.prototype.withIndex = function () {
- return this;
- };
- LeafNode.prototype.isIndexed = function () {
- return true;
- };
- LeafNode.prototype.equals = function (other) {
- if (other === this) {
- return true;
- }
- else if (other.isLeafNode()) {
- var otherLeaf = other;
- return (this.value_ === otherLeaf.value_ &&
- this.priorityNode_.equals(otherLeaf.priorityNode_));
- }
- else {
- return false;
- }
- };
-
-
- LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
- return LeafNode;
- }());
-
-
- var nodeFromJSON$1;
- var MAX_NODE$1;
- function setNodeFromJSON(val) {
- nodeFromJSON$1 = val;
- }
- function setMaxNode(val) {
- MAX_NODE$1 = val;
- }
- var PriorityIndex = (function (_super) {
- __extends(PriorityIndex, _super);
- function PriorityIndex() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- PriorityIndex.prototype.compare = function (a, b) {
- var aPriority = a.node.getPriority();
- var bPriority = b.node.getPriority();
- var indexCmp = aPriority.compareTo(bPriority);
- if (indexCmp === 0) {
- return nameCompare(a.name, b.name);
- }
- else {
- return indexCmp;
- }
- };
- PriorityIndex.prototype.isDefinedOn = function (node) {
- return !node.getPriority().isEmpty();
- };
- PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
- return !oldNode.getPriority().equals(newNode.getPriority());
- };
- PriorityIndex.prototype.minPost = function () {
-
- return NamedNode.MIN;
- };
- PriorityIndex.prototype.maxPost = function () {
- return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
- };
- PriorityIndex.prototype.makePost = function (indexValue, name) {
- var priorityNode = nodeFromJSON$1(indexValue);
- return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
- };
-
-
- PriorityIndex.prototype.toString = function () {
- return '.priority';
- };
- return PriorityIndex;
- }(Index));
- var PRIORITY_INDEX = new PriorityIndex();
-
-
- var LOG_2 = Math.log(2);
- var Base12Num = (function () {
- function Base12Num(length) {
- var logBase2 = function (num) {
-
- return parseInt((Math.log(num) / LOG_2), 10);
- };
- var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
- this.count = logBase2(length + 1);
- this.current_ = this.count - 1;
- var mask = bitMask(this.count);
- this.bits_ = (length + 1) & mask;
- }
- Base12Num.prototype.nextBitIsOne = function () {
-
- var result = !(this.bits_ & (0x1 << this.current_));
- this.current_--;
- return result;
- };
- return Base12Num;
- }());
-
- var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
- childList.sort(cmp);
- var buildBalancedTree = function (low, high) {
- var length = high - low;
- var namedNode;
- var key;
- if (length === 0) {
- return null;
- }
- else if (length === 1) {
- namedNode = childList[low];
- key = keyFn ? keyFn(namedNode) : namedNode;
- return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
- }
- else {
-
- var middle = parseInt((length / 2), 10) + low;
- var left = buildBalancedTree(low, middle);
- var right = buildBalancedTree(middle + 1, high);
- namedNode = childList[middle];
- key = keyFn ? keyFn(namedNode) : namedNode;
- return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
- }
- };
- var buildFrom12Array = function (base12) {
- var node = null;
- var root = null;
- var index = childList.length;
- var buildPennant = function (chunkSize, color) {
- var low = index - chunkSize;
- var high = index;
- index -= chunkSize;
- var childTree = buildBalancedTree(low + 1, high);
- var namedNode = childList[low];
- var key = keyFn ? keyFn(namedNode) : namedNode;
- attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
- };
- var attachPennant = function (pennant) {
- if (node) {
- node.left = pennant;
- node = pennant;
- }
- else {
- root = pennant;
- node = pennant;
- }
- };
- for (var i = 0; i < base12.count; ++i) {
- var isOne = base12.nextBitIsOne();
-
- var chunkSize = Math.pow(2, base12.count - (i + 1));
- if (isOne) {
- buildPennant(chunkSize, LLRBNode.BLACK);
- }
- else {
-
- buildPennant(chunkSize, LLRBNode.BLACK);
- buildPennant(chunkSize, LLRBNode.RED);
- }
- }
- return root;
- };
- var base12 = new Base12Num(childList.length);
- var root = buildFrom12Array(base12);
-
- return new SortedMap(mapSortFn || cmp, root);
- };
-
-
- var _defaultIndexMap;
- var fallbackObject = {};
- var IndexMap = (function () {
- function IndexMap(indexes_, indexSet_) {
- this.indexes_ = indexes_;
- this.indexSet_ = indexSet_;
- }
- Object.defineProperty(IndexMap, "Default", {
-
-
- get: function () {
- assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
- _defaultIndexMap =
- _defaultIndexMap ||
- new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
- return _defaultIndexMap;
- },
- enumerable: false,
- configurable: true
- });
- IndexMap.prototype.get = function (indexKey) {
- var sortedMap = safeGet(this.indexes_, indexKey);
- if (!sortedMap) {
- throw new Error('No index defined for ' + indexKey);
- }
- if (sortedMap instanceof SortedMap) {
- return sortedMap;
- }
- else {
-
-
- return null;
- }
- };
- IndexMap.prototype.hasIndex = function (indexDefinition) {
- return contains(this.indexSet_, indexDefinition.toString());
- };
- IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
- assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
- var childList = [];
- var sawIndexedValue = false;
- var iter = existingChildren.getIterator(NamedNode.Wrap);
- var next = iter.getNext();
- while (next) {
- sawIndexedValue =
- sawIndexedValue || indexDefinition.isDefinedOn(next.node);
- childList.push(next);
- next = iter.getNext();
- }
- var newIndex;
- if (sawIndexedValue) {
- newIndex = buildChildSet(childList, indexDefinition.getCompare());
- }
- else {
- newIndex = fallbackObject;
- }
- var indexName = indexDefinition.toString();
- var newIndexSet = __assign({}, this.indexSet_);
- newIndexSet[indexName] = indexDefinition;
- var newIndexes = __assign({}, this.indexes_);
- newIndexes[indexName] = newIndex;
- return new IndexMap(newIndexes, newIndexSet);
- };
-
-
- IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
- var _this = this;
- var newIndexes = map(this.indexes_, function (indexedChildren, indexName) {
- var index = safeGet(_this.indexSet_, indexName);
- assert(index, 'Missing index implementation for ' + indexName);
- if (indexedChildren === fallbackObject) {
-
- if (index.isDefinedOn(namedNode.node)) {
-
- var childList = [];
- var iter = existingChildren.getIterator(NamedNode.Wrap);
- var next = iter.getNext();
- while (next) {
- if (next.name !== namedNode.name) {
- childList.push(next);
- }
- next = iter.getNext();
- }
- childList.push(namedNode);
- return buildChildSet(childList, index.getCompare());
- }
- else {
-
- return fallbackObject;
- }
- }
- else {
- var existingSnap = existingChildren.get(namedNode.name);
- var newChildren = indexedChildren;
- if (existingSnap) {
- newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
- }
- return newChildren.insert(namedNode, namedNode.node);
- }
- });
- return new IndexMap(newIndexes, this.indexSet_);
- };
-
-
- IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
- var newIndexes = map(this.indexes_, function (indexedChildren) {
- if (indexedChildren === fallbackObject) {
-
- return indexedChildren;
- }
- else {
- var existingSnap = existingChildren.get(namedNode.name);
- if (existingSnap) {
- return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
- }
- else {
-
- return indexedChildren;
- }
- }
- });
- return new IndexMap(newIndexes, this.indexSet_);
- };
- return IndexMap;
- }());
-
-
-
- var EMPTY_NODE;
-
- var ChildrenNode = (function () {
-
-
- function ChildrenNode(children_, priorityNode_, indexMap_) {
- this.children_ = children_;
- this.priorityNode_ = priorityNode_;
- this.indexMap_ = indexMap_;
- this.lazyHash_ = null;
-
-
- if (this.priorityNode_) {
- validatePriorityNode(this.priorityNode_);
- }
- if (this.children_.isEmpty()) {
- assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
- }
- }
- Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
- get: function () {
- return (EMPTY_NODE ||
- (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
- },
- enumerable: false,
- configurable: true
- });
-
- ChildrenNode.prototype.isLeafNode = function () {
- return false;
- };
-
- ChildrenNode.prototype.getPriority = function () {
- return this.priorityNode_ || EMPTY_NODE;
- };
-
- ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
- if (this.children_.isEmpty()) {
-
- return this;
- }
- else {
- return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
- }
- };
-
- ChildrenNode.prototype.getImmediateChild = function (childName) {
-
- if (childName === '.priority') {
- return this.getPriority();
- }
- else {
- var child = this.children_.get(childName);
- return child === null ? EMPTY_NODE : child;
- }
- };
-
- ChildrenNode.prototype.getChild = function (path) {
- var front = pathGetFront(path);
- if (front === null) {
- return this;
- }
- return this.getImmediateChild(front).getChild(pathPopFront(path));
- };
-
- ChildrenNode.prototype.hasChild = function (childName) {
- return this.children_.get(childName) !== null;
- };
-
- ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
- assert(newChildNode, 'We should always be passing snapshot nodes');
- if (childName === '.priority') {
- return this.updatePriority(newChildNode);
- }
- else {
- var namedNode = new NamedNode(childName, newChildNode);
- var newChildren = void 0, newIndexMap = void 0;
- if (newChildNode.isEmpty()) {
- newChildren = this.children_.remove(childName);
- newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
- }
- else {
- newChildren = this.children_.insert(childName, newChildNode);
- newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
- }
- var newPriority = newChildren.isEmpty()
- ? EMPTY_NODE
- : this.priorityNode_;
- return new ChildrenNode(newChildren, newPriority, newIndexMap);
- }
- };
-
- ChildrenNode.prototype.updateChild = function (path, newChildNode) {
- var front = pathGetFront(path);
- if (front === null) {
- return newChildNode;
- }
- else {
- assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
- var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
- return this.updateImmediateChild(front, newImmediateChild);
- }
- };
-
- ChildrenNode.prototype.isEmpty = function () {
- return this.children_.isEmpty();
- };
-
- ChildrenNode.prototype.numChildren = function () {
- return this.children_.count();
- };
-
- ChildrenNode.prototype.val = function (exportFormat) {
- if (this.isEmpty()) {
- return null;
- }
- var obj = {};
- var numKeys = 0, maxKey = 0, allIntegerKeys = true;
- this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
- obj[key] = childNode.val(exportFormat);
- numKeys++;
- if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
- maxKey = Math.max(maxKey, Number(key));
- }
- else {
- allIntegerKeys = false;
- }
- });
- if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
-
- var array = [];
-
- for (var key in obj) {
- array[key] = obj[key];
- }
- return array;
- }
- else {
- if (exportFormat && !this.getPriority().isEmpty()) {
- obj['.priority'] = this.getPriority().val();
- }
- return obj;
- }
- };
-
- ChildrenNode.prototype.hash = function () {
- if (this.lazyHash_ === null) {
- var toHash_1 = '';
- if (!this.getPriority().isEmpty()) {
- toHash_1 +=
- 'priority:' +
- priorityHashText(this.getPriority().val()) +
- ':';
- }
- this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
- var childHash = childNode.hash();
- if (childHash !== '') {
- toHash_1 += ':' + key + ':' + childHash;
- }
- });
- this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
- }
- return this.lazyHash_;
- };
-
- ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
- var idx = this.resolveIndex_(index);
- if (idx) {
- var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
- return predecessor ? predecessor.name : null;
- }
- else {
- return this.children_.getPredecessorKey(childName);
- }
- };
- ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
- var idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- var minKey = idx.minKey();
- return minKey && minKey.name;
- }
- else {
- return this.children_.minKey();
- }
- };
- ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
- var minKey = this.getFirstChildName(indexDefinition);
- if (minKey) {
- return new NamedNode(minKey, this.children_.get(minKey));
- }
- else {
- return null;
- }
- };
-
-
- ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
- var idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- var maxKey = idx.maxKey();
- return maxKey && maxKey.name;
- }
- else {
- return this.children_.maxKey();
- }
- };
- ChildrenNode.prototype.getLastChild = function (indexDefinition) {
- var maxKey = this.getLastChildName(indexDefinition);
- if (maxKey) {
- return new NamedNode(maxKey, this.children_.get(maxKey));
- }
- else {
- return null;
- }
- };
- ChildrenNode.prototype.forEachChild = function (index, action) {
- var idx = this.resolveIndex_(index);
- if (idx) {
- return idx.inorderTraversal(function (wrappedNode) {
- return action(wrappedNode.name, wrappedNode.node);
- });
- }
- else {
- return this.children_.inorderTraversal(action);
- }
- };
- ChildrenNode.prototype.getIterator = function (indexDefinition) {
- return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
- };
- ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
- var idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- return idx.getIteratorFrom(startPost, function (key) { return key; });
- }
- else {
- var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
- var next = iterator.peek();
- while (next != null && indexDefinition.compare(next, startPost) < 0) {
- iterator.getNext();
- next = iterator.peek();
- }
- return iterator;
- }
- };
- ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
- return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
- };
- ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
- var idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- return idx.getReverseIteratorFrom(endPost, function (key) {
- return key;
- });
- }
- else {
- var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
- var next = iterator.peek();
- while (next != null && indexDefinition.compare(next, endPost) > 0) {
- iterator.getNext();
- next = iterator.peek();
- }
- return iterator;
- }
- };
- ChildrenNode.prototype.compareTo = function (other) {
- if (this.isEmpty()) {
- if (other.isEmpty()) {
- return 0;
- }
- else {
- return -1;
- }
- }
- else if (other.isLeafNode() || other.isEmpty()) {
- return 1;
- }
- else if (other === MAX_NODE) {
- return -1;
- }
- else {
-
- return 0;
- }
- };
- ChildrenNode.prototype.withIndex = function (indexDefinition) {
- if (indexDefinition === KEY_INDEX ||
- this.indexMap_.hasIndex(indexDefinition)) {
- return this;
- }
- else {
- var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
- return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
- }
- };
- ChildrenNode.prototype.isIndexed = function (index) {
- return index === KEY_INDEX || this.indexMap_.hasIndex(index);
- };
- ChildrenNode.prototype.equals = function (other) {
- if (other === this) {
- return true;
- }
- else if (other.isLeafNode()) {
- return false;
- }
- else {
- var otherChildrenNode = other;
- if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
- return false;
- }
- else if (this.children_.count() === otherChildrenNode.children_.count()) {
- var thisIter = this.getIterator(PRIORITY_INDEX);
- var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
- var thisCurrent = thisIter.getNext();
- var otherCurrent = otherIter.getNext();
- while (thisCurrent && otherCurrent) {
- if (thisCurrent.name !== otherCurrent.name ||
- !thisCurrent.node.equals(otherCurrent.node)) {
- return false;
- }
- thisCurrent = thisIter.getNext();
- otherCurrent = otherIter.getNext();
- }
- return thisCurrent === null && otherCurrent === null;
- }
- else {
- return false;
- }
- }
- };
-
-
- ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
- if (indexDefinition === KEY_INDEX) {
- return null;
- }
- else {
- return this.indexMap_.get(indexDefinition.toString());
- }
- };
- ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
- return ChildrenNode;
- }());
- var MaxNode = (function (_super) {
- __extends(MaxNode, _super);
- function MaxNode() {
- return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
- }
- MaxNode.prototype.compareTo = function (other) {
- if (other === this) {
- return 0;
- }
- else {
- return 1;
- }
- };
- MaxNode.prototype.equals = function (other) {
-
- return other === this;
- };
- MaxNode.prototype.getPriority = function () {
- return this;
- };
- MaxNode.prototype.getImmediateChild = function (childName) {
- return ChildrenNode.EMPTY_NODE;
- };
- MaxNode.prototype.isEmpty = function () {
- return false;
- };
- return MaxNode;
- }(ChildrenNode));
-
- var MAX_NODE = new MaxNode();
- Object.defineProperties(NamedNode, {
- MIN: {
- value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
- },
- MAX: {
- value: new NamedNode(MAX_NAME, MAX_NODE)
- }
- });
-
- KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
- LeafNode.__childrenNodeConstructor = ChildrenNode;
- setMaxNode$1(MAX_NODE);
- setMaxNode(MAX_NODE);
-
-
- var USE_HINZE = true;
-
- function nodeFromJSON(json, priority) {
- if (priority === void 0) { priority = null; }
- if (json === null) {
- return ChildrenNode.EMPTY_NODE;
- }
- if (typeof json === 'object' && '.priority' in json) {
- priority = json['.priority'];
- }
- assert(priority === null ||
- typeof priority === 'string' ||
- typeof priority === 'number' ||
- (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
- if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
- json = json['.value'];
- }
-
- if (typeof json !== 'object' || '.sv' in json) {
- var jsonLeaf = json;
- return new LeafNode(jsonLeaf, nodeFromJSON(priority));
- }
- if (!(json instanceof Array) && USE_HINZE) {
- var children_1 = [];
- var childrenHavePriority_1 = false;
- var hinzeJsonObj = json;
- each(hinzeJsonObj, function (key, child) {
- if (key.substring(0, 1) !== '.') {
-
- var childNode = nodeFromJSON(child);
- if (!childNode.isEmpty()) {
- childrenHavePriority_1 =
- childrenHavePriority_1 || !childNode.getPriority().isEmpty();
- children_1.push(new NamedNode(key, childNode));
- }
- }
- });
- if (children_1.length === 0) {
- return ChildrenNode.EMPTY_NODE;
- }
- var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
- if (childrenHavePriority_1) {
- var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
- return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
- }
- else {
- return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
- }
- }
- else {
- var node_1 = ChildrenNode.EMPTY_NODE;
- each(json, function (key, childData) {
- if (contains(json, key)) {
- if (key.substring(0, 1) !== '.') {
-
- var childNode = nodeFromJSON(childData);
- if (childNode.isLeafNode() || !childNode.isEmpty()) {
- node_1 = node_1.updateImmediateChild(key, childNode);
- }
- }
- }
- });
- return node_1.updatePriority(nodeFromJSON(priority));
- }
- }
- setNodeFromJSON(nodeFromJSON);
-
-
- var PathIndex = (function (_super) {
- __extends(PathIndex, _super);
- function PathIndex(indexPath_) {
- var _this = _super.call(this) || this;
- _this.indexPath_ = indexPath_;
- assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
- return _this;
- }
- PathIndex.prototype.extractChild = function (snap) {
- return snap.getChild(this.indexPath_);
- };
- PathIndex.prototype.isDefinedOn = function (node) {
- return !node.getChild(this.indexPath_).isEmpty();
- };
- PathIndex.prototype.compare = function (a, b) {
- var aChild = this.extractChild(a.node);
- var bChild = this.extractChild(b.node);
- var indexCmp = aChild.compareTo(bChild);
- if (indexCmp === 0) {
- return nameCompare(a.name, b.name);
- }
- else {
- return indexCmp;
- }
- };
- PathIndex.prototype.makePost = function (indexValue, name) {
- var valueNode = nodeFromJSON(indexValue);
- var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
- return new NamedNode(name, node);
- };
- PathIndex.prototype.maxPost = function () {
- var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
- return new NamedNode(MAX_NAME, node);
- };
- PathIndex.prototype.toString = function () {
- return pathSlice(this.indexPath_, 0).join('/');
- };
- return PathIndex;
- }(Index));
-
-
- var ValueIndex = (function (_super) {
- __extends(ValueIndex, _super);
- function ValueIndex() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- ValueIndex.prototype.compare = function (a, b) {
- var indexCmp = a.node.compareTo(b.node);
- if (indexCmp === 0) {
- return nameCompare(a.name, b.name);
- }
- else {
- return indexCmp;
- }
- };
- ValueIndex.prototype.isDefinedOn = function (node) {
- return true;
- };
- ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
- return !oldNode.equals(newNode);
- };
- ValueIndex.prototype.minPost = function () {
-
- return NamedNode.MIN;
- };
- ValueIndex.prototype.maxPost = function () {
-
- return NamedNode.MAX;
- };
- ValueIndex.prototype.makePost = function (indexValue, name) {
- var valueNode = nodeFromJSON(indexValue);
- return new NamedNode(name, valueNode);
- };
-
-
- ValueIndex.prototype.toString = function () {
- return '.value';
- };
- return ValueIndex;
- }(Index));
- var VALUE_INDEX = new ValueIndex();
-
-
- function changeValue(snapshotNode) {
- return { type: "value" , snapshotNode: snapshotNode };
- }
- function changeChildAdded(childName, snapshotNode) {
- return { type: "child_added" , snapshotNode: snapshotNode, childName: childName };
- }
- function changeChildRemoved(childName, snapshotNode) {
- return { type: "child_removed" , snapshotNode: snapshotNode, childName: childName };
- }
- function changeChildChanged(childName, snapshotNode, oldSnap) {
- return {
- type: "child_changed" ,
- snapshotNode: snapshotNode,
- childName: childName,
- oldSnap: oldSnap
- };
- }
- function changeChildMoved(childName, snapshotNode) {
- return { type: "child_moved" , snapshotNode: snapshotNode, childName: childName };
- }
-
-
-
- var IndexedFilter = (function () {
- function IndexedFilter(index_) {
- this.index_ = index_;
- }
- IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
- assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
- var oldChild = snap.getImmediateChild(key);
-
- if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
-
-
-
- if (oldChild.isEmpty() === newChild.isEmpty()) {
-
-
-
- return snap;
- }
- }
- if (optChangeAccumulator != null) {
- if (newChild.isEmpty()) {
- if (snap.hasChild(key)) {
- optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
- }
- else {
- assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
- }
- }
- else if (oldChild.isEmpty()) {
- optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
- }
- else {
- optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
- }
- }
- if (snap.isLeafNode() && newChild.isEmpty()) {
- return snap;
- }
- else {
-
- return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
- }
- };
- IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
- if (optChangeAccumulator != null) {
- if (!oldSnap.isLeafNode()) {
- oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
- if (!newSnap.hasChild(key)) {
- optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
- }
- });
- }
- if (!newSnap.isLeafNode()) {
- newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
- if (oldSnap.hasChild(key)) {
- var oldChild = oldSnap.getImmediateChild(key);
- if (!oldChild.equals(childNode)) {
- optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
- }
- }
- else {
- optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
- }
- });
- }
- }
- return newSnap.withIndex(this.index_);
- };
- IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
- if (oldSnap.isEmpty()) {
- return ChildrenNode.EMPTY_NODE;
- }
- else {
- return oldSnap.updatePriority(newPriority);
- }
- };
- IndexedFilter.prototype.filtersNodes = function () {
- return false;
- };
- IndexedFilter.prototype.getIndexedFilter = function () {
- return this;
- };
- IndexedFilter.prototype.getIndex = function () {
- return this.index_;
- };
- return IndexedFilter;
- }());
-
-
-
- var RangedFilter = (function () {
- function RangedFilter(params) {
- this.indexedFilter_ = new IndexedFilter(params.getIndex());
- this.index_ = params.getIndex();
- this.startPost_ = RangedFilter.getStartPost_(params);
- this.endPost_ = RangedFilter.getEndPost_(params);
- this.startIsInclusive_ = !params.startAfterSet_;
- this.endIsInclusive_ = !params.endBeforeSet_;
- }
- RangedFilter.prototype.getStartPost = function () {
- return this.startPost_;
- };
- RangedFilter.prototype.getEndPost = function () {
- return this.endPost_;
- };
- RangedFilter.prototype.matches = function (node) {
- var isWithinStart = this.startIsInclusive_
- ? this.index_.compare(this.getStartPost(), node) <= 0
- : this.index_.compare(this.getStartPost(), node) < 0;
- var isWithinEnd = this.endIsInclusive_
- ? this.index_.compare(node, this.getEndPost()) <= 0
- : this.index_.compare(node, this.getEndPost()) < 0;
- return isWithinStart && isWithinEnd;
- };
- RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
- if (!this.matches(new NamedNode(key, newChild))) {
- newChild = ChildrenNode.EMPTY_NODE;
- }
- return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
- };
- RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
- if (newSnap.isLeafNode()) {
-
- newSnap = ChildrenNode.EMPTY_NODE;
- }
- var filtered = newSnap.withIndex(this.index_);
-
- filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
- var self = this;
- newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
- if (!self.matches(new NamedNode(key, childNode))) {
- filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
- }
- });
- return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
- };
- RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
-
- return oldSnap;
- };
- RangedFilter.prototype.filtersNodes = function () {
- return true;
- };
- RangedFilter.prototype.getIndexedFilter = function () {
- return this.indexedFilter_;
- };
- RangedFilter.prototype.getIndex = function () {
- return this.index_;
- };
- RangedFilter.getStartPost_ = function (params) {
- if (params.hasStart()) {
- var startName = params.getIndexStartName();
- return params.getIndex().makePost(params.getIndexStartValue(), startName);
- }
- else {
- return params.getIndex().minPost();
- }
- };
- RangedFilter.getEndPost_ = function (params) {
- if (params.hasEnd()) {
- var endName = params.getIndexEndName();
- return params.getIndex().makePost(params.getIndexEndValue(), endName);
- }
- else {
- return params.getIndex().maxPost();
- }
- };
- return RangedFilter;
- }());
-
-
-
- var LimitedFilter = (function () {
- function LimitedFilter(params) {
- var _this = this;
- this.withinDirectionalStart = function (node) {
- return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
- };
- this.withinDirectionalEnd = function (node) {
- return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
- };
- this.withinStartPost = function (node) {
- var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
- return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
- };
- this.withinEndPost = function (node) {
- var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
- return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
- };
- this.rangedFilter_ = new RangedFilter(params);
- this.index_ = params.getIndex();
- this.limit_ = params.getLimit();
- this.reverse_ = !params.isViewFromLeft();
- this.startIsInclusive_ = !params.startAfterSet_;
- this.endIsInclusive_ = !params.endBeforeSet_;
- }
- LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
- if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
- newChild = ChildrenNode.EMPTY_NODE;
- }
- if (snap.getImmediateChild(key).equals(newChild)) {
-
- return snap;
- }
- else if (snap.numChildren() < this.limit_) {
- return this.rangedFilter_
- .getIndexedFilter()
- .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
- }
- else {
- return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
- }
- };
- LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
- var filtered;
- if (newSnap.isLeafNode() || newSnap.isEmpty()) {
-
- filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
- }
- else {
- if (this.limit_ * 2 < newSnap.numChildren() &&
- newSnap.isIndexed(this.index_)) {
-
- filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
-
- var iterator = void 0;
- if (this.reverse_) {
- iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
- }
- else {
- iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
- }
- var count = 0;
- while (iterator.hasNext() && count < this.limit_) {
- var next = iterator.getNext();
- if (!this.withinDirectionalStart(next)) {
-
- continue;
- }
- else if (!this.withinDirectionalEnd(next)) {
-
- break;
- }
- else {
- filtered = filtered.updateImmediateChild(next.name, next.node);
- count++;
- }
- }
- }
- else {
-
- filtered = newSnap.withIndex(this.index_);
-
- filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
- var iterator = void 0;
- if (this.reverse_) {
- iterator = filtered.getReverseIterator(this.index_);
- }
- else {
- iterator = filtered.getIterator(this.index_);
- }
- var count = 0;
- while (iterator.hasNext()) {
- var next = iterator.getNext();
- var inRange = count < this.limit_ &&
- this.withinDirectionalStart(next) &&
- this.withinDirectionalEnd(next);
- if (inRange) {
- count++;
- }
- else {
- filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
- }
- }
- }
- }
- return this.rangedFilter_
- .getIndexedFilter()
- .updateFullNode(oldSnap, filtered, optChangeAccumulator);
- };
- LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
-
- return oldSnap;
- };
- LimitedFilter.prototype.filtersNodes = function () {
- return true;
- };
- LimitedFilter.prototype.getIndexedFilter = function () {
- return this.rangedFilter_.getIndexedFilter();
- };
- LimitedFilter.prototype.getIndex = function () {
- return this.index_;
- };
- LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
-
- var cmp;
- if (this.reverse_) {
- var indexCmp_1 = this.index_.getCompare();
- cmp = function (a, b) { return indexCmp_1(b, a); };
- }
- else {
- cmp = this.index_.getCompare();
- }
- var oldEventCache = snap;
- assert(oldEventCache.numChildren() === this.limit_, '');
- var newChildNamedNode = new NamedNode(childKey, childSnap);
- var windowBoundary = this.reverse_
- ? oldEventCache.getFirstChild(this.index_)
- : oldEventCache.getLastChild(this.index_);
- var inRange = this.rangedFilter_.matches(newChildNamedNode);
- if (oldEventCache.hasChild(childKey)) {
- var oldChildSnap = oldEventCache.getImmediateChild(childKey);
- var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
- while (nextChild != null &&
- (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
-
-
-
- nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
- }
- var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
- var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
- if (remainsInWindow) {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
- }
- return oldEventCache.updateImmediateChild(childKey, childSnap);
- }
- else {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
- }
- var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
- var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
- if (nextChildInRange) {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
- }
- return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
- }
- else {
- return newEventCache;
- }
- }
- }
- else if (childSnap.isEmpty()) {
-
- return snap;
- }
- else if (inRange) {
- if (cmp(windowBoundary, newChildNamedNode) >= 0) {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
- changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
- }
- return oldEventCache
- .updateImmediateChild(childKey, childSnap)
- .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
- }
- else {
- return snap;
- }
- }
- else {
- return snap;
- }
- };
- return LimitedFilter;
- }());
-
-
-
- var QueryParams = (function () {
- function QueryParams() {
- this.limitSet_ = false;
- this.startSet_ = false;
- this.startNameSet_ = false;
- this.startAfterSet_ = false;
- this.endSet_ = false;
- this.endNameSet_ = false;
- this.endBeforeSet_ = false;
- this.limit_ = 0;
- this.viewFrom_ = '';
- this.indexStartValue_ = null;
- this.indexStartName_ = '';
- this.indexEndValue_ = null;
- this.indexEndName_ = '';
- this.index_ = PRIORITY_INDEX;
- }
- QueryParams.prototype.hasStart = function () {
- return this.startSet_;
- };
-
-
- QueryParams.prototype.isViewFromLeft = function () {
- if (this.viewFrom_ === '') {
-
-
-
-
- return this.startSet_;
- }
- else {
- return this.viewFrom_ === "l" ;
- }
- };
-
-
- QueryParams.prototype.getIndexStartValue = function () {
- assert(this.startSet_, 'Only valid if start has been set');
- return this.indexStartValue_;
- };
-
-
- QueryParams.prototype.getIndexStartName = function () {
- assert(this.startSet_, 'Only valid if start has been set');
- if (this.startNameSet_) {
- return this.indexStartName_;
- }
- else {
- return MIN_NAME;
- }
- };
- QueryParams.prototype.hasEnd = function () {
- return this.endSet_;
- };
-
-
- QueryParams.prototype.getIndexEndValue = function () {
- assert(this.endSet_, 'Only valid if end has been set');
- return this.indexEndValue_;
- };
-
-
- QueryParams.prototype.getIndexEndName = function () {
- assert(this.endSet_, 'Only valid if end has been set');
- if (this.endNameSet_) {
- return this.indexEndName_;
- }
- else {
- return MAX_NAME;
- }
- };
- QueryParams.prototype.hasLimit = function () {
- return this.limitSet_;
- };
-
-
- QueryParams.prototype.hasAnchoredLimit = function () {
- return this.limitSet_ && this.viewFrom_ !== '';
- };
-
-
- QueryParams.prototype.getLimit = function () {
- assert(this.limitSet_, 'Only valid if limit has been set');
- return this.limit_;
- };
- QueryParams.prototype.getIndex = function () {
- return this.index_;
- };
- QueryParams.prototype.loadsAllData = function () {
- return !(this.startSet_ || this.endSet_ || this.limitSet_);
- };
- QueryParams.prototype.isDefault = function () {
- return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
- };
- QueryParams.prototype.copy = function () {
- var copy = new QueryParams();
- copy.limitSet_ = this.limitSet_;
- copy.limit_ = this.limit_;
- copy.startSet_ = this.startSet_;
- copy.startAfterSet_ = this.startAfterSet_;
- copy.indexStartValue_ = this.indexStartValue_;
- copy.startNameSet_ = this.startNameSet_;
- copy.indexStartName_ = this.indexStartName_;
- copy.endSet_ = this.endSet_;
- copy.endBeforeSet_ = this.endBeforeSet_;
- copy.indexEndValue_ = this.indexEndValue_;
- copy.endNameSet_ = this.endNameSet_;
- copy.indexEndName_ = this.indexEndName_;
- copy.index_ = this.index_;
- copy.viewFrom_ = this.viewFrom_;
- return copy;
- };
- return QueryParams;
- }());
- function queryParamsGetNodeFilter(queryParams) {
- if (queryParams.loadsAllData()) {
- return new IndexedFilter(queryParams.getIndex());
- }
- else if (queryParams.hasLimit()) {
- return new LimitedFilter(queryParams);
- }
- else {
- return new RangedFilter(queryParams);
- }
- }
- function queryParamsLimitToFirst(queryParams, newLimit) {
- var newParams = queryParams.copy();
- newParams.limitSet_ = true;
- newParams.limit_ = newLimit;
- newParams.viewFrom_ = "l" ;
- return newParams;
- }
- function queryParamsLimitToLast(queryParams, newLimit) {
- var newParams = queryParams.copy();
- newParams.limitSet_ = true;
- newParams.limit_ = newLimit;
- newParams.viewFrom_ = "r" ;
- return newParams;
- }
- function queryParamsStartAt(queryParams, indexValue, key) {
- var newParams = queryParams.copy();
- newParams.startSet_ = true;
- if (indexValue === undefined) {
- indexValue = null;
- }
- newParams.indexStartValue_ = indexValue;
- if (key != null) {
- newParams.startNameSet_ = true;
- newParams.indexStartName_ = key;
- }
- else {
- newParams.startNameSet_ = false;
- newParams.indexStartName_ = '';
- }
- return newParams;
- }
- function queryParamsStartAfter(queryParams, indexValue, key) {
- var params;
- if (queryParams.index_ === KEY_INDEX || !!key) {
- params = queryParamsStartAt(queryParams, indexValue, key);
- }
- else {
- params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
- }
- params.startAfterSet_ = true;
- return params;
- }
- function queryParamsEndAt(queryParams, indexValue, key) {
- var newParams = queryParams.copy();
- newParams.endSet_ = true;
- if (indexValue === undefined) {
- indexValue = null;
- }
- newParams.indexEndValue_ = indexValue;
- if (key !== undefined) {
- newParams.endNameSet_ = true;
- newParams.indexEndName_ = key;
- }
- else {
- newParams.endNameSet_ = false;
- newParams.indexEndName_ = '';
- }
- return newParams;
- }
- function queryParamsEndBefore(queryParams, indexValue, key) {
- var params;
- if (queryParams.index_ === KEY_INDEX || !!key) {
- params = queryParamsEndAt(queryParams, indexValue, key);
- }
- else {
- params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
- }
- params.endBeforeSet_ = true;
- return params;
- }
- function queryParamsOrderBy(queryParams, index) {
- var newParams = queryParams.copy();
- newParams.index_ = index;
- return newParams;
- }
-
- function queryParamsToRestQueryStringParameters(queryParams) {
- var qs = {};
- if (queryParams.isDefault()) {
- return qs;
- }
- var orderBy;
- if (queryParams.index_ === PRIORITY_INDEX) {
- orderBy = "$priority" ;
- }
- else if (queryParams.index_ === VALUE_INDEX) {
- orderBy = "$value" ;
- }
- else if (queryParams.index_ === KEY_INDEX) {
- orderBy = "$key" ;
- }
- else {
- assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
- orderBy = queryParams.index_.toString();
- }
- qs["orderBy" ] = stringify(orderBy);
- if (queryParams.startSet_) {
- var startParam = queryParams.startAfterSet_
- ? "startAfter"
- : "startAt" ;
- qs[startParam] = stringify(queryParams.indexStartValue_);
- if (queryParams.startNameSet_) {
- qs[startParam] += ',' + stringify(queryParams.indexStartName_);
- }
- }
- if (queryParams.endSet_) {
- var endParam = queryParams.endBeforeSet_
- ? "endBefore"
- : "endAt" ;
- qs[endParam] = stringify(queryParams.indexEndValue_);
- if (queryParams.endNameSet_) {
- qs[endParam] += ',' + stringify(queryParams.indexEndName_);
- }
- }
- if (queryParams.limitSet_) {
- if (queryParams.isViewFromLeft()) {
- qs["limitToFirst" ] = queryParams.limit_;
- }
- else {
- qs["limitToLast" ] = queryParams.limit_;
- }
- }
- return qs;
- }
- function queryParamsGetQueryObject(queryParams) {
- var obj = {};
- if (queryParams.startSet_) {
- obj["sp" ] =
- queryParams.indexStartValue_;
- if (queryParams.startNameSet_) {
- obj["sn" ] =
- queryParams.indexStartName_;
- }
- obj["sin" ] =
- !queryParams.startAfterSet_;
- }
- if (queryParams.endSet_) {
- obj["ep" ] = queryParams.indexEndValue_;
- if (queryParams.endNameSet_) {
- obj["en" ] = queryParams.indexEndName_;
- }
- obj["ein" ] =
- !queryParams.endBeforeSet_;
- }
- if (queryParams.limitSet_) {
- obj["l" ] = queryParams.limit_;
- var viewFrom = queryParams.viewFrom_;
- if (viewFrom === '') {
- if (queryParams.isViewFromLeft()) {
- viewFrom = "l" ;
- }
- else {
- viewFrom = "r" ;
- }
- }
- obj["vf" ] = viewFrom;
- }
-
- if (queryParams.index_ !== PRIORITY_INDEX) {
- obj["i" ] = queryParams.index_.toString();
- }
- return obj;
- }
-
-
-
- var ReadonlyRestClient = (function (_super) {
- __extends(ReadonlyRestClient, _super);
-
-
- function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
- var _this = _super.call(this) || this;
- _this.repoInfo_ = repoInfo_;
- _this.onDataUpdate_ = onDataUpdate_;
- _this.authTokenProvider_ = authTokenProvider_;
- _this.appCheckTokenProvider_ = appCheckTokenProvider_;
-
- _this.log_ = logWrapper('p:rest:');
-
-
- _this.listens_ = {};
- return _this;
- }
- ReadonlyRestClient.prototype.reportStats = function (stats) {
- throw new Error('Method not implemented.');
- };
- ReadonlyRestClient.getListenId_ = function (query, tag) {
- if (tag !== undefined) {
- return 'tag$' + tag;
- }
- else {
- assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
- return query._path.toString();
- }
- };
-
- ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
- var _this = this;
- var pathString = query._path.toString();
- this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
-
- var listenId = ReadonlyRestClient.getListenId_(query, tag);
- var thisListen = {};
- this.listens_[listenId] = thisListen;
- var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
- this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
- var data = result;
- if (error === 404) {
- data = null;
- error = null;
- }
- if (error === null) {
- _this.onDataUpdate_(pathString, data, false, tag);
- }
- if (safeGet(_this.listens_, listenId) === thisListen) {
- var status_1;
- if (!error) {
- status_1 = 'ok';
- }
- else if (error === 401) {
- status_1 = 'permission_denied';
- }
- else {
- status_1 = 'rest_error:' + error;
- }
- onComplete(status_1, null);
- }
- });
- };
-
- ReadonlyRestClient.prototype.unlisten = function (query, tag) {
- var listenId = ReadonlyRestClient.getListenId_(query, tag);
- delete this.listens_[listenId];
- };
- ReadonlyRestClient.prototype.get = function (query) {
- var _this = this;
- var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
- var pathString = query._path.toString();
- var deferred = new Deferred();
- this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
- var data = result;
- if (error === 404) {
- data = null;
- error = null;
- }
- if (error === null) {
- _this.onDataUpdate_(pathString, data,
- false,
- null);
- deferred.resolve(data);
- }
- else {
- deferred.reject(new Error(data));
- }
- });
- return deferred.promise;
- };
-
- ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
-
- };
-
-
- ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
- var _this = this;
- if (queryStringParameters === void 0) { queryStringParameters = {}; }
- queryStringParameters['format'] = 'export';
- return Promise.all([
- this.authTokenProvider_.getToken( false),
- this.appCheckTokenProvider_.getToken( false)
- ]).then(function (_a) {
- var _b = __read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
- if (authToken && authToken.accessToken) {
- queryStringParameters['auth'] = authToken.accessToken;
- }
- if (appCheckToken && appCheckToken.token) {
- queryStringParameters['ac'] = appCheckToken.token;
- }
- var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
- _this.repoInfo_.host +
- pathString +
- '?' +
- 'ns=' +
- _this.repoInfo_.namespace +
- querystring(queryStringParameters);
- _this.log_('Sending REST request for ' + url);
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function () {
- if (callback && xhr.readyState === 4) {
- _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
- var res = null;
- if (xhr.status >= 200 && xhr.status < 300) {
- try {
- res = jsonEval(xhr.responseText);
- }
- catch (e) {
- warn('Failed to parse JSON response for ' +
- url +
- ': ' +
- xhr.responseText);
- }
- callback(null, res);
- }
- else {
-
- if (xhr.status !== 401 && xhr.status !== 404) {
- warn('Got unsuccessful REST response for ' +
- url +
- ' Status: ' +
- xhr.status);
- }
- callback(xhr.status);
- }
- callback = null;
- }
- };
- xhr.open('GET', url, true);
- xhr.send();
- });
- };
- return ReadonlyRestClient;
- }(ServerActions));
-
-
-
- var SnapshotHolder = (function () {
- function SnapshotHolder() {
- this.rootNode_ = ChildrenNode.EMPTY_NODE;
- }
- SnapshotHolder.prototype.getNode = function (path) {
- return this.rootNode_.getChild(path);
- };
- SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
- this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
- };
- return SnapshotHolder;
- }());
-
-
- function newSparseSnapshotTree() {
- return {
- value: null,
- children: new Map()
- };
- }
-
- function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
- if (pathIsEmpty(path)) {
- sparseSnapshotTree.value = data;
- sparseSnapshotTree.children.clear();
- }
- else if (sparseSnapshotTree.value !== null) {
- sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
- }
- else {
- var childKey = pathGetFront(path);
- if (!sparseSnapshotTree.children.has(childKey)) {
- sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
- }
- var child = sparseSnapshotTree.children.get(childKey);
- path = pathPopFront(path);
- sparseSnapshotTreeRemember(child, path, data);
- }
- }
-
- function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
- if (pathIsEmpty(path)) {
- sparseSnapshotTree.value = null;
- sparseSnapshotTree.children.clear();
- return true;
- }
- else {
- if (sparseSnapshotTree.value !== null) {
- if (sparseSnapshotTree.value.isLeafNode()) {
-
- return false;
- }
- else {
- var value = sparseSnapshotTree.value;
- sparseSnapshotTree.value = null;
- value.forEachChild(PRIORITY_INDEX, function (key, tree) {
- sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
- });
- return sparseSnapshotTreeForget(sparseSnapshotTree, path);
- }
- }
- else if (sparseSnapshotTree.children.size > 0) {
- var childKey = pathGetFront(path);
- path = pathPopFront(path);
- if (sparseSnapshotTree.children.has(childKey)) {
- var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
- if (safeToRemove) {
- sparseSnapshotTree.children.delete(childKey);
- }
- }
- return sparseSnapshotTree.children.size === 0;
- }
- else {
- return true;
- }
- }
- }
-
- function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
- if (sparseSnapshotTree.value !== null) {
- func(prefixPath, sparseSnapshotTree.value);
- }
- else {
- sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
- var path = new Path(prefixPath.toString() + '/' + key);
- sparseSnapshotTreeForEachTree(tree, path, func);
- });
- }
- }
-
- function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
- sparseSnapshotTree.children.forEach(function (tree, key) {
- func(key, tree);
- });
- }
-
-
-
- var StatsListener = (function () {
- function StatsListener(collection_) {
- this.collection_ = collection_;
- this.last_ = null;
- }
- StatsListener.prototype.get = function () {
- var newStats = this.collection_.get();
- var delta = __assign({}, newStats);
- if (this.last_) {
- each(this.last_, function (stat, value) {
- delta[stat] = delta[stat] - value;
- });
- }
- this.last_ = newStats;
- return delta;
- };
- return StatsListener;
- }());
-
-
-
-
-
- var FIRST_STATS_MIN_TIME = 10 * 1000;
- var FIRST_STATS_MAX_TIME = 30 * 1000;
-
- var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
- var StatsReporter = (function () {
- function StatsReporter(collection, server_) {
- this.server_ = server_;
- this.statsToReport_ = {};
- this.statsListener_ = new StatsListener(collection);
- var timeout = FIRST_STATS_MIN_TIME +
- (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
- setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
- }
- StatsReporter.prototype.reportStats_ = function () {
- var _this = this;
- var stats = this.statsListener_.get();
- var reportedStats = {};
- var haveStatsToReport = false;
- each(stats, function (stat, value) {
- if (value > 0 && contains(_this.statsToReport_, stat)) {
- reportedStats[stat] = value;
- haveStatsToReport = true;
- }
- });
- if (haveStatsToReport) {
- this.server_.reportStats(reportedStats);
- }
-
- setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
- };
- return StatsReporter;
- }());
-
-
-
- var OperationType;
- (function (OperationType) {
- OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
- OperationType[OperationType["MERGE"] = 1] = "MERGE";
- OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
- OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
- })(OperationType || (OperationType = {}));
- function newOperationSourceUser() {
- return {
- fromUser: true,
- fromServer: false,
- queryId: null,
- tagged: false
- };
- }
- function newOperationSourceServer() {
- return {
- fromUser: false,
- fromServer: true,
- queryId: null,
- tagged: false
- };
- }
- function newOperationSourceServerTaggedQuery(queryId) {
- return {
- fromUser: false,
- fromServer: true,
- queryId: queryId,
- tagged: true
- };
- }
-
-
- var AckUserWrite = (function () {
-
-
- function AckUserWrite(
- /** @inheritDoc */ path,
- /** @inheritDoc */ affectedTree,
- /** @inheritDoc */ revert) {
- this.path = path;
- this.affectedTree = affectedTree;
- this.revert = revert;
-
- this.type = OperationType.ACK_USER_WRITE;
-
- this.source = newOperationSourceUser();
- }
- AckUserWrite.prototype.operationForChild = function (childName) {
- if (!pathIsEmpty(this.path)) {
- assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
- return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
- }
- else if (this.affectedTree.value != null) {
- assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
-
- return this;
- }
- else {
- var childTree = this.affectedTree.subtree(new Path(childName));
- return new AckUserWrite(newEmptyPath(), childTree, this.revert);
- }
- };
- return AckUserWrite;
- }());
-
-
- var ListenComplete = (function () {
- function ListenComplete(source, path) {
- this.source = source;
- this.path = path;
-
- this.type = OperationType.LISTEN_COMPLETE;
- }
- ListenComplete.prototype.operationForChild = function (childName) {
- if (pathIsEmpty(this.path)) {
- return new ListenComplete(this.source, newEmptyPath());
- }
- else {
- return new ListenComplete(this.source, pathPopFront(this.path));
- }
- };
- return ListenComplete;
- }());
-
-
- var Overwrite = (function () {
- function Overwrite(source, path, snap) {
- this.source = source;
- this.path = path;
- this.snap = snap;
-
- this.type = OperationType.OVERWRITE;
- }
- Overwrite.prototype.operationForChild = function (childName) {
- if (pathIsEmpty(this.path)) {
- return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
- }
- else {
- return new Overwrite(this.source, pathPopFront(this.path), this.snap);
- }
- };
- return Overwrite;
- }());
-
-
- var Merge = (function () {
- function Merge(
- /** @inheritDoc */ source,
- /** @inheritDoc */ path,
- /** @inheritDoc */ children) {
- this.source = source;
- this.path = path;
- this.children = children;
-
- this.type = OperationType.MERGE;
- }
- Merge.prototype.operationForChild = function (childName) {
- if (pathIsEmpty(this.path)) {
- var childTree = this.children.subtree(new Path(childName));
- if (childTree.isEmpty()) {
-
- return null;
- }
- else if (childTree.value) {
-
- return new Overwrite(this.source, newEmptyPath(), childTree.value);
- }
- else {
-
- return new Merge(this.source, newEmptyPath(), childTree);
- }
- }
- else {
- assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
- return new Merge(this.source, pathPopFront(this.path), this.children);
- }
- };
- Merge.prototype.toString = function () {
- return ('Operation(' +
- this.path +
- ': ' +
- this.source.toString() +
- ' merge: ' +
- this.children.toString() +
- ')');
- };
- return Merge;
- }());
-
-
-
- var CacheNode = (function () {
- function CacheNode(node_, fullyInitialized_, filtered_) {
- this.node_ = node_;
- this.fullyInitialized_ = fullyInitialized_;
- this.filtered_ = filtered_;
- }
-
-
- CacheNode.prototype.isFullyInitialized = function () {
- return this.fullyInitialized_;
- };
-
-
- CacheNode.prototype.isFiltered = function () {
- return this.filtered_;
- };
- CacheNode.prototype.isCompleteForPath = function (path) {
- if (pathIsEmpty(path)) {
- return this.isFullyInitialized() && !this.filtered_;
- }
- var childKey = pathGetFront(path);
- return this.isCompleteForChild(childKey);
- };
- CacheNode.prototype.isCompleteForChild = function (key) {
- return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
- };
- CacheNode.prototype.getNode = function () {
- return this.node_;
- };
- return CacheNode;
- }());
-
-
-
- var EventGenerator = (function () {
- function EventGenerator(query_) {
- this.query_ = query_;
- this.index_ = this.query_._queryParams.getIndex();
- }
- return EventGenerator;
- }());
-
- function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
- var events = [];
- var moves = [];
- changes.forEach(function (change) {
- if (change.type === "child_changed" &&
- eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
- moves.push(changeChildMoved(change.childName, change.snapshotNode));
- }
- });
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" , changes, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" , changes, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" , moves, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" , changes, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "value" , changes, eventRegistrations, eventCache);
- return events;
- }
-
- function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
- var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
- filteredChanges.sort(function (a, b) {
- return eventGeneratorCompareChanges(eventGenerator, a, b);
- });
- filteredChanges.forEach(function (change) {
- var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
- registrations.forEach(function (registration) {
- if (registration.respondsTo(change.type)) {
- events.push(registration.createEvent(materializedChange, eventGenerator.query_));
- }
- });
- });
- }
- function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
- if (change.type === 'value' || change.type === 'child_removed') {
- return change;
- }
- else {
- change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
- return change;
- }
- }
- function eventGeneratorCompareChanges(eventGenerator, a, b) {
- if (a.childName == null || b.childName == null) {
- throw assertionError('Should only compare child_ events.');
- }
- var aWrapped = new NamedNode(a.childName, a.snapshotNode);
- var bWrapped = new NamedNode(b.childName, b.snapshotNode);
- return eventGenerator.index_.compare(aWrapped, bWrapped);
- }
-
-
- function newViewCache(eventCache, serverCache) {
- return { eventCache: eventCache, serverCache: serverCache };
- }
- function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
- return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
- }
- function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
- return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
- }
- function viewCacheGetCompleteEventSnap(viewCache) {
- return viewCache.eventCache.isFullyInitialized()
- ? viewCache.eventCache.getNode()
- : null;
- }
- function viewCacheGetCompleteServerSnap(viewCache) {
- return viewCache.serverCache.isFullyInitialized()
- ? viewCache.serverCache.getNode()
- : null;
- }
-
-
- var emptyChildrenSingleton;
-
- var EmptyChildren = function () {
- if (!emptyChildrenSingleton) {
- emptyChildrenSingleton = new SortedMap(stringCompare);
- }
- return emptyChildrenSingleton;
- };
-
- var ImmutableTree = (function () {
- function ImmutableTree(value, children) {
- if (children === void 0) { children = EmptyChildren(); }
- this.value = value;
- this.children = children;
- }
- ImmutableTree.fromObject = function (obj) {
- var tree = new ImmutableTree(null);
- each(obj, function (childPath, childSnap) {
- tree = tree.set(new Path(childPath), childSnap);
- });
- return tree;
- };
-
-
- ImmutableTree.prototype.isEmpty = function () {
- return this.value === null && this.children.isEmpty();
- };
-
-
- ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
- if (this.value != null && predicate(this.value)) {
- return { path: newEmptyPath(), value: this.value };
- }
- else {
- if (pathIsEmpty(relativePath)) {
- return null;
- }
- else {
- var front = pathGetFront(relativePath);
- var child = this.children.get(front);
- if (child !== null) {
- var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
- if (childExistingPathAndValue != null) {
- var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
- return { path: fullPath, value: childExistingPathAndValue.value };
- }
- else {
- return null;
- }
- }
- else {
- return null;
- }
- }
- }
- };
-
-
- ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
- return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
- };
-
-
- ImmutableTree.prototype.subtree = function (relativePath) {
- if (pathIsEmpty(relativePath)) {
- return this;
- }
- else {
- var front = pathGetFront(relativePath);
- var childTree = this.children.get(front);
- if (childTree !== null) {
- return childTree.subtree(pathPopFront(relativePath));
- }
- else {
- return new ImmutableTree(null);
- }
- }
- };
-
-
- ImmutableTree.prototype.set = function (relativePath, toSet) {
- if (pathIsEmpty(relativePath)) {
- return new ImmutableTree(toSet, this.children);
- }
- else {
- var front = pathGetFront(relativePath);
- var child = this.children.get(front) || new ImmutableTree(null);
- var newChild = child.set(pathPopFront(relativePath), toSet);
- var newChildren = this.children.insert(front, newChild);
- return new ImmutableTree(this.value, newChildren);
- }
- };
-
-
- ImmutableTree.prototype.remove = function (relativePath) {
- if (pathIsEmpty(relativePath)) {
- if (this.children.isEmpty()) {
- return new ImmutableTree(null);
- }
- else {
- return new ImmutableTree(null, this.children);
- }
- }
- else {
- var front = pathGetFront(relativePath);
- var child = this.children.get(front);
- if (child) {
- var newChild = child.remove(pathPopFront(relativePath));
- var newChildren = void 0;
- if (newChild.isEmpty()) {
- newChildren = this.children.remove(front);
- }
- else {
- newChildren = this.children.insert(front, newChild);
- }
- if (this.value === null && newChildren.isEmpty()) {
- return new ImmutableTree(null);
- }
- else {
- return new ImmutableTree(this.value, newChildren);
- }
- }
- else {
- return this;
- }
- }
- };
-
-
- ImmutableTree.prototype.get = function (relativePath) {
- if (pathIsEmpty(relativePath)) {
- return this.value;
- }
- else {
- var front = pathGetFront(relativePath);
- var child = this.children.get(front);
- if (child) {
- return child.get(pathPopFront(relativePath));
- }
- else {
- return null;
- }
- }
- };
-
-
- ImmutableTree.prototype.setTree = function (relativePath, newTree) {
- if (pathIsEmpty(relativePath)) {
- return newTree;
- }
- else {
- var front = pathGetFront(relativePath);
- var child = this.children.get(front) || new ImmutableTree(null);
- var newChild = child.setTree(pathPopFront(relativePath), newTree);
- var newChildren = void 0;
- if (newChild.isEmpty()) {
- newChildren = this.children.remove(front);
- }
- else {
- newChildren = this.children.insert(front, newChild);
- }
- return new ImmutableTree(this.value, newChildren);
- }
- };
-
-
- ImmutableTree.prototype.fold = function (fn) {
- return this.fold_(newEmptyPath(), fn);
- };
-
-
- ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
- var accum = {};
- this.children.inorderTraversal(function (childKey, childTree) {
- accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
- });
- return fn(pathSoFar, this.value, accum);
- };
-
-
- ImmutableTree.prototype.findOnPath = function (path, f) {
- return this.findOnPath_(path, newEmptyPath(), f);
- };
- ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
- var result = this.value ? f(pathSoFar, this.value) : false;
- if (result) {
- return result;
- }
- else {
- if (pathIsEmpty(pathToFollow)) {
- return null;
- }
- else {
- var front = pathGetFront(pathToFollow);
- var nextChild = this.children.get(front);
- if (nextChild) {
- return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
- }
- else {
- return null;
- }
- }
- }
- };
- ImmutableTree.prototype.foreachOnPath = function (path, f) {
- return this.foreachOnPath_(path, newEmptyPath(), f);
- };
- ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
- if (pathIsEmpty(pathToFollow)) {
- return this;
- }
- else {
- if (this.value) {
- f(currentRelativePath, this.value);
- }
- var front = pathGetFront(pathToFollow);
- var nextChild = this.children.get(front);
- if (nextChild) {
- return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
- }
- else {
- return new ImmutableTree(null);
- }
- }
- };
-
-
- ImmutableTree.prototype.foreach = function (f) {
- this.foreach_(newEmptyPath(), f);
- };
- ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
- this.children.inorderTraversal(function (childName, childTree) {
- childTree.foreach_(pathChild(currentRelativePath, childName), f);
- });
- if (this.value) {
- f(currentRelativePath, this.value);
- }
- };
- ImmutableTree.prototype.foreachChild = function (f) {
- this.children.inorderTraversal(function (childName, childTree) {
- if (childTree.value) {
- f(childName, childTree.value);
- }
- });
- };
- return ImmutableTree;
- }());
-
-
-
- var CompoundWrite = (function () {
- function CompoundWrite(writeTree_) {
- this.writeTree_ = writeTree_;
- }
- CompoundWrite.empty = function () {
- return new CompoundWrite(new ImmutableTree(null));
- };
- return CompoundWrite;
- }());
- function compoundWriteAddWrite(compoundWrite, path, node) {
- if (pathIsEmpty(path)) {
- return new CompoundWrite(new ImmutableTree(node));
- }
- else {
- var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
- if (rootmost != null) {
- var rootMostPath = rootmost.path;
- var value = rootmost.value;
- var relativePath = newRelativePath(rootMostPath, path);
- value = value.updateChild(relativePath, node);
- return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
- }
- else {
- var subtree = new ImmutableTree(node);
- var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
- return new CompoundWrite(newWriteTree);
- }
- }
- }
- function compoundWriteAddWrites(compoundWrite, path, updates) {
- var newWrite = compoundWrite;
- each(updates, function (childKey, node) {
- newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
- });
- return newWrite;
- }
-
- function compoundWriteRemoveWrite(compoundWrite, path) {
- if (pathIsEmpty(path)) {
- return CompoundWrite.empty();
- }
- else {
- var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
- return new CompoundWrite(newWriteTree);
- }
- }
-
- function compoundWriteHasCompleteWrite(compoundWrite, path) {
- return compoundWriteGetCompleteNode(compoundWrite, path) != null;
- }
-
- function compoundWriteGetCompleteNode(compoundWrite, path) {
- var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
- if (rootmost != null) {
- return compoundWrite.writeTree_
- .get(rootmost.path)
- .getChild(newRelativePath(rootmost.path, path));
- }
- else {
- return null;
- }
- }
-
- function compoundWriteGetCompleteChildren(compoundWrite) {
- var children = [];
- var node = compoundWrite.writeTree_.value;
- if (node != null) {
-
- if (!node.isLeafNode()) {
- node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
- children.push(new NamedNode(childName, childNode));
- });
- }
- }
- else {
- compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
- if (childTree.value != null) {
- children.push(new NamedNode(childName, childTree.value));
- }
- });
- }
- return children;
- }
- function compoundWriteChildCompoundWrite(compoundWrite, path) {
- if (pathIsEmpty(path)) {
- return compoundWrite;
- }
- else {
- var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
- if (shadowingNode != null) {
- return new CompoundWrite(new ImmutableTree(shadowingNode));
- }
- else {
- return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
- }
- }
- }
-
- function compoundWriteIsEmpty(compoundWrite) {
- return compoundWrite.writeTree_.isEmpty();
- }
-
- function compoundWriteApply(compoundWrite, node) {
- return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
- }
- function applySubtreeWrite(relativePath, writeTree, node) {
- if (writeTree.value != null) {
-
- return node.updateChild(relativePath, writeTree.value);
- }
- else {
- var priorityWrite_1 = null;
- writeTree.children.inorderTraversal(function (childKey, childTree) {
- if (childKey === '.priority') {
-
-
- assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
- priorityWrite_1 = childTree.value;
- }
- else {
- node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
- }
- });
-
- if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
- node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
- }
- return node;
- }
- }
-
-
-
- function writeTreeChildWrites(writeTree, path) {
- return newWriteTreeRef(path, writeTree);
- }
-
- function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
- assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
- if (visible === undefined) {
- visible = true;
- }
- writeTree.allWrites.push({
- path: path,
- snap: snap,
- writeId: writeId,
- visible: visible
- });
- if (visible) {
- writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
- }
- writeTree.lastWriteId = writeId;
- }
-
- function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
- assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
- writeTree.allWrites.push({
- path: path,
- children: changedChildren,
- writeId: writeId,
- visible: true
- });
- writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
- writeTree.lastWriteId = writeId;
- }
- function writeTreeGetWrite(writeTree, writeId) {
- for (var i = 0; i < writeTree.allWrites.length; i++) {
- var record = writeTree.allWrites[i];
- if (record.writeId === writeId) {
- return record;
- }
- }
- return null;
- }
-
- function writeTreeRemoveWrite(writeTree, writeId) {
-
-
-
-
- var idx = writeTree.allWrites.findIndex(function (s) {
- return s.writeId === writeId;
- });
- assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
- var writeToRemove = writeTree.allWrites[idx];
- writeTree.allWrites.splice(idx, 1);
- var removedWriteWasVisible = writeToRemove.visible;
- var removedWriteOverlapsWithOtherWrites = false;
- var i = writeTree.allWrites.length - 1;
- while (removedWriteWasVisible && i >= 0) {
- var currentWrite = writeTree.allWrites[i];
- if (currentWrite.visible) {
- if (i >= idx &&
- writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
-
- removedWriteWasVisible = false;
- }
- else if (pathContains(writeToRemove.path, currentWrite.path)) {
-
- removedWriteOverlapsWithOtherWrites = true;
- }
- }
- i--;
- }
- if (!removedWriteWasVisible) {
- return false;
- }
- else if (removedWriteOverlapsWithOtherWrites) {
-
- writeTreeResetTree_(writeTree);
- return true;
- }
- else {
-
- if (writeToRemove.snap) {
- writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
- }
- else {
- var children = writeToRemove.children;
- each(children, function (childName) {
- writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
- });
- }
- return true;
- }
- }
- function writeTreeRecordContainsPath_(writeRecord, path) {
- if (writeRecord.snap) {
- return pathContains(writeRecord.path, path);
- }
- else {
- for (var childName in writeRecord.children) {
- if (writeRecord.children.hasOwnProperty(childName) &&
- pathContains(pathChild(writeRecord.path, childName), path)) {
- return true;
- }
- }
- return false;
- }
- }
-
- function writeTreeResetTree_(writeTree) {
- writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
- if (writeTree.allWrites.length > 0) {
- writeTree.lastWriteId =
- writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
- }
- else {
- writeTree.lastWriteId = -1;
- }
- }
-
- function writeTreeDefaultFilter_(write) {
- return write.visible;
- }
-
- function writeTreeLayerTree_(writes, filter, treeRoot) {
- var compoundWrite = CompoundWrite.empty();
- for (var i = 0; i < writes.length; ++i) {
- var write = writes[i];
-
-
-
- if (filter(write)) {
- var writePath = write.path;
- var relativePath = void 0;
- if (write.snap) {
- if (pathContains(treeRoot, writePath)) {
- relativePath = newRelativePath(treeRoot, writePath);
- compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
- }
- else if (pathContains(writePath, treeRoot)) {
- relativePath = newRelativePath(writePath, treeRoot);
- compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
- }
- else ;
- }
- else if (write.children) {
- if (pathContains(treeRoot, writePath)) {
- relativePath = newRelativePath(treeRoot, writePath);
- compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
- }
- else if (pathContains(writePath, treeRoot)) {
- relativePath = newRelativePath(writePath, treeRoot);
- if (pathIsEmpty(relativePath)) {
- compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
- }
- else {
- var child = safeGet(write.children, pathGetFront(relativePath));
- if (child) {
-
- var deepNode = child.getChild(pathPopFront(relativePath));
- compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
- }
- }
- }
- else ;
- }
- else {
- throw assertionError('WriteRecord should have .snap or .children');
- }
- }
- }
- return compoundWrite;
- }
-
- function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
- if (!writeIdsToExclude && !includeHiddenWrites) {
- var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
- if (shadowingNode != null) {
- return shadowingNode;
- }
- else {
- var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- if (compoundWriteIsEmpty(subMerge)) {
- return completeServerCache;
- }
- else if (completeServerCache == null &&
- !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
-
- return null;
- }
- else {
- var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
- return compoundWriteApply(subMerge, layeredCache);
- }
- }
- }
- else {
- var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
- return completeServerCache;
- }
- else {
-
- if (!includeHiddenWrites &&
- completeServerCache == null &&
- !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
- return null;
- }
- else {
- var filter = function (write) {
- return ((write.visible || includeHiddenWrites) &&
- (!writeIdsToExclude ||
- !~writeIdsToExclude.indexOf(write.writeId)) &&
- (pathContains(write.path, treePath) ||
- pathContains(treePath, write.path)));
- };
- var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
- var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
- return compoundWriteApply(mergeAtPath, layeredCache);
- }
- }
- }
- }
-
- function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
- var completeChildren = ChildrenNode.EMPTY_NODE;
- var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
- if (topLevelSet) {
- if (!topLevelSet.isLeafNode()) {
-
- topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
- completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
- });
- }
- return completeChildren;
- }
- else if (completeServerChildren) {
-
-
- var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
- var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
- completeChildren = completeChildren.updateImmediateChild(childName, node);
- });
-
- compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
- completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
- });
- return completeChildren;
- }
- else {
-
-
- var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
- completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
- });
- return completeChildren;
- }
- }
-
- function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
- assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
- var path = pathChild(treePath, childPath);
- if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
-
-
- return null;
- }
- else {
-
- var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
- if (compoundWriteIsEmpty(childMerge)) {
-
- return existingServerSnap.getChild(childPath);
- }
- else {
-
-
-
-
-
-
- return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
- }
- }
- }
-
- function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
- var path = pathChild(treePath, childKey);
- var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
- if (shadowingNode != null) {
- return shadowingNode;
- }
- else {
- if (existingServerSnap.isCompleteForChild(childKey)) {
- var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
- return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
- }
- else {
- return null;
- }
- }
- }
-
- function writeTreeShadowingWrite(writeTree, path) {
- return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
- }
-
- function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
- var toIterate;
- var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
- if (shadowingNode != null) {
- toIterate = shadowingNode;
- }
- else if (completeServerData != null) {
- toIterate = compoundWriteApply(merge, completeServerData);
- }
- else {
-
- return [];
- }
- toIterate = toIterate.withIndex(index);
- if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
- var nodes = [];
- var cmp = index.getCompare();
- var iter = reverse
- ? toIterate.getReverseIteratorFrom(startPost, index)
- : toIterate.getIteratorFrom(startPost, index);
- var next = iter.getNext();
- while (next && nodes.length < count) {
- if (cmp(next, startPost) !== 0) {
- nodes.push(next);
- }
- next = iter.getNext();
- }
- return nodes;
- }
- else {
- return [];
- }
- }
- function newWriteTree() {
- return {
- visibleWrites: CompoundWrite.empty(),
- allWrites: [],
- lastWriteId: -1
- };
- }
-
- function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
- return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
- }
-
- function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
- return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
- }
-
- function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
- return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
- }
-
- function writeTreeRefShadowingWrite(writeTreeRef, path) {
- return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
- }
-
- function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
- return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
- }
-
- function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
- return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
- }
-
- function writeTreeRefChild(writeTreeRef, childName) {
- return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
- }
- function newWriteTreeRef(path, writeTree) {
- return {
- treePath: path,
- writeTree: writeTree
- };
- }
-
-
- var ChildChangeAccumulator = (function () {
- function ChildChangeAccumulator() {
- this.changeMap = new Map();
- }
- ChildChangeAccumulator.prototype.trackChildChange = function (change) {
- var type = change.type;
- var childKey = change.childName;
- assert(type === "child_added" ||
- type === "child_changed" ||
- type === "child_removed" , 'Only child changes supported for tracking');
- assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
- var oldChange = this.changeMap.get(childKey);
- if (oldChange) {
- var oldType = oldChange.type;
- if (type === "child_added" &&
- oldType === "child_removed" ) {
- this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
- }
- else if (type === "child_removed" &&
- oldType === "child_added" ) {
- this.changeMap.delete(childKey);
- }
- else if (type === "child_removed" &&
- oldType === "child_changed" ) {
- this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
- }
- else if (type === "child_changed" &&
- oldType === "child_added" ) {
- this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
- }
- else if (type === "child_changed" &&
- oldType === "child_changed" ) {
- this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
- }
- else {
- throw assertionError('Illegal combination of changes: ' +
- change +
- ' occurred after ' +
- oldChange);
- }
- }
- else {
- this.changeMap.set(childKey, change);
- }
- };
- ChildChangeAccumulator.prototype.getChanges = function () {
- return Array.from(this.changeMap.values());
- };
- return ChildChangeAccumulator;
- }());
-
-
-
-
- var NoCompleteChildSource_ = (function () {
- function NoCompleteChildSource_() {
- }
- NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
- return null;
- };
- NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
- return null;
- };
- return NoCompleteChildSource_;
- }());
-
- var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
-
- var WriteTreeCompleteChildSource = (function () {
- function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
- if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
- this.writes_ = writes_;
- this.viewCache_ = viewCache_;
- this.optCompleteServerCache_ = optCompleteServerCache_;
- }
- WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
- var node = this.viewCache_.eventCache;
- if (node.isCompleteForChild(childKey)) {
- return node.getNode().getImmediateChild(childKey);
- }
- else {
- var serverNode = this.optCompleteServerCache_ != null
- ? new CacheNode(this.optCompleteServerCache_, true, false)
- : this.viewCache_.serverCache;
- return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
- }
- };
- WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
- var completeServerData = this.optCompleteServerCache_ != null
- ? this.optCompleteServerCache_
- : viewCacheGetCompleteServerSnap(this.viewCache_);
- var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
- if (nodes.length === 0) {
- return null;
- }
- else {
- return nodes[0];
- }
- };
- return WriteTreeCompleteChildSource;
- }());
-
-
- function newViewProcessor(filter) {
- return { filter: filter };
- }
- function viewProcessorAssertIndexed(viewProcessor, viewCache) {
- assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
- assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
- }
- function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
- var accumulator = new ChildChangeAccumulator();
- var newViewCache, filterServerNode;
- if (operation.type === OperationType.OVERWRITE) {
- var overwrite = operation;
- if (overwrite.source.fromUser) {
- newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
- }
- else {
- assert(overwrite.source.fromServer, 'Unknown source.');
-
-
-
- filterServerNode =
- overwrite.source.tagged ||
- (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
- newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
- }
- }
- else if (operation.type === OperationType.MERGE) {
- var merge = operation;
- if (merge.source.fromUser) {
- newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
- }
- else {
- assert(merge.source.fromServer, 'Unknown source.');
-
- filterServerNode =
- merge.source.tagged || oldViewCache.serverCache.isFiltered();
- newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
- }
- }
- else if (operation.type === OperationType.ACK_USER_WRITE) {
- var ackUserWrite = operation;
- if (!ackUserWrite.revert) {
- newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
- }
- else {
- newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
- }
- }
- else if (operation.type === OperationType.LISTEN_COMPLETE) {
- newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
- }
- else {
- throw assertionError('Unknown operation type: ' + operation.type);
- }
- var changes = accumulator.getChanges();
- viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
- return { viewCache: newViewCache, changes: changes };
- }
- function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
- var eventSnap = newViewCache.eventCache;
- if (eventSnap.isFullyInitialized()) {
- var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
- var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
- if (accumulator.length > 0 ||
- !oldViewCache.eventCache.isFullyInitialized() ||
- (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
- !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
- accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
- }
- }
- }
- function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
- var oldEventSnap = viewCache.eventCache;
- if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
-
- return viewCache;
- }
- else {
- var newEventCache = void 0, serverNode = void 0;
- if (pathIsEmpty(changePath)) {
-
- assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
- if (viewCache.serverCache.isFiltered()) {
-
-
-
- var serverCache = viewCacheGetCompleteServerSnap(viewCache);
- var completeChildren = serverCache instanceof ChildrenNode
- ? serverCache
- : ChildrenNode.EMPTY_NODE;
- var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
- newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
- }
- else {
- var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
- newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
- }
- }
- else {
- var childKey = pathGetFront(changePath);
- if (childKey === '.priority') {
- assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
- var oldEventNode = oldEventSnap.getNode();
- serverNode = viewCache.serverCache.getNode();
-
- var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
- if (updatedPriority != null) {
- newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
- }
- else {
-
- newEventCache = oldEventSnap.getNode();
- }
- }
- else {
- var childChangePath = pathPopFront(changePath);
-
- var newEventChild = void 0;
- if (oldEventSnap.isCompleteForChild(childKey)) {
- serverNode = viewCache.serverCache.getNode();
- var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
- if (eventChildUpdate != null) {
- newEventChild = oldEventSnap
- .getNode()
- .getImmediateChild(childKey)
- .updateChild(childChangePath, eventChildUpdate);
- }
- else {
-
- newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
- }
- }
- else {
- newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
- }
- if (newEventChild != null) {
- newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
- }
- else {
-
- newEventCache = oldEventSnap.getNode();
- }
- }
- }
- return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
- }
- }
- function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
- var oldServerSnap = oldViewCache.serverCache;
- var newServerCache;
- var serverFilter = filterServerNode
- ? viewProcessor.filter
- : viewProcessor.filter.getIndexedFilter();
- if (pathIsEmpty(changePath)) {
- newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
- }
- else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
-
- var newServerNode = oldServerSnap
- .getNode()
- .updateChild(changePath, changedSnap);
- newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
- }
- else {
- var childKey = pathGetFront(changePath);
- if (!oldServerSnap.isCompleteForPath(changePath) &&
- pathGetLength(changePath) > 1) {
-
- return oldViewCache;
- }
- var childChangePath = pathPopFront(changePath);
- var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
- var newChildNode = childNode.updateChild(childChangePath, changedSnap);
- if (childKey === '.priority') {
- newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
- }
- else {
- newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
- }
- }
- var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
- var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
- return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
- }
- function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
- var oldEventSnap = oldViewCache.eventCache;
- var newViewCache, newEventCache;
- var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
- if (pathIsEmpty(changePath)) {
- newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
- newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
- }
- else {
- var childKey = pathGetFront(changePath);
- if (childKey === '.priority') {
- newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
- newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
- }
- else {
- var childChangePath = pathPopFront(changePath);
- var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
- var newChild = void 0;
- if (pathIsEmpty(childChangePath)) {
-
- newChild = changedSnap;
- }
- else {
- var childNode = source.getCompleteChild(childKey);
- if (childNode != null) {
- if (pathGetBack(childChangePath) === '.priority' &&
- childNode.getChild(pathParent(childChangePath)).isEmpty()) {
-
-
- newChild = childNode;
- }
- else {
- newChild = childNode.updateChild(childChangePath, changedSnap);
- }
- }
- else {
-
- newChild = ChildrenNode.EMPTY_NODE;
- }
- }
- if (!oldChild.equals(newChild)) {
- var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
- newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
- }
- else {
- newViewCache = oldViewCache;
- }
- }
- }
- return newViewCache;
- }
- function viewProcessorCacheHasChild(viewCache, childKey) {
- return viewCache.eventCache.isCompleteForChild(childKey);
- }
- function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
-
-
-
-
-
-
- var curViewCache = viewCache;
- changedChildren.foreach(function (relativePath, childNode) {
- var writePath = pathChild(path, relativePath);
- if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
- curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
- }
- });
- changedChildren.foreach(function (relativePath, childNode) {
- var writePath = pathChild(path, relativePath);
- if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
- curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
- }
- });
- return curViewCache;
- }
- function viewProcessorApplyMerge(viewProcessor, node, merge) {
- merge.foreach(function (relativePath, childNode) {
- node = node.updateChild(relativePath, childNode);
- });
- return node;
- }
- function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
-
-
- if (viewCache.serverCache.getNode().isEmpty() &&
- !viewCache.serverCache.isFullyInitialized()) {
- return viewCache;
- }
-
-
-
-
-
-
- var curViewCache = viewCache;
- var viewMergeTree;
- if (pathIsEmpty(path)) {
- viewMergeTree = changedChildren;
- }
- else {
- viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
- }
- var serverNode = viewCache.serverCache.getNode();
- viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
- if (serverNode.hasChild(childKey)) {
- var serverChild = viewCache.serverCache
- .getNode()
- .getImmediateChild(childKey);
- var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
- curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
- }
- });
- viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
- var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
- childMergeTree.value === null;
- if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
- var serverChild = viewCache.serverCache
- .getNode()
- .getImmediateChild(childKey);
- var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
- curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
- }
- });
- return curViewCache;
- }
- function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
- if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
- return viewCache;
- }
-
- var filterServerNode = viewCache.serverCache.isFiltered();
-
-
- var serverCache = viewCache.serverCache;
- if (affectedTree.value != null) {
-
- if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
- serverCache.isCompleteForPath(ackPath)) {
- return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
- }
- else if (pathIsEmpty(ackPath)) {
-
-
- var changedChildren_1 = new ImmutableTree(null);
- serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
- changedChildren_1 = changedChildren_1.set(new Path(name), node);
- });
- return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
- }
- else {
- return viewCache;
- }
- }
- else {
-
- var changedChildren_2 = new ImmutableTree(null);
- affectedTree.foreach(function (mergePath, value) {
- var serverCachePath = pathChild(ackPath, mergePath);
- if (serverCache.isCompleteForPath(serverCachePath)) {
- changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
- }
- });
- return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
- }
- }
- function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
- var oldServerNode = viewCache.serverCache;
- var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
- return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
- }
- function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
- var complete;
- if (writeTreeRefShadowingWrite(writesCache, path) != null) {
- return viewCache;
- }
- else {
- var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
- var oldEventCache = viewCache.eventCache.getNode();
- var newEventCache = void 0;
- if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
- var newNode = void 0;
- if (viewCache.serverCache.isFullyInitialized()) {
- newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
- }
- else {
- var serverChildren = viewCache.serverCache.getNode();
- assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
- newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
- }
- newNode = newNode;
- newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
- }
- else {
- var childKey = pathGetFront(path);
- var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
- if (newChild == null &&
- viewCache.serverCache.isCompleteForChild(childKey)) {
- newChild = oldEventCache.getImmediateChild(childKey);
- }
- if (newChild != null) {
- newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
- }
- else if (viewCache.eventCache.getNode().hasChild(childKey)) {
-
- newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
- }
- else {
- newEventCache = oldEventCache;
- }
- if (newEventCache.isEmpty() &&
- viewCache.serverCache.isFullyInitialized()) {
-
- complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
- if (complete.isLeafNode()) {
- newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
- }
- }
- }
- complete =
- viewCache.serverCache.isFullyInitialized() ||
- writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
- return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
- }
- }
-
-
-
- var View = (function () {
- function View(query_, initialViewCache) {
- this.query_ = query_;
- this.eventRegistrations_ = [];
- var params = this.query_._queryParams;
- var indexFilter = new IndexedFilter(params.getIndex());
- var filter = queryParamsGetNodeFilter(params);
- this.processor_ = newViewProcessor(filter);
- var initialServerCache = initialViewCache.serverCache;
- var initialEventCache = initialViewCache.eventCache;
-
- var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
- var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
- var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
- var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
- this.viewCache_ = newViewCache(newEventCache, newServerCache);
- this.eventGenerator_ = new EventGenerator(this.query_);
- }
- Object.defineProperty(View.prototype, "query", {
- get: function () {
- return this.query_;
- },
- enumerable: false,
- configurable: true
- });
- return View;
- }());
- function viewGetServerCache(view) {
- return view.viewCache_.serverCache.getNode();
- }
- function viewGetCompleteNode(view) {
- return viewCacheGetCompleteEventSnap(view.viewCache_);
- }
- function viewGetCompleteServerCache(view, path) {
- var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
- if (cache) {
-
-
- if (view.query._queryParams.loadsAllData() ||
- (!pathIsEmpty(path) &&
- !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
- return cache.getChild(path);
- }
- }
- return null;
- }
- function viewIsEmpty(view) {
- return view.eventRegistrations_.length === 0;
- }
- function viewAddEventRegistration(view, eventRegistration) {
- view.eventRegistrations_.push(eventRegistration);
- }
-
- function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
- var cancelEvents = [];
- if (cancelError) {
- assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
- var path_1 = view.query._path;
- view.eventRegistrations_.forEach(function (registration) {
- var maybeEvent = registration.createCancelEvent(cancelError, path_1);
- if (maybeEvent) {
- cancelEvents.push(maybeEvent);
- }
- });
- }
- if (eventRegistration) {
- var remaining = [];
- for (var i = 0; i < view.eventRegistrations_.length; ++i) {
- var existing = view.eventRegistrations_[i];
- if (!existing.matches(eventRegistration)) {
- remaining.push(existing);
- }
- else if (eventRegistration.hasAnyCallback()) {
-
- remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
- break;
- }
- }
- view.eventRegistrations_ = remaining;
- }
- else {
- view.eventRegistrations_ = [];
- }
- return cancelEvents;
- }
-
- function viewApplyOperation(view, operation, writesCache, completeServerCache) {
- if (operation.type === OperationType.MERGE &&
- operation.source.queryId !== null) {
- assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
- assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
- }
- var oldViewCache = view.viewCache_;
- var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
- viewProcessorAssertIndexed(view.processor_, result.viewCache);
- assert(result.viewCache.serverCache.isFullyInitialized() ||
- !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
- view.viewCache_ = result.viewCache;
- return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
- }
- function viewGetInitialEvents(view, registration) {
- var eventSnap = view.viewCache_.eventCache;
- var initialChanges = [];
- if (!eventSnap.getNode().isLeafNode()) {
- var eventNode = eventSnap.getNode();
- eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
- initialChanges.push(changeChildAdded(key, childNode));
- });
- }
- if (eventSnap.isFullyInitialized()) {
- initialChanges.push(changeValue(eventSnap.getNode()));
- }
- return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
- }
- function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
- var registrations = eventRegistration
- ? [eventRegistration]
- : view.eventRegistrations_;
- return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
- }
-
-
- var referenceConstructor$1;
-
- var SyncPoint = (function () {
- function SyncPoint() {
-
-
- this.views = new Map();
- }
- return SyncPoint;
- }());
- function syncPointSetReferenceConstructor(val) {
- assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
- referenceConstructor$1 = val;
- }
- function syncPointGetReferenceConstructor() {
- assert(referenceConstructor$1, 'Reference.ts has not been loaded');
- return referenceConstructor$1;
- }
- function syncPointIsEmpty(syncPoint) {
- return syncPoint.views.size === 0;
- }
- function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
- var e_1, _a;
- var queryId = operation.source.queryId;
- if (queryId !== null) {
- var view = syncPoint.views.get(queryId);
- assert(view != null, 'SyncTree gave us an op for an invalid query.');
- return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
- }
- else {
- var events = [];
- try {
- for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
- var view = _c.value;
- events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
- }
- finally { if (e_1) throw e_1.error; }
- }
- return events;
- }
- }
-
- function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
- var queryId = query._queryIdentifier;
- var view = syncPoint.views.get(queryId);
- if (!view) {
-
- var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
- var eventCacheComplete = false;
- if (eventCache) {
- eventCacheComplete = true;
- }
- else if (serverCache instanceof ChildrenNode) {
- eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
- eventCacheComplete = false;
- }
- else {
- eventCache = ChildrenNode.EMPTY_NODE;
- eventCacheComplete = false;
- }
- var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
- return new View(query, viewCache);
- }
- return view;
- }
-
- function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
- var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
- if (!syncPoint.views.has(query._queryIdentifier)) {
- syncPoint.views.set(query._queryIdentifier, view);
- }
-
- viewAddEventRegistration(view, eventRegistration);
- return viewGetInitialEvents(view, eventRegistration);
- }
-
- function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
- var e_2, _a;
- var queryId = query._queryIdentifier;
- var removed = [];
- var cancelEvents = [];
- var hadCompleteView = syncPointHasCompleteView(syncPoint);
- if (queryId === 'default') {
- try {
-
- for (var _b = __values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
- var _d = __read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
- cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
- if (viewIsEmpty(view)) {
- syncPoint.views.delete(viewQueryId);
-
- if (!view.query._queryParams.loadsAllData()) {
- removed.push(view.query);
- }
- }
- }
- }
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
- }
- finally { if (e_2) throw e_2.error; }
- }
- }
- else {
-
- var view = syncPoint.views.get(queryId);
- if (view) {
- cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
- if (viewIsEmpty(view)) {
- syncPoint.views.delete(queryId);
-
- if (!view.query._queryParams.loadsAllData()) {
- removed.push(view.query);
- }
- }
- }
- }
- if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
-
- removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
- }
- return { removed: removed, events: cancelEvents };
- }
- function syncPointGetQueryViews(syncPoint) {
- var e_3, _a;
- var result = [];
- try {
- for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
- var view = _c.value;
- if (!view.query._queryParams.loadsAllData()) {
- result.push(view);
- }
- }
- }
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
- }
- finally { if (e_3) throw e_3.error; }
- }
- return result;
- }
-
- function syncPointGetCompleteServerCache(syncPoint, path) {
- var e_4, _a;
- var serverCache = null;
- try {
- for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
- var view = _c.value;
- serverCache = serverCache || viewGetCompleteServerCache(view, path);
- }
- }
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
- }
- finally { if (e_4) throw e_4.error; }
- }
- return serverCache;
- }
- function syncPointViewForQuery(syncPoint, query) {
- var params = query._queryParams;
- if (params.loadsAllData()) {
- return syncPointGetCompleteView(syncPoint);
- }
- else {
- var queryId = query._queryIdentifier;
- return syncPoint.views.get(queryId);
- }
- }
- function syncPointViewExistsForQuery(syncPoint, query) {
- return syncPointViewForQuery(syncPoint, query) != null;
- }
- function syncPointHasCompleteView(syncPoint) {
- return syncPointGetCompleteView(syncPoint) != null;
- }
- function syncPointGetCompleteView(syncPoint) {
- var e_5, _a;
- try {
- for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
- var view = _c.value;
- if (view.query._queryParams.loadsAllData()) {
- return view;
- }
- }
- }
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
- }
- finally { if (e_5) throw e_5.error; }
- }
- return null;
- }
-
-
- var referenceConstructor;
- function syncTreeSetReferenceConstructor(val) {
- assert(!referenceConstructor, '__referenceConstructor has already been defined');
- referenceConstructor = val;
- }
- function syncTreeGetReferenceConstructor() {
- assert(referenceConstructor, 'Reference.ts has not been loaded');
- return referenceConstructor;
- }
-
- var syncTreeNextQueryTag_ = 1;
-
- var SyncTree = (function () {
-
-
- function SyncTree(listenProvider_) {
- this.listenProvider_ = listenProvider_;
-
-
- this.syncPointTree_ = new ImmutableTree(null);
-
-
- this.pendingWriteTree_ = newWriteTree();
- this.tagToQueryMap = new Map();
- this.queryToTagMap = new Map();
- }
- return SyncTree;
- }());
-
- function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
-
- writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
- if (!visible) {
- return [];
- }
- else {
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
- }
- }
-
- function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
-
- writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
- var changeTree = ImmutableTree.fromObject(changedChildren);
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
- }
-
- function syncTreeAckUserWrite(syncTree, writeId, revert) {
- if (revert === void 0) { revert = false; }
- var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
- var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
- if (!needToReevaluate) {
- return [];
- }
- else {
- var affectedTree_1 = new ImmutableTree(null);
- if (write.snap != null) {
-
- affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
- }
- else {
- each(write.children, function (pathString) {
- affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
- });
- }
- return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
- }
- }
-
- function syncTreeApplyServerOverwrite(syncTree, path, newData) {
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
- }
-
- function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
- var changeTree = ImmutableTree.fromObject(changedChildren);
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
- }
-
- function syncTreeApplyListenComplete(syncTree, path) {
- return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
- }
-
- function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
- var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
- if (queryKey) {
- var r = syncTreeParseQueryKey_(queryKey);
- var queryPath = r.path, queryId = r.queryId;
- var relativePath = newRelativePath(queryPath, path);
- var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
- return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
- }
- else {
-
- return [];
- }
- }
-
- function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
- if (skipListenerDedup === void 0) { skipListenerDedup = false; }
-
- var path = query._path;
- var maybeSyncPoint = syncTree.syncPointTree_.get(path);
- var cancelEvents = [];
-
-
-
- if (maybeSyncPoint &&
- (query._queryIdentifier === 'default' ||
- syncPointViewExistsForQuery(maybeSyncPoint, query))) {
- var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
- if (syncPointIsEmpty(maybeSyncPoint)) {
- syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
- }
- var removed = removedAndEvents.removed;
- cancelEvents = removedAndEvents.events;
- if (!skipListenerDedup) {
-
-
-
-
- var removingDefault = -1 !==
- removed.findIndex(function (query) {
- return query._queryParams.loadsAllData();
- });
- var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
- return syncPointHasCompleteView(parentSyncPoint);
- });
- if (removingDefault && !covered) {
- var subtree = syncTree.syncPointTree_.subtree(path);
-
-
- if (!subtree.isEmpty()) {
-
- var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
-
- for (var i = 0; i < newViews.length; ++i) {
- var view = newViews[i], newQuery = view.query;
- var listener = syncTreeCreateListenerForView_(syncTree, view);
- syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
- }
- }
-
- }
-
-
-
- if (!covered && removed.length > 0 && !cancelError) {
-
-
- if (removingDefault) {
-
- var defaultTag = null;
- syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
- }
- else {
- removed.forEach(function (queryToRemove) {
- var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
- syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
- });
- }
- }
- }
-
- syncTreeRemoveTags_(syncTree, removed);
- }
- return cancelEvents;
- }
-
- function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
- var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
- if (queryKey != null) {
- var r = syncTreeParseQueryKey_(queryKey);
- var queryPath = r.path, queryId = r.queryId;
- var relativePath = newRelativePath(queryPath, path);
- var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
- return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
- }
- else {
-
- return [];
- }
- }
-
- function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
- var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
- if (queryKey) {
- var r = syncTreeParseQueryKey_(queryKey);
- var queryPath = r.path, queryId = r.queryId;
- var relativePath = newRelativePath(queryPath, path);
- var changeTree = ImmutableTree.fromObject(changedChildren);
- var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
- return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
- }
- else {
-
- return [];
- }
- }
-
- function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
- if (skipSetupListener === void 0) { skipSetupListener = false; }
- var path = query._path;
- var serverCache = null;
- var foundAncestorDefaultView = false;
-
-
- syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
- var relativePath = newRelativePath(pathToSyncPoint, path);
- serverCache =
- serverCache || syncPointGetCompleteServerCache(sp, relativePath);
- foundAncestorDefaultView =
- foundAncestorDefaultView || syncPointHasCompleteView(sp);
- });
- var syncPoint = syncTree.syncPointTree_.get(path);
- if (!syncPoint) {
- syncPoint = new SyncPoint();
- syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
- }
- else {
- foundAncestorDefaultView =
- foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
- serverCache =
- serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- var serverCacheComplete;
- if (serverCache != null) {
- serverCacheComplete = true;
- }
- else {
- serverCacheComplete = false;
- serverCache = ChildrenNode.EMPTY_NODE;
- var subtree = syncTree.syncPointTree_.subtree(path);
- subtree.foreachChild(function (childName, childSyncPoint) {
- var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
- if (completeCache) {
- serverCache = serverCache.updateImmediateChild(childName, completeCache);
- }
- });
- }
- var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
- if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
-
- var queryKey = syncTreeMakeQueryKey_(query);
- assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
- var tag = syncTreeGetNextQueryTag_();
- syncTree.queryToTagMap.set(queryKey, tag);
- syncTree.tagToQueryMap.set(tag, queryKey);
- }
- var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
- var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
- if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
- var view = syncPointViewForQuery(syncPoint, query);
- events = events.concat(syncTreeSetupListener_(syncTree, query, view));
- }
- return events;
- }
-
- function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
- var includeHiddenSets = true;
- var writeTree = syncTree.pendingWriteTree_;
- var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
- var relativePath = newRelativePath(pathSoFar, path);
- var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
- if (serverCache) {
- return serverCache;
- }
- });
- return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
- }
- function syncTreeGetServerValue(syncTree, query) {
- var path = query._path;
- var serverCache = null;
-
-
- syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
- var relativePath = newRelativePath(pathToSyncPoint, path);
- serverCache =
- serverCache || syncPointGetCompleteServerCache(sp, relativePath);
- });
- var syncPoint = syncTree.syncPointTree_.get(path);
- if (!syncPoint) {
- syncPoint = new SyncPoint();
- syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
- }
- else {
- serverCache =
- serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- var serverCacheComplete = serverCache != null;
- var serverCacheNode = serverCacheComplete
- ? new CacheNode(serverCache, true, false)
- : null;
- var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
- var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
- return viewGetCompleteNode(view);
- }
-
- function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
- return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
- null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
- }
-
- function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
- if (pathIsEmpty(operation.path)) {
- return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
- }
- else {
- var syncPoint = syncPointTree.get(newEmptyPath());
-
- if (serverCache == null && syncPoint != null) {
- serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- var events = [];
- var childName = pathGetFront(operation.path);
- var childOperation = operation.operationForChild(childName);
- var childTree = syncPointTree.children.get(childName);
- if (childTree && childOperation) {
- var childServerCache = serverCache
- ? serverCache.getImmediateChild(childName)
- : null;
- var childWritesCache = writeTreeRefChild(writesCache, childName);
- events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
- }
- if (syncPoint) {
- events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
- }
- return events;
- }
- }
-
- function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
- var syncPoint = syncPointTree.get(newEmptyPath());
-
- if (serverCache == null && syncPoint != null) {
- serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- var events = [];
- syncPointTree.children.inorderTraversal(function (childName, childTree) {
- var childServerCache = serverCache
- ? serverCache.getImmediateChild(childName)
- : null;
- var childWritesCache = writeTreeRefChild(writesCache, childName);
- var childOperation = operation.operationForChild(childName);
- if (childOperation) {
- events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
- }
- });
- if (syncPoint) {
- events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
- }
- return events;
- }
- function syncTreeCreateListenerForView_(syncTree, view) {
- var query = view.query;
- var tag = syncTreeTagForQuery(syncTree, query);
- return {
- hashFn: function () {
- var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
- return cache.hash();
- },
- onComplete: function (status) {
- if (status === 'ok') {
- if (tag) {
- return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
- }
- else {
- return syncTreeApplyListenComplete(syncTree, query._path);
- }
- }
- else {
-
-
- var error = errorForServerCode(status, query);
- return syncTreeRemoveEventRegistration(syncTree, query,
- null, error);
- }
- }
- };
- }
-
- function syncTreeTagForQuery(syncTree, query) {
- var queryKey = syncTreeMakeQueryKey_(query);
- return syncTree.queryToTagMap.get(queryKey);
- }
-
- function syncTreeMakeQueryKey_(query) {
- return query._path.toString() + '$' + query._queryIdentifier;
- }
-
- function syncTreeQueryKeyForTag_(syncTree, tag) {
- return syncTree.tagToQueryMap.get(tag);
- }
-
- function syncTreeParseQueryKey_(queryKey) {
- var splitIndex = queryKey.indexOf('$');
- assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
- return {
- queryId: queryKey.substr(splitIndex + 1),
- path: new Path(queryKey.substr(0, splitIndex))
- };
- }
-
- function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
- var syncPoint = syncTree.syncPointTree_.get(queryPath);
- assert(syncPoint, "Missing sync point for query tag that we're tracking");
- var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
- return syncPointApplyOperation(syncPoint, operation, writesCache, null);
- }
-
- function syncTreeCollectDistinctViewsForSubTree_(subtree) {
- return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
- if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
- var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
- return [completeView];
- }
- else {
-
- var views_1 = [];
- if (maybeChildSyncPoint) {
- views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
- }
- each(childMap, function (_key, childViews) {
- views_1 = views_1.concat(childViews);
- });
- return views_1;
- }
- });
- }
-
- function syncTreeQueryForListening_(query) {
- if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
-
-
-
- return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
- }
- else {
- return query;
- }
- }
- function syncTreeRemoveTags_(syncTree, queries) {
- for (var j = 0; j < queries.length; ++j) {
- var removedQuery = queries[j];
- if (!removedQuery._queryParams.loadsAllData()) {
-
- var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
- var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
- syncTree.queryToTagMap.delete(removedQueryKey);
- syncTree.tagToQueryMap.delete(removedQueryTag);
- }
- }
- }
-
- function syncTreeGetNextQueryTag_() {
- return syncTreeNextQueryTag_++;
- }
-
- function syncTreeSetupListener_(syncTree, query, view) {
- var path = query._path;
- var tag = syncTreeTagForQuery(syncTree, query);
- var listener = syncTreeCreateListenerForView_(syncTree, view);
- var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
- var subtree = syncTree.syncPointTree_.subtree(path);
-
-
- if (tag) {
- assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
- }
- else {
-
- var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
- if (!pathIsEmpty(relativePath) &&
- maybeChildSyncPoint &&
- syncPointHasCompleteView(maybeChildSyncPoint)) {
- return [syncPointGetCompleteView(maybeChildSyncPoint).query];
- }
- else {
-
- var queries_1 = [];
- if (maybeChildSyncPoint) {
- queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
- }
- each(childMap, function (_key, childQueries) {
- queries_1 = queries_1.concat(childQueries);
- });
- return queries_1;
- }
- });
- for (var i = 0; i < queriesToStop.length; ++i) {
- var queryToStop = queriesToStop[i];
- syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
- }
- }
- return events;
- }
-
-
- var ExistingValueProvider = (function () {
- function ExistingValueProvider(node_) {
- this.node_ = node_;
- }
- ExistingValueProvider.prototype.getImmediateChild = function (childName) {
- var child = this.node_.getImmediateChild(childName);
- return new ExistingValueProvider(child);
- };
- ExistingValueProvider.prototype.node = function () {
- return this.node_;
- };
- return ExistingValueProvider;
- }());
- var DeferredValueProvider = (function () {
- function DeferredValueProvider(syncTree, path) {
- this.syncTree_ = syncTree;
- this.path_ = path;
- }
- DeferredValueProvider.prototype.getImmediateChild = function (childName) {
- var childPath = pathChild(this.path_, childName);
- return new DeferredValueProvider(this.syncTree_, childPath);
- };
- DeferredValueProvider.prototype.node = function () {
- return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
- };
- return DeferredValueProvider;
- }());
-
- var generateWithValues = function (values) {
- values = values || {};
- values['timestamp'] = values['timestamp'] || new Date().getTime();
- return values;
- };
-
- var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
- if (!value || typeof value !== 'object') {
- return value;
- }
- assert('.sv' in value, 'Unexpected leaf node or priority contents');
- if (typeof value['.sv'] === 'string') {
- return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
- }
- else if (typeof value['.sv'] === 'object') {
- return resolveComplexDeferredValue(value['.sv'], existingVal);
- }
- else {
- assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
- }
- };
- var resolveScalarDeferredValue = function (op, existing, serverValues) {
- switch (op) {
- case 'timestamp':
- return serverValues['timestamp'];
- default:
- assert(false, 'Unexpected server value: ' + op);
- }
- };
- var resolveComplexDeferredValue = function (op, existing, unused) {
- if (!op.hasOwnProperty('increment')) {
- assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
- }
- var delta = op['increment'];
- if (typeof delta !== 'number') {
- assert(false, 'Unexpected increment value: ' + delta);
- }
- var existingNode = existing.node();
- assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
-
- if (!existingNode.isLeafNode()) {
- return delta;
- }
- var leaf = existingNode;
- var existingVal = leaf.getValue();
- if (typeof existingVal !== 'number') {
- return delta;
- }
-
- return existingVal + delta;
- };
-
- var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
- return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
- };
-
- var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
- return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
- };
- function resolveDeferredValue(node, existingVal, serverValues) {
- var rawPri = node.getPriority().val();
- var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
- var newNode;
- if (node.isLeafNode()) {
- var leafNode = node;
- var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
- if (value !== leafNode.getValue() ||
- priority !== leafNode.getPriority().val()) {
- return new LeafNode(value, nodeFromJSON(priority));
- }
- else {
- return node;
- }
- }
- else {
- var childrenNode = node;
- newNode = childrenNode;
- if (priority !== childrenNode.getPriority().val()) {
- newNode = newNode.updatePriority(new LeafNode(priority));
- }
- childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
- var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
- if (newChildNode !== childNode) {
- newNode = newNode.updateImmediateChild(childName, newChildNode);
- }
- });
- return newNode;
- }
- }
-
-
-
- var Tree = (function () {
-
-
- function Tree(name, parent, node) {
- if (name === void 0) { name = ''; }
- if (parent === void 0) { parent = null; }
- if (node === void 0) { node = { children: {}, childCount: 0 }; }
- this.name = name;
- this.parent = parent;
- this.node = node;
- }
- return Tree;
- }());
-
- function treeSubTree(tree, pathObj) {
-
- var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
- var child = tree, next = pathGetFront(path);
- while (next !== null) {
- var childNode = safeGet(child.node.children, next) || {
- children: {},
- childCount: 0
- };
- child = new Tree(next, child, childNode);
- path = pathPopFront(path);
- next = pathGetFront(path);
- }
- return child;
- }
-
- function treeGetValue(tree) {
- return tree.node.value;
- }
-
- function treeSetValue(tree, value) {
- tree.node.value = value;
- treeUpdateParents(tree);
- }
-
- function treeHasChildren(tree) {
- return tree.node.childCount > 0;
- }
-
- function treeIsEmpty(tree) {
- return treeGetValue(tree) === undefined && !treeHasChildren(tree);
- }
-
- function treeForEachChild(tree, action) {
- each(tree.node.children, function (child, childTree) {
- action(new Tree(child, tree, childTree));
- });
- }
-
- function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
- if (includeSelf && !childrenFirst) {
- action(tree);
- }
- treeForEachChild(tree, function (child) {
- treeForEachDescendant(child, action, true, childrenFirst);
- });
- if (includeSelf && childrenFirst) {
- action(tree);
- }
- }
-
- function treeForEachAncestor(tree, action, includeSelf) {
- var node = includeSelf ? tree : tree.parent;
- while (node !== null) {
- if (action(node)) {
- return true;
- }
- node = node.parent;
- }
- return false;
- }
-
- function treeGetPath(tree) {
- return new Path(tree.parent === null
- ? tree.name
- : treeGetPath(tree.parent) + '/' + tree.name);
- }
-
- function treeUpdateParents(tree) {
- if (tree.parent !== null) {
- treeUpdateChild(tree.parent, tree.name, tree);
- }
- }
-
- function treeUpdateChild(tree, childName, child) {
- var childEmpty = treeIsEmpty(child);
- var childExists = contains(tree.node.children, childName);
- if (childEmpty && childExists) {
- delete tree.node.children[childName];
- tree.node.childCount--;
- treeUpdateParents(tree);
- }
- else if (!childEmpty && !childExists) {
- tree.node.children[childName] = child.node;
- tree.node.childCount++;
- treeUpdateParents(tree);
- }
- }
-
-
-
- var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
-
- var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
-
- var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
- var isValidKey = function (key) {
- return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
- };
- var isValidPathString = function (pathString) {
- return (typeof pathString === 'string' &&
- pathString.length !== 0 &&
- !INVALID_PATH_REGEX_.test(pathString));
- };
- var isValidRootPathString = function (pathString) {
- if (pathString) {
-
- pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
- }
- return isValidPathString(pathString);
- };
- var isValidPriority = function (priority) {
- return (priority === null ||
- typeof priority === 'string' ||
- (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
- (priority &&
- typeof priority === 'object' &&
-
- contains(priority, '.sv')));
- };
-
- var validateFirebaseDataArg = function (fnName, value, path, optional) {
- if (optional && value === undefined) {
- return;
- }
- validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
- };
-
- var validateFirebaseData = function (errorPrefix, data, path_) {
- var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
- if (data === undefined) {
- throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
- }
- if (typeof data === 'function') {
- throw new Error(errorPrefix +
- 'contains a function ' +
- validationPathToErrorString(path) +
- ' with contents = ' +
- data.toString());
- }
- if (isInvalidJSONNumber(data)) {
- throw new Error(errorPrefix +
- 'contains ' +
- data.toString() +
- ' ' +
- validationPathToErrorString(path));
- }
-
- if (typeof data === 'string' &&
- data.length > MAX_LEAF_SIZE_ / 3 &&
- stringLength(data) > MAX_LEAF_SIZE_) {
- throw new Error(errorPrefix +
- 'contains a string greater than ' +
- MAX_LEAF_SIZE_ +
- ' utf8 bytes ' +
- validationPathToErrorString(path) +
- " ('" +
- data.substring(0, 50) +
- "...')");
- }
-
-
- if (data && typeof data === 'object') {
- var hasDotValue_1 = false;
- var hasActualChild_1 = false;
- each(data, function (key, value) {
- if (key === '.value') {
- hasDotValue_1 = true;
- }
- else if (key !== '.priority' && key !== '.sv') {
- hasActualChild_1 = true;
- if (!isValidKey(key)) {
- throw new Error(errorPrefix +
- ' contains an invalid key (' +
- key +
- ') ' +
- validationPathToErrorString(path) +
- '. Keys must be non-empty strings ' +
- 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
- }
- }
- validationPathPush(path, key);
- validateFirebaseData(errorPrefix, value, path);
- validationPathPop(path);
- });
- if (hasDotValue_1 && hasActualChild_1) {
- throw new Error(errorPrefix +
- ' contains ".value" child ' +
- validationPathToErrorString(path) +
- ' in addition to actual children.');
- }
- }
- };
-
- var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
- var i, curPath;
- for (i = 0; i < mergePaths.length; i++) {
- curPath = mergePaths[i];
- var keys = pathSlice(curPath);
- for (var j = 0; j < keys.length; j++) {
- if (keys[j] === '.priority' && j === keys.length - 1) ;
- else if (!isValidKey(keys[j])) {
- throw new Error(errorPrefix +
- 'contains an invalid key (' +
- keys[j] +
- ') in path ' +
- curPath.toString() +
- '. Keys must be non-empty strings ' +
- 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
- }
- }
- }
-
-
-
- mergePaths.sort(pathCompare);
- var prevPath = null;
- for (i = 0; i < mergePaths.length; i++) {
- curPath = mergePaths[i];
- if (prevPath !== null && pathContains(prevPath, curPath)) {
- throw new Error(errorPrefix +
- 'contains a path ' +
- prevPath.toString() +
- ' that is ancestor of another path ' +
- curPath.toString());
- }
- prevPath = curPath;
- }
- };
-
- var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
- if (optional && data === undefined) {
- return;
- }
- var errorPrefix$1 = errorPrefix(fnName, 'values');
- if (!(data && typeof data === 'object') || Array.isArray(data)) {
- throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
- }
- var mergePaths = [];
- each(data, function (key, value) {
- var curPath = new Path(key);
- validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
- if (pathGetBack(curPath) === '.priority') {
- if (!isValidPriority(value)) {
- throw new Error(errorPrefix$1 +
- "contains an invalid value for '" +
- curPath.toString() +
- "', which must be a valid " +
- 'Firebase priority (a string, finite number, server value, or null).');
- }
- }
- mergePaths.push(curPath);
- });
- validateFirebaseMergePaths(errorPrefix$1, mergePaths);
- };
- var validatePriority = function (fnName, priority, optional) {
- if (optional && priority === undefined) {
- return;
- }
- if (isInvalidJSONNumber(priority)) {
- throw new Error(errorPrefix(fnName, 'priority') +
- 'is ' +
- priority.toString() +
- ', but must be a valid Firebase priority (a string, finite number, ' +
- 'server value, or null).');
- }
-
- if (!isValidPriority(priority)) {
- throw new Error(errorPrefix(fnName, 'priority') +
- 'must be a valid Firebase priority ' +
- '(a string, finite number, server value, or null).');
- }
- };
- var validateKey = function (fnName, argumentName, key, optional) {
- if (optional && key === undefined) {
- return;
- }
- if (!isValidKey(key)) {
- throw new Error(errorPrefix(fnName, argumentName) +
- 'was an invalid key = "' +
- key +
- '". Firebase keys must be non-empty strings and ' +
- 'can\'t contain ".", "#", "$", "/", "[", or "]").');
- }
- };
-
- var validatePathString = function (fnName, argumentName, pathString, optional) {
- if (optional && pathString === undefined) {
- return;
- }
- if (!isValidPathString(pathString)) {
- throw new Error(errorPrefix(fnName, argumentName) +
- 'was an invalid path = "' +
- pathString +
- '". Paths must be non-empty strings and ' +
- 'can\'t contain ".", "#", "$", "[", or "]"');
- }
- };
- var validateRootPathString = function (fnName, argumentName, pathString, optional) {
- if (pathString) {
-
- pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
- }
- validatePathString(fnName, argumentName, pathString, optional);
- };
-
- var validateWritablePath = function (fnName, path) {
- if (pathGetFront(path) === '.info') {
- throw new Error(fnName + " failed = Can't modify data under /.info/");
- }
- };
- var validateUrl = function (fnName, parsedUrl) {
-
- var pathString = parsedUrl.path.toString();
- if (!(typeof parsedUrl.repoInfo.host === 'string') ||
- parsedUrl.repoInfo.host.length === 0 ||
- (!isValidKey(parsedUrl.repoInfo.namespace) &&
- parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
- (pathString.length !== 0 && !isValidRootPathString(pathString))) {
- throw new Error(errorPrefix(fnName, 'url') +
- 'must be a valid firebase URL and ' +
- 'the path can\'t contain ".", "#", "$", "[", or "]".');
- }
- };
-
-
-
- var EventQueue = (function () {
- function EventQueue() {
- this.eventLists_ = [];
-
-
- this.recursionDepth_ = 0;
- }
- return EventQueue;
- }());
-
- function eventQueueQueueEvents(eventQueue, eventDataList) {
-
- var currList = null;
- for (var i = 0; i < eventDataList.length; i++) {
- var data = eventDataList[i];
- var path = data.getPath();
- if (currList !== null && !pathEquals(path, currList.path)) {
- eventQueue.eventLists_.push(currList);
- currList = null;
- }
- if (currList === null) {
- currList = { events: [], path: path };
- }
- currList.events.push(data);
- }
- if (currList) {
- eventQueue.eventLists_.push(currList);
- }
- }
-
- function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
- eventQueueQueueEvents(eventQueue, eventDataList);
- eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
- return pathEquals(eventPath, path);
- });
- }
-
- function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
- eventQueueQueueEvents(eventQueue, eventDataList);
- eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
- return pathContains(eventPath, changedPath) ||
- pathContains(changedPath, eventPath);
- });
- }
- function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
- eventQueue.recursionDepth_++;
- var sentAll = true;
- for (var i = 0; i < eventQueue.eventLists_.length; i++) {
- var eventList = eventQueue.eventLists_[i];
- if (eventList) {
- var eventPath = eventList.path;
- if (predicate(eventPath)) {
- eventListRaise(eventQueue.eventLists_[i]);
- eventQueue.eventLists_[i] = null;
- }
- else {
- sentAll = false;
- }
- }
- }
- if (sentAll) {
- eventQueue.eventLists_ = [];
- }
- eventQueue.recursionDepth_--;
- }
-
- function eventListRaise(eventList) {
- for (var i = 0; i < eventList.events.length; i++) {
- var eventData = eventList.events[i];
- if (eventData !== null) {
- eventList.events[i] = null;
- var eventFn = eventData.getEventRunner();
- if (logger) {
- log('event: ' + eventData.toString());
- }
- exceptionGuard(eventFn);
- }
- }
- }
-
-
- var INTERRUPT_REASON = 'repo_interrupt';
-
- var MAX_TRANSACTION_RETRIES = 25;
-
- var Repo = (function () {
- function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
- this.repoInfo_ = repoInfo_;
- this.forceRestClient_ = forceRestClient_;
- this.authTokenProvider_ = authTokenProvider_;
- this.appCheckProvider_ = appCheckProvider_;
- this.dataUpdateCount = 0;
- this.statsListener_ = null;
- this.eventQueue_ = new EventQueue();
- this.nextWriteId_ = 1;
- this.interceptServerDataCallback_ = null;
-
- this.onDisconnect_ = newSparseSnapshotTree();
-
- this.transactionQueueTree_ = new Tree();
-
- this.persistentConnection_ = null;
-
- this.key = this.repoInfo_.toURLString();
- }
-
-
- Repo.prototype.toString = function () {
- return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
- };
- return Repo;
- }());
- function repoStart(repo, appId, authOverride) {
- repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
- if (repo.forceRestClient_ || beingCrawled()) {
- repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
- repoOnDataUpdate(repo, pathString, data, isMerge, tag);
- }, repo.authTokenProvider_, repo.appCheckProvider_);
-
- setTimeout(function () { return repoOnConnectStatus(repo, true); }, 0);
- }
- else {
-
- if (typeof authOverride !== 'undefined' && authOverride !== null) {
- if (typeof authOverride !== 'object') {
- throw new Error('Only objects are supported for option databaseAuthVariableOverride');
- }
- try {
- stringify(authOverride);
- }
- catch (e) {
- throw new Error('Invalid authOverride provided: ' + e);
- }
- }
- repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
- repoOnDataUpdate(repo, pathString, data, isMerge, tag);
- }, function (connectStatus) {
- repoOnConnectStatus(repo, connectStatus);
- }, function (updates) {
- repoOnServerInfoUpdate(repo, updates);
- }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
- repo.server_ = repo.persistentConnection_;
- }
- repo.authTokenProvider_.addTokenChangeListener(function (token) {
- repo.server_.refreshAuthToken(token);
- });
- repo.appCheckProvider_.addTokenChangeListener(function (result) {
- repo.server_.refreshAppCheckToken(result.token);
- });
-
-
- repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
-
- repo.infoData_ = new SnapshotHolder();
- repo.infoSyncTree_ = new SyncTree({
- startListening: function (query, tag, currentHashFn, onComplete) {
- var infoEvents = [];
- var node = repo.infoData_.getNode(query._path);
-
-
- if (!node.isEmpty()) {
- infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
- setTimeout(function () {
- onComplete('ok');
- }, 0);
- }
- return infoEvents;
- },
- stopListening: function () { }
- });
- repoUpdateInfo(repo, 'connected', false);
- repo.serverSyncTree_ = new SyncTree({
- startListening: function (query, tag, currentHashFn, onComplete) {
- repo.server_.listen(query, currentHashFn, tag, function (status, data) {
- var events = onComplete(status, data);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
- });
-
- return [];
- },
- stopListening: function (query, tag) {
- repo.server_.unlisten(query, tag);
- }
- });
- }
-
- function repoServerTime(repo) {
- var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
- var offset = offsetNode.val() || 0;
- return new Date().getTime() + offset;
- }
-
- function repoGenerateServerValues(repo) {
- return generateWithValues({
- timestamp: repoServerTime(repo)
- });
- }
-
- function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
-
- repo.dataUpdateCount++;
- var path = new Path(pathString);
- data = repo.interceptServerDataCallback_
- ? repo.interceptServerDataCallback_(pathString, data)
- : data;
- var events = [];
- if (tag) {
- if (isMerge) {
- var taggedChildren = map(data, function (raw) { return nodeFromJSON(raw); });
- events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
- }
- else {
- var taggedSnap = nodeFromJSON(data);
- events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
- }
- }
- else if (isMerge) {
- var changedChildren = map(data, function (raw) { return nodeFromJSON(raw); });
- events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
- }
- else {
- var snap = nodeFromJSON(data);
- events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
- }
- var affectedPath = path;
- if (events.length > 0) {
-
-
- affectedPath = repoRerunTransactions(repo, path);
- }
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
- }
- function repoOnConnectStatus(repo, connectStatus) {
- repoUpdateInfo(repo, 'connected', connectStatus);
- if (connectStatus === false) {
- repoRunOnDisconnectEvents(repo);
- }
- }
- function repoOnServerInfoUpdate(repo, updates) {
- each(updates, function (key, value) {
- repoUpdateInfo(repo, key, value);
- });
- }
- function repoUpdateInfo(repo, pathString, value) {
- var path = new Path('/.info/' + pathString);
- var newNode = nodeFromJSON(value);
- repo.infoData_.updateSnapshot(path, newNode);
- var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
- }
- function repoGetNextWriteId(repo) {
- return repo.nextWriteId_++;
- }
-
- function repoGetValue(repo, query, eventRegistration) {
-
- var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
- if (cached != null) {
- return Promise.resolve(cached);
- }
- return repo.server_.get(query).then(function (payload) {
- var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
-
-
- syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
- var events;
- if (query._queryParams.loadsAllData()) {
- events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
- }
- else {
- var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
- events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
- }
-
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
- syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
- return node;
- }, function (err) {
- repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
- return Promise.reject(new Error(err));
- });
- }
- function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
- repoLog(repo, 'set', {
- path: path.toString(),
- value: newVal,
- priority: newPriority
- });
-
-
- var serverValues = repoGenerateServerValues(repo);
- var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
- var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
- var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
- var writeId = repoGetNextWriteId(repo);
- var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
- eventQueueQueueEvents(repo.eventQueue_, events);
- repo.server_.put(path.toString(), newNodeUnresolved.val( true), function (status, errorReason) {
- var success = status === 'ok';
- if (!success) {
- warn('set at ' + path + ' failed: ' + status);
- }
- var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- var affectedPath = repoAbortTransactions(repo, path);
- repoRerunTransactions(repo, affectedPath);
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
- }
- function repoUpdate(repo, path, childrenToMerge, onComplete) {
- repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
-
- var empty = true;
- var serverValues = repoGenerateServerValues(repo);
- var changedChildren = {};
- each(childrenToMerge, function (changedKey, changedValue) {
- empty = false;
- changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
- });
- if (!empty) {
- var writeId_1 = repoGetNextWriteId(repo);
- var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
- eventQueueQueueEvents(repo.eventQueue_, events);
- repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
- var success = status === 'ok';
- if (!success) {
- warn('update at ' + path + ' failed: ' + status);
- }
- var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
- var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- each(childrenToMerge, function (changedPath) {
- var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
- repoRerunTransactions(repo, affectedPath);
- });
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
- }
- else {
- log("update() called with empty data. Don't do anything.");
- repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
- }
- }
-
- function repoRunOnDisconnectEvents(repo) {
- repoLog(repo, 'onDisconnectEvents');
- var serverValues = repoGenerateServerValues(repo);
- var resolvedOnDisconnectTree = newSparseSnapshotTree();
- sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
- var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
- sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
- });
- var events = [];
- sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
- events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
- var affectedPath = repoAbortTransactions(repo, path);
- repoRerunTransactions(repo, affectedPath);
- });
- repo.onDisconnect_ = newSparseSnapshotTree();
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
- }
- function repoOnDisconnectCancel(repo, path, onComplete) {
- repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
- if (status === 'ok') {
- sparseSnapshotTreeForget(repo.onDisconnect_, path);
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoOnDisconnectSet(repo, path, value, onComplete) {
- var newNode = nodeFromJSON(value);
- repo.server_.onDisconnectPut(path.toString(), newNode.val( true), function (status, errorReason) {
- if (status === 'ok') {
- sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
- var newNode = nodeFromJSON(value, priority);
- repo.server_.onDisconnectPut(path.toString(), newNode.val( true), function (status, errorReason) {
- if (status === 'ok') {
- sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
- if (isEmpty(childrenToMerge)) {
- log("onDisconnect().update() called with empty data. Don't do anything.");
- repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
- return;
- }
- repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
- if (status === 'ok') {
- each(childrenToMerge, function (childName, childNode) {
- var newChildNode = nodeFromJSON(childNode);
- sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
- });
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
- var events;
- if (pathGetFront(query._path) === '.info') {
- events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
- }
- else {
- events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
- }
- eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
- }
- function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
-
-
- var events;
- if (pathGetFront(query._path) === '.info') {
- events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
- }
- else {
- events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
- }
- eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
- }
- function repoInterrupt(repo) {
- if (repo.persistentConnection_) {
- repo.persistentConnection_.interrupt(INTERRUPT_REASON);
- }
- }
- function repoResume(repo) {
- if (repo.persistentConnection_) {
- repo.persistentConnection_.resume(INTERRUPT_REASON);
- }
- }
- function repoLog(repo) {
- var varArgs = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- varArgs[_i - 1] = arguments[_i];
- }
- var prefix = '';
- if (repo.persistentConnection_) {
- prefix = repo.persistentConnection_.id + ':';
- }
- log.apply(void 0, __spreadArray([prefix], __read(varArgs), false));
- }
- function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
- if (callback) {
- exceptionGuard(function () {
- if (status === 'ok') {
- callback(null);
- }
- else {
- var code = (status || 'error').toUpperCase();
- var message = code;
- if (errorReason) {
- message += ': ' + errorReason;
- }
- var error = new Error(message);
-
- error.code = code;
- callback(error);
- }
- });
- }
- }
-
- function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
- repoLog(repo, 'transaction on ' + path);
-
- var transaction = {
- path: path,
- update: transactionUpdate,
- onComplete: onComplete,
-
- status: null,
-
-
- order: LUIDGenerator(),
-
- applyLocally: applyLocally,
-
- retryCount: 0,
-
- unwatcher: unwatcher,
-
- abortReason: null,
- currentWriteId: null,
- currentInputSnapshot: null,
- currentOutputSnapshotRaw: null,
- currentOutputSnapshotResolved: null
- };
-
- var currentState = repoGetLatestState(repo, path, undefined);
- transaction.currentInputSnapshot = currentState;
- var newVal = transaction.update(currentState.val());
- if (newVal === undefined) {
-
- transaction.unwatcher();
- transaction.currentOutputSnapshotRaw = null;
- transaction.currentOutputSnapshotResolved = null;
- if (transaction.onComplete) {
- transaction.onComplete(null, false, transaction.currentInputSnapshot);
- }
- }
- else {
- validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
-
- transaction.status = 0 ;
- var queueNode = treeSubTree(repo.transactionQueueTree_, path);
- var nodeQueue = treeGetValue(queueNode) || [];
- nodeQueue.push(transaction);
- treeSetValue(queueNode, nodeQueue);
-
-
-
-
- var priorityForNode = void 0;
- if (typeof newVal === 'object' &&
- newVal !== null &&
- contains(newVal, '.priority')) {
-
- priorityForNode = safeGet(newVal, '.priority');
- assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
- 'Priority must be a valid string, finite number, server value, or null.');
- }
- else {
- var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
- ChildrenNode.EMPTY_NODE;
- priorityForNode = currentNode.getPriority().val();
- }
- var serverValues = repoGenerateServerValues(repo);
- var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
- var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
- transaction.currentOutputSnapshotRaw = newNodeUnresolved;
- transaction.currentOutputSnapshotResolved = newNode;
- transaction.currentWriteId = repoGetNextWriteId(repo);
- var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
- repoSendReadyTransactions(repo, repo.transactionQueueTree_);
- }
- }
-
- function repoGetLatestState(repo, path, excludeSets) {
- return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
- ChildrenNode.EMPTY_NODE);
- }
-
- function repoSendReadyTransactions(repo, node) {
- if (node === void 0) { node = repo.transactionQueueTree_; }
-
- if (!node) {
- repoPruneCompletedTransactionsBelowNode(repo, node);
- }
- if (treeGetValue(node)) {
- var queue = repoBuildTransactionQueue(repo, node);
- assert(queue.length > 0, 'Sending zero length transaction queue');
- var allRun = queue.every(function (transaction) { return transaction.status === 0 ; });
-
- if (allRun) {
- repoSendTransactionQueue(repo, treeGetPath(node), queue);
- }
- }
- else if (treeHasChildren(node)) {
- treeForEachChild(node, function (childNode) {
- repoSendReadyTransactions(repo, childNode);
- });
- }
- }
-
- function repoSendTransactionQueue(repo, path, queue) {
-
- var setsToIgnore = queue.map(function (txn) {
- return txn.currentWriteId;
- });
- var latestState = repoGetLatestState(repo, path, setsToIgnore);
- var snapToSend = latestState;
- var latestHash = latestState.hash();
- for (var i = 0; i < queue.length; i++) {
- var txn = queue[i];
- assert(txn.status === 0 , 'tryToSendTransactionQueue_: items in queue should all be run.');
- txn.status = 1 ;
- txn.retryCount++;
- var relativePath = newRelativePath(path, txn.path);
-
- snapToSend = snapToSend.updateChild(relativePath , txn.currentOutputSnapshotRaw);
- }
- var dataToSend = snapToSend.val(true);
- var pathToSend = path;
-
- repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
- repoLog(repo, 'transaction put response', {
- path: pathToSend.toString(),
- status: status
- });
- var events = [];
- if (status === 'ok') {
-
-
-
- var callbacks = [];
- var _loop_1 = function (i) {
- queue[i].status = 2 ;
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
- if (queue[i].onComplete) {
-
-
- callbacks.push(function () {
- return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
- });
- }
- queue[i].unwatcher();
- };
- for (var i = 0; i < queue.length; i++) {
- _loop_1(i);
- }
-
- repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
-
- repoSendReadyTransactions(repo, repo.transactionQueueTree_);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
-
- for (var i = 0; i < callbacks.length; i++) {
- exceptionGuard(callbacks[i]);
- }
- }
- else {
-
- if (status === 'datastale') {
- for (var i = 0; i < queue.length; i++) {
- if (queue[i].status === 3 ) {
- queue[i].status = 4 ;
- }
- else {
- queue[i].status = 0 ;
- }
- }
- }
- else {
- warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
- for (var i = 0; i < queue.length; i++) {
- queue[i].status = 4 ;
- queue[i].abortReason = status;
- }
- }
- repoRerunTransactions(repo, path);
- }
- }, latestHash);
- }
-
- function repoRerunTransactions(repo, changedPath) {
- var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
- var path = treeGetPath(rootMostTransactionNode);
- var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
- repoRerunTransactionQueue(repo, queue, path);
- return path;
- }
-
- function repoRerunTransactionQueue(repo, queue, path) {
- if (queue.length === 0) {
- return;
- }
-
-
-
- var callbacks = [];
- var events = [];
-
- var txnsToRerun = queue.filter(function (q) {
- return q.status === 0 ;
- });
- var setsToIgnore = txnsToRerun.map(function (q) {
- return q.currentWriteId;
- });
- var _loop_2 = function (i) {
- var transaction = queue[i];
- var relativePath = newRelativePath(path, transaction.path);
- var abortTransaction = false, abortReason;
- assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
- if (transaction.status === 4 ) {
- abortTransaction = true;
- abortReason = transaction.abortReason;
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
- }
- else if (transaction.status === 0 ) {
- if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
- abortTransaction = true;
- abortReason = 'maxretry';
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
- }
- else {
-
- var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
- transaction.currentInputSnapshot = currentNode;
- var newData = queue[i].update(currentNode.val());
- if (newData !== undefined) {
- validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
- var newDataNode = nodeFromJSON(newData);
- var hasExplicitPriority = typeof newData === 'object' &&
- newData != null &&
- contains(newData, '.priority');
- if (!hasExplicitPriority) {
-
- newDataNode = newDataNode.updatePriority(currentNode.getPriority());
- }
- var oldWriteId = transaction.currentWriteId;
- var serverValues = repoGenerateServerValues(repo);
- var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
- transaction.currentOutputSnapshotRaw = newDataNode;
- transaction.currentOutputSnapshotResolved = newNodeResolved;
- transaction.currentWriteId = repoGetNextWriteId(repo);
-
- setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
- events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
- }
- else {
- abortTransaction = true;
- abortReason = 'nodata';
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
- }
- }
- }
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
- events = [];
- if (abortTransaction) {
-
- queue[i].status = 2 ;
-
-
-
- (function (unwatcher) {
- setTimeout(unwatcher, Math.floor(0));
- })(queue[i].unwatcher);
- if (queue[i].onComplete) {
- if (abortReason === 'nodata') {
- callbacks.push(function () {
- return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
- });
- }
- else {
- callbacks.push(function () {
- return queue[i].onComplete(new Error(abortReason), false, null);
- });
- }
- }
- }
- };
- for (var i = 0; i < queue.length; i++) {
- _loop_2(i);
- }
-
- repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
-
- for (var i = 0; i < callbacks.length; i++) {
- exceptionGuard(callbacks[i]);
- }
-
- repoSendReadyTransactions(repo, repo.transactionQueueTree_);
- }
-
- function repoGetAncestorTransactionNode(repo, path) {
- var front;
-
-
- var transactionNode = repo.transactionQueueTree_;
- front = pathGetFront(path);
- while (front !== null && treeGetValue(transactionNode) === undefined) {
- transactionNode = treeSubTree(transactionNode, front);
- path = pathPopFront(path);
- front = pathGetFront(path);
- }
- return transactionNode;
- }
-
- function repoBuildTransactionQueue(repo, transactionNode) {
-
- var transactionQueue = [];
- repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
-
- transactionQueue.sort(function (a, b) { return a.order - b.order; });
- return transactionQueue;
- }
- function repoAggregateTransactionQueuesForNode(repo, node, queue) {
- var nodeQueue = treeGetValue(node);
- if (nodeQueue) {
- for (var i = 0; i < nodeQueue.length; i++) {
- queue.push(nodeQueue[i]);
- }
- }
- treeForEachChild(node, function (child) {
- repoAggregateTransactionQueuesForNode(repo, child, queue);
- });
- }
-
- function repoPruneCompletedTransactionsBelowNode(repo, node) {
- var queue = treeGetValue(node);
- if (queue) {
- var to = 0;
- for (var from = 0; from < queue.length; from++) {
- if (queue[from].status !== 2 ) {
- queue[to] = queue[from];
- to++;
- }
- }
- queue.length = to;
- treeSetValue(node, queue.length > 0 ? queue : undefined);
- }
- treeForEachChild(node, function (childNode) {
- repoPruneCompletedTransactionsBelowNode(repo, childNode);
- });
- }
-
- function repoAbortTransactions(repo, path) {
- var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
- var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
- treeForEachAncestor(transactionNode, function (node) {
- repoAbortTransactionsOnNode(repo, node);
- });
- repoAbortTransactionsOnNode(repo, transactionNode);
- treeForEachDescendant(transactionNode, function (node) {
- repoAbortTransactionsOnNode(repo, node);
- });
- return affectedPath;
- }
-
- function repoAbortTransactionsOnNode(repo, node) {
- var queue = treeGetValue(node);
- if (queue) {
-
-
-
- var callbacks = [];
-
-
- var events = [];
- var lastSent = -1;
- for (var i = 0; i < queue.length; i++) {
- if (queue[i].status === 3 ) ;
- else if (queue[i].status === 1 ) {
- assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
- lastSent = i;
-
- queue[i].status = 3 ;
- queue[i].abortReason = 'set';
- }
- else {
- assert(queue[i].status === 0 , 'Unexpected transaction status in abort');
-
- queue[i].unwatcher();
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
- if (queue[i].onComplete) {
- callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
- }
- }
- }
- if (lastSent === -1) {
-
- treeSetValue(node, undefined);
- }
- else {
-
- queue.length = lastSent + 1;
- }
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
- for (var i = 0; i < callbacks.length; i++) {
- exceptionGuard(callbacks[i]);
- }
- }
- }
-
-
- function decodePath(pathString) {
- var pathStringDecoded = '';
- var pieces = pathString.split('/');
- for (var i = 0; i < pieces.length; i++) {
- if (pieces[i].length > 0) {
- var piece = pieces[i];
- try {
- piece = decodeURIComponent(piece.replace(/\+/g, ' '));
- }
- catch (e) { }
- pathStringDecoded += '/' + piece;
- }
- }
- return pathStringDecoded;
- }
-
- function decodeQuery(queryString) {
- var e_1, _a;
- var results = {};
- if (queryString.charAt(0) === '?') {
- queryString = queryString.substring(1);
- }
- try {
- for (var _b = __values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
- var segment = _c.value;
- if (segment.length === 0) {
- continue;
- }
- var kv = segment.split('=');
- if (kv.length === 2) {
- results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
- }
- else {
- warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
- }
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
- }
- finally { if (e_1) throw e_1.error; }
- }
- return results;
- }
- var parseRepoInfo = function (dataURL, nodeAdmin) {
- var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
- if (parsedUrl.domain === 'firebase.com') {
- fatal(parsedUrl.host +
- ' is no longer supported. ' +
- 'Please use <YOUR FIREBASE>.firebaseio.com instead');
- }
-
- if ((!namespace || namespace === 'undefined') &&
- parsedUrl.domain !== 'localhost') {
- fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
- }
- if (!parsedUrl.secure) {
- warnIfPageIsSecure();
- }
- var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
- return {
- repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
- '',
- namespace !== parsedUrl.subdomain),
- path: new Path(parsedUrl.pathString)
- };
- };
- var parseDatabaseURL = function (dataURL) {
-
- var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
-
- var secure = true, scheme = 'https', port = 443;
-
- if (typeof dataURL === 'string') {
-
- var colonInd = dataURL.indexOf('//');
- if (colonInd >= 0) {
- scheme = dataURL.substring(0, colonInd - 1);
- dataURL = dataURL.substring(colonInd + 2);
- }
-
- var slashInd = dataURL.indexOf('/');
- if (slashInd === -1) {
- slashInd = dataURL.length;
- }
- var questionMarkInd = dataURL.indexOf('?');
- if (questionMarkInd === -1) {
- questionMarkInd = dataURL.length;
- }
- host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
- if (slashInd < questionMarkInd) {
-
- pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
- }
- var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
-
- colonInd = host.indexOf(':');
- if (colonInd >= 0) {
- secure = scheme === 'https' || scheme === 'wss';
- port = parseInt(host.substring(colonInd + 1), 10);
- }
- else {
- colonInd = host.length;
- }
- var hostWithoutPort = host.slice(0, colonInd);
- if (hostWithoutPort.toLowerCase() === 'localhost') {
- domain = 'localhost';
- }
- else if (hostWithoutPort.split('.').length <= 2) {
- domain = hostWithoutPort;
- }
- else {
-
- var dotInd = host.indexOf('.');
- subdomain = host.substring(0, dotInd).toLowerCase();
- domain = host.substring(dotInd + 1);
-
- namespace = subdomain;
- }
-
- if ('ns' in queryParams) {
- namespace = queryParams['ns'];
- }
- }
- return {
- host: host,
- port: port,
- domain: domain,
- subdomain: subdomain,
- secure: secure,
- scheme: scheme,
- pathString: pathString,
- namespace: namespace
- };
- };
-
-
-
- var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
-
- var nextPushId = (function () {
-
-
- var lastPushTime = 0;
-
-
-
-
- var lastRandChars = [];
- return function (now) {
- var duplicateTime = now === lastPushTime;
- lastPushTime = now;
- var i;
- var timeStampChars = new Array(8);
- for (i = 7; i >= 0; i--) {
- timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
-
-
- now = Math.floor(now / 64);
- }
- assert(now === 0, 'Cannot push at time == 0');
- var id = timeStampChars.join('');
- if (!duplicateTime) {
- for (i = 0; i < 12; i++) {
- lastRandChars[i] = Math.floor(Math.random() * 64);
- }
- }
- else {
-
-
- for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
- lastRandChars[i] = 0;
- }
- lastRandChars[i]++;
- }
- for (i = 0; i < 12; i++) {
- id += PUSH_CHARS.charAt(lastRandChars[i]);
- }
- assert(id.length === 20, 'nextPushId: Length should be 20.');
- return id;
- };
- })();
-
-
-
- var DataEvent = (function () {
-
-
- function DataEvent(eventType, eventRegistration, snapshot, prevName) {
- this.eventType = eventType;
- this.eventRegistration = eventRegistration;
- this.snapshot = snapshot;
- this.prevName = prevName;
- }
- DataEvent.prototype.getPath = function () {
- var ref = this.snapshot.ref;
- if (this.eventType === 'value') {
- return ref._path;
- }
- else {
- return ref.parent._path;
- }
- };
- DataEvent.prototype.getEventType = function () {
- return this.eventType;
- };
- DataEvent.prototype.getEventRunner = function () {
- return this.eventRegistration.getEventRunner(this);
- };
- DataEvent.prototype.toString = function () {
- return (this.getPath().toString() +
- ':' +
- this.eventType +
- ':' +
- stringify(this.snapshot.exportVal()));
- };
- return DataEvent;
- }());
- var CancelEvent = (function () {
- function CancelEvent(eventRegistration, error, path) {
- this.eventRegistration = eventRegistration;
- this.error = error;
- this.path = path;
- }
- CancelEvent.prototype.getPath = function () {
- return this.path;
- };
- CancelEvent.prototype.getEventType = function () {
- return 'cancel';
- };
- CancelEvent.prototype.getEventRunner = function () {
- return this.eventRegistration.getEventRunner(this);
- };
- CancelEvent.prototype.toString = function () {
- return this.path.toString() + ':cancel';
- };
- return CancelEvent;
- }());
-
-
-
- var CallbackContext = (function () {
- function CallbackContext(snapshotCallback, cancelCallback) {
- this.snapshotCallback = snapshotCallback;
- this.cancelCallback = cancelCallback;
- }
- CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
- this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
- };
- CallbackContext.prototype.onCancel = function (error) {
- assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
- return this.cancelCallback.call(null, error);
- };
- Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
- get: function () {
- return !!this.cancelCallback;
- },
- enumerable: false,
- configurable: true
- });
- CallbackContext.prototype.matches = function (other) {
- return (this.snapshotCallback === other.snapshotCallback ||
- (this.snapshotCallback.userCallback !== undefined &&
- this.snapshotCallback.userCallback ===
- other.snapshotCallback.userCallback &&
- this.snapshotCallback.context === other.snapshotCallback.context));
- };
- return CallbackContext;
- }());
-
-
-
- var OnDisconnect = (function () {
-
- function OnDisconnect(_repo, _path) {
- this._repo = _repo;
- this._path = _path;
- }
-
-
- OnDisconnect.prototype.cancel = function () {
- var deferred = new Deferred();
- repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
- return deferred.promise;
- };
-
-
- OnDisconnect.prototype.remove = function () {
- validateWritablePath('OnDisconnect.remove', this._path);
- var deferred = new Deferred();
- repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
- return deferred.promise;
- };
-
-
- OnDisconnect.prototype.set = function (value) {
- validateWritablePath('OnDisconnect.set', this._path);
- validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
- var deferred = new Deferred();
- repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
- return deferred.promise;
- };
-
-
- OnDisconnect.prototype.setWithPriority = function (value, priority) {
- validateWritablePath('OnDisconnect.setWithPriority', this._path);
- validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
- validatePriority('OnDisconnect.setWithPriority', priority, false);
- var deferred = new Deferred();
- repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
- return deferred.promise;
- };
-
-
- OnDisconnect.prototype.update = function (values) {
- validateWritablePath('OnDisconnect.update', this._path);
- validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
- var deferred = new Deferred();
- repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
- return deferred.promise;
- };
- return OnDisconnect;
- }());
-
-
-
- var QueryImpl = (function () {
-
-
- function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
- this._repo = _repo;
- this._path = _path;
- this._queryParams = _queryParams;
- this._orderByCalled = _orderByCalled;
- }
- Object.defineProperty(QueryImpl.prototype, "key", {
- get: function () {
- if (pathIsEmpty(this._path)) {
- return null;
- }
- else {
- return pathGetBack(this._path);
- }
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(QueryImpl.prototype, "ref", {
- get: function () {
- return new ReferenceImpl(this._repo, this._path);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
- get: function () {
- var obj = queryParamsGetQueryObject(this._queryParams);
- var id = ObjectToUniqueKey(obj);
- return id === '{}' ? 'default' : id;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(QueryImpl.prototype, "_queryObject", {
-
-
- get: function () {
- return queryParamsGetQueryObject(this._queryParams);
- },
- enumerable: false,
- configurable: true
- });
- QueryImpl.prototype.isEqual = function (other) {
- other = getModularInstance(other);
- if (!(other instanceof QueryImpl)) {
- return false;
- }
- var sameRepo = this._repo === other._repo;
- var samePath = pathEquals(this._path, other._path);
- var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
- return sameRepo && samePath && sameQueryIdentifier;
- };
- QueryImpl.prototype.toJSON = function () {
- return this.toString();
- };
- QueryImpl.prototype.toString = function () {
- return this._repo.toString() + pathToUrlEncodedString(this._path);
- };
- return QueryImpl;
- }());
-
- function validateNoPreviousOrderByCall(query, fnName) {
- if (query._orderByCalled === true) {
- throw new Error(fnName + ": You can't combine multiple orderBy calls.");
- }
- }
-
- function validateQueryEndpoints(params) {
- var startNode = null;
- var endNode = null;
- if (params.hasStart()) {
- startNode = params.getIndexStartValue();
- }
- if (params.hasEnd()) {
- endNode = params.getIndexEndValue();
- }
- if (params.getIndex() === KEY_INDEX) {
- var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
- 'startAt(), endAt(), or equalTo().';
- var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
- 'endAt(), endBefore(), or equalTo() must be a string.';
- if (params.hasStart()) {
- var startName = params.getIndexStartName();
- if (startName !== MIN_NAME) {
- throw new Error(tooManyArgsError);
- }
- else if (typeof startNode !== 'string') {
- throw new Error(wrongArgTypeError);
- }
- }
- if (params.hasEnd()) {
- var endName = params.getIndexEndName();
- if (endName !== MAX_NAME) {
- throw new Error(tooManyArgsError);
- }
- else if (typeof endNode !== 'string') {
- throw new Error(wrongArgTypeError);
- }
- }
- }
- else if (params.getIndex() === PRIORITY_INDEX) {
- if ((startNode != null && !isValidPriority(startNode)) ||
- (endNode != null && !isValidPriority(endNode))) {
- throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
- 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
- '(null, a number, or a string).');
- }
- }
- else {
- assert(params.getIndex() instanceof PathIndex ||
- params.getIndex() === VALUE_INDEX, 'unknown index type.');
- if ((startNode != null && typeof startNode === 'object') ||
- (endNode != null && typeof endNode === 'object')) {
- throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
- 'equalTo() cannot be an object.');
- }
- }
- }
-
- function validateLimit(params) {
- if (params.hasStart() &&
- params.hasEnd() &&
- params.hasLimit() &&
- !params.hasAnchoredLimit()) {
- throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
- 'limitToFirst() or limitToLast() instead.');
- }
- }
-
- var ReferenceImpl = (function (_super) {
- __extends(ReferenceImpl, _super);
-
- function ReferenceImpl(repo, path) {
- return _super.call(this, repo, path, new QueryParams(), false) || this;
- }
- Object.defineProperty(ReferenceImpl.prototype, "parent", {
- get: function () {
- var parentPath = pathParent(this._path);
- return parentPath === null
- ? null
- : new ReferenceImpl(this._repo, parentPath);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(ReferenceImpl.prototype, "root", {
- get: function () {
- var ref = this;
- while (ref.parent !== null) {
- ref = ref.parent;
- }
- return ref;
- },
- enumerable: false,
- configurable: true
- });
- return ReferenceImpl;
- }(QueryImpl));
-
- var DataSnapshot = (function () {
-
-
- function DataSnapshot(_node,
- /**
- * The location of this DataSnapshot.
- */
- ref, _index) {
- this._node = _node;
- this.ref = ref;
- this._index = _index;
- }
- Object.defineProperty(DataSnapshot.prototype, "priority", {
-
-
- get: function () {
-
- return this._node.getPriority().val();
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(DataSnapshot.prototype, "key", {
-
-
- get: function () {
- return this.ref.key;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(DataSnapshot.prototype, "size", {
-
- get: function () {
- return this._node.numChildren();
- },
- enumerable: false,
- configurable: true
- });
-
-
- DataSnapshot.prototype.child = function (path) {
- var childPath = new Path(path);
- var childRef = child(this.ref, path);
- return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
- };
-
-
- DataSnapshot.prototype.exists = function () {
- return !this._node.isEmpty();
- };
-
-
-
- DataSnapshot.prototype.exportVal = function () {
- return this._node.val(true);
- };
-
-
- DataSnapshot.prototype.forEach = function (action) {
- var _this = this;
- if (this._node.isLeafNode()) {
- return false;
- }
- var childrenNode = this._node;
-
- return !!childrenNode.forEachChild(this._index, function (key, node) {
- return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
- });
- };
-
-
- DataSnapshot.prototype.hasChild = function (path) {
- var childPath = new Path(path);
- return !this._node.getChild(childPath).isEmpty();
- };
-
-
- DataSnapshot.prototype.hasChildren = function () {
- if (this._node.isLeafNode()) {
- return false;
- }
- else {
- return !this._node.isEmpty();
- }
- };
-
-
- DataSnapshot.prototype.toJSON = function () {
- return this.exportVal();
- };
-
-
-
- DataSnapshot.prototype.val = function () {
- return this._node.val();
- };
- return DataSnapshot;
- }());
-
- function ref(db, path) {
- db = getModularInstance(db);
- db._checkNotDeleted('ref');
- return path !== undefined ? child(db._root, path) : db._root;
- }
-
- function refFromURL(db, url) {
- db = getModularInstance(db);
- db._checkNotDeleted('refFromURL');
- var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
- validateUrl('refFromURL', parsedURL);
- var repoInfo = parsedURL.repoInfo;
- if (!db._repo.repoInfo_.isCustomHost() &&
- repoInfo.host !== db._repo.repoInfo_.host) {
- fatal('refFromURL' +
- ': Host name does not match the current database: ' +
- '(found ' +
- repoInfo.host +
- ' but expected ' +
- db._repo.repoInfo_.host +
- ')');
- }
- return ref(db, parsedURL.path.toString());
- }
-
- function child(parent, path) {
- parent = getModularInstance(parent);
- if (pathGetFront(parent._path) === null) {
- validateRootPathString('child', 'path', path, false);
- }
- else {
- validatePathString('child', 'path', path, false);
- }
- return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
- }
-
- function onDisconnect(ref) {
- ref = getModularInstance(ref);
- return new OnDisconnect(ref._repo, ref._path);
- }
-
- function push(parent, value) {
- parent = getModularInstance(parent);
- validateWritablePath('push', parent._path);
- validateFirebaseDataArg('push', value, parent._path, true);
- var now = repoServerTime(parent._repo);
- var name = nextPushId(now);
-
-
-
-
-
-
- var thennablePushRef = child(parent, name);
- var pushRef = child(parent, name);
- var promise;
- if (value != null) {
- promise = set(pushRef, value).then(function () { return pushRef; });
- }
- else {
- promise = Promise.resolve(pushRef);
- }
- thennablePushRef.then = promise.then.bind(promise);
- thennablePushRef.catch = promise.then.bind(promise, undefined);
- return thennablePushRef;
- }
-
- function remove(ref) {
- validateWritablePath('remove', ref._path);
- return set(ref, null);
- }
-
- function set(ref, value) {
- ref = getModularInstance(ref);
- validateWritablePath('set', ref._path);
- validateFirebaseDataArg('set', value, ref._path, false);
- var deferred = new Deferred();
- repoSetWithPriority(ref._repo, ref._path, value,
- null, deferred.wrapCallback(function () { }));
- return deferred.promise;
- }
-
- function setPriority(ref, priority) {
- ref = getModularInstance(ref);
- validateWritablePath('setPriority', ref._path);
- validatePriority('setPriority', priority, false);
- var deferred = new Deferred();
- repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
- return deferred.promise;
- }
-
- function setWithPriority(ref, value, priority) {
- validateWritablePath('setWithPriority', ref._path);
- validateFirebaseDataArg('setWithPriority', value, ref._path, false);
- validatePriority('setWithPriority', priority, false);
- if (ref.key === '.length' || ref.key === '.keys') {
- throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
- }
- var deferred = new Deferred();
- repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
- return deferred.promise;
- }
-
- function update(ref, values) {
- validateFirebaseMergeDataArg('update', values, ref._path, false);
- var deferred = new Deferred();
- repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
- return deferred.promise;
- }
-
- function get(query) {
- query = getModularInstance(query);
- var callbackContext = new CallbackContext(function () { });
- var container = new ValueEventRegistration(callbackContext);
- return repoGetValue(query._repo, query, container).then(function (node) {
- return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
- });
- }
-
- var ValueEventRegistration = (function () {
- function ValueEventRegistration(callbackContext) {
- this.callbackContext = callbackContext;
- }
- ValueEventRegistration.prototype.respondsTo = function (eventType) {
- return eventType === 'value';
- };
- ValueEventRegistration.prototype.createEvent = function (change, query) {
- var index = query._queryParams.getIndex();
- return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
- };
- ValueEventRegistration.prototype.getEventRunner = function (eventData) {
- var _this = this;
- if (eventData.getEventType() === 'cancel') {
- return function () {
- return _this.callbackContext.onCancel(eventData.error);
- };
- }
- else {
- return function () {
- return _this.callbackContext.onValue(eventData.snapshot, null);
- };
- }
- };
- ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
- if (this.callbackContext.hasCancelCallback) {
- return new CancelEvent(this, error, path);
- }
- else {
- return null;
- }
- };
- ValueEventRegistration.prototype.matches = function (other) {
- if (!(other instanceof ValueEventRegistration)) {
- return false;
- }
- else if (!other.callbackContext || !this.callbackContext) {
-
- return true;
- }
- else {
- return other.callbackContext.matches(this.callbackContext);
- }
- };
- ValueEventRegistration.prototype.hasAnyCallback = function () {
- return this.callbackContext !== null;
- };
- return ValueEventRegistration;
- }());
-
- var ChildEventRegistration = (function () {
- function ChildEventRegistration(eventType, callbackContext) {
- this.eventType = eventType;
- this.callbackContext = callbackContext;
- }
- ChildEventRegistration.prototype.respondsTo = function (eventType) {
- var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
- eventToCheck =
- eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
- return this.eventType === eventToCheck;
- };
- ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
- if (this.callbackContext.hasCancelCallback) {
- return new CancelEvent(this, error, path);
- }
- else {
- return null;
- }
- };
- ChildEventRegistration.prototype.createEvent = function (change, query) {
- assert(change.childName != null, 'Child events should have a childName.');
- var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
- var index = query._queryParams.getIndex();
- return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
- };
- ChildEventRegistration.prototype.getEventRunner = function (eventData) {
- var _this = this;
- if (eventData.getEventType() === 'cancel') {
- return function () {
- return _this.callbackContext.onCancel(eventData.error);
- };
- }
- else {
- return function () {
- return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
- };
- }
- };
- ChildEventRegistration.prototype.matches = function (other) {
- if (other instanceof ChildEventRegistration) {
- return (this.eventType === other.eventType &&
- (!this.callbackContext ||
- !other.callbackContext ||
- this.callbackContext.matches(other.callbackContext)));
- }
- return false;
- };
- ChildEventRegistration.prototype.hasAnyCallback = function () {
- return !!this.callbackContext;
- };
- return ChildEventRegistration;
- }());
- function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
- var cancelCallback;
- if (typeof cancelCallbackOrListenOptions === 'object') {
- cancelCallback = undefined;
- options = cancelCallbackOrListenOptions;
- }
- if (typeof cancelCallbackOrListenOptions === 'function') {
- cancelCallback = cancelCallbackOrListenOptions;
- }
- if (options && options.onlyOnce) {
- var userCallback_1 = callback;
- var onceCallback = function (dataSnapshot, previousChildName) {
- repoRemoveEventCallbackForQuery(query._repo, query, container);
- userCallback_1(dataSnapshot, previousChildName);
- };
- onceCallback.userCallback = callback.userCallback;
- onceCallback.context = callback.context;
- callback = onceCallback;
- }
- var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
- var container = eventType === 'value'
- ? new ValueEventRegistration(callbackContext)
- : new ChildEventRegistration(eventType, callbackContext);
- repoAddEventCallbackForQuery(query._repo, query, container);
- return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
- }
- function onValue(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
- }
-
- function off(query, eventType, callback) {
- var container = null;
- var expCallback = callback ? new CallbackContext(callback) : null;
- if (eventType === 'value') {
- container = new ValueEventRegistration(expCallback);
- }
- else if (eventType) {
- container = new ChildEventRegistration(eventType, expCallback);
- }
- repoRemoveEventCallbackForQuery(query._repo, query, container);
- }
-
- var QueryConstraint = (function () {
- function QueryConstraint() {
- }
- return QueryConstraint;
- }());
- var QueryEndAtConstraint = (function (_super) {
- __extends(QueryEndAtConstraint, _super);
- function QueryEndAtConstraint(_value, _key) {
- var _this = _super.call(this) || this;
- _this._value = _value;
- _this._key = _key;
- return _this;
- }
- QueryEndAtConstraint.prototype._apply = function (query) {
- validateFirebaseDataArg('endAt', this._value, query._path, true);
- var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasEnd()) {
- throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
- 'endBefore or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- };
- return QueryEndAtConstraint;
- }(QueryConstraint));
-
- function endAt(value, key) {
- validateKey('endAt', 'key', key, true);
- return new QueryEndAtConstraint(value, key);
- }
- var QueryEndBeforeConstraint = (function (_super) {
- __extends(QueryEndBeforeConstraint, _super);
- function QueryEndBeforeConstraint(_value, _key) {
- var _this = _super.call(this) || this;
- _this._value = _value;
- _this._key = _key;
- return _this;
- }
- QueryEndBeforeConstraint.prototype._apply = function (query) {
- validateFirebaseDataArg('endBefore', this._value, query._path, false);
- var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasEnd()) {
- throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
- 'endBefore or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- };
- return QueryEndBeforeConstraint;
- }(QueryConstraint));
-
- function endBefore(value, key) {
- validateKey('endBefore', 'key', key, true);
- return new QueryEndBeforeConstraint(value, key);
- }
- var QueryStartAtConstraint = (function (_super) {
- __extends(QueryStartAtConstraint, _super);
- function QueryStartAtConstraint(_value, _key) {
- var _this = _super.call(this) || this;
- _this._value = _value;
- _this._key = _key;
- return _this;
- }
- QueryStartAtConstraint.prototype._apply = function (query) {
- validateFirebaseDataArg('startAt', this._value, query._path, true);
- var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasStart()) {
- throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
- 'startBefore or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- };
- return QueryStartAtConstraint;
- }(QueryConstraint));
-
- function startAt(value, key) {
- if (value === void 0) { value = null; }
- validateKey('startAt', 'key', key, true);
- return new QueryStartAtConstraint(value, key);
- }
- var QueryStartAfterConstraint = (function (_super) {
- __extends(QueryStartAfterConstraint, _super);
- function QueryStartAfterConstraint(_value, _key) {
- var _this = _super.call(this) || this;
- _this._value = _value;
- _this._key = _key;
- return _this;
- }
- QueryStartAfterConstraint.prototype._apply = function (query) {
- validateFirebaseDataArg('startAfter', this._value, query._path, false);
- var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasStart()) {
- throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
- 'startAfter, or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- };
- return QueryStartAfterConstraint;
- }(QueryConstraint));
-
- function startAfter(value, key) {
- validateKey('startAfter', 'key', key, true);
- return new QueryStartAfterConstraint(value, key);
- }
- var QueryLimitToFirstConstraint = (function (_super) {
- __extends(QueryLimitToFirstConstraint, _super);
- function QueryLimitToFirstConstraint(_limit) {
- var _this = _super.call(this) || this;
- _this._limit = _limit;
- return _this;
- }
- QueryLimitToFirstConstraint.prototype._apply = function (query) {
- if (query._queryParams.hasLimit()) {
- throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
- 'or limitToLast).');
- }
- return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
- };
- return QueryLimitToFirstConstraint;
- }(QueryConstraint));
-
- function limitToFirst(limit) {
- if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
- throw new Error('limitToFirst: First argument must be a positive integer.');
- }
- return new QueryLimitToFirstConstraint(limit);
- }
- var QueryLimitToLastConstraint = (function (_super) {
- __extends(QueryLimitToLastConstraint, _super);
- function QueryLimitToLastConstraint(_limit) {
- var _this = _super.call(this) || this;
- _this._limit = _limit;
- return _this;
- }
- QueryLimitToLastConstraint.prototype._apply = function (query) {
- if (query._queryParams.hasLimit()) {
- throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
- 'or limitToLast).');
- }
- return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
- };
- return QueryLimitToLastConstraint;
- }(QueryConstraint));
-
- function limitToLast(limit) {
- if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
- throw new Error('limitToLast: First argument must be a positive integer.');
- }
- return new QueryLimitToLastConstraint(limit);
- }
- var QueryOrderByChildConstraint = (function (_super) {
- __extends(QueryOrderByChildConstraint, _super);
- function QueryOrderByChildConstraint(_path) {
- var _this = _super.call(this) || this;
- _this._path = _path;
- return _this;
- }
- QueryOrderByChildConstraint.prototype._apply = function (query) {
- validateNoPreviousOrderByCall(query, 'orderByChild');
- var parsedPath = new Path(this._path);
- if (pathIsEmpty(parsedPath)) {
- throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
- }
- var index = new PathIndex(parsedPath);
- var newParams = queryParamsOrderBy(query._queryParams, index);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- };
- return QueryOrderByChildConstraint;
- }(QueryConstraint));
-
- function orderByChild(path) {
- if (path === '$key') {
- throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
- }
- else if (path === '$priority') {
- throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
- }
- else if (path === '$value') {
- throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
- }
- validatePathString('orderByChild', 'path', path, false);
- return new QueryOrderByChildConstraint(path);
- }
- var QueryOrderByKeyConstraint = (function (_super) {
- __extends(QueryOrderByKeyConstraint, _super);
- function QueryOrderByKeyConstraint() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- QueryOrderByKeyConstraint.prototype._apply = function (query) {
- validateNoPreviousOrderByCall(query, 'orderByKey');
- var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- };
- return QueryOrderByKeyConstraint;
- }(QueryConstraint));
-
- function orderByKey() {
- return new QueryOrderByKeyConstraint();
- }
- var QueryOrderByPriorityConstraint = (function (_super) {
- __extends(QueryOrderByPriorityConstraint, _super);
- function QueryOrderByPriorityConstraint() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- QueryOrderByPriorityConstraint.prototype._apply = function (query) {
- validateNoPreviousOrderByCall(query, 'orderByPriority');
- var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- };
- return QueryOrderByPriorityConstraint;
- }(QueryConstraint));
-
- function orderByPriority() {
- return new QueryOrderByPriorityConstraint();
- }
- var QueryOrderByValueConstraint = (function (_super) {
- __extends(QueryOrderByValueConstraint, _super);
- function QueryOrderByValueConstraint() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- QueryOrderByValueConstraint.prototype._apply = function (query) {
- validateNoPreviousOrderByCall(query, 'orderByValue');
- var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- };
- return QueryOrderByValueConstraint;
- }(QueryConstraint));
-
- function orderByValue() {
- return new QueryOrderByValueConstraint();
- }
- var QueryEqualToValueConstraint = (function (_super) {
- __extends(QueryEqualToValueConstraint, _super);
- function QueryEqualToValueConstraint(_value, _key) {
- var _this = _super.call(this) || this;
- _this._value = _value;
- _this._key = _key;
- return _this;
- }
- QueryEqualToValueConstraint.prototype._apply = function (query) {
- validateFirebaseDataArg('equalTo', this._value, query._path, false);
- if (query._queryParams.hasStart()) {
- throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
- 'equalTo).');
- }
- if (query._queryParams.hasEnd()) {
- throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
- 'equalTo).');
- }
- return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
- };
- return QueryEqualToValueConstraint;
- }(QueryConstraint));
-
- function equalTo(value, key) {
- validateKey('equalTo', 'key', key, true);
- return new QueryEqualToValueConstraint(value, key);
- }
-
- function query(query) {
- var e_1, _a;
- var queryConstraints = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- queryConstraints[_i - 1] = arguments[_i];
- }
- var queryImpl = getModularInstance(query);
- try {
- for (var queryConstraints_1 = __values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
- var constraint = queryConstraints_1_1.value;
- queryImpl = constraint._apply(queryImpl);
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
- }
- finally { if (e_1) throw e_1.error; }
- }
- return queryImpl;
- }
-
- syncPointSetReferenceConstructor(ReferenceImpl);
- syncTreeSetReferenceConstructor(ReferenceImpl);
-
-
- var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
-
- var repos = {};
-
- var useRestClient = false;
-
- function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
- repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
- false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
- if (tokenProvider) {
- repo.authTokenProvider_ = tokenProvider;
- }
- }
-
- function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
- var dbUrl = url || app.options.databaseURL;
- if (dbUrl === undefined) {
- if (!app.options.projectId) {
- fatal("Can't determine Firebase Database URL. Be sure to include " +
- ' a Project ID when calling firebase.initializeApp().');
- }
- log('Using default host for project ', app.options.projectId);
- dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
- }
- var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
- var repoInfo = parsedUrl.repoInfo;
- var isEmulator;
- var dbEmulatorHost = undefined;
- if (typeof process !== 'undefined' && process.env) {
- dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
- }
- if (dbEmulatorHost) {
- isEmulator = true;
- dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
- parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
- repoInfo = parsedUrl.repoInfo;
- }
- else {
- isEmulator = !parsedUrl.repoInfo.secure;
- }
- var authTokenProvider = nodeAdmin && isEmulator
- ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
- : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
- validateUrl('Invalid Firebase Database URL', parsedUrl);
- if (!pathIsEmpty(parsedUrl.path)) {
- fatal('Database URL must point to the root of a Firebase Database ' +
- '(not including a child path).');
- }
- var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
- return new Database(repo, app);
- }
-
- function repoManagerDeleteRepo(repo, appName) {
- var appRepos = repos[appName];
-
- if (!appRepos || appRepos[repo.key] !== repo) {
- fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
- }
- repoInterrupt(repo);
- delete appRepos[repo.key];
- }
-
- function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
- var appRepos = repos[app.name];
- if (!appRepos) {
- appRepos = {};
- repos[app.name] = appRepos;
- }
- var repo = appRepos[repoInfo.toURLString()];
- if (repo) {
- fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
- }
- repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
- appRepos[repoInfo.toURLString()] = repo;
- return repo;
- }
-
- function repoManagerForceRestClient(forceRestClient) {
- useRestClient = forceRestClient;
- }
-
- var Database = (function () {
-
- function Database(_repoInternal,
- /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
- app) {
- this._repoInternal = _repoInternal;
- this.app = app;
- /** Represents a `Database` instance. */
- this['type'] = 'database';
- /** Track if the instance has been used (root or repo accessed) */
- this._instanceStarted = false;
- }
- Object.defineProperty(Database.prototype, "_repo", {
- get: function () {
- if (!this._instanceStarted) {
- repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
- this._instanceStarted = true;
- }
- return this._repoInternal;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Database.prototype, "_root", {
- get: function () {
- if (!this._rootInternal) {
- this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
- }
- return this._rootInternal;
- },
- enumerable: false,
- configurable: true
- });
- Database.prototype._delete = function () {
- if (this._rootInternal !== null) {
- repoManagerDeleteRepo(this._repo, this.app.name);
- this._repoInternal = null;
- this._rootInternal = null;
- }
- return Promise.resolve();
- };
- Database.prototype._checkNotDeleted = function (apiName) {
- if (this._rootInternal === null) {
- fatal('Cannot call ' + apiName + ' on a deleted database.');
- }
- };
- return Database;
- }());
- function checkTransportInit() {
- if (TransportManager.IS_TRANSPORT_INITIALIZED) {
- warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
- }
- }
-
- function forceWebSockets() {
- checkTransportInit();
- BrowserPollConnection.forceDisallow();
- }
-
- function forceLongPolling() {
- checkTransportInit();
- WebSocketConnection.forceDisallow();
- BrowserPollConnection.forceAllow();
- }
-
- function getDatabase(app, url) {
- if (app === void 0) { app = getApp(); }
- var db = _getProvider(app, 'database').getImmediate({
- identifier: url
- });
- if (!db._instanceStarted) {
- var emulator = getDefaultEmulatorHostnameAndPort('database');
- if (emulator) {
- connectDatabaseEmulator.apply(void 0, __spreadArray([db], __read(emulator), false));
- }
- }
- return db;
- }
-
- function connectDatabaseEmulator(db, host, port, options) {
- if (options === void 0) { options = {}; }
- db = getModularInstance(db);
- db._checkNotDeleted('useEmulator');
- if (db._instanceStarted) {
- fatal('Cannot call useEmulator() after instance has already been initialized.');
- }
- var repo = db._repoInternal;
- var tokenProvider = undefined;
- if (repo.repoInfo_.nodeAdmin) {
- if (options.mockUserToken) {
- fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
- }
- tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
- }
- else if (options.mockUserToken) {
- var token = typeof options.mockUserToken === 'string'
- ? options.mockUserToken
- : createMockUserToken(options.mockUserToken, db.app.options.projectId);
- tokenProvider = new EmulatorTokenProvider(token);
- }
-
- repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
- }
-
- function goOffline(db) {
- db = getModularInstance(db);
- db._checkNotDeleted('goOffline');
- repoInterrupt(db._repo);
- }
-
- function goOnline(db) {
- db = getModularInstance(db);
- db._checkNotDeleted('goOnline');
- repoResume(db._repo);
- }
- function enableLogging(logger, persistent) {
- enableLogging$1(logger, persistent);
- }
-
-
- function registerDatabase(variant) {
- setSDKVersion(SDK_VERSION$1);
- _registerComponent(new Component('database', function (container, _a) {
- var url = _a.instanceIdentifier;
- var app = container.getProvider('app').getImmediate();
- var authProvider = container.getProvider('auth-internal');
- var appCheckProvider = container.getProvider('app-check-internal');
- return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
- }, "PUBLIC" ).setMultipleInstances(true));
- registerVersion(name, version, variant);
-
- registerVersion(name, version, 'esm5');
- }
-
-
- var SERVER_TIMESTAMP = {
- '.sv': 'timestamp'
- };
-
- function serverTimestamp() {
- return SERVER_TIMESTAMP;
- }
-
- function increment(delta) {
- return {
- '.sv': {
- 'increment': delta
- }
- };
- }
-
-
-
- var TransactionResult = (function () {
-
- function TransactionResult(
- /** Whether the transaction was successfully committed. */
- committed,
- /** The resulting data snapshot. */
- snapshot) {
- this.committed = committed;
- this.snapshot = snapshot;
- }
-
- TransactionResult.prototype.toJSON = function () {
- return { committed: this.committed, snapshot: this.snapshot.toJSON() };
- };
- return TransactionResult;
- }());
-
- function runTransaction(ref,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- transactionUpdate, options) {
- var _a;
- ref = getModularInstance(ref);
- validateWritablePath('Reference.transaction', ref._path);
- if (ref.key === '.length' || ref.key === '.keys') {
- throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
- }
- var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
- var deferred = new Deferred();
- var promiseComplete = function (error, committed, node) {
- var dataSnapshot = null;
- if (error) {
- deferred.reject(error);
- }
- else {
- dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
- deferred.resolve(new TransactionResult(committed, dataSnapshot));
- }
- };
- // Add a watch to make sure we get server updates.
- var unwatcher = onValue(ref, function () { });
- repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
- return deferred.promise;
- }
-
- /**
- * @license
- * Copyright 2017 Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
- this.sendRequest('q', { p: pathString }, onComplete);
- };
-
- PersistentConnection.prototype.echo = function (data, onEcho) {
- this.sendRequest('echo', { d: data }, onEcho);
- };
-
- var hijackHash = function (newHash) {
- var oldPut = PersistentConnection.prototype.put;
- PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
- if (hash !== undefined) {
- hash = newHash();
- }
- oldPut.call(this, pathString, data, onComplete, hash);
- };
- return function () {
- PersistentConnection.prototype.put = oldPut;
- };
- };
-
- var forceRestClient = function (forceRestClient) {
- repoManagerForceRestClient(forceRestClient);
- };
-
-
- registerDatabase();
-
- export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };
|