index.esm2017.js 537 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005
  1. import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';
  2. import { Component, ComponentContainer, Provider } from '@firebase/component';
  3. import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';
  4. import { Logger, LogLevel } from '@firebase/logger';
  5. const name = "@firebase/database";
  6. const version = "1.0.9";
  7. /**
  8. * @license
  9. * Copyright 2019 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /** The semver (www.semver.org) version of the SDK. */
  24. let SDK_VERSION = '';
  25. /**
  26. * SDK_VERSION should be set before any database instance is created
  27. * @internal
  28. */
  29. function setSDKVersion(version) {
  30. SDK_VERSION = version;
  31. }
  32. /**
  33. * @license
  34. * Copyright 2017 Google LLC
  35. *
  36. * Licensed under the Apache License, Version 2.0 (the "License");
  37. * you may not use this file except in compliance with the License.
  38. * You may obtain a copy of the License at
  39. *
  40. * http://www.apache.org/licenses/LICENSE-2.0
  41. *
  42. * Unless required by applicable law or agreed to in writing, software
  43. * distributed under the License is distributed on an "AS IS" BASIS,
  44. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  45. * See the License for the specific language governing permissions and
  46. * limitations under the License.
  47. */
  48. /**
  49. * Wraps a DOM Storage object and:
  50. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  51. * - prefixes names with "firebase:" to avoid collisions with app data.
  52. *
  53. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  54. * and one for localStorage.
  55. *
  56. */
  57. class DOMStorageWrapper {
  58. /**
  59. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  60. */
  61. constructor(domStorage_) {
  62. this.domStorage_ = domStorage_;
  63. // Use a prefix to avoid collisions with other stuff saved by the app.
  64. this.prefix_ = 'firebase:';
  65. }
  66. /**
  67. * @param key - The key to save the value under
  68. * @param value - The value being stored, or null to remove the key.
  69. */
  70. set(key, value) {
  71. if (value == null) {
  72. this.domStorage_.removeItem(this.prefixedName_(key));
  73. }
  74. else {
  75. this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
  76. }
  77. }
  78. /**
  79. * @returns The value that was stored under this key, or null
  80. */
  81. get(key) {
  82. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  83. if (storedVal == null) {
  84. return null;
  85. }
  86. else {
  87. return jsonEval(storedVal);
  88. }
  89. }
  90. remove(key) {
  91. this.domStorage_.removeItem(this.prefixedName_(key));
  92. }
  93. prefixedName_(name) {
  94. return this.prefix_ + name;
  95. }
  96. toString() {
  97. return this.domStorage_.toString();
  98. }
  99. }
  100. /**
  101. * @license
  102. * Copyright 2017 Google LLC
  103. *
  104. * Licensed under the Apache License, Version 2.0 (the "License");
  105. * you may not use this file except in compliance with the License.
  106. * You may obtain a copy of the License at
  107. *
  108. * http://www.apache.org/licenses/LICENSE-2.0
  109. *
  110. * Unless required by applicable law or agreed to in writing, software
  111. * distributed under the License is distributed on an "AS IS" BASIS,
  112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  113. * See the License for the specific language governing permissions and
  114. * limitations under the License.
  115. */
  116. /**
  117. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  118. * (TODO: create interface for both to implement).
  119. */
  120. class MemoryStorage {
  121. constructor() {
  122. this.cache_ = {};
  123. this.isInMemoryStorage = true;
  124. }
  125. set(key, value) {
  126. if (value == null) {
  127. delete this.cache_[key];
  128. }
  129. else {
  130. this.cache_[key] = value;
  131. }
  132. }
  133. get(key) {
  134. if (contains(this.cache_, key)) {
  135. return this.cache_[key];
  136. }
  137. return null;
  138. }
  139. remove(key) {
  140. delete this.cache_[key];
  141. }
  142. }
  143. /**
  144. * @license
  145. * Copyright 2017 Google LLC
  146. *
  147. * Licensed under the Apache License, Version 2.0 (the "License");
  148. * you may not use this file except in compliance with the License.
  149. * You may obtain a copy of the License at
  150. *
  151. * http://www.apache.org/licenses/LICENSE-2.0
  152. *
  153. * Unless required by applicable law or agreed to in writing, software
  154. * distributed under the License is distributed on an "AS IS" BASIS,
  155. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  156. * See the License for the specific language governing permissions and
  157. * limitations under the License.
  158. */
  159. /**
  160. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  161. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  162. * to reflect this type
  163. *
  164. * @param domStorageName - Name of the underlying storage object
  165. * (e.g. 'localStorage' or 'sessionStorage').
  166. * @returns Turning off type information until a common interface is defined.
  167. */
  168. const createStoragefor = function (domStorageName) {
  169. try {
  170. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  171. // so it must be inside the try/catch.
  172. if (typeof window !== 'undefined' &&
  173. typeof window[domStorageName] !== 'undefined') {
  174. // Need to test cache. Just because it's here doesn't mean it works
  175. const domStorage = window[domStorageName];
  176. domStorage.setItem('firebase:sentinel', 'cache');
  177. domStorage.removeItem('firebase:sentinel');
  178. return new DOMStorageWrapper(domStorage);
  179. }
  180. }
  181. catch (e) { }
  182. // Failed to create wrapper. Just return in-memory storage.
  183. // TODO: log?
  184. return new MemoryStorage();
  185. };
  186. /** A storage object that lasts across sessions */
  187. const PersistentStorage = createStoragefor('localStorage');
  188. /** A storage object that only lasts one session */
  189. const SessionStorage = createStoragefor('sessionStorage');
  190. /**
  191. * @license
  192. * Copyright 2017 Google LLC
  193. *
  194. * Licensed under the Apache License, Version 2.0 (the "License");
  195. * you may not use this file except in compliance with the License.
  196. * You may obtain a copy of the License at
  197. *
  198. * http://www.apache.org/licenses/LICENSE-2.0
  199. *
  200. * Unless required by applicable law or agreed to in writing, software
  201. * distributed under the License is distributed on an "AS IS" BASIS,
  202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  203. * See the License for the specific language governing permissions and
  204. * limitations under the License.
  205. */
  206. const logClient = new Logger('@firebase/database');
  207. /**
  208. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  209. */
  210. const LUIDGenerator = (function () {
  211. let id = 1;
  212. return function () {
  213. return id++;
  214. };
  215. })();
  216. /**
  217. * Sha1 hash of the input string
  218. * @param str - The string to hash
  219. * @returns {!string} The resulting hash
  220. */
  221. const sha1 = function (str) {
  222. const utf8Bytes = stringToByteArray(str);
  223. const sha1 = new Sha1();
  224. sha1.update(utf8Bytes);
  225. const sha1Bytes = sha1.digest();
  226. return base64.encodeByteArray(sha1Bytes);
  227. };
  228. const buildLogMessage_ = function (...varArgs) {
  229. let message = '';
  230. for (let i = 0; i < varArgs.length; i++) {
  231. const arg = varArgs[i];
  232. if (Array.isArray(arg) ||
  233. (arg &&
  234. typeof arg === 'object' &&
  235. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  236. typeof arg.length === 'number')) {
  237. message += buildLogMessage_.apply(null, arg);
  238. }
  239. else if (typeof arg === 'object') {
  240. message += stringify(arg);
  241. }
  242. else {
  243. message += arg;
  244. }
  245. message += ' ';
  246. }
  247. return message;
  248. };
  249. /**
  250. * Use this for all debug messages in Firebase.
  251. */
  252. let logger = null;
  253. /**
  254. * Flag to check for log availability on first log message
  255. */
  256. let firstLog_ = true;
  257. /**
  258. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  259. * @param logger_ - A flag to turn on logging, or a custom logger
  260. * @param persistent - Whether or not to persist logging settings across refreshes
  261. */
  262. const enableLogging$1 = function (logger_, persistent) {
  263. assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  264. if (logger_ === true) {
  265. logClient.logLevel = LogLevel.VERBOSE;
  266. logger = logClient.log.bind(logClient);
  267. if (persistent) {
  268. SessionStorage.set('logging_enabled', true);
  269. }
  270. }
  271. else if (typeof logger_ === 'function') {
  272. logger = logger_;
  273. }
  274. else {
  275. logger = null;
  276. SessionStorage.remove('logging_enabled');
  277. }
  278. };
  279. const log = function (...varArgs) {
  280. if (firstLog_ === true) {
  281. firstLog_ = false;
  282. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  283. enableLogging$1(true);
  284. }
  285. }
  286. if (logger) {
  287. const message = buildLogMessage_.apply(null, varArgs);
  288. logger(message);
  289. }
  290. };
  291. const logWrapper = function (prefix) {
  292. return function (...varArgs) {
  293. log(prefix, ...varArgs);
  294. };
  295. };
  296. const error = function (...varArgs) {
  297. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  298. logClient.error(message);
  299. };
  300. const fatal = function (...varArgs) {
  301. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  302. logClient.error(message);
  303. throw new Error(message);
  304. };
  305. const warn = function (...varArgs) {
  306. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  307. logClient.warn(message);
  308. };
  309. /**
  310. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  311. * does not use https.
  312. */
  313. const warnIfPageIsSecure = function () {
  314. // Be very careful accessing browser globals. Who knows what may or may not exist.
  315. if (typeof window !== 'undefined' &&
  316. window.location &&
  317. window.location.protocol &&
  318. window.location.protocol.indexOf('https:') !== -1) {
  319. warn('Insecure Firebase access from a secure page. ' +
  320. 'Please use https in calls to new Firebase().');
  321. }
  322. };
  323. /**
  324. * Returns true if data is NaN, or +/- Infinity.
  325. */
  326. const isInvalidJSONNumber = function (data) {
  327. return (typeof data === 'number' &&
  328. (data !== data || // NaN
  329. data === Number.POSITIVE_INFINITY ||
  330. data === Number.NEGATIVE_INFINITY));
  331. };
  332. const executeWhenDOMReady = function (fn) {
  333. if (isNodeSdk() || document.readyState === 'complete') {
  334. fn();
  335. }
  336. else {
  337. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  338. // fire before onload), but fall back to onload.
  339. let called = false;
  340. const wrappedFn = function () {
  341. if (!document.body) {
  342. setTimeout(wrappedFn, Math.floor(10));
  343. return;
  344. }
  345. if (!called) {
  346. called = true;
  347. fn();
  348. }
  349. };
  350. if (document.addEventListener) {
  351. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  352. // fallback to onload.
  353. window.addEventListener('load', wrappedFn, false);
  354. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  355. }
  356. else if (document.attachEvent) {
  357. // IE.
  358. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  359. document.attachEvent('onreadystatechange', () => {
  360. if (document.readyState === 'complete') {
  361. wrappedFn();
  362. }
  363. });
  364. // fallback to onload.
  365. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  366. window.attachEvent('onload', wrappedFn);
  367. // jQuery has an extra hack for IE that we could employ (based on
  368. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  369. // I'm hoping we don't need it.
  370. }
  371. }
  372. };
  373. /**
  374. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  375. */
  376. const MIN_NAME = '[MIN_NAME]';
  377. /**
  378. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  379. */
  380. const MAX_NAME = '[MAX_NAME]';
  381. /**
  382. * Compares valid Firebase key names, plus min and max name
  383. */
  384. const nameCompare = function (a, b) {
  385. if (a === b) {
  386. return 0;
  387. }
  388. else if (a === MIN_NAME || b === MAX_NAME) {
  389. return -1;
  390. }
  391. else if (b === MIN_NAME || a === MAX_NAME) {
  392. return 1;
  393. }
  394. else {
  395. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  396. if (aAsInt !== null) {
  397. if (bAsInt !== null) {
  398. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  399. }
  400. else {
  401. return -1;
  402. }
  403. }
  404. else if (bAsInt !== null) {
  405. return 1;
  406. }
  407. else {
  408. return a < b ? -1 : 1;
  409. }
  410. }
  411. };
  412. /**
  413. * @returns {!number} comparison result.
  414. */
  415. const stringCompare = function (a, b) {
  416. if (a === b) {
  417. return 0;
  418. }
  419. else if (a < b) {
  420. return -1;
  421. }
  422. else {
  423. return 1;
  424. }
  425. };
  426. const requireKey = function (key, obj) {
  427. if (obj && key in obj) {
  428. return obj[key];
  429. }
  430. else {
  431. throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
  432. }
  433. };
  434. const ObjectToUniqueKey = function (obj) {
  435. if (typeof obj !== 'object' || obj === null) {
  436. return stringify(obj);
  437. }
  438. const keys = [];
  439. // eslint-disable-next-line guard-for-in
  440. for (const k in obj) {
  441. keys.push(k);
  442. }
  443. // Export as json, but with the keys sorted.
  444. keys.sort();
  445. let key = '{';
  446. for (let i = 0; i < keys.length; i++) {
  447. if (i !== 0) {
  448. key += ',';
  449. }
  450. key += stringify(keys[i]);
  451. key += ':';
  452. key += ObjectToUniqueKey(obj[keys[i]]);
  453. }
  454. key += '}';
  455. return key;
  456. };
  457. /**
  458. * Splits a string into a number of smaller segments of maximum size
  459. * @param str - The string
  460. * @param segsize - The maximum number of chars in the string.
  461. * @returns The string, split into appropriately-sized chunks
  462. */
  463. const splitStringBySize = function (str, segsize) {
  464. const len = str.length;
  465. if (len <= segsize) {
  466. return [str];
  467. }
  468. const dataSegs = [];
  469. for (let c = 0; c < len; c += segsize) {
  470. if (c + segsize > len) {
  471. dataSegs.push(str.substring(c, len));
  472. }
  473. else {
  474. dataSegs.push(str.substring(c, c + segsize));
  475. }
  476. }
  477. return dataSegs;
  478. };
  479. /**
  480. * Apply a function to each (key, value) pair in an object or
  481. * apply a function to each (index, value) pair in an array
  482. * @param obj - The object or array to iterate over
  483. * @param fn - The function to apply
  484. */
  485. function each(obj, fn) {
  486. for (const key in obj) {
  487. if (obj.hasOwnProperty(key)) {
  488. fn(key, obj[key]);
  489. }
  490. }
  491. }
  492. /**
  493. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  494. * I made one modification at the end and removed the NaN / Infinity
  495. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  496. * @param v - A double
  497. *
  498. */
  499. const doubleToIEEE754String = function (v) {
  500. assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  501. const ebits = 11, fbits = 52;
  502. const bias = (1 << (ebits - 1)) - 1;
  503. let s, e, f, ln, i;
  504. // Compute sign, exponent, fraction
  505. // Skip NaN / Infinity handling --MJL.
  506. if (v === 0) {
  507. e = 0;
  508. f = 0;
  509. s = 1 / v === -Infinity ? 1 : 0;
  510. }
  511. else {
  512. s = v < 0;
  513. v = Math.abs(v);
  514. if (v >= Math.pow(2, 1 - bias)) {
  515. // Normalized
  516. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  517. e = ln + bias;
  518. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  519. }
  520. else {
  521. // Denormalized
  522. e = 0;
  523. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  524. }
  525. }
  526. // Pack sign, exponent, fraction
  527. const bits = [];
  528. for (i = fbits; i; i -= 1) {
  529. bits.push(f % 2 ? 1 : 0);
  530. f = Math.floor(f / 2);
  531. }
  532. for (i = ebits; i; i -= 1) {
  533. bits.push(e % 2 ? 1 : 0);
  534. e = Math.floor(e / 2);
  535. }
  536. bits.push(s ? 1 : 0);
  537. bits.reverse();
  538. const str = bits.join('');
  539. // Return the data as a hex string. --MJL
  540. let hexByteString = '';
  541. for (i = 0; i < 64; i += 8) {
  542. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  543. if (hexByte.length === 1) {
  544. hexByte = '0' + hexByte;
  545. }
  546. hexByteString = hexByteString + hexByte;
  547. }
  548. return hexByteString.toLowerCase();
  549. };
  550. /**
  551. * Used to detect if we're in a Chrome content script (which executes in an
  552. * isolated environment where long-polling doesn't work).
  553. */
  554. const isChromeExtensionContentScript = function () {
  555. return !!(typeof window === 'object' &&
  556. window['chrome'] &&
  557. window['chrome']['extension'] &&
  558. !/^chrome/.test(window.location.href));
  559. };
  560. /**
  561. * Used to detect if we're in a Windows 8 Store app.
  562. */
  563. const isWindowsStoreApp = function () {
  564. // Check for the presence of a couple WinRT globals
  565. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  566. };
  567. /**
  568. * Converts a server error code to a JavaScript Error
  569. */
  570. function errorForServerCode(code, query) {
  571. let reason = 'Unknown Error';
  572. if (code === 'too_big') {
  573. reason =
  574. 'The data requested exceeds the maximum size ' +
  575. 'that can be accessed with a single request.';
  576. }
  577. else if (code === 'permission_denied') {
  578. reason = "Client doesn't have permission to access the desired data.";
  579. }
  580. else if (code === 'unavailable') {
  581. reason = 'The service is unavailable';
  582. }
  583. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  584. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  585. error.code = code.toUpperCase();
  586. return error;
  587. }
  588. /**
  589. * Used to test for integer-looking strings
  590. */
  591. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  592. /**
  593. * For use in keys, the minimum possible 32-bit integer.
  594. */
  595. const INTEGER_32_MIN = -2147483648;
  596. /**
  597. * For use in keys, the maximum possible 32-bit integer.
  598. */
  599. const INTEGER_32_MAX = 2147483647;
  600. /**
  601. * If the string contains a 32-bit integer, return it. Else return null.
  602. */
  603. const tryParseInt = function (str) {
  604. if (INTEGER_REGEXP_.test(str)) {
  605. const intVal = Number(str);
  606. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  607. return intVal;
  608. }
  609. }
  610. return null;
  611. };
  612. /**
  613. * Helper to run some code but catch any exceptions and re-throw them later.
  614. * Useful for preventing user callbacks from breaking internal code.
  615. *
  616. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  617. * convenient (we don't have to try to figure out when is a safe point to
  618. * re-throw it), and the behavior seems reasonable:
  619. *
  620. * * If you aren't pausing on exceptions, you get an error in the console with
  621. * the correct stack trace.
  622. * * If you're pausing on all exceptions, the debugger will pause on your
  623. * exception and then again when we rethrow it.
  624. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  625. * on us re-throwing it.
  626. *
  627. * @param fn - The code to guard.
  628. */
  629. const exceptionGuard = function (fn) {
  630. try {
  631. fn();
  632. }
  633. catch (e) {
  634. // Re-throw exception when it's safe.
  635. setTimeout(() => {
  636. // It used to be that "throw e" would result in a good console error with
  637. // relevant context, but as of Chrome 39, you just get the firebase.js
  638. // file/line number where we re-throw it, which is useless. So we log
  639. // e.stack explicitly.
  640. const stack = e.stack || '';
  641. warn('Exception was thrown by user callback.', stack);
  642. throw e;
  643. }, Math.floor(0));
  644. }
  645. };
  646. /**
  647. * @returns {boolean} true if we think we're currently being crawled.
  648. */
  649. const beingCrawled = function () {
  650. const userAgent = (typeof window === 'object' &&
  651. window['navigator'] &&
  652. window['navigator']['userAgent']) ||
  653. '';
  654. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  655. // believe to support JavaScript/AJAX rendering.
  656. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  657. // would have seen the page" is flaky if we don't treat it as a crawler.
  658. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  659. };
  660. /**
  661. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  662. *
  663. * It is removed with clearTimeout() as normal.
  664. *
  665. * @param fn - Function to run.
  666. * @param time - Milliseconds to wait before running.
  667. * @returns The setTimeout() return value.
  668. */
  669. const setTimeoutNonBlocking = function (fn, time) {
  670. const timeout = setTimeout(fn, time);
  671. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  672. if (typeof timeout === 'number' &&
  673. // @ts-ignore Is only defined in Deno environments.
  674. typeof Deno !== 'undefined' &&
  675. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  676. Deno['unrefTimer']) {
  677. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  678. Deno.unrefTimer(timeout);
  679. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  680. }
  681. else if (typeof timeout === 'object' && timeout['unref']) {
  682. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  683. timeout['unref']();
  684. }
  685. return timeout;
  686. };
  687. /**
  688. * @license
  689. * Copyright 2021 Google LLC
  690. *
  691. * Licensed under the Apache License, Version 2.0 (the "License");
  692. * you may not use this file except in compliance with the License.
  693. * You may obtain a copy of the License at
  694. *
  695. * http://www.apache.org/licenses/LICENSE-2.0
  696. *
  697. * Unless required by applicable law or agreed to in writing, software
  698. * distributed under the License is distributed on an "AS IS" BASIS,
  699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  700. * See the License for the specific language governing permissions and
  701. * limitations under the License.
  702. */
  703. /**
  704. * Abstraction around AppCheck's token fetching capabilities.
  705. */
  706. class AppCheckTokenProvider {
  707. constructor(appName_, appCheckProvider) {
  708. this.appName_ = appName_;
  709. this.appCheckProvider = appCheckProvider;
  710. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  711. if (!this.appCheck) {
  712. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  713. }
  714. }
  715. getToken(forceRefresh) {
  716. if (!this.appCheck) {
  717. return new Promise((resolve, reject) => {
  718. // Support delayed initialization of FirebaseAppCheck. This allows our
  719. // customers to initialize the RTDB SDK before initializing Firebase
  720. // AppCheck and ensures that all requests are authenticated if a token
  721. // becomes available before the timeout below expires.
  722. setTimeout(() => {
  723. if (this.appCheck) {
  724. this.getToken(forceRefresh).then(resolve, reject);
  725. }
  726. else {
  727. resolve(null);
  728. }
  729. }, 0);
  730. });
  731. }
  732. return this.appCheck.getToken(forceRefresh);
  733. }
  734. addTokenChangeListener(listener) {
  735. var _a;
  736. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  737. }
  738. notifyForInvalidToken() {
  739. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  740. 'are invalid. This usually indicates your app was not initialized correctly.');
  741. }
  742. }
  743. /**
  744. * @license
  745. * Copyright 2017 Google LLC
  746. *
  747. * Licensed under the Apache License, Version 2.0 (the "License");
  748. * you may not use this file except in compliance with the License.
  749. * You may obtain a copy of the License at
  750. *
  751. * http://www.apache.org/licenses/LICENSE-2.0
  752. *
  753. * Unless required by applicable law or agreed to in writing, software
  754. * distributed under the License is distributed on an "AS IS" BASIS,
  755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  756. * See the License for the specific language governing permissions and
  757. * limitations under the License.
  758. */
  759. /**
  760. * Abstraction around FirebaseApp's token fetching capabilities.
  761. */
  762. class FirebaseAuthTokenProvider {
  763. constructor(appName_, firebaseOptions_, authProvider_) {
  764. this.appName_ = appName_;
  765. this.firebaseOptions_ = firebaseOptions_;
  766. this.authProvider_ = authProvider_;
  767. this.auth_ = null;
  768. this.auth_ = authProvider_.getImmediate({ optional: true });
  769. if (!this.auth_) {
  770. authProvider_.onInit(auth => (this.auth_ = auth));
  771. }
  772. }
  773. getToken(forceRefresh) {
  774. if (!this.auth_) {
  775. return new Promise((resolve, reject) => {
  776. // Support delayed initialization of FirebaseAuth. This allows our
  777. // customers to initialize the RTDB SDK before initializing Firebase
  778. // Auth and ensures that all requests are authenticated if a token
  779. // becomes available before the timeout below expires.
  780. setTimeout(() => {
  781. if (this.auth_) {
  782. this.getToken(forceRefresh).then(resolve, reject);
  783. }
  784. else {
  785. resolve(null);
  786. }
  787. }, 0);
  788. });
  789. }
  790. return this.auth_.getToken(forceRefresh).catch(error => {
  791. // TODO: Need to figure out all the cases this is raised and whether
  792. // this makes sense.
  793. if (error && error.code === 'auth/token-not-initialized') {
  794. log('Got auth/token-not-initialized error. Treating as null token.');
  795. return null;
  796. }
  797. else {
  798. return Promise.reject(error);
  799. }
  800. });
  801. }
  802. addTokenChangeListener(listener) {
  803. // TODO: We might want to wrap the listener and call it with no args to
  804. // avoid a leaky abstraction, but that makes removing the listener harder.
  805. if (this.auth_) {
  806. this.auth_.addAuthTokenListener(listener);
  807. }
  808. else {
  809. this.authProvider_
  810. .get()
  811. .then(auth => auth.addAuthTokenListener(listener));
  812. }
  813. }
  814. removeTokenChangeListener(listener) {
  815. this.authProvider_
  816. .get()
  817. .then(auth => auth.removeAuthTokenListener(listener));
  818. }
  819. notifyForInvalidToken() {
  820. let errorMessage = 'Provided authentication credentials for the app named "' +
  821. this.appName_ +
  822. '" are invalid. This usually indicates your app was not ' +
  823. 'initialized correctly. ';
  824. if ('credential' in this.firebaseOptions_) {
  825. errorMessage +=
  826. 'Make sure the "credential" property provided to initializeApp() ' +
  827. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  828. 'project.';
  829. }
  830. else if ('serviceAccount' in this.firebaseOptions_) {
  831. errorMessage +=
  832. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  833. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  834. 'project.';
  835. }
  836. else {
  837. errorMessage +=
  838. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  839. 'initializeApp() match the values provided for your app at ' +
  840. 'https://console.firebase.google.com/.';
  841. }
  842. warn(errorMessage);
  843. }
  844. }
  845. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  846. class EmulatorTokenProvider {
  847. constructor(accessToken) {
  848. this.accessToken = accessToken;
  849. }
  850. getToken(forceRefresh) {
  851. return Promise.resolve({
  852. accessToken: this.accessToken
  853. });
  854. }
  855. addTokenChangeListener(listener) {
  856. // Invoke the listener immediately to match the behavior in Firebase Auth
  857. // (see packages/auth/src/auth.js#L1807)
  858. listener(this.accessToken);
  859. }
  860. removeTokenChangeListener(listener) { }
  861. notifyForInvalidToken() { }
  862. }
  863. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  864. EmulatorTokenProvider.OWNER = 'owner';
  865. /**
  866. * @license
  867. * Copyright 2017 Google LLC
  868. *
  869. * Licensed under the Apache License, Version 2.0 (the "License");
  870. * you may not use this file except in compliance with the License.
  871. * You may obtain a copy of the License at
  872. *
  873. * http://www.apache.org/licenses/LICENSE-2.0
  874. *
  875. * Unless required by applicable law or agreed to in writing, software
  876. * distributed under the License is distributed on an "AS IS" BASIS,
  877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  878. * See the License for the specific language governing permissions and
  879. * limitations under the License.
  880. */
  881. const PROTOCOL_VERSION = '5';
  882. const VERSION_PARAM = 'v';
  883. const TRANSPORT_SESSION_PARAM = 's';
  884. const REFERER_PARAM = 'r';
  885. const FORGE_REF = 'f';
  886. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  887. // firebase.corp.google.com
  888. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  889. const LAST_SESSION_PARAM = 'ls';
  890. const APPLICATION_ID_PARAM = 'p';
  891. const APP_CHECK_TOKEN_PARAM = 'ac';
  892. const WEBSOCKET = 'websocket';
  893. const LONG_POLLING = 'long_polling';
  894. /**
  895. * @license
  896. * Copyright 2017 Google LLC
  897. *
  898. * Licensed under the Apache License, Version 2.0 (the "License");
  899. * you may not use this file except in compliance with the License.
  900. * You may obtain a copy of the License at
  901. *
  902. * http://www.apache.org/licenses/LICENSE-2.0
  903. *
  904. * Unless required by applicable law or agreed to in writing, software
  905. * distributed under the License is distributed on an "AS IS" BASIS,
  906. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  907. * See the License for the specific language governing permissions and
  908. * limitations under the License.
  909. */
  910. /**
  911. * A class that holds metadata about a Repo object
  912. */
  913. class RepoInfo {
  914. /**
  915. * @param host - Hostname portion of the url for the repo
  916. * @param secure - Whether or not this repo is accessed over ssl
  917. * @param namespace - The namespace represented by the repo
  918. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  919. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  920. * @param persistenceKey - Override the default session persistence storage key
  921. */
  922. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {
  923. this.secure = secure;
  924. this.namespace = namespace;
  925. this.webSocketOnly = webSocketOnly;
  926. this.nodeAdmin = nodeAdmin;
  927. this.persistenceKey = persistenceKey;
  928. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  929. this.isUsingEmulator = isUsingEmulator;
  930. this._host = host.toLowerCase();
  931. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  932. this.internalHost =
  933. PersistentStorage.get('host:' + host) || this._host;
  934. }
  935. isCacheableHost() {
  936. return this.internalHost.substr(0, 2) === 's-';
  937. }
  938. isCustomHost() {
  939. return (this._domain !== 'firebaseio.com' &&
  940. this._domain !== 'firebaseio-demo.com');
  941. }
  942. get host() {
  943. return this._host;
  944. }
  945. set host(newHost) {
  946. if (newHost !== this.internalHost) {
  947. this.internalHost = newHost;
  948. if (this.isCacheableHost()) {
  949. PersistentStorage.set('host:' + this._host, this.internalHost);
  950. }
  951. }
  952. }
  953. toString() {
  954. let str = this.toURLString();
  955. if (this.persistenceKey) {
  956. str += '<' + this.persistenceKey + '>';
  957. }
  958. return str;
  959. }
  960. toURLString() {
  961. const protocol = this.secure ? 'https://' : 'http://';
  962. const query = this.includeNamespaceInQueryParams
  963. ? `?ns=${this.namespace}`
  964. : '';
  965. return `${protocol}${this.host}/${query}`;
  966. }
  967. }
  968. function repoInfoNeedsQueryParam(repoInfo) {
  969. return (repoInfo.host !== repoInfo.internalHost ||
  970. repoInfo.isCustomHost() ||
  971. repoInfo.includeNamespaceInQueryParams);
  972. }
  973. /**
  974. * Returns the websocket URL for this repo
  975. * @param repoInfo - RepoInfo object
  976. * @param type - of connection
  977. * @param params - list
  978. * @returns The URL for this repo
  979. */
  980. function repoInfoConnectionURL(repoInfo, type, params) {
  981. assert(typeof type === 'string', 'typeof type must == string');
  982. assert(typeof params === 'object', 'typeof params must == object');
  983. let connURL;
  984. if (type === WEBSOCKET) {
  985. connURL =
  986. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  987. }
  988. else if (type === LONG_POLLING) {
  989. connURL =
  990. (repoInfo.secure ? 'https://' : 'http://') +
  991. repoInfo.internalHost +
  992. '/.lp?';
  993. }
  994. else {
  995. throw new Error('Unknown connection type: ' + type);
  996. }
  997. if (repoInfoNeedsQueryParam(repoInfo)) {
  998. params['ns'] = repoInfo.namespace;
  999. }
  1000. const pairs = [];
  1001. each(params, (key, value) => {
  1002. pairs.push(key + '=' + value);
  1003. });
  1004. return connURL + pairs.join('&');
  1005. }
  1006. /**
  1007. * @license
  1008. * Copyright 2017 Google LLC
  1009. *
  1010. * Licensed under the Apache License, Version 2.0 (the "License");
  1011. * you may not use this file except in compliance with the License.
  1012. * You may obtain a copy of the License at
  1013. *
  1014. * http://www.apache.org/licenses/LICENSE-2.0
  1015. *
  1016. * Unless required by applicable law or agreed to in writing, software
  1017. * distributed under the License is distributed on an "AS IS" BASIS,
  1018. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1019. * See the License for the specific language governing permissions and
  1020. * limitations under the License.
  1021. */
  1022. /**
  1023. * Tracks a collection of stats.
  1024. */
  1025. class StatsCollection {
  1026. constructor() {
  1027. this.counters_ = {};
  1028. }
  1029. incrementCounter(name, amount = 1) {
  1030. if (!contains(this.counters_, name)) {
  1031. this.counters_[name] = 0;
  1032. }
  1033. this.counters_[name] += amount;
  1034. }
  1035. get() {
  1036. return deepCopy(this.counters_);
  1037. }
  1038. }
  1039. /**
  1040. * @license
  1041. * Copyright 2017 Google LLC
  1042. *
  1043. * Licensed under the Apache License, Version 2.0 (the "License");
  1044. * you may not use this file except in compliance with the License.
  1045. * You may obtain a copy of the License at
  1046. *
  1047. * http://www.apache.org/licenses/LICENSE-2.0
  1048. *
  1049. * Unless required by applicable law or agreed to in writing, software
  1050. * distributed under the License is distributed on an "AS IS" BASIS,
  1051. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1052. * See the License for the specific language governing permissions and
  1053. * limitations under the License.
  1054. */
  1055. const collections = {};
  1056. const reporters = {};
  1057. function statsManagerGetCollection(repoInfo) {
  1058. const hashString = repoInfo.toString();
  1059. if (!collections[hashString]) {
  1060. collections[hashString] = new StatsCollection();
  1061. }
  1062. return collections[hashString];
  1063. }
  1064. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  1065. const hashString = repoInfo.toString();
  1066. if (!reporters[hashString]) {
  1067. reporters[hashString] = creatorFunction();
  1068. }
  1069. return reporters[hashString];
  1070. }
  1071. /**
  1072. * @license
  1073. * Copyright 2017 Google LLC
  1074. *
  1075. * Licensed under the Apache License, Version 2.0 (the "License");
  1076. * you may not use this file except in compliance with the License.
  1077. * You may obtain a copy of the License at
  1078. *
  1079. * http://www.apache.org/licenses/LICENSE-2.0
  1080. *
  1081. * Unless required by applicable law or agreed to in writing, software
  1082. * distributed under the License is distributed on an "AS IS" BASIS,
  1083. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1084. * See the License for the specific language governing permissions and
  1085. * limitations under the License.
  1086. */
  1087. /**
  1088. * This class ensures the packets from the server arrive in order
  1089. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1090. */
  1091. class PacketReceiver {
  1092. /**
  1093. * @param onMessage_
  1094. */
  1095. constructor(onMessage_) {
  1096. this.onMessage_ = onMessage_;
  1097. this.pendingResponses = [];
  1098. this.currentResponseNum = 0;
  1099. this.closeAfterResponse = -1;
  1100. this.onClose = null;
  1101. }
  1102. closeAfter(responseNum, callback) {
  1103. this.closeAfterResponse = responseNum;
  1104. this.onClose = callback;
  1105. if (this.closeAfterResponse < this.currentResponseNum) {
  1106. this.onClose();
  1107. this.onClose = null;
  1108. }
  1109. }
  1110. /**
  1111. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1112. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1113. * browsers will respond in the same order as the requests we sent
  1114. */
  1115. handleResponse(requestNum, data) {
  1116. this.pendingResponses[requestNum] = data;
  1117. while (this.pendingResponses[this.currentResponseNum]) {
  1118. const toProcess = this.pendingResponses[this.currentResponseNum];
  1119. delete this.pendingResponses[this.currentResponseNum];
  1120. for (let i = 0; i < toProcess.length; ++i) {
  1121. if (toProcess[i]) {
  1122. exceptionGuard(() => {
  1123. this.onMessage_(toProcess[i]);
  1124. });
  1125. }
  1126. }
  1127. if (this.currentResponseNum === this.closeAfterResponse) {
  1128. if (this.onClose) {
  1129. this.onClose();
  1130. this.onClose = null;
  1131. }
  1132. break;
  1133. }
  1134. this.currentResponseNum++;
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * @license
  1140. * Copyright 2017 Google LLC
  1141. *
  1142. * Licensed under the Apache License, Version 2.0 (the "License");
  1143. * you may not use this file except in compliance with the License.
  1144. * You may obtain a copy of the License at
  1145. *
  1146. * http://www.apache.org/licenses/LICENSE-2.0
  1147. *
  1148. * Unless required by applicable law or agreed to in writing, software
  1149. * distributed under the License is distributed on an "AS IS" BASIS,
  1150. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1151. * See the License for the specific language governing permissions and
  1152. * limitations under the License.
  1153. */
  1154. // URL query parameters associated with longpolling
  1155. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1156. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1157. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1158. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1159. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1160. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1161. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1162. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1163. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1164. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1165. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1166. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1167. //Data size constants.
  1168. //TODO: Perf: the maximum length actually differs from browser to browser.
  1169. // We should check what browser we're on and set accordingly.
  1170. const MAX_URL_DATA_SIZE = 1870;
  1171. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1172. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1173. /**
  1174. * Keepalive period
  1175. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1176. * length of 30 seconds that we can't exceed.
  1177. */
  1178. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1179. /**
  1180. * How long to wait before aborting a long-polling connection attempt.
  1181. */
  1182. const LP_CONNECT_TIMEOUT = 30000;
  1183. /**
  1184. * This class manages a single long-polling connection.
  1185. */
  1186. class BrowserPollConnection {
  1187. /**
  1188. * @param connId An identifier for this connection, used for logging
  1189. * @param repoInfo The info for the endpoint to send data to.
  1190. * @param applicationId The Firebase App ID for this project.
  1191. * @param appCheckToken The AppCheck token for this client.
  1192. * @param authToken The AuthToken to use for this connection.
  1193. * @param transportSessionId Optional transportSessionid if we are
  1194. * reconnecting for an existing transport session
  1195. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1196. * already created a connection previously
  1197. */
  1198. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1199. this.connId = connId;
  1200. this.repoInfo = repoInfo;
  1201. this.applicationId = applicationId;
  1202. this.appCheckToken = appCheckToken;
  1203. this.authToken = authToken;
  1204. this.transportSessionId = transportSessionId;
  1205. this.lastSessionId = lastSessionId;
  1206. this.bytesSent = 0;
  1207. this.bytesReceived = 0;
  1208. this.everConnected_ = false;
  1209. this.log_ = logWrapper(connId);
  1210. this.stats_ = statsManagerGetCollection(repoInfo);
  1211. this.urlFn = (params) => {
  1212. // Always add the token if we have one.
  1213. if (this.appCheckToken) {
  1214. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1215. }
  1216. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1217. };
  1218. }
  1219. /**
  1220. * @param onMessage - Callback when messages arrive
  1221. * @param onDisconnect - Callback with connection lost.
  1222. */
  1223. open(onMessage, onDisconnect) {
  1224. this.curSegmentNum = 0;
  1225. this.onDisconnect_ = onDisconnect;
  1226. this.myPacketOrderer = new PacketReceiver(onMessage);
  1227. this.isClosed_ = false;
  1228. this.connectTimeoutTimer_ = setTimeout(() => {
  1229. this.log_('Timed out trying to connect.');
  1230. // Make sure we clear the host cache
  1231. this.onClosed_();
  1232. this.connectTimeoutTimer_ = null;
  1233. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1234. }, Math.floor(LP_CONNECT_TIMEOUT));
  1235. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1236. executeWhenDOMReady(() => {
  1237. if (this.isClosed_) {
  1238. return;
  1239. }
  1240. //Set up a callback that gets triggered once a connection is set up.
  1241. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1242. const [command, arg1, arg2, arg3, arg4] = args;
  1243. this.incrementIncomingBytes_(args);
  1244. if (!this.scriptTagHolder) {
  1245. return; // we closed the connection.
  1246. }
  1247. if (this.connectTimeoutTimer_) {
  1248. clearTimeout(this.connectTimeoutTimer_);
  1249. this.connectTimeoutTimer_ = null;
  1250. }
  1251. this.everConnected_ = true;
  1252. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1253. this.id = arg1;
  1254. this.password = arg2;
  1255. }
  1256. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1257. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1258. if (arg1) {
  1259. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1260. // through our already open polls), so don't send any more.
  1261. this.scriptTagHolder.sendNewPolls = false;
  1262. // arg1 in this case is the last response number sent by the server. We should try to receive
  1263. // all of the responses up to this one before closing
  1264. this.myPacketOrderer.closeAfter(arg1, () => {
  1265. this.onClosed_();
  1266. });
  1267. }
  1268. else {
  1269. this.onClosed_();
  1270. }
  1271. }
  1272. else {
  1273. throw new Error('Unrecognized command received: ' + command);
  1274. }
  1275. }, (...args) => {
  1276. const [pN, data] = args;
  1277. this.incrementIncomingBytes_(args);
  1278. this.myPacketOrderer.handleResponse(pN, data);
  1279. }, () => {
  1280. this.onClosed_();
  1281. }, this.urlFn);
  1282. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1283. //from cache.
  1284. const urlParams = {};
  1285. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1286. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1287. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1288. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1289. this.scriptTagHolder.uniqueCallbackIdentifier;
  1290. }
  1291. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1292. if (this.transportSessionId) {
  1293. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1294. }
  1295. if (this.lastSessionId) {
  1296. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1297. }
  1298. if (this.applicationId) {
  1299. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1300. }
  1301. if (this.appCheckToken) {
  1302. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1303. }
  1304. if (typeof location !== 'undefined' &&
  1305. location.hostname &&
  1306. FORGE_DOMAIN_RE.test(location.hostname)) {
  1307. urlParams[REFERER_PARAM] = FORGE_REF;
  1308. }
  1309. const connectURL = this.urlFn(urlParams);
  1310. this.log_('Connecting via long-poll to ' + connectURL);
  1311. this.scriptTagHolder.addTag(connectURL, () => {
  1312. /* do nothing */
  1313. });
  1314. });
  1315. }
  1316. /**
  1317. * Call this when a handshake has completed successfully and we want to consider the connection established
  1318. */
  1319. start() {
  1320. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1321. this.addDisconnectPingFrame(this.id, this.password);
  1322. }
  1323. /**
  1324. * Forces long polling to be considered as a potential transport
  1325. */
  1326. static forceAllow() {
  1327. BrowserPollConnection.forceAllow_ = true;
  1328. }
  1329. /**
  1330. * Forces longpolling to not be considered as a potential transport
  1331. */
  1332. static forceDisallow() {
  1333. BrowserPollConnection.forceDisallow_ = true;
  1334. }
  1335. // Static method, use string literal so it can be accessed in a generic way
  1336. static isAvailable() {
  1337. if (isNodeSdk()) {
  1338. return false;
  1339. }
  1340. else if (BrowserPollConnection.forceAllow_) {
  1341. return true;
  1342. }
  1343. else {
  1344. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1345. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1346. return (!BrowserPollConnection.forceDisallow_ &&
  1347. typeof document !== 'undefined' &&
  1348. document.createElement != null &&
  1349. !isChromeExtensionContentScript() &&
  1350. !isWindowsStoreApp());
  1351. }
  1352. }
  1353. /**
  1354. * No-op for polling
  1355. */
  1356. markConnectionHealthy() { }
  1357. /**
  1358. * Stops polling and cleans up the iframe
  1359. */
  1360. shutdown_() {
  1361. this.isClosed_ = true;
  1362. if (this.scriptTagHolder) {
  1363. this.scriptTagHolder.close();
  1364. this.scriptTagHolder = null;
  1365. }
  1366. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1367. if (this.myDisconnFrame) {
  1368. document.body.removeChild(this.myDisconnFrame);
  1369. this.myDisconnFrame = null;
  1370. }
  1371. if (this.connectTimeoutTimer_) {
  1372. clearTimeout(this.connectTimeoutTimer_);
  1373. this.connectTimeoutTimer_ = null;
  1374. }
  1375. }
  1376. /**
  1377. * Triggered when this transport is closed
  1378. */
  1379. onClosed_() {
  1380. if (!this.isClosed_) {
  1381. this.log_('Longpoll is closing itself');
  1382. this.shutdown_();
  1383. if (this.onDisconnect_) {
  1384. this.onDisconnect_(this.everConnected_);
  1385. this.onDisconnect_ = null;
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1391. * that we've left.
  1392. */
  1393. close() {
  1394. if (!this.isClosed_) {
  1395. this.log_('Longpoll is being closed.');
  1396. this.shutdown_();
  1397. }
  1398. }
  1399. /**
  1400. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1401. * broken into chunks (since URLs have a small maximum length).
  1402. * @param data - The JSON data to transmit.
  1403. */
  1404. send(data) {
  1405. const dataStr = stringify(data);
  1406. this.bytesSent += dataStr.length;
  1407. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1408. //first, lets get the base64-encoded data
  1409. const base64data = base64Encode(dataStr);
  1410. //We can only fit a certain amount in each URL, so we need to split this request
  1411. //up into multiple pieces if it doesn't fit in one request.
  1412. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1413. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1414. //of segments so that we can reassemble the packet on the server.
  1415. for (let i = 0; i < dataSegs.length; i++) {
  1416. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1417. this.curSegmentNum++;
  1418. }
  1419. }
  1420. /**
  1421. * This is how we notify the server that we're leaving.
  1422. * We aren't able to send requests with DHTML on a window close event, but we can
  1423. * trigger XHR requests in some browsers (everything but Opera basically).
  1424. */
  1425. addDisconnectPingFrame(id, pw) {
  1426. if (isNodeSdk()) {
  1427. return;
  1428. }
  1429. this.myDisconnFrame = document.createElement('iframe');
  1430. const urlParams = {};
  1431. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1432. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1433. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1434. this.myDisconnFrame.src = this.urlFn(urlParams);
  1435. this.myDisconnFrame.style.display = 'none';
  1436. document.body.appendChild(this.myDisconnFrame);
  1437. }
  1438. /**
  1439. * Used to track the bytes received by this client
  1440. */
  1441. incrementIncomingBytes_(args) {
  1442. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1443. const bytesReceived = stringify(args).length;
  1444. this.bytesReceived += bytesReceived;
  1445. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1446. }
  1447. }
  1448. /*********************************************************************************************
  1449. * A wrapper around an iframe that is used as a long-polling script holder.
  1450. *********************************************************************************************/
  1451. class FirebaseIFrameScriptHolder {
  1452. /**
  1453. * @param commandCB - The callback to be called when control commands are received from the server.
  1454. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1455. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1456. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1457. */
  1458. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1459. this.onDisconnect = onDisconnect;
  1460. this.urlFn = urlFn;
  1461. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1462. //problems in some browsers.
  1463. this.outstandingRequests = new Set();
  1464. //A queue of the pending segments waiting for transmission to the server.
  1465. this.pendingSegs = [];
  1466. //A serial number. We use this for two things:
  1467. // 1) A way to ensure the browser doesn't cache responses to polls
  1468. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1469. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1470. // JSONP code in the order it was added to the iframe.
  1471. this.currentSerial = Math.floor(Math.random() * 100000000);
  1472. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1473. // incoming data from the server that we're waiting for).
  1474. this.sendNewPolls = true;
  1475. if (!isNodeSdk()) {
  1476. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1477. //iframes where we put the long-polling script tags. We have two callbacks:
  1478. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1479. // 2) Message Callback - Triggered when new data arrives.
  1480. this.uniqueCallbackIdentifier = LUIDGenerator();
  1481. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1482. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1483. onMessageCB;
  1484. //Create an iframe for us to add script tags to.
  1485. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1486. // Set the iframe's contents.
  1487. let script = '';
  1488. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1489. // for ie9, but ie8 needs to do it again in the document itself.
  1490. if (this.myIFrame.src &&
  1491. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1492. const currentDomain = document.domain;
  1493. script = '<script>document.domain="' + currentDomain + '";</script>';
  1494. }
  1495. const iframeContents = '<html><body>' + script + '</body></html>';
  1496. try {
  1497. this.myIFrame.doc.open();
  1498. this.myIFrame.doc.write(iframeContents);
  1499. this.myIFrame.doc.close();
  1500. }
  1501. catch (e) {
  1502. log('frame writing exception');
  1503. if (e.stack) {
  1504. log(e.stack);
  1505. }
  1506. log(e);
  1507. }
  1508. }
  1509. else {
  1510. this.commandCB = commandCB;
  1511. this.onMessageCB = onMessageCB;
  1512. }
  1513. }
  1514. /**
  1515. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1516. * actually use.
  1517. */
  1518. static createIFrame_() {
  1519. const iframe = document.createElement('iframe');
  1520. iframe.style.display = 'none';
  1521. // This is necessary in order to initialize the document inside the iframe
  1522. if (document.body) {
  1523. document.body.appendChild(iframe);
  1524. try {
  1525. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1526. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1527. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1528. const a = iframe.contentWindow.document;
  1529. if (!a) {
  1530. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1531. log('No IE domain setting required');
  1532. }
  1533. }
  1534. catch (e) {
  1535. const domain = document.domain;
  1536. iframe.src =
  1537. "javascript:void((function(){document.open();document.domain='" +
  1538. domain +
  1539. "';document.close();})())";
  1540. }
  1541. }
  1542. else {
  1543. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1544. // never gets hit.
  1545. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1546. }
  1547. // Get the document of the iframe in a browser-specific way.
  1548. if (iframe.contentDocument) {
  1549. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1550. }
  1551. else if (iframe.contentWindow) {
  1552. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1553. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1554. }
  1555. else if (iframe.document) {
  1556. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1557. iframe.doc = iframe.document; //others?
  1558. }
  1559. return iframe;
  1560. }
  1561. /**
  1562. * Cancel all outstanding queries and remove the frame.
  1563. */
  1564. close() {
  1565. //Mark this iframe as dead, so no new requests are sent.
  1566. this.alive = false;
  1567. if (this.myIFrame) {
  1568. //We have to actually remove all of the html inside this iframe before removing it from the
  1569. //window, or IE will continue loading and executing the script tags we've already added, which
  1570. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1571. this.myIFrame.doc.body.textContent = '';
  1572. setTimeout(() => {
  1573. if (this.myIFrame !== null) {
  1574. document.body.removeChild(this.myIFrame);
  1575. this.myIFrame = null;
  1576. }
  1577. }, Math.floor(0));
  1578. }
  1579. // Protect from being called recursively.
  1580. const onDisconnect = this.onDisconnect;
  1581. if (onDisconnect) {
  1582. this.onDisconnect = null;
  1583. onDisconnect();
  1584. }
  1585. }
  1586. /**
  1587. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1588. * @param id - The ID of this connection
  1589. * @param pw - The password for this connection
  1590. */
  1591. startLongPoll(id, pw) {
  1592. this.myID = id;
  1593. this.myPW = pw;
  1594. this.alive = true;
  1595. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1596. while (this.newRequest_()) { }
  1597. }
  1598. /**
  1599. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1600. * too many outstanding requests and we are still alive.
  1601. *
  1602. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1603. * needed.
  1604. */
  1605. newRequest_() {
  1606. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1607. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1608. // close the old request.
  1609. if (this.alive &&
  1610. this.sendNewPolls &&
  1611. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1612. //construct our url
  1613. this.currentSerial++;
  1614. const urlParams = {};
  1615. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1616. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1617. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1618. let theURL = this.urlFn(urlParams);
  1619. //Now add as much data as we can.
  1620. let curDataString = '';
  1621. let i = 0;
  1622. while (this.pendingSegs.length > 0) {
  1623. //first, lets see if the next segment will fit.
  1624. const nextSeg = this.pendingSegs[0];
  1625. if (nextSeg.d.length +
  1626. SEG_HEADER_SIZE +
  1627. curDataString.length <=
  1628. MAX_URL_DATA_SIZE) {
  1629. //great, the segment will fit. Lets append it.
  1630. const theSeg = this.pendingSegs.shift();
  1631. curDataString =
  1632. curDataString +
  1633. '&' +
  1634. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1635. i +
  1636. '=' +
  1637. theSeg.seg +
  1638. '&' +
  1639. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1640. i +
  1641. '=' +
  1642. theSeg.ts +
  1643. '&' +
  1644. FIREBASE_LONGPOLL_DATA_PARAM +
  1645. i +
  1646. '=' +
  1647. theSeg.d;
  1648. i++;
  1649. }
  1650. else {
  1651. break;
  1652. }
  1653. }
  1654. theURL = theURL + curDataString;
  1655. this.addLongPollTag_(theURL, this.currentSerial);
  1656. return true;
  1657. }
  1658. else {
  1659. return false;
  1660. }
  1661. }
  1662. /**
  1663. * Queue a packet for transmission to the server.
  1664. * @param segnum - A sequential id for this packet segment used for reassembly
  1665. * @param totalsegs - The total number of segments in this packet
  1666. * @param data - The data for this segment.
  1667. */
  1668. enqueueSegment(segnum, totalsegs, data) {
  1669. //add this to the queue of segments to send.
  1670. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  1671. //send the data immediately if there isn't already data being transmitted, unless
  1672. //startLongPoll hasn't been called yet.
  1673. if (this.alive) {
  1674. this.newRequest_();
  1675. }
  1676. }
  1677. /**
  1678. * Add a script tag for a regular long-poll request.
  1679. * @param url - The URL of the script tag.
  1680. * @param serial - The serial number of the request.
  1681. */
  1682. addLongPollTag_(url, serial) {
  1683. //remember that we sent this request.
  1684. this.outstandingRequests.add(serial);
  1685. const doNewRequest = () => {
  1686. this.outstandingRequests.delete(serial);
  1687. this.newRequest_();
  1688. };
  1689. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  1690. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  1691. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  1692. const readyStateCB = () => {
  1693. // Request completed. Cancel the keepalive.
  1694. clearTimeout(keepaliveTimeout);
  1695. // Trigger a new request so we can continue receiving data.
  1696. doNewRequest();
  1697. };
  1698. this.addTag(url, readyStateCB);
  1699. }
  1700. /**
  1701. * Add an arbitrary script tag to the iframe.
  1702. * @param url - The URL for the script tag source.
  1703. * @param loadCB - A callback to be triggered once the script has loaded.
  1704. */
  1705. addTag(url, loadCB) {
  1706. if (isNodeSdk()) {
  1707. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1708. this.doNodeLongPoll(url, loadCB);
  1709. }
  1710. else {
  1711. setTimeout(() => {
  1712. try {
  1713. // if we're already closed, don't add this poll
  1714. if (!this.sendNewPolls) {
  1715. return;
  1716. }
  1717. const newScript = this.myIFrame.doc.createElement('script');
  1718. newScript.type = 'text/javascript';
  1719. newScript.async = true;
  1720. newScript.src = url;
  1721. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1722. newScript.onload = newScript.onreadystatechange =
  1723. function () {
  1724. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1725. const rstate = newScript.readyState;
  1726. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  1727. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1728. newScript.onload = newScript.onreadystatechange = null;
  1729. if (newScript.parentNode) {
  1730. newScript.parentNode.removeChild(newScript);
  1731. }
  1732. loadCB();
  1733. }
  1734. };
  1735. newScript.onerror = () => {
  1736. log('Long-poll script failed to load: ' + url);
  1737. this.sendNewPolls = false;
  1738. this.close();
  1739. };
  1740. this.myIFrame.doc.body.appendChild(newScript);
  1741. }
  1742. catch (e) {
  1743. // TODO: we should make this error visible somehow
  1744. }
  1745. }, Math.floor(1));
  1746. }
  1747. }
  1748. }
  1749. /**
  1750. * @license
  1751. * Copyright 2017 Google LLC
  1752. *
  1753. * Licensed under the Apache License, Version 2.0 (the "License");
  1754. * you may not use this file except in compliance with the License.
  1755. * You may obtain a copy of the License at
  1756. *
  1757. * http://www.apache.org/licenses/LICENSE-2.0
  1758. *
  1759. * Unless required by applicable law or agreed to in writing, software
  1760. * distributed under the License is distributed on an "AS IS" BASIS,
  1761. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1762. * See the License for the specific language governing permissions and
  1763. * limitations under the License.
  1764. */
  1765. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  1766. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  1767. let WebSocketImpl = null;
  1768. if (typeof MozWebSocket !== 'undefined') {
  1769. WebSocketImpl = MozWebSocket;
  1770. }
  1771. else if (typeof WebSocket !== 'undefined') {
  1772. WebSocketImpl = WebSocket;
  1773. }
  1774. /**
  1775. * Create a new websocket connection with the given callbacks.
  1776. */
  1777. class WebSocketConnection {
  1778. /**
  1779. * @param connId identifier for this transport
  1780. * @param repoInfo The info for the websocket endpoint.
  1781. * @param applicationId The Firebase App ID for this project.
  1782. * @param appCheckToken The App Check Token for this client.
  1783. * @param authToken The Auth Token for this client.
  1784. * @param transportSessionId Optional transportSessionId if this is connecting
  1785. * to an existing transport session
  1786. * @param lastSessionId Optional lastSessionId if there was a previous
  1787. * connection
  1788. */
  1789. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1790. this.connId = connId;
  1791. this.applicationId = applicationId;
  1792. this.appCheckToken = appCheckToken;
  1793. this.authToken = authToken;
  1794. this.keepaliveTimer = null;
  1795. this.frames = null;
  1796. this.totalFrames = 0;
  1797. this.bytesSent = 0;
  1798. this.bytesReceived = 0;
  1799. this.log_ = logWrapper(this.connId);
  1800. this.stats_ = statsManagerGetCollection(repoInfo);
  1801. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  1802. this.nodeAdmin = repoInfo.nodeAdmin;
  1803. }
  1804. /**
  1805. * @param repoInfo - The info for the websocket endpoint.
  1806. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  1807. * session
  1808. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  1809. * @returns connection url
  1810. */
  1811. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  1812. const urlParams = {};
  1813. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1814. if (!isNodeSdk() &&
  1815. typeof location !== 'undefined' &&
  1816. location.hostname &&
  1817. FORGE_DOMAIN_RE.test(location.hostname)) {
  1818. urlParams[REFERER_PARAM] = FORGE_REF;
  1819. }
  1820. if (transportSessionId) {
  1821. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1822. }
  1823. if (lastSessionId) {
  1824. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1825. }
  1826. if (appCheckToken) {
  1827. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1828. }
  1829. if (applicationId) {
  1830. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1831. }
  1832. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1833. }
  1834. /**
  1835. * @param onMessage - Callback when messages arrive
  1836. * @param onDisconnect - Callback with connection lost.
  1837. */
  1838. open(onMessage, onDisconnect) {
  1839. this.onDisconnect = onDisconnect;
  1840. this.onMessage = onMessage;
  1841. this.log_('Websocket connecting to ' + this.connURL);
  1842. this.everConnected_ = false;
  1843. // Assume failure until proven otherwise.
  1844. PersistentStorage.set('previous_websocket_failure', true);
  1845. try {
  1846. let options;
  1847. if (isNodeSdk()) {
  1848. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1849. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1850. options = {
  1851. headers: {
  1852. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  1853. 'X-Firebase-GMPID': this.applicationId || ''
  1854. }
  1855. };
  1856. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1857. // Note that we send the credentials here even if they aren't admin credentials, which is
  1858. // not a problem.
  1859. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1860. // through the websocket connection once it is established.
  1861. if (this.authToken) {
  1862. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1863. }
  1864. if (this.appCheckToken) {
  1865. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1866. }
  1867. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1868. const env = process['env'];
  1869. const proxy = this.connURL.indexOf('wss://') === 0
  1870. ? env['HTTPS_PROXY'] || env['https_proxy']
  1871. : env['HTTP_PROXY'] || env['http_proxy'];
  1872. if (proxy) {
  1873. options['proxy'] = { origin: proxy };
  1874. }
  1875. }
  1876. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1877. }
  1878. catch (e) {
  1879. this.log_('Error instantiating WebSocket.');
  1880. const error = e.message || e.data;
  1881. if (error) {
  1882. this.log_(error);
  1883. }
  1884. this.onClosed_();
  1885. return;
  1886. }
  1887. this.mySock.onopen = () => {
  1888. this.log_('Websocket connected.');
  1889. this.everConnected_ = true;
  1890. };
  1891. this.mySock.onclose = () => {
  1892. this.log_('Websocket connection was disconnected.');
  1893. this.mySock = null;
  1894. this.onClosed_();
  1895. };
  1896. this.mySock.onmessage = m => {
  1897. this.handleIncomingFrame(m);
  1898. };
  1899. this.mySock.onerror = e => {
  1900. this.log_('WebSocket error. Closing connection.');
  1901. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1902. const error = e.message || e.data;
  1903. if (error) {
  1904. this.log_(error);
  1905. }
  1906. this.onClosed_();
  1907. };
  1908. }
  1909. /**
  1910. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1911. */
  1912. start() { }
  1913. static forceDisallow() {
  1914. WebSocketConnection.forceDisallow_ = true;
  1915. }
  1916. static isAvailable() {
  1917. let isOldAndroid = false;
  1918. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1919. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1920. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1921. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1922. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1923. isOldAndroid = true;
  1924. }
  1925. }
  1926. }
  1927. return (!isOldAndroid &&
  1928. WebSocketImpl !== null &&
  1929. !WebSocketConnection.forceDisallow_);
  1930. }
  1931. /**
  1932. * Returns true if we previously failed to connect with this transport.
  1933. */
  1934. static previouslyFailed() {
  1935. // If our persistent storage is actually only in-memory storage,
  1936. // we default to assuming that it previously failed to be safe.
  1937. return (PersistentStorage.isInMemoryStorage ||
  1938. PersistentStorage.get('previous_websocket_failure') === true);
  1939. }
  1940. markConnectionHealthy() {
  1941. PersistentStorage.remove('previous_websocket_failure');
  1942. }
  1943. appendFrame_(data) {
  1944. this.frames.push(data);
  1945. if (this.frames.length === this.totalFrames) {
  1946. const fullMess = this.frames.join('');
  1947. this.frames = null;
  1948. const jsonMess = jsonEval(fullMess);
  1949. //handle the message
  1950. this.onMessage(jsonMess);
  1951. }
  1952. }
  1953. /**
  1954. * @param frameCount - The number of frames we are expecting from the server
  1955. */
  1956. handleNewFrameCount_(frameCount) {
  1957. this.totalFrames = frameCount;
  1958. this.frames = [];
  1959. }
  1960. /**
  1961. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1962. * @returns Any remaining data to be process, or null if there is none
  1963. */
  1964. extractFrameCount_(data) {
  1965. assert(this.frames === null, 'We already have a frame buffer');
  1966. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1967. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1968. if (data.length <= 6) {
  1969. const frameCount = Number(data);
  1970. if (!isNaN(frameCount)) {
  1971. this.handleNewFrameCount_(frameCount);
  1972. return null;
  1973. }
  1974. }
  1975. this.handleNewFrameCount_(1);
  1976. return data;
  1977. }
  1978. /**
  1979. * Process a websocket frame that has arrived from the server.
  1980. * @param mess - The frame data
  1981. */
  1982. handleIncomingFrame(mess) {
  1983. if (this.mySock === null) {
  1984. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1985. }
  1986. const data = mess['data'];
  1987. this.bytesReceived += data.length;
  1988. this.stats_.incrementCounter('bytes_received', data.length);
  1989. this.resetKeepAlive();
  1990. if (this.frames !== null) {
  1991. // we're buffering
  1992. this.appendFrame_(data);
  1993. }
  1994. else {
  1995. // try to parse out a frame count, otherwise, assume 1 and process it
  1996. const remainingData = this.extractFrameCount_(data);
  1997. if (remainingData !== null) {
  1998. this.appendFrame_(remainingData);
  1999. }
  2000. }
  2001. }
  2002. /**
  2003. * Send a message to the server
  2004. * @param data - The JSON object to transmit
  2005. */
  2006. send(data) {
  2007. this.resetKeepAlive();
  2008. const dataStr = stringify(data);
  2009. this.bytesSent += dataStr.length;
  2010. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  2011. //We can only fit a certain amount in each websocket frame, so we need to split this request
  2012. //up into multiple pieces if it doesn't fit in one request.
  2013. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  2014. //Send the length header
  2015. if (dataSegs.length > 1) {
  2016. this.sendString_(String(dataSegs.length));
  2017. }
  2018. //Send the actual data in segments.
  2019. for (let i = 0; i < dataSegs.length; i++) {
  2020. this.sendString_(dataSegs[i]);
  2021. }
  2022. }
  2023. shutdown_() {
  2024. this.isClosed_ = true;
  2025. if (this.keepaliveTimer) {
  2026. clearInterval(this.keepaliveTimer);
  2027. this.keepaliveTimer = null;
  2028. }
  2029. if (this.mySock) {
  2030. this.mySock.close();
  2031. this.mySock = null;
  2032. }
  2033. }
  2034. onClosed_() {
  2035. if (!this.isClosed_) {
  2036. this.log_('WebSocket is closing itself');
  2037. this.shutdown_();
  2038. // since this is an internal close, trigger the close listener
  2039. if (this.onDisconnect) {
  2040. this.onDisconnect(this.everConnected_);
  2041. this.onDisconnect = null;
  2042. }
  2043. }
  2044. }
  2045. /**
  2046. * External-facing close handler.
  2047. * Close the websocket and kill the connection.
  2048. */
  2049. close() {
  2050. if (!this.isClosed_) {
  2051. this.log_('WebSocket is being closed');
  2052. this.shutdown_();
  2053. }
  2054. }
  2055. /**
  2056. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  2057. * the last activity.
  2058. */
  2059. resetKeepAlive() {
  2060. clearInterval(this.keepaliveTimer);
  2061. this.keepaliveTimer = setInterval(() => {
  2062. //If there has been no websocket activity for a while, send a no-op
  2063. if (this.mySock) {
  2064. this.sendString_('0');
  2065. }
  2066. this.resetKeepAlive();
  2067. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2068. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  2069. }
  2070. /**
  2071. * Send a string over the websocket.
  2072. *
  2073. * @param str - String to send.
  2074. */
  2075. sendString_(str) {
  2076. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  2077. // calls for some unknown reason. We treat these as an error and disconnect.
  2078. // See https://app.asana.com/0/58926111402292/68021340250410
  2079. try {
  2080. this.mySock.send(str);
  2081. }
  2082. catch (e) {
  2083. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  2084. setTimeout(this.onClosed_.bind(this), 0);
  2085. }
  2086. }
  2087. }
  2088. /**
  2089. * Number of response before we consider the connection "healthy."
  2090. */
  2091. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  2092. /**
  2093. * Time to wait for the connection te become healthy before giving up.
  2094. */
  2095. WebSocketConnection.healthyTimeout = 30000;
  2096. /**
  2097. * @license
  2098. * Copyright 2017 Google LLC
  2099. *
  2100. * Licensed under the Apache License, Version 2.0 (the "License");
  2101. * you may not use this file except in compliance with the License.
  2102. * You may obtain a copy of the License at
  2103. *
  2104. * http://www.apache.org/licenses/LICENSE-2.0
  2105. *
  2106. * Unless required by applicable law or agreed to in writing, software
  2107. * distributed under the License is distributed on an "AS IS" BASIS,
  2108. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2109. * See the License for the specific language governing permissions and
  2110. * limitations under the License.
  2111. */
  2112. /**
  2113. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2114. * lifecycle.
  2115. *
  2116. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2117. * they are available.
  2118. */
  2119. class TransportManager {
  2120. /**
  2121. * @param repoInfo - Metadata around the namespace we're connecting to
  2122. */
  2123. constructor(repoInfo) {
  2124. this.initTransports_(repoInfo);
  2125. }
  2126. static get ALL_TRANSPORTS() {
  2127. return [BrowserPollConnection, WebSocketConnection];
  2128. }
  2129. /**
  2130. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2131. * TransportManager has already set up transports_
  2132. */
  2133. static get IS_TRANSPORT_INITIALIZED() {
  2134. return this.globalTransportInitialized_;
  2135. }
  2136. initTransports_(repoInfo) {
  2137. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2138. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2139. if (repoInfo.webSocketOnly) {
  2140. if (!isWebSocketsAvailable) {
  2141. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2142. }
  2143. isSkipPollConnection = true;
  2144. }
  2145. if (isSkipPollConnection) {
  2146. this.transports_ = [WebSocketConnection];
  2147. }
  2148. else {
  2149. const transports = (this.transports_ = []);
  2150. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2151. if (transport && transport['isAvailable']()) {
  2152. transports.push(transport);
  2153. }
  2154. }
  2155. TransportManager.globalTransportInitialized_ = true;
  2156. }
  2157. }
  2158. /**
  2159. * @returns The constructor for the initial transport to use
  2160. */
  2161. initialTransport() {
  2162. if (this.transports_.length > 0) {
  2163. return this.transports_[0];
  2164. }
  2165. else {
  2166. throw new Error('No transports available');
  2167. }
  2168. }
  2169. /**
  2170. * @returns The constructor for the next transport, or null
  2171. */
  2172. upgradeTransport() {
  2173. if (this.transports_.length > 1) {
  2174. return this.transports_[1];
  2175. }
  2176. else {
  2177. return null;
  2178. }
  2179. }
  2180. }
  2181. // Keeps track of whether the TransportManager has already chosen a transport to use
  2182. TransportManager.globalTransportInitialized_ = false;
  2183. /**
  2184. * @license
  2185. * Copyright 2017 Google LLC
  2186. *
  2187. * Licensed under the Apache License, Version 2.0 (the "License");
  2188. * you may not use this file except in compliance with the License.
  2189. * You may obtain a copy of the License at
  2190. *
  2191. * http://www.apache.org/licenses/LICENSE-2.0
  2192. *
  2193. * Unless required by applicable law or agreed to in writing, software
  2194. * distributed under the License is distributed on an "AS IS" BASIS,
  2195. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2196. * See the License for the specific language governing permissions and
  2197. * limitations under the License.
  2198. */
  2199. // Abort upgrade attempt if it takes longer than 60s.
  2200. const UPGRADE_TIMEOUT = 60000;
  2201. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2202. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2203. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2204. // If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)
  2205. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2206. // but we've sent/received enough bytes, we don't cancel the connection.
  2207. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2208. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2209. const MESSAGE_TYPE = 't';
  2210. const MESSAGE_DATA = 'd';
  2211. const CONTROL_SHUTDOWN = 's';
  2212. const CONTROL_RESET = 'r';
  2213. const CONTROL_ERROR = 'e';
  2214. const CONTROL_PONG = 'o';
  2215. const SWITCH_ACK = 'a';
  2216. const END_TRANSMISSION = 'n';
  2217. const PING = 'p';
  2218. const SERVER_HELLO = 'h';
  2219. /**
  2220. * Creates a new real-time connection to the server using whichever method works
  2221. * best in the current browser.
  2222. */
  2223. class Connection {
  2224. /**
  2225. * @param id - an id for this connection
  2226. * @param repoInfo_ - the info for the endpoint to connect to
  2227. * @param applicationId_ - the Firebase App ID for this project
  2228. * @param appCheckToken_ - The App Check Token for this device.
  2229. * @param authToken_ - The auth token for this session.
  2230. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2231. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2232. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2233. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2234. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2235. */
  2236. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2237. this.id = id;
  2238. this.repoInfo_ = repoInfo_;
  2239. this.applicationId_ = applicationId_;
  2240. this.appCheckToken_ = appCheckToken_;
  2241. this.authToken_ = authToken_;
  2242. this.onMessage_ = onMessage_;
  2243. this.onReady_ = onReady_;
  2244. this.onDisconnect_ = onDisconnect_;
  2245. this.onKill_ = onKill_;
  2246. this.lastSessionId = lastSessionId;
  2247. this.connectionCount = 0;
  2248. this.pendingDataMessages = [];
  2249. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2250. this.log_ = logWrapper('c:' + this.id + ':');
  2251. this.transportManager_ = new TransportManager(repoInfo_);
  2252. this.log_('Connection created');
  2253. this.start_();
  2254. }
  2255. /**
  2256. * Starts a connection attempt
  2257. */
  2258. start_() {
  2259. const conn = this.transportManager_.initialTransport();
  2260. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2261. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2262. // can consider the transport healthy.
  2263. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2264. const onMessageReceived = this.connReceiver_(this.conn_);
  2265. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2266. this.tx_ = this.conn_;
  2267. this.rx_ = this.conn_;
  2268. this.secondaryConn_ = null;
  2269. this.isHealthy_ = false;
  2270. /*
  2271. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2272. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2273. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2274. * still have the context of your originating frame.
  2275. */
  2276. setTimeout(() => {
  2277. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2278. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2279. }, Math.floor(0));
  2280. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2281. if (healthyTimeoutMS > 0) {
  2282. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2283. this.healthyTimeout_ = null;
  2284. if (!this.isHealthy_) {
  2285. if (this.conn_ &&
  2286. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2287. this.log_('Connection exceeded healthy timeout but has received ' +
  2288. this.conn_.bytesReceived +
  2289. ' bytes. Marking connection healthy.');
  2290. this.isHealthy_ = true;
  2291. this.conn_.markConnectionHealthy();
  2292. }
  2293. else if (this.conn_ &&
  2294. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2295. this.log_('Connection exceeded healthy timeout but has sent ' +
  2296. this.conn_.bytesSent +
  2297. ' bytes. Leaving connection alive.');
  2298. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2299. // the server.
  2300. }
  2301. else {
  2302. this.log_('Closing unhealthy connection after timeout.');
  2303. this.close();
  2304. }
  2305. }
  2306. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2307. }, Math.floor(healthyTimeoutMS));
  2308. }
  2309. }
  2310. nextTransportId_() {
  2311. return 'c:' + this.id + ':' + this.connectionCount++;
  2312. }
  2313. disconnReceiver_(conn) {
  2314. return everConnected => {
  2315. if (conn === this.conn_) {
  2316. this.onConnectionLost_(everConnected);
  2317. }
  2318. else if (conn === this.secondaryConn_) {
  2319. this.log_('Secondary connection lost.');
  2320. this.onSecondaryConnectionLost_();
  2321. }
  2322. else {
  2323. this.log_('closing an old connection');
  2324. }
  2325. };
  2326. }
  2327. connReceiver_(conn) {
  2328. return (message) => {
  2329. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2330. if (conn === this.rx_) {
  2331. this.onPrimaryMessageReceived_(message);
  2332. }
  2333. else if (conn === this.secondaryConn_) {
  2334. this.onSecondaryMessageReceived_(message);
  2335. }
  2336. else {
  2337. this.log_('message on old connection');
  2338. }
  2339. }
  2340. };
  2341. }
  2342. /**
  2343. * @param dataMsg - An arbitrary data message to be sent to the server
  2344. */
  2345. sendRequest(dataMsg) {
  2346. // wrap in a data message envelope and send it on
  2347. const msg = { t: 'd', d: dataMsg };
  2348. this.sendData_(msg);
  2349. }
  2350. tryCleanupConnection() {
  2351. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2352. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2353. this.conn_ = this.secondaryConn_;
  2354. this.secondaryConn_ = null;
  2355. // the server will shutdown the old connection
  2356. }
  2357. }
  2358. onSecondaryControl_(controlData) {
  2359. if (MESSAGE_TYPE in controlData) {
  2360. const cmd = controlData[MESSAGE_TYPE];
  2361. if (cmd === SWITCH_ACK) {
  2362. this.upgradeIfSecondaryHealthy_();
  2363. }
  2364. else if (cmd === CONTROL_RESET) {
  2365. // Most likely the session wasn't valid. Abandon the switch attempt
  2366. this.log_('Got a reset on secondary, closing it');
  2367. this.secondaryConn_.close();
  2368. // If we were already using this connection for something, than we need to fully close
  2369. if (this.tx_ === this.secondaryConn_ ||
  2370. this.rx_ === this.secondaryConn_) {
  2371. this.close();
  2372. }
  2373. }
  2374. else if (cmd === CONTROL_PONG) {
  2375. this.log_('got pong on secondary.');
  2376. this.secondaryResponsesRequired_--;
  2377. this.upgradeIfSecondaryHealthy_();
  2378. }
  2379. }
  2380. }
  2381. onSecondaryMessageReceived_(parsedData) {
  2382. const layer = requireKey('t', parsedData);
  2383. const data = requireKey('d', parsedData);
  2384. if (layer === 'c') {
  2385. this.onSecondaryControl_(data);
  2386. }
  2387. else if (layer === 'd') {
  2388. // got a data message, but we're still second connection. Need to buffer it up
  2389. this.pendingDataMessages.push(data);
  2390. }
  2391. else {
  2392. throw new Error('Unknown protocol layer: ' + layer);
  2393. }
  2394. }
  2395. upgradeIfSecondaryHealthy_() {
  2396. if (this.secondaryResponsesRequired_ <= 0) {
  2397. this.log_('Secondary connection is healthy.');
  2398. this.isHealthy_ = true;
  2399. this.secondaryConn_.markConnectionHealthy();
  2400. this.proceedWithUpgrade_();
  2401. }
  2402. else {
  2403. // Send a ping to make sure the connection is healthy.
  2404. this.log_('sending ping on secondary.');
  2405. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2406. }
  2407. }
  2408. proceedWithUpgrade_() {
  2409. // tell this connection to consider itself open
  2410. this.secondaryConn_.start();
  2411. // send ack
  2412. this.log_('sending client ack on secondary');
  2413. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2414. // send end packet on primary transport, switch to sending on this one
  2415. // can receive on this one, buffer responses until end received on primary transport
  2416. this.log_('Ending transmission on primary');
  2417. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2418. this.tx_ = this.secondaryConn_;
  2419. this.tryCleanupConnection();
  2420. }
  2421. onPrimaryMessageReceived_(parsedData) {
  2422. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2423. const layer = requireKey('t', parsedData);
  2424. const data = requireKey('d', parsedData);
  2425. if (layer === 'c') {
  2426. this.onControl_(data);
  2427. }
  2428. else if (layer === 'd') {
  2429. this.onDataMessage_(data);
  2430. }
  2431. }
  2432. onDataMessage_(message) {
  2433. this.onPrimaryResponse_();
  2434. // We don't do anything with data messages, just kick them up a level
  2435. this.onMessage_(message);
  2436. }
  2437. onPrimaryResponse_() {
  2438. if (!this.isHealthy_) {
  2439. this.primaryResponsesRequired_--;
  2440. if (this.primaryResponsesRequired_ <= 0) {
  2441. this.log_('Primary connection is healthy.');
  2442. this.isHealthy_ = true;
  2443. this.conn_.markConnectionHealthy();
  2444. }
  2445. }
  2446. }
  2447. onControl_(controlData) {
  2448. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2449. if (MESSAGE_DATA in controlData) {
  2450. const payload = controlData[MESSAGE_DATA];
  2451. if (cmd === SERVER_HELLO) {
  2452. const handshakePayload = Object.assign({}, payload);
  2453. if (this.repoInfo_.isUsingEmulator) {
  2454. // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.
  2455. handshakePayload.h = this.repoInfo_.host;
  2456. }
  2457. this.onHandshake_(handshakePayload);
  2458. }
  2459. else if (cmd === END_TRANSMISSION) {
  2460. this.log_('recvd end transmission on primary');
  2461. this.rx_ = this.secondaryConn_;
  2462. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2463. this.onDataMessage_(this.pendingDataMessages[i]);
  2464. }
  2465. this.pendingDataMessages = [];
  2466. this.tryCleanupConnection();
  2467. }
  2468. else if (cmd === CONTROL_SHUTDOWN) {
  2469. // This was previously the 'onKill' callback passed to the lower-level connection
  2470. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2471. this.onConnectionShutdown_(payload);
  2472. }
  2473. else if (cmd === CONTROL_RESET) {
  2474. // payload in this case is the host we should contact
  2475. this.onReset_(payload);
  2476. }
  2477. else if (cmd === CONTROL_ERROR) {
  2478. error('Server Error: ' + payload);
  2479. }
  2480. else if (cmd === CONTROL_PONG) {
  2481. this.log_('got pong on primary.');
  2482. this.onPrimaryResponse_();
  2483. this.sendPingOnPrimaryIfNecessary_();
  2484. }
  2485. else {
  2486. error('Unknown control packet command: ' + cmd);
  2487. }
  2488. }
  2489. }
  2490. /**
  2491. * @param handshake - The handshake data returned from the server
  2492. */
  2493. onHandshake_(handshake) {
  2494. const timestamp = handshake.ts;
  2495. const version = handshake.v;
  2496. const host = handshake.h;
  2497. this.sessionId = handshake.s;
  2498. this.repoInfo_.host = host;
  2499. // if we've already closed the connection, then don't bother trying to progress further
  2500. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2501. this.conn_.start();
  2502. this.onConnectionEstablished_(this.conn_, timestamp);
  2503. if (PROTOCOL_VERSION !== version) {
  2504. warn('Protocol version mismatch detected');
  2505. }
  2506. // TODO: do we want to upgrade? when? maybe a delay?
  2507. this.tryStartUpgrade_();
  2508. }
  2509. }
  2510. tryStartUpgrade_() {
  2511. const conn = this.transportManager_.upgradeTransport();
  2512. if (conn) {
  2513. this.startUpgrade_(conn);
  2514. }
  2515. }
  2516. startUpgrade_(conn) {
  2517. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2518. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2519. // can consider the transport healthy.
  2520. this.secondaryResponsesRequired_ =
  2521. conn['responsesRequiredToBeHealthy'] || 0;
  2522. const onMessage = this.connReceiver_(this.secondaryConn_);
  2523. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2524. this.secondaryConn_.open(onMessage, onDisconnect);
  2525. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2526. setTimeoutNonBlocking(() => {
  2527. if (this.secondaryConn_) {
  2528. this.log_('Timed out trying to upgrade.');
  2529. this.secondaryConn_.close();
  2530. }
  2531. }, Math.floor(UPGRADE_TIMEOUT));
  2532. }
  2533. onReset_(host) {
  2534. this.log_('Reset packet received. New host: ' + host);
  2535. this.repoInfo_.host = host;
  2536. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2537. // We don't currently support resets after the connection has already been established
  2538. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2539. this.close();
  2540. }
  2541. else {
  2542. // Close whatever connections we have open and start again.
  2543. this.closeConnections_();
  2544. this.start_();
  2545. }
  2546. }
  2547. onConnectionEstablished_(conn, timestamp) {
  2548. this.log_('Realtime connection established.');
  2549. this.conn_ = conn;
  2550. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2551. if (this.onReady_) {
  2552. this.onReady_(timestamp, this.sessionId);
  2553. this.onReady_ = null;
  2554. }
  2555. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2556. // send some pings.
  2557. if (this.primaryResponsesRequired_ === 0) {
  2558. this.log_('Primary connection is healthy.');
  2559. this.isHealthy_ = true;
  2560. }
  2561. else {
  2562. setTimeoutNonBlocking(() => {
  2563. this.sendPingOnPrimaryIfNecessary_();
  2564. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2565. }
  2566. }
  2567. sendPingOnPrimaryIfNecessary_() {
  2568. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2569. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2570. this.log_('sending ping on primary.');
  2571. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2572. }
  2573. }
  2574. onSecondaryConnectionLost_() {
  2575. const conn = this.secondaryConn_;
  2576. this.secondaryConn_ = null;
  2577. if (this.tx_ === conn || this.rx_ === conn) {
  2578. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2579. this.close();
  2580. }
  2581. }
  2582. /**
  2583. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2584. * we should flush the host cache
  2585. */
  2586. onConnectionLost_(everConnected) {
  2587. this.conn_ = null;
  2588. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2589. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2590. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2591. this.log_('Realtime connection failed.');
  2592. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2593. if (this.repoInfo_.isCacheableHost()) {
  2594. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2595. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2596. this.repoInfo_.internalHost = this.repoInfo_.host;
  2597. }
  2598. }
  2599. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2600. this.log_('Realtime connection lost.');
  2601. }
  2602. this.close();
  2603. }
  2604. onConnectionShutdown_(reason) {
  2605. this.log_('Connection shutdown command received. Shutting down...');
  2606. if (this.onKill_) {
  2607. this.onKill_(reason);
  2608. this.onKill_ = null;
  2609. }
  2610. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2611. // so clear the callback.
  2612. this.onDisconnect_ = null;
  2613. this.close();
  2614. }
  2615. sendData_(data) {
  2616. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2617. throw 'Connection is not connected';
  2618. }
  2619. else {
  2620. this.tx_.send(data);
  2621. }
  2622. }
  2623. /**
  2624. * Cleans up this connection, calling the appropriate callbacks
  2625. */
  2626. close() {
  2627. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2628. this.log_('Closing realtime connection.');
  2629. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2630. this.closeConnections_();
  2631. if (this.onDisconnect_) {
  2632. this.onDisconnect_();
  2633. this.onDisconnect_ = null;
  2634. }
  2635. }
  2636. }
  2637. closeConnections_() {
  2638. this.log_('Shutting down all connections');
  2639. if (this.conn_) {
  2640. this.conn_.close();
  2641. this.conn_ = null;
  2642. }
  2643. if (this.secondaryConn_) {
  2644. this.secondaryConn_.close();
  2645. this.secondaryConn_ = null;
  2646. }
  2647. if (this.healthyTimeout_) {
  2648. clearTimeout(this.healthyTimeout_);
  2649. this.healthyTimeout_ = null;
  2650. }
  2651. }
  2652. }
  2653. /**
  2654. * @license
  2655. * Copyright 2017 Google LLC
  2656. *
  2657. * Licensed under the Apache License, Version 2.0 (the "License");
  2658. * you may not use this file except in compliance with the License.
  2659. * You may obtain a copy of the License at
  2660. *
  2661. * http://www.apache.org/licenses/LICENSE-2.0
  2662. *
  2663. * Unless required by applicable law or agreed to in writing, software
  2664. * distributed under the License is distributed on an "AS IS" BASIS,
  2665. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2666. * See the License for the specific language governing permissions and
  2667. * limitations under the License.
  2668. */
  2669. /**
  2670. * Interface defining the set of actions that can be performed against the Firebase server
  2671. * (basically corresponds to our wire protocol).
  2672. *
  2673. * @interface
  2674. */
  2675. class ServerActions {
  2676. put(pathString, data, onComplete, hash) { }
  2677. merge(pathString, data, onComplete, hash) { }
  2678. /**
  2679. * Refreshes the auth token for the current connection.
  2680. * @param token - The authentication token
  2681. */
  2682. refreshAuthToken(token) { }
  2683. /**
  2684. * Refreshes the app check token for the current connection.
  2685. * @param token The app check token
  2686. */
  2687. refreshAppCheckToken(token) { }
  2688. onDisconnectPut(pathString, data, onComplete) { }
  2689. onDisconnectMerge(pathString, data, onComplete) { }
  2690. onDisconnectCancel(pathString, onComplete) { }
  2691. reportStats(stats) { }
  2692. }
  2693. /**
  2694. * @license
  2695. * Copyright 2017 Google LLC
  2696. *
  2697. * Licensed under the Apache License, Version 2.0 (the "License");
  2698. * you may not use this file except in compliance with the License.
  2699. * You may obtain a copy of the License at
  2700. *
  2701. * http://www.apache.org/licenses/LICENSE-2.0
  2702. *
  2703. * Unless required by applicable law or agreed to in writing, software
  2704. * distributed under the License is distributed on an "AS IS" BASIS,
  2705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2706. * See the License for the specific language governing permissions and
  2707. * limitations under the License.
  2708. */
  2709. /**
  2710. * Base class to be used if you want to emit events. Call the constructor with
  2711. * the set of allowed event names.
  2712. */
  2713. class EventEmitter {
  2714. constructor(allowedEvents_) {
  2715. this.allowedEvents_ = allowedEvents_;
  2716. this.listeners_ = {};
  2717. assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2718. }
  2719. /**
  2720. * To be called by derived classes to trigger events.
  2721. */
  2722. trigger(eventType, ...varArgs) {
  2723. if (Array.isArray(this.listeners_[eventType])) {
  2724. // Clone the list, since callbacks could add/remove listeners.
  2725. const listeners = [...this.listeners_[eventType]];
  2726. for (let i = 0; i < listeners.length; i++) {
  2727. listeners[i].callback.apply(listeners[i].context, varArgs);
  2728. }
  2729. }
  2730. }
  2731. on(eventType, callback, context) {
  2732. this.validateEventType_(eventType);
  2733. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2734. this.listeners_[eventType].push({ callback, context });
  2735. const eventData = this.getInitialEvent(eventType);
  2736. if (eventData) {
  2737. callback.apply(context, eventData);
  2738. }
  2739. }
  2740. off(eventType, callback, context) {
  2741. this.validateEventType_(eventType);
  2742. const listeners = this.listeners_[eventType] || [];
  2743. for (let i = 0; i < listeners.length; i++) {
  2744. if (listeners[i].callback === callback &&
  2745. (!context || context === listeners[i].context)) {
  2746. listeners.splice(i, 1);
  2747. return;
  2748. }
  2749. }
  2750. }
  2751. validateEventType_(eventType) {
  2752. assert(this.allowedEvents_.find(et => {
  2753. return et === eventType;
  2754. }), 'Unknown event: ' + eventType);
  2755. }
  2756. }
  2757. /**
  2758. * @license
  2759. * Copyright 2017 Google LLC
  2760. *
  2761. * Licensed under the Apache License, Version 2.0 (the "License");
  2762. * you may not use this file except in compliance with the License.
  2763. * You may obtain a copy of the License at
  2764. *
  2765. * http://www.apache.org/licenses/LICENSE-2.0
  2766. *
  2767. * Unless required by applicable law or agreed to in writing, software
  2768. * distributed under the License is distributed on an "AS IS" BASIS,
  2769. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2770. * See the License for the specific language governing permissions and
  2771. * limitations under the License.
  2772. */
  2773. /**
  2774. * Monitors online state (as reported by window.online/offline events).
  2775. *
  2776. * The expectation is that this could have many false positives (thinks we are online
  2777. * when we're not), but no false negatives. So we can safely use it to determine when
  2778. * we definitely cannot reach the internet.
  2779. */
  2780. class OnlineMonitor extends EventEmitter {
  2781. constructor() {
  2782. super(['online']);
  2783. this.online_ = true;
  2784. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2785. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2786. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2787. // for Cordova.
  2788. if (typeof window !== 'undefined' &&
  2789. typeof window.addEventListener !== 'undefined' &&
  2790. !isMobileCordova()) {
  2791. window.addEventListener('online', () => {
  2792. if (!this.online_) {
  2793. this.online_ = true;
  2794. this.trigger('online', true);
  2795. }
  2796. }, false);
  2797. window.addEventListener('offline', () => {
  2798. if (this.online_) {
  2799. this.online_ = false;
  2800. this.trigger('online', false);
  2801. }
  2802. }, false);
  2803. }
  2804. }
  2805. static getInstance() {
  2806. return new OnlineMonitor();
  2807. }
  2808. getInitialEvent(eventType) {
  2809. assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2810. return [this.online_];
  2811. }
  2812. currentlyOnline() {
  2813. return this.online_;
  2814. }
  2815. }
  2816. /**
  2817. * @license
  2818. * Copyright 2017 Google LLC
  2819. *
  2820. * Licensed under the Apache License, Version 2.0 (the "License");
  2821. * you may not use this file except in compliance with the License.
  2822. * You may obtain a copy of the License at
  2823. *
  2824. * http://www.apache.org/licenses/LICENSE-2.0
  2825. *
  2826. * Unless required by applicable law or agreed to in writing, software
  2827. * distributed under the License is distributed on an "AS IS" BASIS,
  2828. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2829. * See the License for the specific language governing permissions and
  2830. * limitations under the License.
  2831. */
  2832. /** Maximum key depth. */
  2833. const MAX_PATH_DEPTH = 32;
  2834. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2835. const MAX_PATH_LENGTH_BYTES = 768;
  2836. /**
  2837. * An immutable object representing a parsed path. It's immutable so that you
  2838. * can pass them around to other functions without worrying about them changing
  2839. * it.
  2840. */
  2841. class Path {
  2842. /**
  2843. * @param pathOrString - Path string to parse, or another path, or the raw
  2844. * tokens array
  2845. */
  2846. constructor(pathOrString, pieceNum) {
  2847. if (pieceNum === void 0) {
  2848. this.pieces_ = pathOrString.split('/');
  2849. // Remove empty pieces.
  2850. let copyTo = 0;
  2851. for (let i = 0; i < this.pieces_.length; i++) {
  2852. if (this.pieces_[i].length > 0) {
  2853. this.pieces_[copyTo] = this.pieces_[i];
  2854. copyTo++;
  2855. }
  2856. }
  2857. this.pieces_.length = copyTo;
  2858. this.pieceNum_ = 0;
  2859. }
  2860. else {
  2861. this.pieces_ = pathOrString;
  2862. this.pieceNum_ = pieceNum;
  2863. }
  2864. }
  2865. toString() {
  2866. let pathString = '';
  2867. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2868. if (this.pieces_[i] !== '') {
  2869. pathString += '/' + this.pieces_[i];
  2870. }
  2871. }
  2872. return pathString || '/';
  2873. }
  2874. }
  2875. function newEmptyPath() {
  2876. return new Path('');
  2877. }
  2878. function pathGetFront(path) {
  2879. if (path.pieceNum_ >= path.pieces_.length) {
  2880. return null;
  2881. }
  2882. return path.pieces_[path.pieceNum_];
  2883. }
  2884. /**
  2885. * @returns The number of segments in this path
  2886. */
  2887. function pathGetLength(path) {
  2888. return path.pieces_.length - path.pieceNum_;
  2889. }
  2890. function pathPopFront(path) {
  2891. let pieceNum = path.pieceNum_;
  2892. if (pieceNum < path.pieces_.length) {
  2893. pieceNum++;
  2894. }
  2895. return new Path(path.pieces_, pieceNum);
  2896. }
  2897. function pathGetBack(path) {
  2898. if (path.pieceNum_ < path.pieces_.length) {
  2899. return path.pieces_[path.pieces_.length - 1];
  2900. }
  2901. return null;
  2902. }
  2903. function pathToUrlEncodedString(path) {
  2904. let pathString = '';
  2905. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2906. if (path.pieces_[i] !== '') {
  2907. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2908. }
  2909. }
  2910. return pathString || '/';
  2911. }
  2912. /**
  2913. * Shallow copy of the parts of the path.
  2914. *
  2915. */
  2916. function pathSlice(path, begin = 0) {
  2917. return path.pieces_.slice(path.pieceNum_ + begin);
  2918. }
  2919. function pathParent(path) {
  2920. if (path.pieceNum_ >= path.pieces_.length) {
  2921. return null;
  2922. }
  2923. const pieces = [];
  2924. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2925. pieces.push(path.pieces_[i]);
  2926. }
  2927. return new Path(pieces, 0);
  2928. }
  2929. function pathChild(path, childPathObj) {
  2930. const pieces = [];
  2931. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2932. pieces.push(path.pieces_[i]);
  2933. }
  2934. if (childPathObj instanceof Path) {
  2935. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2936. pieces.push(childPathObj.pieces_[i]);
  2937. }
  2938. }
  2939. else {
  2940. const childPieces = childPathObj.split('/');
  2941. for (let i = 0; i < childPieces.length; i++) {
  2942. if (childPieces[i].length > 0) {
  2943. pieces.push(childPieces[i]);
  2944. }
  2945. }
  2946. }
  2947. return new Path(pieces, 0);
  2948. }
  2949. /**
  2950. * @returns True if there are no segments in this path
  2951. */
  2952. function pathIsEmpty(path) {
  2953. return path.pieceNum_ >= path.pieces_.length;
  2954. }
  2955. /**
  2956. * @returns The path from outerPath to innerPath
  2957. */
  2958. function newRelativePath(outerPath, innerPath) {
  2959. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2960. if (outer === null) {
  2961. return innerPath;
  2962. }
  2963. else if (outer === inner) {
  2964. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2965. }
  2966. else {
  2967. throw new Error('INTERNAL ERROR: innerPath (' +
  2968. innerPath +
  2969. ') is not within ' +
  2970. 'outerPath (' +
  2971. outerPath +
  2972. ')');
  2973. }
  2974. }
  2975. /**
  2976. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2977. */
  2978. function pathCompare(left, right) {
  2979. const leftKeys = pathSlice(left, 0);
  2980. const rightKeys = pathSlice(right, 0);
  2981. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2982. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2983. if (cmp !== 0) {
  2984. return cmp;
  2985. }
  2986. }
  2987. if (leftKeys.length === rightKeys.length) {
  2988. return 0;
  2989. }
  2990. return leftKeys.length < rightKeys.length ? -1 : 1;
  2991. }
  2992. /**
  2993. * @returns true if paths are the same.
  2994. */
  2995. function pathEquals(path, other) {
  2996. if (pathGetLength(path) !== pathGetLength(other)) {
  2997. return false;
  2998. }
  2999. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3000. if (path.pieces_[i] !== other.pieces_[j]) {
  3001. return false;
  3002. }
  3003. }
  3004. return true;
  3005. }
  3006. /**
  3007. * @returns True if this path is a parent of (or the same as) other
  3008. */
  3009. function pathContains(path, other) {
  3010. let i = path.pieceNum_;
  3011. let j = other.pieceNum_;
  3012. if (pathGetLength(path) > pathGetLength(other)) {
  3013. return false;
  3014. }
  3015. while (i < path.pieces_.length) {
  3016. if (path.pieces_[i] !== other.pieces_[j]) {
  3017. return false;
  3018. }
  3019. ++i;
  3020. ++j;
  3021. }
  3022. return true;
  3023. }
  3024. /**
  3025. * Dynamic (mutable) path used to count path lengths.
  3026. *
  3027. * This class is used to efficiently check paths for valid
  3028. * length (in UTF8 bytes) and depth (used in path validation).
  3029. *
  3030. * Throws Error exception if path is ever invalid.
  3031. *
  3032. * The definition of a path always begins with '/'.
  3033. */
  3034. class ValidationPath {
  3035. /**
  3036. * @param path - Initial Path.
  3037. * @param errorPrefix_ - Prefix for any error messages.
  3038. */
  3039. constructor(path, errorPrefix_) {
  3040. this.errorPrefix_ = errorPrefix_;
  3041. this.parts_ = pathSlice(path, 0);
  3042. /** Initialize to number of '/' chars needed in path. */
  3043. this.byteLength_ = Math.max(1, this.parts_.length);
  3044. for (let i = 0; i < this.parts_.length; i++) {
  3045. this.byteLength_ += stringLength(this.parts_[i]);
  3046. }
  3047. validationPathCheckValid(this);
  3048. }
  3049. }
  3050. function validationPathPush(validationPath, child) {
  3051. // Count the needed '/'
  3052. if (validationPath.parts_.length > 0) {
  3053. validationPath.byteLength_ += 1;
  3054. }
  3055. validationPath.parts_.push(child);
  3056. validationPath.byteLength_ += stringLength(child);
  3057. validationPathCheckValid(validationPath);
  3058. }
  3059. function validationPathPop(validationPath) {
  3060. const last = validationPath.parts_.pop();
  3061. validationPath.byteLength_ -= stringLength(last);
  3062. // Un-count the previous '/'
  3063. if (validationPath.parts_.length > 0) {
  3064. validationPath.byteLength_ -= 1;
  3065. }
  3066. }
  3067. function validationPathCheckValid(validationPath) {
  3068. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3069. throw new Error(validationPath.errorPrefix_ +
  3070. 'has a key path longer than ' +
  3071. MAX_PATH_LENGTH_BYTES +
  3072. ' bytes (' +
  3073. validationPath.byteLength_ +
  3074. ').');
  3075. }
  3076. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3077. throw new Error(validationPath.errorPrefix_ +
  3078. 'path specified exceeds the maximum depth that can be written (' +
  3079. MAX_PATH_DEPTH +
  3080. ') or object contains a cycle ' +
  3081. validationPathToErrorString(validationPath));
  3082. }
  3083. }
  3084. /**
  3085. * String for use in error messages - uses '.' notation for path.
  3086. */
  3087. function validationPathToErrorString(validationPath) {
  3088. if (validationPath.parts_.length === 0) {
  3089. return '';
  3090. }
  3091. return "in property '" + validationPath.parts_.join('.') + "'";
  3092. }
  3093. /**
  3094. * @license
  3095. * Copyright 2017 Google LLC
  3096. *
  3097. * Licensed under the Apache License, Version 2.0 (the "License");
  3098. * you may not use this file except in compliance with the License.
  3099. * You may obtain a copy of the License at
  3100. *
  3101. * http://www.apache.org/licenses/LICENSE-2.0
  3102. *
  3103. * Unless required by applicable law or agreed to in writing, software
  3104. * distributed under the License is distributed on an "AS IS" BASIS,
  3105. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3106. * See the License for the specific language governing permissions and
  3107. * limitations under the License.
  3108. */
  3109. class VisibilityMonitor extends EventEmitter {
  3110. constructor() {
  3111. super(['visible']);
  3112. let hidden;
  3113. let visibilityChange;
  3114. if (typeof document !== 'undefined' &&
  3115. typeof document.addEventListener !== 'undefined') {
  3116. if (typeof document['hidden'] !== 'undefined') {
  3117. // Opera 12.10 and Firefox 18 and later support
  3118. visibilityChange = 'visibilitychange';
  3119. hidden = 'hidden';
  3120. }
  3121. else if (typeof document['mozHidden'] !== 'undefined') {
  3122. visibilityChange = 'mozvisibilitychange';
  3123. hidden = 'mozHidden';
  3124. }
  3125. else if (typeof document['msHidden'] !== 'undefined') {
  3126. visibilityChange = 'msvisibilitychange';
  3127. hidden = 'msHidden';
  3128. }
  3129. else if (typeof document['webkitHidden'] !== 'undefined') {
  3130. visibilityChange = 'webkitvisibilitychange';
  3131. hidden = 'webkitHidden';
  3132. }
  3133. }
  3134. // Initially, we always assume we are visible. This ensures that in browsers
  3135. // without page visibility support or in cases where we are never visible
  3136. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3137. // reconnects
  3138. this.visible_ = true;
  3139. if (visibilityChange) {
  3140. document.addEventListener(visibilityChange, () => {
  3141. const visible = !document[hidden];
  3142. if (visible !== this.visible_) {
  3143. this.visible_ = visible;
  3144. this.trigger('visible', visible);
  3145. }
  3146. }, false);
  3147. }
  3148. }
  3149. static getInstance() {
  3150. return new VisibilityMonitor();
  3151. }
  3152. getInitialEvent(eventType) {
  3153. assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3154. return [this.visible_];
  3155. }
  3156. }
  3157. /**
  3158. * @license
  3159. * Copyright 2017 Google LLC
  3160. *
  3161. * Licensed under the Apache License, Version 2.0 (the "License");
  3162. * you may not use this file except in compliance with the License.
  3163. * You may obtain a copy of the License at
  3164. *
  3165. * http://www.apache.org/licenses/LICENSE-2.0
  3166. *
  3167. * Unless required by applicable law or agreed to in writing, software
  3168. * distributed under the License is distributed on an "AS IS" BASIS,
  3169. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3170. * See the License for the specific language governing permissions and
  3171. * limitations under the License.
  3172. */
  3173. const RECONNECT_MIN_DELAY = 1000;
  3174. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3175. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3176. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3177. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3178. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3179. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3180. const INVALID_TOKEN_THRESHOLD = 3;
  3181. /**
  3182. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3183. *
  3184. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3185. * in quotes to make sure the closure compiler does not minify them.
  3186. */
  3187. class PersistentConnection extends ServerActions {
  3188. /**
  3189. * @param repoInfo_ - Data about the namespace we are connecting to
  3190. * @param applicationId_ - The Firebase App ID for this project
  3191. * @param onDataUpdate_ - A callback for new data from the server
  3192. */
  3193. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3194. super();
  3195. this.repoInfo_ = repoInfo_;
  3196. this.applicationId_ = applicationId_;
  3197. this.onDataUpdate_ = onDataUpdate_;
  3198. this.onConnectStatus_ = onConnectStatus_;
  3199. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3200. this.authTokenProvider_ = authTokenProvider_;
  3201. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3202. this.authOverride_ = authOverride_;
  3203. // Used for diagnostic logging.
  3204. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3205. this.log_ = logWrapper('p:' + this.id + ':');
  3206. this.interruptReasons_ = {};
  3207. this.listens = new Map();
  3208. this.outstandingPuts_ = [];
  3209. this.outstandingGets_ = [];
  3210. this.outstandingPutCount_ = 0;
  3211. this.outstandingGetCount_ = 0;
  3212. this.onDisconnectRequestQueue_ = [];
  3213. this.connected_ = false;
  3214. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3215. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3216. this.securityDebugCallback_ = null;
  3217. this.lastSessionId = null;
  3218. this.establishConnectionTimer_ = null;
  3219. this.visible_ = false;
  3220. // Before we get connected, we keep a queue of pending messages to send.
  3221. this.requestCBHash_ = {};
  3222. this.requestNumber_ = 0;
  3223. this.realtime_ = null;
  3224. this.authToken_ = null;
  3225. this.appCheckToken_ = null;
  3226. this.forceTokenRefresh_ = false;
  3227. this.invalidAuthTokenCount_ = 0;
  3228. this.invalidAppCheckTokenCount_ = 0;
  3229. this.firstConnection_ = true;
  3230. this.lastConnectionAttemptTime_ = null;
  3231. this.lastConnectionEstablishedTime_ = null;
  3232. if (authOverride_ && !isNodeSdk()) {
  3233. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3234. }
  3235. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3236. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3237. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3238. }
  3239. }
  3240. sendRequest(action, body, onResponse) {
  3241. const curReqNum = ++this.requestNumber_;
  3242. const msg = { r: curReqNum, a: action, b: body };
  3243. this.log_(stringify(msg));
  3244. assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3245. this.realtime_.sendRequest(msg);
  3246. if (onResponse) {
  3247. this.requestCBHash_[curReqNum] = onResponse;
  3248. }
  3249. }
  3250. get(query) {
  3251. this.initConnection_();
  3252. const deferred = new Deferred();
  3253. const request = {
  3254. p: query._path.toString(),
  3255. q: query._queryObject
  3256. };
  3257. const outstandingGet = {
  3258. action: 'g',
  3259. request,
  3260. onComplete: (message) => {
  3261. const payload = message['d'];
  3262. if (message['s'] === 'ok') {
  3263. deferred.resolve(payload);
  3264. }
  3265. else {
  3266. deferred.reject(payload);
  3267. }
  3268. }
  3269. };
  3270. this.outstandingGets_.push(outstandingGet);
  3271. this.outstandingGetCount_++;
  3272. const index = this.outstandingGets_.length - 1;
  3273. if (this.connected_) {
  3274. this.sendGet_(index);
  3275. }
  3276. return deferred.promise;
  3277. }
  3278. listen(query, currentHashFn, tag, onComplete) {
  3279. this.initConnection_();
  3280. const queryId = query._queryIdentifier;
  3281. const pathString = query._path.toString();
  3282. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3283. if (!this.listens.has(pathString)) {
  3284. this.listens.set(pathString, new Map());
  3285. }
  3286. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3287. assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3288. const listenSpec = {
  3289. onComplete,
  3290. hashFn: currentHashFn,
  3291. query,
  3292. tag
  3293. };
  3294. this.listens.get(pathString).set(queryId, listenSpec);
  3295. if (this.connected_) {
  3296. this.sendListen_(listenSpec);
  3297. }
  3298. }
  3299. sendGet_(index) {
  3300. const get = this.outstandingGets_[index];
  3301. this.sendRequest('g', get.request, (message) => {
  3302. delete this.outstandingGets_[index];
  3303. this.outstandingGetCount_--;
  3304. if (this.outstandingGetCount_ === 0) {
  3305. this.outstandingGets_ = [];
  3306. }
  3307. if (get.onComplete) {
  3308. get.onComplete(message);
  3309. }
  3310. });
  3311. }
  3312. sendListen_(listenSpec) {
  3313. const query = listenSpec.query;
  3314. const pathString = query._path.toString();
  3315. const queryId = query._queryIdentifier;
  3316. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3317. const req = { /*path*/ p: pathString };
  3318. const action = 'q';
  3319. // Only bother to send query if it's non-default.
  3320. if (listenSpec.tag) {
  3321. req['q'] = query._queryObject;
  3322. req['t'] = listenSpec.tag;
  3323. }
  3324. req[ /*hash*/'h'] = listenSpec.hashFn();
  3325. this.sendRequest(action, req, (message) => {
  3326. const payload = message[ /*data*/'d'];
  3327. const status = message[ /*status*/'s'];
  3328. // print warnings in any case...
  3329. PersistentConnection.warnOnListenWarnings_(payload, query);
  3330. const currentListenSpec = this.listens.get(pathString) &&
  3331. this.listens.get(pathString).get(queryId);
  3332. // only trigger actions if the listen hasn't been removed and readded
  3333. if (currentListenSpec === listenSpec) {
  3334. this.log_('listen response', message);
  3335. if (status !== 'ok') {
  3336. this.removeListen_(pathString, queryId);
  3337. }
  3338. if (listenSpec.onComplete) {
  3339. listenSpec.onComplete(status, payload);
  3340. }
  3341. }
  3342. });
  3343. }
  3344. static warnOnListenWarnings_(payload, query) {
  3345. if (payload && typeof payload === 'object' && contains(payload, 'w')) {
  3346. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3347. const warnings = safeGet(payload, 'w');
  3348. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3349. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3350. const indexPath = query._path.toString();
  3351. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3352. `filtered on the client. Consider adding ${indexSpec} at ` +
  3353. `${indexPath} to your security rules for better performance.`);
  3354. }
  3355. }
  3356. }
  3357. refreshAuthToken(token) {
  3358. this.authToken_ = token;
  3359. this.log_('Auth token refreshed');
  3360. if (this.authToken_) {
  3361. this.tryAuth();
  3362. }
  3363. else {
  3364. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3365. //the credential so we dont become authenticated next time we connect.
  3366. if (this.connected_) {
  3367. this.sendRequest('unauth', {}, () => { });
  3368. }
  3369. }
  3370. this.reduceReconnectDelayIfAdminCredential_(token);
  3371. }
  3372. reduceReconnectDelayIfAdminCredential_(credential) {
  3373. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3374. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3375. const isFirebaseSecret = credential && credential.length === 40;
  3376. if (isFirebaseSecret || isAdmin(credential)) {
  3377. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3378. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3379. }
  3380. }
  3381. refreshAppCheckToken(token) {
  3382. this.appCheckToken_ = token;
  3383. this.log_('App check token refreshed');
  3384. if (this.appCheckToken_) {
  3385. this.tryAppCheck();
  3386. }
  3387. else {
  3388. //If we're connected we want to let the server know to unauthenticate us.
  3389. //If we're not connected, simply delete the credential so we dont become
  3390. // authenticated next time we connect.
  3391. if (this.connected_) {
  3392. this.sendRequest('unappeck', {}, () => { });
  3393. }
  3394. }
  3395. }
  3396. /**
  3397. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3398. * a auth revoked (the connection is closed).
  3399. */
  3400. tryAuth() {
  3401. if (this.connected_ && this.authToken_) {
  3402. const token = this.authToken_;
  3403. const authMethod = isValidFormat(token) ? 'auth' : 'gauth';
  3404. const requestData = { cred: token };
  3405. if (this.authOverride_ === null) {
  3406. requestData['noauth'] = true;
  3407. }
  3408. else if (typeof this.authOverride_ === 'object') {
  3409. requestData['authvar'] = this.authOverride_;
  3410. }
  3411. this.sendRequest(authMethod, requestData, (res) => {
  3412. const status = res[ /*status*/'s'];
  3413. const data = res[ /*data*/'d'] || 'error';
  3414. if (this.authToken_ === token) {
  3415. if (status === 'ok') {
  3416. this.invalidAuthTokenCount_ = 0;
  3417. }
  3418. else {
  3419. // Triggers reconnect and force refresh for auth token
  3420. this.onAuthRevoked_(status, data);
  3421. }
  3422. }
  3423. });
  3424. }
  3425. }
  3426. /**
  3427. * Attempts to authenticate with the given token. If the authentication
  3428. * attempt fails, it's triggered like the token was revoked (the connection is
  3429. * closed).
  3430. */
  3431. tryAppCheck() {
  3432. if (this.connected_ && this.appCheckToken_) {
  3433. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3434. const status = res[ /*status*/'s'];
  3435. const data = res[ /*data*/'d'] || 'error';
  3436. if (status === 'ok') {
  3437. this.invalidAppCheckTokenCount_ = 0;
  3438. }
  3439. else {
  3440. this.onAppCheckRevoked_(status, data);
  3441. }
  3442. });
  3443. }
  3444. }
  3445. /**
  3446. * @inheritDoc
  3447. */
  3448. unlisten(query, tag) {
  3449. const pathString = query._path.toString();
  3450. const queryId = query._queryIdentifier;
  3451. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3452. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3453. const listen = this.removeListen_(pathString, queryId);
  3454. if (listen && this.connected_) {
  3455. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3456. }
  3457. }
  3458. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3459. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3460. const req = { /*path*/ p: pathString };
  3461. const action = 'n';
  3462. // Only bother sending queryId if it's non-default.
  3463. if (tag) {
  3464. req['q'] = queryObj;
  3465. req['t'] = tag;
  3466. }
  3467. this.sendRequest(action, req);
  3468. }
  3469. onDisconnectPut(pathString, data, onComplete) {
  3470. this.initConnection_();
  3471. if (this.connected_) {
  3472. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3473. }
  3474. else {
  3475. this.onDisconnectRequestQueue_.push({
  3476. pathString,
  3477. action: 'o',
  3478. data,
  3479. onComplete
  3480. });
  3481. }
  3482. }
  3483. onDisconnectMerge(pathString, data, onComplete) {
  3484. this.initConnection_();
  3485. if (this.connected_) {
  3486. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3487. }
  3488. else {
  3489. this.onDisconnectRequestQueue_.push({
  3490. pathString,
  3491. action: 'om',
  3492. data,
  3493. onComplete
  3494. });
  3495. }
  3496. }
  3497. onDisconnectCancel(pathString, onComplete) {
  3498. this.initConnection_();
  3499. if (this.connected_) {
  3500. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3501. }
  3502. else {
  3503. this.onDisconnectRequestQueue_.push({
  3504. pathString,
  3505. action: 'oc',
  3506. data: null,
  3507. onComplete
  3508. });
  3509. }
  3510. }
  3511. sendOnDisconnect_(action, pathString, data, onComplete) {
  3512. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3513. this.log_('onDisconnect ' + action, request);
  3514. this.sendRequest(action, request, (response) => {
  3515. if (onComplete) {
  3516. setTimeout(() => {
  3517. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3518. }, Math.floor(0));
  3519. }
  3520. });
  3521. }
  3522. put(pathString, data, onComplete, hash) {
  3523. this.putInternal('p', pathString, data, onComplete, hash);
  3524. }
  3525. merge(pathString, data, onComplete, hash) {
  3526. this.putInternal('m', pathString, data, onComplete, hash);
  3527. }
  3528. putInternal(action, pathString, data, onComplete, hash) {
  3529. this.initConnection_();
  3530. const request = {
  3531. /*path*/ p: pathString,
  3532. /*data*/ d: data
  3533. };
  3534. if (hash !== undefined) {
  3535. request[ /*hash*/'h'] = hash;
  3536. }
  3537. // TODO: Only keep track of the most recent put for a given path?
  3538. this.outstandingPuts_.push({
  3539. action,
  3540. request,
  3541. onComplete
  3542. });
  3543. this.outstandingPutCount_++;
  3544. const index = this.outstandingPuts_.length - 1;
  3545. if (this.connected_) {
  3546. this.sendPut_(index);
  3547. }
  3548. else {
  3549. this.log_('Buffering put: ' + pathString);
  3550. }
  3551. }
  3552. sendPut_(index) {
  3553. const action = this.outstandingPuts_[index].action;
  3554. const request = this.outstandingPuts_[index].request;
  3555. const onComplete = this.outstandingPuts_[index].onComplete;
  3556. this.outstandingPuts_[index].queued = this.connected_;
  3557. this.sendRequest(action, request, (message) => {
  3558. this.log_(action + ' response', message);
  3559. delete this.outstandingPuts_[index];
  3560. this.outstandingPutCount_--;
  3561. // Clean up array occasionally.
  3562. if (this.outstandingPutCount_ === 0) {
  3563. this.outstandingPuts_ = [];
  3564. }
  3565. if (onComplete) {
  3566. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3567. }
  3568. });
  3569. }
  3570. reportStats(stats) {
  3571. // If we're not connected, we just drop the stats.
  3572. if (this.connected_) {
  3573. const request = { /*counters*/ c: stats };
  3574. this.log_('reportStats', request);
  3575. this.sendRequest(/*stats*/ 's', request, result => {
  3576. const status = result[ /*status*/'s'];
  3577. if (status !== 'ok') {
  3578. const errorReason = result[ /* data */'d'];
  3579. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3580. }
  3581. });
  3582. }
  3583. }
  3584. onDataMessage_(message) {
  3585. if ('r' in message) {
  3586. // this is a response
  3587. this.log_('from server: ' + stringify(message));
  3588. const reqNum = message['r'];
  3589. const onResponse = this.requestCBHash_[reqNum];
  3590. if (onResponse) {
  3591. delete this.requestCBHash_[reqNum];
  3592. onResponse(message[ /*body*/'b']);
  3593. }
  3594. }
  3595. else if ('error' in message) {
  3596. throw 'A server-side error has occurred: ' + message['error'];
  3597. }
  3598. else if ('a' in message) {
  3599. // a and b are action and body, respectively
  3600. this.onDataPush_(message['a'], message['b']);
  3601. }
  3602. }
  3603. onDataPush_(action, body) {
  3604. this.log_('handleServerMessage', action, body);
  3605. if (action === 'd') {
  3606. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3607. /*isMerge*/ false, body['t']);
  3608. }
  3609. else if (action === 'm') {
  3610. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3611. /*isMerge=*/ true, body['t']);
  3612. }
  3613. else if (action === 'c') {
  3614. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3615. }
  3616. else if (action === 'ac') {
  3617. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3618. }
  3619. else if (action === 'apc') {
  3620. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3621. }
  3622. else if (action === 'sd') {
  3623. this.onSecurityDebugPacket_(body);
  3624. }
  3625. else {
  3626. error('Unrecognized action received from server: ' +
  3627. stringify(action) +
  3628. '\nAre you using the latest client?');
  3629. }
  3630. }
  3631. onReady_(timestamp, sessionId) {
  3632. this.log_('connection ready');
  3633. this.connected_ = true;
  3634. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3635. this.handleTimestamp_(timestamp);
  3636. this.lastSessionId = sessionId;
  3637. if (this.firstConnection_) {
  3638. this.sendConnectStats_();
  3639. }
  3640. this.restoreState_();
  3641. this.firstConnection_ = false;
  3642. this.onConnectStatus_(true);
  3643. }
  3644. scheduleConnect_(timeout) {
  3645. assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3646. if (this.establishConnectionTimer_) {
  3647. clearTimeout(this.establishConnectionTimer_);
  3648. }
  3649. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3650. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3651. this.establishConnectionTimer_ = setTimeout(() => {
  3652. this.establishConnectionTimer_ = null;
  3653. this.establishConnection_();
  3654. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3655. }, Math.floor(timeout));
  3656. }
  3657. initConnection_() {
  3658. if (!this.realtime_ && this.firstConnection_) {
  3659. this.scheduleConnect_(0);
  3660. }
  3661. }
  3662. onVisible_(visible) {
  3663. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3664. if (visible &&
  3665. !this.visible_ &&
  3666. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3667. this.log_('Window became visible. Reducing delay.');
  3668. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3669. if (!this.realtime_) {
  3670. this.scheduleConnect_(0);
  3671. }
  3672. }
  3673. this.visible_ = visible;
  3674. }
  3675. onOnline_(online) {
  3676. if (online) {
  3677. this.log_('Browser went online.');
  3678. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3679. if (!this.realtime_) {
  3680. this.scheduleConnect_(0);
  3681. }
  3682. }
  3683. else {
  3684. this.log_('Browser went offline. Killing connection.');
  3685. if (this.realtime_) {
  3686. this.realtime_.close();
  3687. }
  3688. }
  3689. }
  3690. onRealtimeDisconnect_() {
  3691. this.log_('data client disconnected');
  3692. this.connected_ = false;
  3693. this.realtime_ = null;
  3694. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3695. this.cancelSentTransactions_();
  3696. // Clear out the pending requests.
  3697. this.requestCBHash_ = {};
  3698. if (this.shouldReconnect_()) {
  3699. if (!this.visible_) {
  3700. this.log_("Window isn't visible. Delaying reconnect.");
  3701. this.reconnectDelay_ = this.maxReconnectDelay_;
  3702. this.lastConnectionAttemptTime_ = new Date().getTime();
  3703. }
  3704. else if (this.lastConnectionEstablishedTime_) {
  3705. // If we've been connected long enough, reset reconnect delay to minimum.
  3706. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3707. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3708. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3709. }
  3710. this.lastConnectionEstablishedTime_ = null;
  3711. }
  3712. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3713. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3714. reconnectDelay = Math.random() * reconnectDelay;
  3715. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3716. this.scheduleConnect_(reconnectDelay);
  3717. // Adjust reconnect delay for next time.
  3718. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3719. }
  3720. this.onConnectStatus_(false);
  3721. }
  3722. async establishConnection_() {
  3723. if (this.shouldReconnect_()) {
  3724. this.log_('Making a connection attempt');
  3725. this.lastConnectionAttemptTime_ = new Date().getTime();
  3726. this.lastConnectionEstablishedTime_ = null;
  3727. const onDataMessage = this.onDataMessage_.bind(this);
  3728. const onReady = this.onReady_.bind(this);
  3729. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3730. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3731. const lastSessionId = this.lastSessionId;
  3732. let canceled = false;
  3733. let connection = null;
  3734. const closeFn = function () {
  3735. if (connection) {
  3736. connection.close();
  3737. }
  3738. else {
  3739. canceled = true;
  3740. onDisconnect();
  3741. }
  3742. };
  3743. const sendRequestFn = function (msg) {
  3744. assert(connection, "sendRequest call when we're not connected not allowed.");
  3745. connection.sendRequest(msg);
  3746. };
  3747. this.realtime_ = {
  3748. close: closeFn,
  3749. sendRequest: sendRequestFn
  3750. };
  3751. const forceRefresh = this.forceTokenRefresh_;
  3752. this.forceTokenRefresh_ = false;
  3753. try {
  3754. // First fetch auth and app check token, and establish connection after
  3755. // fetching the token was successful
  3756. const [authToken, appCheckToken] = await Promise.all([
  3757. this.authTokenProvider_.getToken(forceRefresh),
  3758. this.appCheckTokenProvider_.getToken(forceRefresh)
  3759. ]);
  3760. if (!canceled) {
  3761. log('getToken() completed. Creating connection.');
  3762. this.authToken_ = authToken && authToken.accessToken;
  3763. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3764. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3765. /* onKill= */ reason => {
  3766. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3767. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3768. }, lastSessionId);
  3769. }
  3770. else {
  3771. log('getToken() completed but was canceled');
  3772. }
  3773. }
  3774. catch (error) {
  3775. this.log_('Failed to get token: ' + error);
  3776. if (!canceled) {
  3777. if (this.repoInfo_.nodeAdmin) {
  3778. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3779. // But getToken() may also just have temporarily failed, so we still want to
  3780. // continue retrying.
  3781. warn(error);
  3782. }
  3783. closeFn();
  3784. }
  3785. }
  3786. }
  3787. }
  3788. interrupt(reason) {
  3789. log('Interrupting connection for reason: ' + reason);
  3790. this.interruptReasons_[reason] = true;
  3791. if (this.realtime_) {
  3792. this.realtime_.close();
  3793. }
  3794. else {
  3795. if (this.establishConnectionTimer_) {
  3796. clearTimeout(this.establishConnectionTimer_);
  3797. this.establishConnectionTimer_ = null;
  3798. }
  3799. if (this.connected_) {
  3800. this.onRealtimeDisconnect_();
  3801. }
  3802. }
  3803. }
  3804. resume(reason) {
  3805. log('Resuming connection for reason: ' + reason);
  3806. delete this.interruptReasons_[reason];
  3807. if (isEmpty(this.interruptReasons_)) {
  3808. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3809. if (!this.realtime_) {
  3810. this.scheduleConnect_(0);
  3811. }
  3812. }
  3813. }
  3814. handleTimestamp_(timestamp) {
  3815. const delta = timestamp - new Date().getTime();
  3816. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3817. }
  3818. cancelSentTransactions_() {
  3819. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3820. const put = this.outstandingPuts_[i];
  3821. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3822. if (put.onComplete) {
  3823. put.onComplete('disconnect');
  3824. }
  3825. delete this.outstandingPuts_[i];
  3826. this.outstandingPutCount_--;
  3827. }
  3828. }
  3829. // Clean up array occasionally.
  3830. if (this.outstandingPutCount_ === 0) {
  3831. this.outstandingPuts_ = [];
  3832. }
  3833. }
  3834. onListenRevoked_(pathString, query) {
  3835. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3836. let queryId;
  3837. if (!query) {
  3838. queryId = 'default';
  3839. }
  3840. else {
  3841. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3842. }
  3843. const listen = this.removeListen_(pathString, queryId);
  3844. if (listen && listen.onComplete) {
  3845. listen.onComplete('permission_denied');
  3846. }
  3847. }
  3848. removeListen_(pathString, queryId) {
  3849. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3850. let listen;
  3851. if (this.listens.has(normalizedPathString)) {
  3852. const map = this.listens.get(normalizedPathString);
  3853. listen = map.get(queryId);
  3854. map.delete(queryId);
  3855. if (map.size === 0) {
  3856. this.listens.delete(normalizedPathString);
  3857. }
  3858. }
  3859. else {
  3860. // all listens for this path has already been removed
  3861. listen = undefined;
  3862. }
  3863. return listen;
  3864. }
  3865. onAuthRevoked_(statusCode, explanation) {
  3866. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3867. this.authToken_ = null;
  3868. this.forceTokenRefresh_ = true;
  3869. this.realtime_.close();
  3870. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3871. // We'll wait a couple times before logging the warning / increasing the
  3872. // retry period since oauth tokens will report as "invalid" if they're
  3873. // just expired. Plus there may be transient issues that resolve themselves.
  3874. this.invalidAuthTokenCount_++;
  3875. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3876. // Set a long reconnect delay because recovery is unlikely
  3877. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3878. // Notify the auth token provider that the token is invalid, which will log
  3879. // a warning
  3880. this.authTokenProvider_.notifyForInvalidToken();
  3881. }
  3882. }
  3883. }
  3884. onAppCheckRevoked_(statusCode, explanation) {
  3885. log('App check token revoked: ' + statusCode + '/' + explanation);
  3886. this.appCheckToken_ = null;
  3887. this.forceTokenRefresh_ = true;
  3888. // Note: We don't close the connection as the developer may not have
  3889. // enforcement enabled. The backend closes connections with enforcements.
  3890. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3891. // We'll wait a couple times before logging the warning / increasing the
  3892. // retry period since oauth tokens will report as "invalid" if they're
  3893. // just expired. Plus there may be transient issues that resolve themselves.
  3894. this.invalidAppCheckTokenCount_++;
  3895. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3896. this.appCheckTokenProvider_.notifyForInvalidToken();
  3897. }
  3898. }
  3899. }
  3900. onSecurityDebugPacket_(body) {
  3901. if (this.securityDebugCallback_) {
  3902. this.securityDebugCallback_(body);
  3903. }
  3904. else {
  3905. if ('msg' in body) {
  3906. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3907. }
  3908. }
  3909. }
  3910. restoreState_() {
  3911. //Re-authenticate ourselves if we have a credential stored.
  3912. this.tryAuth();
  3913. this.tryAppCheck();
  3914. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3915. // make sure to send listens before puts.
  3916. for (const queries of this.listens.values()) {
  3917. for (const listenSpec of queries.values()) {
  3918. this.sendListen_(listenSpec);
  3919. }
  3920. }
  3921. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3922. if (this.outstandingPuts_[i]) {
  3923. this.sendPut_(i);
  3924. }
  3925. }
  3926. while (this.onDisconnectRequestQueue_.length) {
  3927. const request = this.onDisconnectRequestQueue_.shift();
  3928. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3929. }
  3930. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3931. if (this.outstandingGets_[i]) {
  3932. this.sendGet_(i);
  3933. }
  3934. }
  3935. }
  3936. /**
  3937. * Sends client stats for first connection
  3938. */
  3939. sendConnectStats_() {
  3940. const stats = {};
  3941. let clientName = 'js';
  3942. if (isNodeSdk()) {
  3943. if (this.repoInfo_.nodeAdmin) {
  3944. clientName = 'admin_node';
  3945. }
  3946. else {
  3947. clientName = 'node';
  3948. }
  3949. }
  3950. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3951. if (isMobileCordova()) {
  3952. stats['framework.cordova'] = 1;
  3953. }
  3954. else if (isReactNative()) {
  3955. stats['framework.reactnative'] = 1;
  3956. }
  3957. this.reportStats(stats);
  3958. }
  3959. shouldReconnect_() {
  3960. const online = OnlineMonitor.getInstance().currentlyOnline();
  3961. return isEmpty(this.interruptReasons_) && online;
  3962. }
  3963. }
  3964. PersistentConnection.nextPersistentConnectionId_ = 0;
  3965. /**
  3966. * Counter for number of connections created. Mainly used for tagging in the logs
  3967. */
  3968. PersistentConnection.nextConnectionId_ = 0;
  3969. /**
  3970. * @license
  3971. * Copyright 2017 Google LLC
  3972. *
  3973. * Licensed under the Apache License, Version 2.0 (the "License");
  3974. * you may not use this file except in compliance with the License.
  3975. * You may obtain a copy of the License at
  3976. *
  3977. * http://www.apache.org/licenses/LICENSE-2.0
  3978. *
  3979. * Unless required by applicable law or agreed to in writing, software
  3980. * distributed under the License is distributed on an "AS IS" BASIS,
  3981. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3982. * See the License for the specific language governing permissions and
  3983. * limitations under the License.
  3984. */
  3985. class NamedNode {
  3986. constructor(name, node) {
  3987. this.name = name;
  3988. this.node = node;
  3989. }
  3990. static Wrap(name, node) {
  3991. return new NamedNode(name, node);
  3992. }
  3993. }
  3994. /**
  3995. * @license
  3996. * Copyright 2017 Google LLC
  3997. *
  3998. * Licensed under the Apache License, Version 2.0 (the "License");
  3999. * you may not use this file except in compliance with the License.
  4000. * You may obtain a copy of the License at
  4001. *
  4002. * http://www.apache.org/licenses/LICENSE-2.0
  4003. *
  4004. * Unless required by applicable law or agreed to in writing, software
  4005. * distributed under the License is distributed on an "AS IS" BASIS,
  4006. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4007. * See the License for the specific language governing permissions and
  4008. * limitations under the License.
  4009. */
  4010. class Index {
  4011. /**
  4012. * @returns A standalone comparison function for
  4013. * this index
  4014. */
  4015. getCompare() {
  4016. return this.compare.bind(this);
  4017. }
  4018. /**
  4019. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4020. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4021. *
  4022. *
  4023. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4024. */
  4025. indexedValueChanged(oldNode, newNode) {
  4026. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4027. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4028. return this.compare(oldWrapped, newWrapped) !== 0;
  4029. }
  4030. /**
  4031. * @returns a node wrapper that will sort equal to or less than
  4032. * any other node wrapper, using this index
  4033. */
  4034. minPost() {
  4035. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4036. return NamedNode.MIN;
  4037. }
  4038. }
  4039. /**
  4040. * @license
  4041. * Copyright 2017 Google LLC
  4042. *
  4043. * Licensed under the Apache License, Version 2.0 (the "License");
  4044. * you may not use this file except in compliance with the License.
  4045. * You may obtain a copy of the License at
  4046. *
  4047. * http://www.apache.org/licenses/LICENSE-2.0
  4048. *
  4049. * Unless required by applicable law or agreed to in writing, software
  4050. * distributed under the License is distributed on an "AS IS" BASIS,
  4051. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4052. * See the License for the specific language governing permissions and
  4053. * limitations under the License.
  4054. */
  4055. let __EMPTY_NODE;
  4056. class KeyIndex extends Index {
  4057. static get __EMPTY_NODE() {
  4058. return __EMPTY_NODE;
  4059. }
  4060. static set __EMPTY_NODE(val) {
  4061. __EMPTY_NODE = val;
  4062. }
  4063. compare(a, b) {
  4064. return nameCompare(a.name, b.name);
  4065. }
  4066. isDefinedOn(node) {
  4067. // We could probably return true here (since every node has a key), but it's never called
  4068. // so just leaving unimplemented for now.
  4069. throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4070. }
  4071. indexedValueChanged(oldNode, newNode) {
  4072. return false; // The key for a node never changes.
  4073. }
  4074. minPost() {
  4075. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4076. return NamedNode.MIN;
  4077. }
  4078. maxPost() {
  4079. // TODO: This should really be created once and cached in a static property, but
  4080. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4081. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4082. }
  4083. makePost(indexValue, name) {
  4084. assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4085. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4086. return new NamedNode(indexValue, __EMPTY_NODE);
  4087. }
  4088. /**
  4089. * @returns String representation for inclusion in a query spec
  4090. */
  4091. toString() {
  4092. return '.key';
  4093. }
  4094. }
  4095. const KEY_INDEX = new KeyIndex();
  4096. /**
  4097. * @license
  4098. * Copyright 2017 Google LLC
  4099. *
  4100. * Licensed under the Apache License, Version 2.0 (the "License");
  4101. * you may not use this file except in compliance with the License.
  4102. * You may obtain a copy of the License at
  4103. *
  4104. * http://www.apache.org/licenses/LICENSE-2.0
  4105. *
  4106. * Unless required by applicable law or agreed to in writing, software
  4107. * distributed under the License is distributed on an "AS IS" BASIS,
  4108. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4109. * See the License for the specific language governing permissions and
  4110. * limitations under the License.
  4111. */
  4112. /**
  4113. * An iterator over an LLRBNode.
  4114. */
  4115. class SortedMapIterator {
  4116. /**
  4117. * @param node - Node to iterate.
  4118. * @param isReverse_ - Whether or not to iterate in reverse
  4119. */
  4120. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4121. this.isReverse_ = isReverse_;
  4122. this.resultGenerator_ = resultGenerator_;
  4123. this.nodeStack_ = [];
  4124. let cmp = 1;
  4125. while (!node.isEmpty()) {
  4126. node = node;
  4127. cmp = startKey ? comparator(node.key, startKey) : 1;
  4128. // flip the comparison if we're going in reverse
  4129. if (isReverse_) {
  4130. cmp *= -1;
  4131. }
  4132. if (cmp < 0) {
  4133. // This node is less than our start key. ignore it
  4134. if (this.isReverse_) {
  4135. node = node.left;
  4136. }
  4137. else {
  4138. node = node.right;
  4139. }
  4140. }
  4141. else if (cmp === 0) {
  4142. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4143. this.nodeStack_.push(node);
  4144. break;
  4145. }
  4146. else {
  4147. // This node is greater than our start key, add it to the stack and move to the next one
  4148. this.nodeStack_.push(node);
  4149. if (this.isReverse_) {
  4150. node = node.right;
  4151. }
  4152. else {
  4153. node = node.left;
  4154. }
  4155. }
  4156. }
  4157. }
  4158. getNext() {
  4159. if (this.nodeStack_.length === 0) {
  4160. return null;
  4161. }
  4162. let node = this.nodeStack_.pop();
  4163. let result;
  4164. if (this.resultGenerator_) {
  4165. result = this.resultGenerator_(node.key, node.value);
  4166. }
  4167. else {
  4168. result = { key: node.key, value: node.value };
  4169. }
  4170. if (this.isReverse_) {
  4171. node = node.left;
  4172. while (!node.isEmpty()) {
  4173. this.nodeStack_.push(node);
  4174. node = node.right;
  4175. }
  4176. }
  4177. else {
  4178. node = node.right;
  4179. while (!node.isEmpty()) {
  4180. this.nodeStack_.push(node);
  4181. node = node.left;
  4182. }
  4183. }
  4184. return result;
  4185. }
  4186. hasNext() {
  4187. return this.nodeStack_.length > 0;
  4188. }
  4189. peek() {
  4190. if (this.nodeStack_.length === 0) {
  4191. return null;
  4192. }
  4193. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4194. if (this.resultGenerator_) {
  4195. return this.resultGenerator_(node.key, node.value);
  4196. }
  4197. else {
  4198. return { key: node.key, value: node.value };
  4199. }
  4200. }
  4201. }
  4202. /**
  4203. * Represents a node in a Left-leaning Red-Black tree.
  4204. */
  4205. class LLRBNode {
  4206. /**
  4207. * @param key - Key associated with this node.
  4208. * @param value - Value associated with this node.
  4209. * @param color - Whether this node is red.
  4210. * @param left - Left child.
  4211. * @param right - Right child.
  4212. */
  4213. constructor(key, value, color, left, right) {
  4214. this.key = key;
  4215. this.value = value;
  4216. this.color = color != null ? color : LLRBNode.RED;
  4217. this.left =
  4218. left != null ? left : SortedMap.EMPTY_NODE;
  4219. this.right =
  4220. right != null ? right : SortedMap.EMPTY_NODE;
  4221. }
  4222. /**
  4223. * Returns a copy of the current node, optionally replacing pieces of it.
  4224. *
  4225. * @param key - New key for the node, or null.
  4226. * @param value - New value for the node, or null.
  4227. * @param color - New color for the node, or null.
  4228. * @param left - New left child for the node, or null.
  4229. * @param right - New right child for the node, or null.
  4230. * @returns The node copy.
  4231. */
  4232. copy(key, value, color, left, right) {
  4233. return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  4234. }
  4235. /**
  4236. * @returns The total number of nodes in the tree.
  4237. */
  4238. count() {
  4239. return this.left.count() + 1 + this.right.count();
  4240. }
  4241. /**
  4242. * @returns True if the tree is empty.
  4243. */
  4244. isEmpty() {
  4245. return false;
  4246. }
  4247. /**
  4248. * Traverses the tree in key order and calls the specified action function
  4249. * for each node.
  4250. *
  4251. * @param action - Callback function to be called for each
  4252. * node. If it returns true, traversal is aborted.
  4253. * @returns The first truthy value returned by action, or the last falsey
  4254. * value returned by action
  4255. */
  4256. inorderTraversal(action) {
  4257. return (this.left.inorderTraversal(action) ||
  4258. !!action(this.key, this.value) ||
  4259. this.right.inorderTraversal(action));
  4260. }
  4261. /**
  4262. * Traverses the tree in reverse key order and calls the specified action function
  4263. * for each node.
  4264. *
  4265. * @param action - Callback function to be called for each
  4266. * node. If it returns true, traversal is aborted.
  4267. * @returns True if traversal was aborted.
  4268. */
  4269. reverseTraversal(action) {
  4270. return (this.right.reverseTraversal(action) ||
  4271. action(this.key, this.value) ||
  4272. this.left.reverseTraversal(action));
  4273. }
  4274. /**
  4275. * @returns The minimum node in the tree.
  4276. */
  4277. min_() {
  4278. if (this.left.isEmpty()) {
  4279. return this;
  4280. }
  4281. else {
  4282. return this.left.min_();
  4283. }
  4284. }
  4285. /**
  4286. * @returns The maximum key in the tree.
  4287. */
  4288. minKey() {
  4289. return this.min_().key;
  4290. }
  4291. /**
  4292. * @returns The maximum key in the tree.
  4293. */
  4294. maxKey() {
  4295. if (this.right.isEmpty()) {
  4296. return this.key;
  4297. }
  4298. else {
  4299. return this.right.maxKey();
  4300. }
  4301. }
  4302. /**
  4303. * @param key - Key to insert.
  4304. * @param value - Value to insert.
  4305. * @param comparator - Comparator.
  4306. * @returns New tree, with the key/value added.
  4307. */
  4308. insert(key, value, comparator) {
  4309. let n = this;
  4310. const cmp = comparator(key, n.key);
  4311. if (cmp < 0) {
  4312. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4313. }
  4314. else if (cmp === 0) {
  4315. n = n.copy(null, value, null, null, null);
  4316. }
  4317. else {
  4318. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4319. }
  4320. return n.fixUp_();
  4321. }
  4322. /**
  4323. * @returns New tree, with the minimum key removed.
  4324. */
  4325. removeMin_() {
  4326. if (this.left.isEmpty()) {
  4327. return SortedMap.EMPTY_NODE;
  4328. }
  4329. let n = this;
  4330. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4331. n = n.moveRedLeft_();
  4332. }
  4333. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4334. return n.fixUp_();
  4335. }
  4336. /**
  4337. * @param key - The key of the item to remove.
  4338. * @param comparator - Comparator.
  4339. * @returns New tree, with the specified item removed.
  4340. */
  4341. remove(key, comparator) {
  4342. let n, smallest;
  4343. n = this;
  4344. if (comparator(key, n.key) < 0) {
  4345. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4346. n = n.moveRedLeft_();
  4347. }
  4348. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4349. }
  4350. else {
  4351. if (n.left.isRed_()) {
  4352. n = n.rotateRight_();
  4353. }
  4354. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4355. n = n.moveRedRight_();
  4356. }
  4357. if (comparator(key, n.key) === 0) {
  4358. if (n.right.isEmpty()) {
  4359. return SortedMap.EMPTY_NODE;
  4360. }
  4361. else {
  4362. smallest = n.right.min_();
  4363. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4364. }
  4365. }
  4366. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4367. }
  4368. return n.fixUp_();
  4369. }
  4370. /**
  4371. * @returns Whether this is a RED node.
  4372. */
  4373. isRed_() {
  4374. return this.color;
  4375. }
  4376. /**
  4377. * @returns New tree after performing any needed rotations.
  4378. */
  4379. fixUp_() {
  4380. let n = this;
  4381. if (n.right.isRed_() && !n.left.isRed_()) {
  4382. n = n.rotateLeft_();
  4383. }
  4384. if (n.left.isRed_() && n.left.left.isRed_()) {
  4385. n = n.rotateRight_();
  4386. }
  4387. if (n.left.isRed_() && n.right.isRed_()) {
  4388. n = n.colorFlip_();
  4389. }
  4390. return n;
  4391. }
  4392. /**
  4393. * @returns New tree, after moveRedLeft.
  4394. */
  4395. moveRedLeft_() {
  4396. let n = this.colorFlip_();
  4397. if (n.right.left.isRed_()) {
  4398. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4399. n = n.rotateLeft_();
  4400. n = n.colorFlip_();
  4401. }
  4402. return n;
  4403. }
  4404. /**
  4405. * @returns New tree, after moveRedRight.
  4406. */
  4407. moveRedRight_() {
  4408. let n = this.colorFlip_();
  4409. if (n.left.left.isRed_()) {
  4410. n = n.rotateRight_();
  4411. n = n.colorFlip_();
  4412. }
  4413. return n;
  4414. }
  4415. /**
  4416. * @returns New tree, after rotateLeft.
  4417. */
  4418. rotateLeft_() {
  4419. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4420. return this.right.copy(null, null, this.color, nl, null);
  4421. }
  4422. /**
  4423. * @returns New tree, after rotateRight.
  4424. */
  4425. rotateRight_() {
  4426. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4427. return this.left.copy(null, null, this.color, null, nr);
  4428. }
  4429. /**
  4430. * @returns Newt ree, after colorFlip.
  4431. */
  4432. colorFlip_() {
  4433. const left = this.left.copy(null, null, !this.left.color, null, null);
  4434. const right = this.right.copy(null, null, !this.right.color, null, null);
  4435. return this.copy(null, null, !this.color, left, right);
  4436. }
  4437. /**
  4438. * For testing.
  4439. *
  4440. * @returns True if all is well.
  4441. */
  4442. checkMaxDepth_() {
  4443. const blackDepth = this.check_();
  4444. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4445. }
  4446. check_() {
  4447. if (this.isRed_() && this.left.isRed_()) {
  4448. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4449. }
  4450. if (this.right.isRed_()) {
  4451. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4452. }
  4453. const blackDepth = this.left.check_();
  4454. if (blackDepth !== this.right.check_()) {
  4455. throw new Error('Black depths differ');
  4456. }
  4457. else {
  4458. return blackDepth + (this.isRed_() ? 0 : 1);
  4459. }
  4460. }
  4461. }
  4462. LLRBNode.RED = true;
  4463. LLRBNode.BLACK = false;
  4464. /**
  4465. * Represents an empty node (a leaf node in the Red-Black Tree).
  4466. */
  4467. class LLRBEmptyNode {
  4468. /**
  4469. * Returns a copy of the current node.
  4470. *
  4471. * @returns The node copy.
  4472. */
  4473. copy(key, value, color, left, right) {
  4474. return this;
  4475. }
  4476. /**
  4477. * Returns a copy of the tree, with the specified key/value added.
  4478. *
  4479. * @param key - Key to be added.
  4480. * @param value - Value to be added.
  4481. * @param comparator - Comparator.
  4482. * @returns New tree, with item added.
  4483. */
  4484. insert(key, value, comparator) {
  4485. return new LLRBNode(key, value, null);
  4486. }
  4487. /**
  4488. * Returns a copy of the tree, with the specified key removed.
  4489. *
  4490. * @param key - The key to remove.
  4491. * @param comparator - Comparator.
  4492. * @returns New tree, with item removed.
  4493. */
  4494. remove(key, comparator) {
  4495. return this;
  4496. }
  4497. /**
  4498. * @returns The total number of nodes in the tree.
  4499. */
  4500. count() {
  4501. return 0;
  4502. }
  4503. /**
  4504. * @returns True if the tree is empty.
  4505. */
  4506. isEmpty() {
  4507. return true;
  4508. }
  4509. /**
  4510. * Traverses the tree in key order and calls the specified action function
  4511. * for each node.
  4512. *
  4513. * @param action - Callback function to be called for each
  4514. * node. If it returns true, traversal is aborted.
  4515. * @returns True if traversal was aborted.
  4516. */
  4517. inorderTraversal(action) {
  4518. return false;
  4519. }
  4520. /**
  4521. * Traverses the tree in reverse key order and calls the specified action function
  4522. * for each node.
  4523. *
  4524. * @param action - Callback function to be called for each
  4525. * node. If it returns true, traversal is aborted.
  4526. * @returns True if traversal was aborted.
  4527. */
  4528. reverseTraversal(action) {
  4529. return false;
  4530. }
  4531. minKey() {
  4532. return null;
  4533. }
  4534. maxKey() {
  4535. return null;
  4536. }
  4537. check_() {
  4538. return 0;
  4539. }
  4540. /**
  4541. * @returns Whether this node is red.
  4542. */
  4543. isRed_() {
  4544. return false;
  4545. }
  4546. }
  4547. /**
  4548. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4549. * tree.
  4550. */
  4551. class SortedMap {
  4552. /**
  4553. * @param comparator_ - Key comparator.
  4554. * @param root_ - Optional root node for the map.
  4555. */
  4556. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4557. this.comparator_ = comparator_;
  4558. this.root_ = root_;
  4559. }
  4560. /**
  4561. * Returns a copy of the map, with the specified key/value added or replaced.
  4562. * (TODO: We should perhaps rename this method to 'put')
  4563. *
  4564. * @param key - Key to be added.
  4565. * @param value - Value to be added.
  4566. * @returns New map, with item added.
  4567. */
  4568. insert(key, value) {
  4569. return new SortedMap(this.comparator_, this.root_
  4570. .insert(key, value, this.comparator_)
  4571. .copy(null, null, LLRBNode.BLACK, null, null));
  4572. }
  4573. /**
  4574. * Returns a copy of the map, with the specified key removed.
  4575. *
  4576. * @param key - The key to remove.
  4577. * @returns New map, with item removed.
  4578. */
  4579. remove(key) {
  4580. return new SortedMap(this.comparator_, this.root_
  4581. .remove(key, this.comparator_)
  4582. .copy(null, null, LLRBNode.BLACK, null, null));
  4583. }
  4584. /**
  4585. * Returns the value of the node with the given key, or null.
  4586. *
  4587. * @param key - The key to look up.
  4588. * @returns The value of the node with the given key, or null if the
  4589. * key doesn't exist.
  4590. */
  4591. get(key) {
  4592. let cmp;
  4593. let node = this.root_;
  4594. while (!node.isEmpty()) {
  4595. cmp = this.comparator_(key, node.key);
  4596. if (cmp === 0) {
  4597. return node.value;
  4598. }
  4599. else if (cmp < 0) {
  4600. node = node.left;
  4601. }
  4602. else if (cmp > 0) {
  4603. node = node.right;
  4604. }
  4605. }
  4606. return null;
  4607. }
  4608. /**
  4609. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4610. * @param key - The key to find the predecessor of
  4611. * @returns The predecessor key.
  4612. */
  4613. getPredecessorKey(key) {
  4614. let cmp, node = this.root_, rightParent = null;
  4615. while (!node.isEmpty()) {
  4616. cmp = this.comparator_(key, node.key);
  4617. if (cmp === 0) {
  4618. if (!node.left.isEmpty()) {
  4619. node = node.left;
  4620. while (!node.right.isEmpty()) {
  4621. node = node.right;
  4622. }
  4623. return node.key;
  4624. }
  4625. else if (rightParent) {
  4626. return rightParent.key;
  4627. }
  4628. else {
  4629. return null; // first item.
  4630. }
  4631. }
  4632. else if (cmp < 0) {
  4633. node = node.left;
  4634. }
  4635. else if (cmp > 0) {
  4636. rightParent = node;
  4637. node = node.right;
  4638. }
  4639. }
  4640. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4641. }
  4642. /**
  4643. * @returns True if the map is empty.
  4644. */
  4645. isEmpty() {
  4646. return this.root_.isEmpty();
  4647. }
  4648. /**
  4649. * @returns The total number of nodes in the map.
  4650. */
  4651. count() {
  4652. return this.root_.count();
  4653. }
  4654. /**
  4655. * @returns The minimum key in the map.
  4656. */
  4657. minKey() {
  4658. return this.root_.minKey();
  4659. }
  4660. /**
  4661. * @returns The maximum key in the map.
  4662. */
  4663. maxKey() {
  4664. return this.root_.maxKey();
  4665. }
  4666. /**
  4667. * Traverses the map in key order and calls the specified action function
  4668. * for each key/value pair.
  4669. *
  4670. * @param action - Callback function to be called
  4671. * for each key/value pair. If action returns true, traversal is aborted.
  4672. * @returns The first truthy value returned by action, or the last falsey
  4673. * value returned by action
  4674. */
  4675. inorderTraversal(action) {
  4676. return this.root_.inorderTraversal(action);
  4677. }
  4678. /**
  4679. * Traverses the map in reverse key order and calls the specified action function
  4680. * for each key/value pair.
  4681. *
  4682. * @param action - Callback function to be called
  4683. * for each key/value pair. If action returns true, traversal is aborted.
  4684. * @returns True if the traversal was aborted.
  4685. */
  4686. reverseTraversal(action) {
  4687. return this.root_.reverseTraversal(action);
  4688. }
  4689. /**
  4690. * Returns an iterator over the SortedMap.
  4691. * @returns The iterator.
  4692. */
  4693. getIterator(resultGenerator) {
  4694. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4695. }
  4696. getIteratorFrom(key, resultGenerator) {
  4697. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4698. }
  4699. getReverseIteratorFrom(key, resultGenerator) {
  4700. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4701. }
  4702. getReverseIterator(resultGenerator) {
  4703. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4704. }
  4705. }
  4706. /**
  4707. * Always use the same empty node, to reduce memory.
  4708. */
  4709. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4710. /**
  4711. * @license
  4712. * Copyright 2017 Google LLC
  4713. *
  4714. * Licensed under the Apache License, Version 2.0 (the "License");
  4715. * you may not use this file except in compliance with the License.
  4716. * You may obtain a copy of the License at
  4717. *
  4718. * http://www.apache.org/licenses/LICENSE-2.0
  4719. *
  4720. * Unless required by applicable law or agreed to in writing, software
  4721. * distributed under the License is distributed on an "AS IS" BASIS,
  4722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4723. * See the License for the specific language governing permissions and
  4724. * limitations under the License.
  4725. */
  4726. function NAME_ONLY_COMPARATOR(left, right) {
  4727. return nameCompare(left.name, right.name);
  4728. }
  4729. function NAME_COMPARATOR(left, right) {
  4730. return nameCompare(left, right);
  4731. }
  4732. /**
  4733. * @license
  4734. * Copyright 2017 Google LLC
  4735. *
  4736. * Licensed under the Apache License, Version 2.0 (the "License");
  4737. * you may not use this file except in compliance with the License.
  4738. * You may obtain a copy of the License at
  4739. *
  4740. * http://www.apache.org/licenses/LICENSE-2.0
  4741. *
  4742. * Unless required by applicable law or agreed to in writing, software
  4743. * distributed under the License is distributed on an "AS IS" BASIS,
  4744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4745. * See the License for the specific language governing permissions and
  4746. * limitations under the License.
  4747. */
  4748. let MAX_NODE$2;
  4749. function setMaxNode$1(val) {
  4750. MAX_NODE$2 = val;
  4751. }
  4752. const priorityHashText = function (priority) {
  4753. if (typeof priority === 'number') {
  4754. return 'number:' + doubleToIEEE754String(priority);
  4755. }
  4756. else {
  4757. return 'string:' + priority;
  4758. }
  4759. };
  4760. /**
  4761. * Validates that a priority snapshot Node is valid.
  4762. */
  4763. const validatePriorityNode = function (priorityNode) {
  4764. if (priorityNode.isLeafNode()) {
  4765. const val = priorityNode.val();
  4766. assert(typeof val === 'string' ||
  4767. typeof val === 'number' ||
  4768. (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
  4769. }
  4770. else {
  4771. assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4772. }
  4773. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4774. assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4775. };
  4776. /**
  4777. * @license
  4778. * Copyright 2017 Google LLC
  4779. *
  4780. * Licensed under the Apache License, Version 2.0 (the "License");
  4781. * you may not use this file except in compliance with the License.
  4782. * You may obtain a copy of the License at
  4783. *
  4784. * http://www.apache.org/licenses/LICENSE-2.0
  4785. *
  4786. * Unless required by applicable law or agreed to in writing, software
  4787. * distributed under the License is distributed on an "AS IS" BASIS,
  4788. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4789. * See the License for the specific language governing permissions and
  4790. * limitations under the License.
  4791. */
  4792. let __childrenNodeConstructor;
  4793. /**
  4794. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4795. * implements Node and stores the value of the node (a string,
  4796. * number, or boolean) accessible via getValue().
  4797. */
  4798. class LeafNode {
  4799. /**
  4800. * @param value_ - The value to store in this leaf node. The object type is
  4801. * possible in the event of a deferred value
  4802. * @param priorityNode_ - The priority of this node.
  4803. */
  4804. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4805. this.value_ = value_;
  4806. this.priorityNode_ = priorityNode_;
  4807. this.lazyHash_ = null;
  4808. assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4809. validatePriorityNode(this.priorityNode_);
  4810. }
  4811. static set __childrenNodeConstructor(val) {
  4812. __childrenNodeConstructor = val;
  4813. }
  4814. static get __childrenNodeConstructor() {
  4815. return __childrenNodeConstructor;
  4816. }
  4817. /** @inheritDoc */
  4818. isLeafNode() {
  4819. return true;
  4820. }
  4821. /** @inheritDoc */
  4822. getPriority() {
  4823. return this.priorityNode_;
  4824. }
  4825. /** @inheritDoc */
  4826. updatePriority(newPriorityNode) {
  4827. return new LeafNode(this.value_, newPriorityNode);
  4828. }
  4829. /** @inheritDoc */
  4830. getImmediateChild(childName) {
  4831. // Hack to treat priority as a regular child
  4832. if (childName === '.priority') {
  4833. return this.priorityNode_;
  4834. }
  4835. else {
  4836. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4837. }
  4838. }
  4839. /** @inheritDoc */
  4840. getChild(path) {
  4841. if (pathIsEmpty(path)) {
  4842. return this;
  4843. }
  4844. else if (pathGetFront(path) === '.priority') {
  4845. return this.priorityNode_;
  4846. }
  4847. else {
  4848. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4849. }
  4850. }
  4851. hasChild() {
  4852. return false;
  4853. }
  4854. /** @inheritDoc */
  4855. getPredecessorChildName(childName, childNode) {
  4856. return null;
  4857. }
  4858. /** @inheritDoc */
  4859. updateImmediateChild(childName, newChildNode) {
  4860. if (childName === '.priority') {
  4861. return this.updatePriority(newChildNode);
  4862. }
  4863. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4864. return this;
  4865. }
  4866. else {
  4867. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4868. }
  4869. }
  4870. /** @inheritDoc */
  4871. updateChild(path, newChildNode) {
  4872. const front = pathGetFront(path);
  4873. if (front === null) {
  4874. return newChildNode;
  4875. }
  4876. else if (newChildNode.isEmpty() && front !== '.priority') {
  4877. return this;
  4878. }
  4879. else {
  4880. assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4881. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4882. }
  4883. }
  4884. /** @inheritDoc */
  4885. isEmpty() {
  4886. return false;
  4887. }
  4888. /** @inheritDoc */
  4889. numChildren() {
  4890. return 0;
  4891. }
  4892. /** @inheritDoc */
  4893. forEachChild(index, action) {
  4894. return false;
  4895. }
  4896. val(exportFormat) {
  4897. if (exportFormat && !this.getPriority().isEmpty()) {
  4898. return {
  4899. '.value': this.getValue(),
  4900. '.priority': this.getPriority().val()
  4901. };
  4902. }
  4903. else {
  4904. return this.getValue();
  4905. }
  4906. }
  4907. /** @inheritDoc */
  4908. hash() {
  4909. if (this.lazyHash_ === null) {
  4910. let toHash = '';
  4911. if (!this.priorityNode_.isEmpty()) {
  4912. toHash +=
  4913. 'priority:' +
  4914. priorityHashText(this.priorityNode_.val()) +
  4915. ':';
  4916. }
  4917. const type = typeof this.value_;
  4918. toHash += type + ':';
  4919. if (type === 'number') {
  4920. toHash += doubleToIEEE754String(this.value_);
  4921. }
  4922. else {
  4923. toHash += this.value_;
  4924. }
  4925. this.lazyHash_ = sha1(toHash);
  4926. }
  4927. return this.lazyHash_;
  4928. }
  4929. /**
  4930. * Returns the value of the leaf node.
  4931. * @returns The value of the node.
  4932. */
  4933. getValue() {
  4934. return this.value_;
  4935. }
  4936. compareTo(other) {
  4937. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4938. return 1;
  4939. }
  4940. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4941. return -1;
  4942. }
  4943. else {
  4944. assert(other.isLeafNode(), 'Unknown node type');
  4945. return this.compareToLeafNode_(other);
  4946. }
  4947. }
  4948. /**
  4949. * Comparison specifically for two leaf nodes
  4950. */
  4951. compareToLeafNode_(otherLeaf) {
  4952. const otherLeafType = typeof otherLeaf.value_;
  4953. const thisLeafType = typeof this.value_;
  4954. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4955. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4956. assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4957. assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4958. if (otherIndex === thisIndex) {
  4959. // Same type, compare values
  4960. if (thisLeafType === 'object') {
  4961. // Deferred value nodes are all equal, but we should also never get to this point...
  4962. return 0;
  4963. }
  4964. else {
  4965. // Note that this works because true > false, all others are number or string comparisons
  4966. if (this.value_ < otherLeaf.value_) {
  4967. return -1;
  4968. }
  4969. else if (this.value_ === otherLeaf.value_) {
  4970. return 0;
  4971. }
  4972. else {
  4973. return 1;
  4974. }
  4975. }
  4976. }
  4977. else {
  4978. return thisIndex - otherIndex;
  4979. }
  4980. }
  4981. withIndex() {
  4982. return this;
  4983. }
  4984. isIndexed() {
  4985. return true;
  4986. }
  4987. equals(other) {
  4988. if (other === this) {
  4989. return true;
  4990. }
  4991. else if (other.isLeafNode()) {
  4992. const otherLeaf = other;
  4993. return (this.value_ === otherLeaf.value_ &&
  4994. this.priorityNode_.equals(otherLeaf.priorityNode_));
  4995. }
  4996. else {
  4997. return false;
  4998. }
  4999. }
  5000. }
  5001. /**
  5002. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5003. * the same type, the comparison falls back to their value
  5004. */
  5005. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5006. /**
  5007. * @license
  5008. * Copyright 2017 Google LLC
  5009. *
  5010. * Licensed under the Apache License, Version 2.0 (the "License");
  5011. * you may not use this file except in compliance with the License.
  5012. * You may obtain a copy of the License at
  5013. *
  5014. * http://www.apache.org/licenses/LICENSE-2.0
  5015. *
  5016. * Unless required by applicable law or agreed to in writing, software
  5017. * distributed under the License is distributed on an "AS IS" BASIS,
  5018. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5019. * See the License for the specific language governing permissions and
  5020. * limitations under the License.
  5021. */
  5022. let nodeFromJSON$1;
  5023. let MAX_NODE$1;
  5024. function setNodeFromJSON(val) {
  5025. nodeFromJSON$1 = val;
  5026. }
  5027. function setMaxNode(val) {
  5028. MAX_NODE$1 = val;
  5029. }
  5030. class PriorityIndex extends Index {
  5031. compare(a, b) {
  5032. const aPriority = a.node.getPriority();
  5033. const bPriority = b.node.getPriority();
  5034. const indexCmp = aPriority.compareTo(bPriority);
  5035. if (indexCmp === 0) {
  5036. return nameCompare(a.name, b.name);
  5037. }
  5038. else {
  5039. return indexCmp;
  5040. }
  5041. }
  5042. isDefinedOn(node) {
  5043. return !node.getPriority().isEmpty();
  5044. }
  5045. indexedValueChanged(oldNode, newNode) {
  5046. return !oldNode.getPriority().equals(newNode.getPriority());
  5047. }
  5048. minPost() {
  5049. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5050. return NamedNode.MIN;
  5051. }
  5052. maxPost() {
  5053. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5054. }
  5055. makePost(indexValue, name) {
  5056. const priorityNode = nodeFromJSON$1(indexValue);
  5057. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5058. }
  5059. /**
  5060. * @returns String representation for inclusion in a query spec
  5061. */
  5062. toString() {
  5063. return '.priority';
  5064. }
  5065. }
  5066. const PRIORITY_INDEX = new PriorityIndex();
  5067. /**
  5068. * @license
  5069. * Copyright 2017 Google LLC
  5070. *
  5071. * Licensed under the Apache License, Version 2.0 (the "License");
  5072. * you may not use this file except in compliance with the License.
  5073. * You may obtain a copy of the License at
  5074. *
  5075. * http://www.apache.org/licenses/LICENSE-2.0
  5076. *
  5077. * Unless required by applicable law or agreed to in writing, software
  5078. * distributed under the License is distributed on an "AS IS" BASIS,
  5079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5080. * See the License for the specific language governing permissions and
  5081. * limitations under the License.
  5082. */
  5083. const LOG_2 = Math.log(2);
  5084. class Base12Num {
  5085. constructor(length) {
  5086. const logBase2 = (num) =>
  5087. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5088. parseInt((Math.log(num) / LOG_2), 10);
  5089. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5090. this.count = logBase2(length + 1);
  5091. this.current_ = this.count - 1;
  5092. const mask = bitMask(this.count);
  5093. this.bits_ = (length + 1) & mask;
  5094. }
  5095. nextBitIsOne() {
  5096. //noinspection JSBitwiseOperatorUsage
  5097. const result = !(this.bits_ & (0x1 << this.current_));
  5098. this.current_--;
  5099. return result;
  5100. }
  5101. }
  5102. /**
  5103. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5104. * function
  5105. *
  5106. * Uses the algorithm described in the paper linked here:
  5107. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5108. *
  5109. * @param childList - Unsorted list of children
  5110. * @param cmp - The comparison method to be used
  5111. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5112. * type is not NamedNode
  5113. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5114. */
  5115. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5116. childList.sort(cmp);
  5117. const buildBalancedTree = function (low, high) {
  5118. const length = high - low;
  5119. let namedNode;
  5120. let key;
  5121. if (length === 0) {
  5122. return null;
  5123. }
  5124. else if (length === 1) {
  5125. namedNode = childList[low];
  5126. key = keyFn ? keyFn(namedNode) : namedNode;
  5127. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5128. }
  5129. else {
  5130. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5131. const middle = parseInt((length / 2), 10) + low;
  5132. const left = buildBalancedTree(low, middle);
  5133. const right = buildBalancedTree(middle + 1, high);
  5134. namedNode = childList[middle];
  5135. key = keyFn ? keyFn(namedNode) : namedNode;
  5136. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5137. }
  5138. };
  5139. const buildFrom12Array = function (base12) {
  5140. let node = null;
  5141. let root = null;
  5142. let index = childList.length;
  5143. const buildPennant = function (chunkSize, color) {
  5144. const low = index - chunkSize;
  5145. const high = index;
  5146. index -= chunkSize;
  5147. const childTree = buildBalancedTree(low + 1, high);
  5148. const namedNode = childList[low];
  5149. const key = keyFn ? keyFn(namedNode) : namedNode;
  5150. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5151. };
  5152. const attachPennant = function (pennant) {
  5153. if (node) {
  5154. node.left = pennant;
  5155. node = pennant;
  5156. }
  5157. else {
  5158. root = pennant;
  5159. node = pennant;
  5160. }
  5161. };
  5162. for (let i = 0; i < base12.count; ++i) {
  5163. const isOne = base12.nextBitIsOne();
  5164. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5165. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5166. if (isOne) {
  5167. buildPennant(chunkSize, LLRBNode.BLACK);
  5168. }
  5169. else {
  5170. // current == 2
  5171. buildPennant(chunkSize, LLRBNode.BLACK);
  5172. buildPennant(chunkSize, LLRBNode.RED);
  5173. }
  5174. }
  5175. return root;
  5176. };
  5177. const base12 = new Base12Num(childList.length);
  5178. const root = buildFrom12Array(base12);
  5179. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5180. return new SortedMap(mapSortFn || cmp, root);
  5181. };
  5182. /**
  5183. * @license
  5184. * Copyright 2017 Google LLC
  5185. *
  5186. * Licensed under the Apache License, Version 2.0 (the "License");
  5187. * you may not use this file except in compliance with the License.
  5188. * You may obtain a copy of the License at
  5189. *
  5190. * http://www.apache.org/licenses/LICENSE-2.0
  5191. *
  5192. * Unless required by applicable law or agreed to in writing, software
  5193. * distributed under the License is distributed on an "AS IS" BASIS,
  5194. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5195. * See the License for the specific language governing permissions and
  5196. * limitations under the License.
  5197. */
  5198. let _defaultIndexMap;
  5199. const fallbackObject = {};
  5200. class IndexMap {
  5201. constructor(indexes_, indexSet_) {
  5202. this.indexes_ = indexes_;
  5203. this.indexSet_ = indexSet_;
  5204. }
  5205. /**
  5206. * The default IndexMap for nodes without a priority
  5207. */
  5208. static get Default() {
  5209. assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5210. _defaultIndexMap =
  5211. _defaultIndexMap ||
  5212. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5213. return _defaultIndexMap;
  5214. }
  5215. get(indexKey) {
  5216. const sortedMap = safeGet(this.indexes_, indexKey);
  5217. if (!sortedMap) {
  5218. throw new Error('No index defined for ' + indexKey);
  5219. }
  5220. if (sortedMap instanceof SortedMap) {
  5221. return sortedMap;
  5222. }
  5223. else {
  5224. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5225. // regular child map
  5226. return null;
  5227. }
  5228. }
  5229. hasIndex(indexDefinition) {
  5230. return contains(this.indexSet_, indexDefinition.toString());
  5231. }
  5232. addIndex(indexDefinition, existingChildren) {
  5233. assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5234. const childList = [];
  5235. let sawIndexedValue = false;
  5236. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5237. let next = iter.getNext();
  5238. while (next) {
  5239. sawIndexedValue =
  5240. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5241. childList.push(next);
  5242. next = iter.getNext();
  5243. }
  5244. let newIndex;
  5245. if (sawIndexedValue) {
  5246. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5247. }
  5248. else {
  5249. newIndex = fallbackObject;
  5250. }
  5251. const indexName = indexDefinition.toString();
  5252. const newIndexSet = Object.assign({}, this.indexSet_);
  5253. newIndexSet[indexName] = indexDefinition;
  5254. const newIndexes = Object.assign({}, this.indexes_);
  5255. newIndexes[indexName] = newIndex;
  5256. return new IndexMap(newIndexes, newIndexSet);
  5257. }
  5258. /**
  5259. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5260. */
  5261. addToIndexes(namedNode, existingChildren) {
  5262. const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
  5263. const index = safeGet(this.indexSet_, indexName);
  5264. assert(index, 'Missing index implementation for ' + indexName);
  5265. if (indexedChildren === fallbackObject) {
  5266. // Check to see if we need to index everything
  5267. if (index.isDefinedOn(namedNode.node)) {
  5268. // We need to build this index
  5269. const childList = [];
  5270. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5271. let next = iter.getNext();
  5272. while (next) {
  5273. if (next.name !== namedNode.name) {
  5274. childList.push(next);
  5275. }
  5276. next = iter.getNext();
  5277. }
  5278. childList.push(namedNode);
  5279. return buildChildSet(childList, index.getCompare());
  5280. }
  5281. else {
  5282. // No change, this remains a fallback
  5283. return fallbackObject;
  5284. }
  5285. }
  5286. else {
  5287. const existingSnap = existingChildren.get(namedNode.name);
  5288. let newChildren = indexedChildren;
  5289. if (existingSnap) {
  5290. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5291. }
  5292. return newChildren.insert(namedNode, namedNode.node);
  5293. }
  5294. });
  5295. return new IndexMap(newIndexes, this.indexSet_);
  5296. }
  5297. /**
  5298. * Create a new IndexMap instance with the given value removed
  5299. */
  5300. removeFromIndexes(namedNode, existingChildren) {
  5301. const newIndexes = map(this.indexes_, (indexedChildren) => {
  5302. if (indexedChildren === fallbackObject) {
  5303. // This is the fallback. Just return it, nothing to do in this case
  5304. return indexedChildren;
  5305. }
  5306. else {
  5307. const existingSnap = existingChildren.get(namedNode.name);
  5308. if (existingSnap) {
  5309. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5310. }
  5311. else {
  5312. // No record of this child
  5313. return indexedChildren;
  5314. }
  5315. }
  5316. });
  5317. return new IndexMap(newIndexes, this.indexSet_);
  5318. }
  5319. }
  5320. /**
  5321. * @license
  5322. * Copyright 2017 Google LLC
  5323. *
  5324. * Licensed under the Apache License, Version 2.0 (the "License");
  5325. * you may not use this file except in compliance with the License.
  5326. * You may obtain a copy of the License at
  5327. *
  5328. * http://www.apache.org/licenses/LICENSE-2.0
  5329. *
  5330. * Unless required by applicable law or agreed to in writing, software
  5331. * distributed under the License is distributed on an "AS IS" BASIS,
  5332. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5333. * See the License for the specific language governing permissions and
  5334. * limitations under the License.
  5335. */
  5336. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5337. let EMPTY_NODE;
  5338. /**
  5339. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5340. * (i.e. nodes with children). It implements Node and stores the
  5341. * list of children in the children property, sorted by child name.
  5342. */
  5343. class ChildrenNode {
  5344. /**
  5345. * @param children_ - List of children of this node..
  5346. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5347. */
  5348. constructor(children_, priorityNode_, indexMap_) {
  5349. this.children_ = children_;
  5350. this.priorityNode_ = priorityNode_;
  5351. this.indexMap_ = indexMap_;
  5352. this.lazyHash_ = null;
  5353. /**
  5354. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5355. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5356. * class instead of an empty ChildrenNode.
  5357. */
  5358. if (this.priorityNode_) {
  5359. validatePriorityNode(this.priorityNode_);
  5360. }
  5361. if (this.children_.isEmpty()) {
  5362. assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5363. }
  5364. }
  5365. static get EMPTY_NODE() {
  5366. return (EMPTY_NODE ||
  5367. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5368. }
  5369. /** @inheritDoc */
  5370. isLeafNode() {
  5371. return false;
  5372. }
  5373. /** @inheritDoc */
  5374. getPriority() {
  5375. return this.priorityNode_ || EMPTY_NODE;
  5376. }
  5377. /** @inheritDoc */
  5378. updatePriority(newPriorityNode) {
  5379. if (this.children_.isEmpty()) {
  5380. // Don't allow priorities on empty nodes
  5381. return this;
  5382. }
  5383. else {
  5384. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5385. }
  5386. }
  5387. /** @inheritDoc */
  5388. getImmediateChild(childName) {
  5389. // Hack to treat priority as a regular child
  5390. if (childName === '.priority') {
  5391. return this.getPriority();
  5392. }
  5393. else {
  5394. const child = this.children_.get(childName);
  5395. return child === null ? EMPTY_NODE : child;
  5396. }
  5397. }
  5398. /** @inheritDoc */
  5399. getChild(path) {
  5400. const front = pathGetFront(path);
  5401. if (front === null) {
  5402. return this;
  5403. }
  5404. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5405. }
  5406. /** @inheritDoc */
  5407. hasChild(childName) {
  5408. return this.children_.get(childName) !== null;
  5409. }
  5410. /** @inheritDoc */
  5411. updateImmediateChild(childName, newChildNode) {
  5412. assert(newChildNode, 'We should always be passing snapshot nodes');
  5413. if (childName === '.priority') {
  5414. return this.updatePriority(newChildNode);
  5415. }
  5416. else {
  5417. const namedNode = new NamedNode(childName, newChildNode);
  5418. let newChildren, newIndexMap;
  5419. if (newChildNode.isEmpty()) {
  5420. newChildren = this.children_.remove(childName);
  5421. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5422. }
  5423. else {
  5424. newChildren = this.children_.insert(childName, newChildNode);
  5425. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5426. }
  5427. const newPriority = newChildren.isEmpty()
  5428. ? EMPTY_NODE
  5429. : this.priorityNode_;
  5430. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5431. }
  5432. }
  5433. /** @inheritDoc */
  5434. updateChild(path, newChildNode) {
  5435. const front = pathGetFront(path);
  5436. if (front === null) {
  5437. return newChildNode;
  5438. }
  5439. else {
  5440. assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5441. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5442. return this.updateImmediateChild(front, newImmediateChild);
  5443. }
  5444. }
  5445. /** @inheritDoc */
  5446. isEmpty() {
  5447. return this.children_.isEmpty();
  5448. }
  5449. /** @inheritDoc */
  5450. numChildren() {
  5451. return this.children_.count();
  5452. }
  5453. /** @inheritDoc */
  5454. val(exportFormat) {
  5455. if (this.isEmpty()) {
  5456. return null;
  5457. }
  5458. const obj = {};
  5459. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5460. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5461. obj[key] = childNode.val(exportFormat);
  5462. numKeys++;
  5463. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5464. maxKey = Math.max(maxKey, Number(key));
  5465. }
  5466. else {
  5467. allIntegerKeys = false;
  5468. }
  5469. });
  5470. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5471. // convert to array.
  5472. const array = [];
  5473. // eslint-disable-next-line guard-for-in
  5474. for (const key in obj) {
  5475. array[key] = obj[key];
  5476. }
  5477. return array;
  5478. }
  5479. else {
  5480. if (exportFormat && !this.getPriority().isEmpty()) {
  5481. obj['.priority'] = this.getPriority().val();
  5482. }
  5483. return obj;
  5484. }
  5485. }
  5486. /** @inheritDoc */
  5487. hash() {
  5488. if (this.lazyHash_ === null) {
  5489. let toHash = '';
  5490. if (!this.getPriority().isEmpty()) {
  5491. toHash +=
  5492. 'priority:' +
  5493. priorityHashText(this.getPriority().val()) +
  5494. ':';
  5495. }
  5496. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5497. const childHash = childNode.hash();
  5498. if (childHash !== '') {
  5499. toHash += ':' + key + ':' + childHash;
  5500. }
  5501. });
  5502. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5503. }
  5504. return this.lazyHash_;
  5505. }
  5506. /** @inheritDoc */
  5507. getPredecessorChildName(childName, childNode, index) {
  5508. const idx = this.resolveIndex_(index);
  5509. if (idx) {
  5510. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5511. return predecessor ? predecessor.name : null;
  5512. }
  5513. else {
  5514. return this.children_.getPredecessorKey(childName);
  5515. }
  5516. }
  5517. getFirstChildName(indexDefinition) {
  5518. const idx = this.resolveIndex_(indexDefinition);
  5519. if (idx) {
  5520. const minKey = idx.minKey();
  5521. return minKey && minKey.name;
  5522. }
  5523. else {
  5524. return this.children_.minKey();
  5525. }
  5526. }
  5527. getFirstChild(indexDefinition) {
  5528. const minKey = this.getFirstChildName(indexDefinition);
  5529. if (minKey) {
  5530. return new NamedNode(minKey, this.children_.get(minKey));
  5531. }
  5532. else {
  5533. return null;
  5534. }
  5535. }
  5536. /**
  5537. * Given an index, return the key name of the largest value we have, according to that index
  5538. */
  5539. getLastChildName(indexDefinition) {
  5540. const idx = this.resolveIndex_(indexDefinition);
  5541. if (idx) {
  5542. const maxKey = idx.maxKey();
  5543. return maxKey && maxKey.name;
  5544. }
  5545. else {
  5546. return this.children_.maxKey();
  5547. }
  5548. }
  5549. getLastChild(indexDefinition) {
  5550. const maxKey = this.getLastChildName(indexDefinition);
  5551. if (maxKey) {
  5552. return new NamedNode(maxKey, this.children_.get(maxKey));
  5553. }
  5554. else {
  5555. return null;
  5556. }
  5557. }
  5558. forEachChild(index, action) {
  5559. const idx = this.resolveIndex_(index);
  5560. if (idx) {
  5561. return idx.inorderTraversal(wrappedNode => {
  5562. return action(wrappedNode.name, wrappedNode.node);
  5563. });
  5564. }
  5565. else {
  5566. return this.children_.inorderTraversal(action);
  5567. }
  5568. }
  5569. getIterator(indexDefinition) {
  5570. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5571. }
  5572. getIteratorFrom(startPost, indexDefinition) {
  5573. const idx = this.resolveIndex_(indexDefinition);
  5574. if (idx) {
  5575. return idx.getIteratorFrom(startPost, key => key);
  5576. }
  5577. else {
  5578. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5579. let next = iterator.peek();
  5580. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5581. iterator.getNext();
  5582. next = iterator.peek();
  5583. }
  5584. return iterator;
  5585. }
  5586. }
  5587. getReverseIterator(indexDefinition) {
  5588. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5589. }
  5590. getReverseIteratorFrom(endPost, indexDefinition) {
  5591. const idx = this.resolveIndex_(indexDefinition);
  5592. if (idx) {
  5593. return idx.getReverseIteratorFrom(endPost, key => {
  5594. return key;
  5595. });
  5596. }
  5597. else {
  5598. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5599. let next = iterator.peek();
  5600. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5601. iterator.getNext();
  5602. next = iterator.peek();
  5603. }
  5604. return iterator;
  5605. }
  5606. }
  5607. compareTo(other) {
  5608. if (this.isEmpty()) {
  5609. if (other.isEmpty()) {
  5610. return 0;
  5611. }
  5612. else {
  5613. return -1;
  5614. }
  5615. }
  5616. else if (other.isLeafNode() || other.isEmpty()) {
  5617. return 1;
  5618. }
  5619. else if (other === MAX_NODE) {
  5620. return -1;
  5621. }
  5622. else {
  5623. // Must be another node with children.
  5624. return 0;
  5625. }
  5626. }
  5627. withIndex(indexDefinition) {
  5628. if (indexDefinition === KEY_INDEX ||
  5629. this.indexMap_.hasIndex(indexDefinition)) {
  5630. return this;
  5631. }
  5632. else {
  5633. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5634. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5635. }
  5636. }
  5637. isIndexed(index) {
  5638. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5639. }
  5640. equals(other) {
  5641. if (other === this) {
  5642. return true;
  5643. }
  5644. else if (other.isLeafNode()) {
  5645. return false;
  5646. }
  5647. else {
  5648. const otherChildrenNode = other;
  5649. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5650. return false;
  5651. }
  5652. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5653. const thisIter = this.getIterator(PRIORITY_INDEX);
  5654. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5655. let thisCurrent = thisIter.getNext();
  5656. let otherCurrent = otherIter.getNext();
  5657. while (thisCurrent && otherCurrent) {
  5658. if (thisCurrent.name !== otherCurrent.name ||
  5659. !thisCurrent.node.equals(otherCurrent.node)) {
  5660. return false;
  5661. }
  5662. thisCurrent = thisIter.getNext();
  5663. otherCurrent = otherIter.getNext();
  5664. }
  5665. return thisCurrent === null && otherCurrent === null;
  5666. }
  5667. else {
  5668. return false;
  5669. }
  5670. }
  5671. }
  5672. /**
  5673. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5674. * instead.
  5675. *
  5676. */
  5677. resolveIndex_(indexDefinition) {
  5678. if (indexDefinition === KEY_INDEX) {
  5679. return null;
  5680. }
  5681. else {
  5682. return this.indexMap_.get(indexDefinition.toString());
  5683. }
  5684. }
  5685. }
  5686. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5687. class MaxNode extends ChildrenNode {
  5688. constructor() {
  5689. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5690. }
  5691. compareTo(other) {
  5692. if (other === this) {
  5693. return 0;
  5694. }
  5695. else {
  5696. return 1;
  5697. }
  5698. }
  5699. equals(other) {
  5700. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5701. return other === this;
  5702. }
  5703. getPriority() {
  5704. return this;
  5705. }
  5706. getImmediateChild(childName) {
  5707. return ChildrenNode.EMPTY_NODE;
  5708. }
  5709. isEmpty() {
  5710. return false;
  5711. }
  5712. }
  5713. /**
  5714. * Marker that will sort higher than any other snapshot.
  5715. */
  5716. const MAX_NODE = new MaxNode();
  5717. Object.defineProperties(NamedNode, {
  5718. MIN: {
  5719. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5720. },
  5721. MAX: {
  5722. value: new NamedNode(MAX_NAME, MAX_NODE)
  5723. }
  5724. });
  5725. /**
  5726. * Reference Extensions
  5727. */
  5728. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5729. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5730. setMaxNode$1(MAX_NODE);
  5731. setMaxNode(MAX_NODE);
  5732. /**
  5733. * @license
  5734. * Copyright 2017 Google LLC
  5735. *
  5736. * Licensed under the Apache License, Version 2.0 (the "License");
  5737. * you may not use this file except in compliance with the License.
  5738. * You may obtain a copy of the License at
  5739. *
  5740. * http://www.apache.org/licenses/LICENSE-2.0
  5741. *
  5742. * Unless required by applicable law or agreed to in writing, software
  5743. * distributed under the License is distributed on an "AS IS" BASIS,
  5744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5745. * See the License for the specific language governing permissions and
  5746. * limitations under the License.
  5747. */
  5748. const USE_HINZE = true;
  5749. /**
  5750. * Constructs a snapshot node representing the passed JSON and returns it.
  5751. * @param json - JSON to create a node for.
  5752. * @param priority - Optional priority to use. This will be ignored if the
  5753. * passed JSON contains a .priority property.
  5754. */
  5755. function nodeFromJSON(json, priority = null) {
  5756. if (json === null) {
  5757. return ChildrenNode.EMPTY_NODE;
  5758. }
  5759. if (typeof json === 'object' && '.priority' in json) {
  5760. priority = json['.priority'];
  5761. }
  5762. assert(priority === null ||
  5763. typeof priority === 'string' ||
  5764. typeof priority === 'number' ||
  5765. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5766. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5767. json = json['.value'];
  5768. }
  5769. // Valid leaf nodes include non-objects or server-value wrapper objects
  5770. if (typeof json !== 'object' || '.sv' in json) {
  5771. const jsonLeaf = json;
  5772. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5773. }
  5774. if (!(json instanceof Array) && USE_HINZE) {
  5775. const children = [];
  5776. let childrenHavePriority = false;
  5777. const hinzeJsonObj = json;
  5778. each(hinzeJsonObj, (key, child) => {
  5779. if (key.substring(0, 1) !== '.') {
  5780. // Ignore metadata nodes
  5781. const childNode = nodeFromJSON(child);
  5782. if (!childNode.isEmpty()) {
  5783. childrenHavePriority =
  5784. childrenHavePriority || !childNode.getPriority().isEmpty();
  5785. children.push(new NamedNode(key, childNode));
  5786. }
  5787. }
  5788. });
  5789. if (children.length === 0) {
  5790. return ChildrenNode.EMPTY_NODE;
  5791. }
  5792. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5793. if (childrenHavePriority) {
  5794. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5795. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5796. }
  5797. else {
  5798. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5799. }
  5800. }
  5801. else {
  5802. let node = ChildrenNode.EMPTY_NODE;
  5803. each(json, (key, childData) => {
  5804. if (contains(json, key)) {
  5805. if (key.substring(0, 1) !== '.') {
  5806. // ignore metadata nodes.
  5807. const childNode = nodeFromJSON(childData);
  5808. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5809. node = node.updateImmediateChild(key, childNode);
  5810. }
  5811. }
  5812. }
  5813. });
  5814. return node.updatePriority(nodeFromJSON(priority));
  5815. }
  5816. }
  5817. setNodeFromJSON(nodeFromJSON);
  5818. /**
  5819. * @license
  5820. * Copyright 2017 Google LLC
  5821. *
  5822. * Licensed under the Apache License, Version 2.0 (the "License");
  5823. * you may not use this file except in compliance with the License.
  5824. * You may obtain a copy of the License at
  5825. *
  5826. * http://www.apache.org/licenses/LICENSE-2.0
  5827. *
  5828. * Unless required by applicable law or agreed to in writing, software
  5829. * distributed under the License is distributed on an "AS IS" BASIS,
  5830. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5831. * See the License for the specific language governing permissions and
  5832. * limitations under the License.
  5833. */
  5834. class PathIndex extends Index {
  5835. constructor(indexPath_) {
  5836. super();
  5837. this.indexPath_ = indexPath_;
  5838. assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5839. }
  5840. extractChild(snap) {
  5841. return snap.getChild(this.indexPath_);
  5842. }
  5843. isDefinedOn(node) {
  5844. return !node.getChild(this.indexPath_).isEmpty();
  5845. }
  5846. compare(a, b) {
  5847. const aChild = this.extractChild(a.node);
  5848. const bChild = this.extractChild(b.node);
  5849. const indexCmp = aChild.compareTo(bChild);
  5850. if (indexCmp === 0) {
  5851. return nameCompare(a.name, b.name);
  5852. }
  5853. else {
  5854. return indexCmp;
  5855. }
  5856. }
  5857. makePost(indexValue, name) {
  5858. const valueNode = nodeFromJSON(indexValue);
  5859. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5860. return new NamedNode(name, node);
  5861. }
  5862. maxPost() {
  5863. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5864. return new NamedNode(MAX_NAME, node);
  5865. }
  5866. toString() {
  5867. return pathSlice(this.indexPath_, 0).join('/');
  5868. }
  5869. }
  5870. /**
  5871. * @license
  5872. * Copyright 2017 Google LLC
  5873. *
  5874. * Licensed under the Apache License, Version 2.0 (the "License");
  5875. * you may not use this file except in compliance with the License.
  5876. * You may obtain a copy of the License at
  5877. *
  5878. * http://www.apache.org/licenses/LICENSE-2.0
  5879. *
  5880. * Unless required by applicable law or agreed to in writing, software
  5881. * distributed under the License is distributed on an "AS IS" BASIS,
  5882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5883. * See the License for the specific language governing permissions and
  5884. * limitations under the License.
  5885. */
  5886. class ValueIndex extends Index {
  5887. compare(a, b) {
  5888. const indexCmp = a.node.compareTo(b.node);
  5889. if (indexCmp === 0) {
  5890. return nameCompare(a.name, b.name);
  5891. }
  5892. else {
  5893. return indexCmp;
  5894. }
  5895. }
  5896. isDefinedOn(node) {
  5897. return true;
  5898. }
  5899. indexedValueChanged(oldNode, newNode) {
  5900. return !oldNode.equals(newNode);
  5901. }
  5902. minPost() {
  5903. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5904. return NamedNode.MIN;
  5905. }
  5906. maxPost() {
  5907. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5908. return NamedNode.MAX;
  5909. }
  5910. makePost(indexValue, name) {
  5911. const valueNode = nodeFromJSON(indexValue);
  5912. return new NamedNode(name, valueNode);
  5913. }
  5914. /**
  5915. * @returns String representation for inclusion in a query spec
  5916. */
  5917. toString() {
  5918. return '.value';
  5919. }
  5920. }
  5921. const VALUE_INDEX = new ValueIndex();
  5922. /**
  5923. * @license
  5924. * Copyright 2017 Google LLC
  5925. *
  5926. * Licensed under the Apache License, Version 2.0 (the "License");
  5927. * you may not use this file except in compliance with the License.
  5928. * You may obtain a copy of the License at
  5929. *
  5930. * http://www.apache.org/licenses/LICENSE-2.0
  5931. *
  5932. * Unless required by applicable law or agreed to in writing, software
  5933. * distributed under the License is distributed on an "AS IS" BASIS,
  5934. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5935. * See the License for the specific language governing permissions and
  5936. * limitations under the License.
  5937. */
  5938. function changeValue(snapshotNode) {
  5939. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5940. }
  5941. function changeChildAdded(childName, snapshotNode) {
  5942. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5943. }
  5944. function changeChildRemoved(childName, snapshotNode) {
  5945. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5946. }
  5947. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5948. return {
  5949. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5950. snapshotNode,
  5951. childName,
  5952. oldSnap
  5953. };
  5954. }
  5955. function changeChildMoved(childName, snapshotNode) {
  5956. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5957. }
  5958. /**
  5959. * @license
  5960. * Copyright 2017 Google LLC
  5961. *
  5962. * Licensed under the Apache License, Version 2.0 (the "License");
  5963. * you may not use this file except in compliance with the License.
  5964. * You may obtain a copy of the License at
  5965. *
  5966. * http://www.apache.org/licenses/LICENSE-2.0
  5967. *
  5968. * Unless required by applicable law or agreed to in writing, software
  5969. * distributed under the License is distributed on an "AS IS" BASIS,
  5970. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5971. * See the License for the specific language governing permissions and
  5972. * limitations under the License.
  5973. */
  5974. /**
  5975. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5976. */
  5977. class IndexedFilter {
  5978. constructor(index_) {
  5979. this.index_ = index_;
  5980. }
  5981. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5982. assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5983. const oldChild = snap.getImmediateChild(key);
  5984. // Check if anything actually changed.
  5985. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5986. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5987. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5988. // to avoid treating these cases as "nothing changed."
  5989. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5990. // Nothing changed.
  5991. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  5992. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  5993. return snap;
  5994. }
  5995. }
  5996. if (optChangeAccumulator != null) {
  5997. if (newChild.isEmpty()) {
  5998. if (snap.hasChild(key)) {
  5999. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6000. }
  6001. else {
  6002. assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6003. }
  6004. }
  6005. else if (oldChild.isEmpty()) {
  6006. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6007. }
  6008. else {
  6009. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6010. }
  6011. }
  6012. if (snap.isLeafNode() && newChild.isEmpty()) {
  6013. return snap;
  6014. }
  6015. else {
  6016. // Make sure the node is indexed
  6017. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6018. }
  6019. }
  6020. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6021. if (optChangeAccumulator != null) {
  6022. if (!oldSnap.isLeafNode()) {
  6023. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6024. if (!newSnap.hasChild(key)) {
  6025. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6026. }
  6027. });
  6028. }
  6029. if (!newSnap.isLeafNode()) {
  6030. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6031. if (oldSnap.hasChild(key)) {
  6032. const oldChild = oldSnap.getImmediateChild(key);
  6033. if (!oldChild.equals(childNode)) {
  6034. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6035. }
  6036. }
  6037. else {
  6038. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6039. }
  6040. });
  6041. }
  6042. }
  6043. return newSnap.withIndex(this.index_);
  6044. }
  6045. updatePriority(oldSnap, newPriority) {
  6046. if (oldSnap.isEmpty()) {
  6047. return ChildrenNode.EMPTY_NODE;
  6048. }
  6049. else {
  6050. return oldSnap.updatePriority(newPriority);
  6051. }
  6052. }
  6053. filtersNodes() {
  6054. return false;
  6055. }
  6056. getIndexedFilter() {
  6057. return this;
  6058. }
  6059. getIndex() {
  6060. return this.index_;
  6061. }
  6062. }
  6063. /**
  6064. * @license
  6065. * Copyright 2017 Google LLC
  6066. *
  6067. * Licensed under the Apache License, Version 2.0 (the "License");
  6068. * you may not use this file except in compliance with the License.
  6069. * You may obtain a copy of the License at
  6070. *
  6071. * http://www.apache.org/licenses/LICENSE-2.0
  6072. *
  6073. * Unless required by applicable law or agreed to in writing, software
  6074. * distributed under the License is distributed on an "AS IS" BASIS,
  6075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6076. * See the License for the specific language governing permissions and
  6077. * limitations under the License.
  6078. */
  6079. /**
  6080. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6081. */
  6082. class RangedFilter {
  6083. constructor(params) {
  6084. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6085. this.index_ = params.getIndex();
  6086. this.startPost_ = RangedFilter.getStartPost_(params);
  6087. this.endPost_ = RangedFilter.getEndPost_(params);
  6088. this.startIsInclusive_ = !params.startAfterSet_;
  6089. this.endIsInclusive_ = !params.endBeforeSet_;
  6090. }
  6091. getStartPost() {
  6092. return this.startPost_;
  6093. }
  6094. getEndPost() {
  6095. return this.endPost_;
  6096. }
  6097. matches(node) {
  6098. const isWithinStart = this.startIsInclusive_
  6099. ? this.index_.compare(this.getStartPost(), node) <= 0
  6100. : this.index_.compare(this.getStartPost(), node) < 0;
  6101. const isWithinEnd = this.endIsInclusive_
  6102. ? this.index_.compare(node, this.getEndPost()) <= 0
  6103. : this.index_.compare(node, this.getEndPost()) < 0;
  6104. return isWithinStart && isWithinEnd;
  6105. }
  6106. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6107. if (!this.matches(new NamedNode(key, newChild))) {
  6108. newChild = ChildrenNode.EMPTY_NODE;
  6109. }
  6110. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6111. }
  6112. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6113. if (newSnap.isLeafNode()) {
  6114. // Make sure we have a children node with the correct index, not a leaf node;
  6115. newSnap = ChildrenNode.EMPTY_NODE;
  6116. }
  6117. let filtered = newSnap.withIndex(this.index_);
  6118. // Don't support priorities on queries
  6119. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6120. const self = this;
  6121. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6122. if (!self.matches(new NamedNode(key, childNode))) {
  6123. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6124. }
  6125. });
  6126. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6127. }
  6128. updatePriority(oldSnap, newPriority) {
  6129. // Don't support priorities on queries
  6130. return oldSnap;
  6131. }
  6132. filtersNodes() {
  6133. return true;
  6134. }
  6135. getIndexedFilter() {
  6136. return this.indexedFilter_;
  6137. }
  6138. getIndex() {
  6139. return this.index_;
  6140. }
  6141. static getStartPost_(params) {
  6142. if (params.hasStart()) {
  6143. const startName = params.getIndexStartName();
  6144. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6145. }
  6146. else {
  6147. return params.getIndex().minPost();
  6148. }
  6149. }
  6150. static getEndPost_(params) {
  6151. if (params.hasEnd()) {
  6152. const endName = params.getIndexEndName();
  6153. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6154. }
  6155. else {
  6156. return params.getIndex().maxPost();
  6157. }
  6158. }
  6159. }
  6160. /**
  6161. * @license
  6162. * Copyright 2017 Google LLC
  6163. *
  6164. * Licensed under the Apache License, Version 2.0 (the "License");
  6165. * you may not use this file except in compliance with the License.
  6166. * You may obtain a copy of the License at
  6167. *
  6168. * http://www.apache.org/licenses/LICENSE-2.0
  6169. *
  6170. * Unless required by applicable law or agreed to in writing, software
  6171. * distributed under the License is distributed on an "AS IS" BASIS,
  6172. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6173. * See the License for the specific language governing permissions and
  6174. * limitations under the License.
  6175. */
  6176. /**
  6177. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6178. */
  6179. class LimitedFilter {
  6180. constructor(params) {
  6181. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6182. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6183. this.withinStartPost = (node) => {
  6184. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6185. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6186. };
  6187. this.withinEndPost = (node) => {
  6188. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6189. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6190. };
  6191. this.rangedFilter_ = new RangedFilter(params);
  6192. this.index_ = params.getIndex();
  6193. this.limit_ = params.getLimit();
  6194. this.reverse_ = !params.isViewFromLeft();
  6195. this.startIsInclusive_ = !params.startAfterSet_;
  6196. this.endIsInclusive_ = !params.endBeforeSet_;
  6197. }
  6198. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6199. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6200. newChild = ChildrenNode.EMPTY_NODE;
  6201. }
  6202. if (snap.getImmediateChild(key).equals(newChild)) {
  6203. // No change
  6204. return snap;
  6205. }
  6206. else if (snap.numChildren() < this.limit_) {
  6207. return this.rangedFilter_
  6208. .getIndexedFilter()
  6209. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6210. }
  6211. else {
  6212. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6213. }
  6214. }
  6215. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6216. let filtered;
  6217. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6218. // Make sure we have a children node with the correct index, not a leaf node;
  6219. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6220. }
  6221. else {
  6222. if (this.limit_ * 2 < newSnap.numChildren() &&
  6223. newSnap.isIndexed(this.index_)) {
  6224. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6225. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6226. // anchor to the startPost, endPost, or last element as appropriate
  6227. let iterator;
  6228. if (this.reverse_) {
  6229. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6230. }
  6231. else {
  6232. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6233. }
  6234. let count = 0;
  6235. while (iterator.hasNext() && count < this.limit_) {
  6236. const next = iterator.getNext();
  6237. if (!this.withinDirectionalStart(next)) {
  6238. // if we have not reached the start, skip to the next element
  6239. continue;
  6240. }
  6241. else if (!this.withinDirectionalEnd(next)) {
  6242. // if we have reached the end, stop adding elements
  6243. break;
  6244. }
  6245. else {
  6246. filtered = filtered.updateImmediateChild(next.name, next.node);
  6247. count++;
  6248. }
  6249. }
  6250. }
  6251. else {
  6252. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6253. filtered = newSnap.withIndex(this.index_);
  6254. // Don't support priorities on queries
  6255. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6256. let iterator;
  6257. if (this.reverse_) {
  6258. iterator = filtered.getReverseIterator(this.index_);
  6259. }
  6260. else {
  6261. iterator = filtered.getIterator(this.index_);
  6262. }
  6263. let count = 0;
  6264. while (iterator.hasNext()) {
  6265. const next = iterator.getNext();
  6266. const inRange = count < this.limit_ &&
  6267. this.withinDirectionalStart(next) &&
  6268. this.withinDirectionalEnd(next);
  6269. if (inRange) {
  6270. count++;
  6271. }
  6272. else {
  6273. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6274. }
  6275. }
  6276. }
  6277. }
  6278. return this.rangedFilter_
  6279. .getIndexedFilter()
  6280. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6281. }
  6282. updatePriority(oldSnap, newPriority) {
  6283. // Don't support priorities on queries
  6284. return oldSnap;
  6285. }
  6286. filtersNodes() {
  6287. return true;
  6288. }
  6289. getIndexedFilter() {
  6290. return this.rangedFilter_.getIndexedFilter();
  6291. }
  6292. getIndex() {
  6293. return this.index_;
  6294. }
  6295. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6296. // TODO: rename all cache stuff etc to general snap terminology
  6297. let cmp;
  6298. if (this.reverse_) {
  6299. const indexCmp = this.index_.getCompare();
  6300. cmp = (a, b) => indexCmp(b, a);
  6301. }
  6302. else {
  6303. cmp = this.index_.getCompare();
  6304. }
  6305. const oldEventCache = snap;
  6306. assert(oldEventCache.numChildren() === this.limit_, '');
  6307. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6308. const windowBoundary = this.reverse_
  6309. ? oldEventCache.getFirstChild(this.index_)
  6310. : oldEventCache.getLastChild(this.index_);
  6311. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6312. if (oldEventCache.hasChild(childKey)) {
  6313. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6314. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6315. while (nextChild != null &&
  6316. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6317. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6318. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6319. // the limited filter...
  6320. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6321. }
  6322. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6323. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6324. if (remainsInWindow) {
  6325. if (changeAccumulator != null) {
  6326. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6327. }
  6328. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6329. }
  6330. else {
  6331. if (changeAccumulator != null) {
  6332. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6333. }
  6334. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6335. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6336. if (nextChildInRange) {
  6337. if (changeAccumulator != null) {
  6338. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6339. }
  6340. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6341. }
  6342. else {
  6343. return newEventCache;
  6344. }
  6345. }
  6346. }
  6347. else if (childSnap.isEmpty()) {
  6348. // we're deleting a node, but it was not in the window, so ignore it
  6349. return snap;
  6350. }
  6351. else if (inRange) {
  6352. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6353. if (changeAccumulator != null) {
  6354. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6355. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6356. }
  6357. return oldEventCache
  6358. .updateImmediateChild(childKey, childSnap)
  6359. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6360. }
  6361. else {
  6362. return snap;
  6363. }
  6364. }
  6365. else {
  6366. return snap;
  6367. }
  6368. }
  6369. }
  6370. /**
  6371. * @license
  6372. * Copyright 2017 Google LLC
  6373. *
  6374. * Licensed under the Apache License, Version 2.0 (the "License");
  6375. * you may not use this file except in compliance with the License.
  6376. * You may obtain a copy of the License at
  6377. *
  6378. * http://www.apache.org/licenses/LICENSE-2.0
  6379. *
  6380. * Unless required by applicable law or agreed to in writing, software
  6381. * distributed under the License is distributed on an "AS IS" BASIS,
  6382. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6383. * See the License for the specific language governing permissions and
  6384. * limitations under the License.
  6385. */
  6386. /**
  6387. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6388. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6389. * user-facing API level, so it is not done here.
  6390. *
  6391. * @internal
  6392. */
  6393. class QueryParams {
  6394. constructor() {
  6395. this.limitSet_ = false;
  6396. this.startSet_ = false;
  6397. this.startNameSet_ = false;
  6398. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6399. this.endSet_ = false;
  6400. this.endNameSet_ = false;
  6401. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6402. this.limit_ = 0;
  6403. this.viewFrom_ = '';
  6404. this.indexStartValue_ = null;
  6405. this.indexStartName_ = '';
  6406. this.indexEndValue_ = null;
  6407. this.indexEndName_ = '';
  6408. this.index_ = PRIORITY_INDEX;
  6409. }
  6410. hasStart() {
  6411. return this.startSet_;
  6412. }
  6413. /**
  6414. * @returns True if it would return from left.
  6415. */
  6416. isViewFromLeft() {
  6417. if (this.viewFrom_ === '') {
  6418. // limit(), rather than limitToFirst or limitToLast was called.
  6419. // This means that only one of startSet_ and endSet_ is true. Use them
  6420. // to calculate which side of the view to anchor to. If neither is set,
  6421. // anchor to the end.
  6422. return this.startSet_;
  6423. }
  6424. else {
  6425. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6426. }
  6427. }
  6428. /**
  6429. * Only valid to call if hasStart() returns true
  6430. */
  6431. getIndexStartValue() {
  6432. assert(this.startSet_, 'Only valid if start has been set');
  6433. return this.indexStartValue_;
  6434. }
  6435. /**
  6436. * Only valid to call if hasStart() returns true.
  6437. * Returns the starting key name for the range defined by these query parameters
  6438. */
  6439. getIndexStartName() {
  6440. assert(this.startSet_, 'Only valid if start has been set');
  6441. if (this.startNameSet_) {
  6442. return this.indexStartName_;
  6443. }
  6444. else {
  6445. return MIN_NAME;
  6446. }
  6447. }
  6448. hasEnd() {
  6449. return this.endSet_;
  6450. }
  6451. /**
  6452. * Only valid to call if hasEnd() returns true.
  6453. */
  6454. getIndexEndValue() {
  6455. assert(this.endSet_, 'Only valid if end has been set');
  6456. return this.indexEndValue_;
  6457. }
  6458. /**
  6459. * Only valid to call if hasEnd() returns true.
  6460. * Returns the end key name for the range defined by these query parameters
  6461. */
  6462. getIndexEndName() {
  6463. assert(this.endSet_, 'Only valid if end has been set');
  6464. if (this.endNameSet_) {
  6465. return this.indexEndName_;
  6466. }
  6467. else {
  6468. return MAX_NAME;
  6469. }
  6470. }
  6471. hasLimit() {
  6472. return this.limitSet_;
  6473. }
  6474. /**
  6475. * @returns True if a limit has been set and it has been explicitly anchored
  6476. */
  6477. hasAnchoredLimit() {
  6478. return this.limitSet_ && this.viewFrom_ !== '';
  6479. }
  6480. /**
  6481. * Only valid to call if hasLimit() returns true
  6482. */
  6483. getLimit() {
  6484. assert(this.limitSet_, 'Only valid if limit has been set');
  6485. return this.limit_;
  6486. }
  6487. getIndex() {
  6488. return this.index_;
  6489. }
  6490. loadsAllData() {
  6491. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6492. }
  6493. isDefault() {
  6494. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6495. }
  6496. copy() {
  6497. const copy = new QueryParams();
  6498. copy.limitSet_ = this.limitSet_;
  6499. copy.limit_ = this.limit_;
  6500. copy.startSet_ = this.startSet_;
  6501. copy.startAfterSet_ = this.startAfterSet_;
  6502. copy.indexStartValue_ = this.indexStartValue_;
  6503. copy.startNameSet_ = this.startNameSet_;
  6504. copy.indexStartName_ = this.indexStartName_;
  6505. copy.endSet_ = this.endSet_;
  6506. copy.endBeforeSet_ = this.endBeforeSet_;
  6507. copy.indexEndValue_ = this.indexEndValue_;
  6508. copy.endNameSet_ = this.endNameSet_;
  6509. copy.indexEndName_ = this.indexEndName_;
  6510. copy.index_ = this.index_;
  6511. copy.viewFrom_ = this.viewFrom_;
  6512. return copy;
  6513. }
  6514. }
  6515. function queryParamsGetNodeFilter(queryParams) {
  6516. if (queryParams.loadsAllData()) {
  6517. return new IndexedFilter(queryParams.getIndex());
  6518. }
  6519. else if (queryParams.hasLimit()) {
  6520. return new LimitedFilter(queryParams);
  6521. }
  6522. else {
  6523. return new RangedFilter(queryParams);
  6524. }
  6525. }
  6526. function queryParamsLimitToFirst(queryParams, newLimit) {
  6527. const newParams = queryParams.copy();
  6528. newParams.limitSet_ = true;
  6529. newParams.limit_ = newLimit;
  6530. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6531. return newParams;
  6532. }
  6533. function queryParamsLimitToLast(queryParams, newLimit) {
  6534. const newParams = queryParams.copy();
  6535. newParams.limitSet_ = true;
  6536. newParams.limit_ = newLimit;
  6537. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6538. return newParams;
  6539. }
  6540. function queryParamsStartAt(queryParams, indexValue, key) {
  6541. const newParams = queryParams.copy();
  6542. newParams.startSet_ = true;
  6543. if (indexValue === undefined) {
  6544. indexValue = null;
  6545. }
  6546. newParams.indexStartValue_ = indexValue;
  6547. if (key != null) {
  6548. newParams.startNameSet_ = true;
  6549. newParams.indexStartName_ = key;
  6550. }
  6551. else {
  6552. newParams.startNameSet_ = false;
  6553. newParams.indexStartName_ = '';
  6554. }
  6555. return newParams;
  6556. }
  6557. function queryParamsStartAfter(queryParams, indexValue, key) {
  6558. let params;
  6559. if (queryParams.index_ === KEY_INDEX || !!key) {
  6560. params = queryParamsStartAt(queryParams, indexValue, key);
  6561. }
  6562. else {
  6563. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6564. }
  6565. params.startAfterSet_ = true;
  6566. return params;
  6567. }
  6568. function queryParamsEndAt(queryParams, indexValue, key) {
  6569. const newParams = queryParams.copy();
  6570. newParams.endSet_ = true;
  6571. if (indexValue === undefined) {
  6572. indexValue = null;
  6573. }
  6574. newParams.indexEndValue_ = indexValue;
  6575. if (key !== undefined) {
  6576. newParams.endNameSet_ = true;
  6577. newParams.indexEndName_ = key;
  6578. }
  6579. else {
  6580. newParams.endNameSet_ = false;
  6581. newParams.indexEndName_ = '';
  6582. }
  6583. return newParams;
  6584. }
  6585. function queryParamsEndBefore(queryParams, indexValue, key) {
  6586. let params;
  6587. if (queryParams.index_ === KEY_INDEX || !!key) {
  6588. params = queryParamsEndAt(queryParams, indexValue, key);
  6589. }
  6590. else {
  6591. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6592. }
  6593. params.endBeforeSet_ = true;
  6594. return params;
  6595. }
  6596. function queryParamsOrderBy(queryParams, index) {
  6597. const newParams = queryParams.copy();
  6598. newParams.index_ = index;
  6599. return newParams;
  6600. }
  6601. /**
  6602. * Returns a set of REST query string parameters representing this query.
  6603. *
  6604. * @returns query string parameters
  6605. */
  6606. function queryParamsToRestQueryStringParameters(queryParams) {
  6607. const qs = {};
  6608. if (queryParams.isDefault()) {
  6609. return qs;
  6610. }
  6611. let orderBy;
  6612. if (queryParams.index_ === PRIORITY_INDEX) {
  6613. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6614. }
  6615. else if (queryParams.index_ === VALUE_INDEX) {
  6616. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6617. }
  6618. else if (queryParams.index_ === KEY_INDEX) {
  6619. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6620. }
  6621. else {
  6622. assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6623. orderBy = queryParams.index_.toString();
  6624. }
  6625. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);
  6626. if (queryParams.startSet_) {
  6627. const startParam = queryParams.startAfterSet_
  6628. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6629. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6630. qs[startParam] = stringify(queryParams.indexStartValue_);
  6631. if (queryParams.startNameSet_) {
  6632. qs[startParam] += ',' + stringify(queryParams.indexStartName_);
  6633. }
  6634. }
  6635. if (queryParams.endSet_) {
  6636. const endParam = queryParams.endBeforeSet_
  6637. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6638. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6639. qs[endParam] = stringify(queryParams.indexEndValue_);
  6640. if (queryParams.endNameSet_) {
  6641. qs[endParam] += ',' + stringify(queryParams.indexEndName_);
  6642. }
  6643. }
  6644. if (queryParams.limitSet_) {
  6645. if (queryParams.isViewFromLeft()) {
  6646. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6647. }
  6648. else {
  6649. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6650. }
  6651. }
  6652. return qs;
  6653. }
  6654. function queryParamsGetQueryObject(queryParams) {
  6655. const obj = {};
  6656. if (queryParams.startSet_) {
  6657. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6658. queryParams.indexStartValue_;
  6659. if (queryParams.startNameSet_) {
  6660. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6661. queryParams.indexStartName_;
  6662. }
  6663. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6664. !queryParams.startAfterSet_;
  6665. }
  6666. if (queryParams.endSet_) {
  6667. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6668. if (queryParams.endNameSet_) {
  6669. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6670. }
  6671. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6672. !queryParams.endBeforeSet_;
  6673. }
  6674. if (queryParams.limitSet_) {
  6675. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6676. let viewFrom = queryParams.viewFrom_;
  6677. if (viewFrom === '') {
  6678. if (queryParams.isViewFromLeft()) {
  6679. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6680. }
  6681. else {
  6682. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6683. }
  6684. }
  6685. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6686. }
  6687. // For now, priority index is the default, so we only specify if it's some other index
  6688. if (queryParams.index_ !== PRIORITY_INDEX) {
  6689. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6690. }
  6691. return obj;
  6692. }
  6693. /**
  6694. * @license
  6695. * Copyright 2017 Google LLC
  6696. *
  6697. * Licensed under the Apache License, Version 2.0 (the "License");
  6698. * you may not use this file except in compliance with the License.
  6699. * You may obtain a copy of the License at
  6700. *
  6701. * http://www.apache.org/licenses/LICENSE-2.0
  6702. *
  6703. * Unless required by applicable law or agreed to in writing, software
  6704. * distributed under the License is distributed on an "AS IS" BASIS,
  6705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6706. * See the License for the specific language governing permissions and
  6707. * limitations under the License.
  6708. */
  6709. /**
  6710. * An implementation of ServerActions that communicates with the server via REST requests.
  6711. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6712. * persistent connection (using WebSockets or long-polling)
  6713. */
  6714. class ReadonlyRestClient extends ServerActions {
  6715. /**
  6716. * @param repoInfo_ - Data about the namespace we are connecting to
  6717. * @param onDataUpdate_ - A callback for new data from the server
  6718. */
  6719. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6720. super();
  6721. this.repoInfo_ = repoInfo_;
  6722. this.onDataUpdate_ = onDataUpdate_;
  6723. this.authTokenProvider_ = authTokenProvider_;
  6724. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6725. /** @private {function(...[*])} */
  6726. this.log_ = logWrapper('p:rest:');
  6727. /**
  6728. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6729. * that's been removed. :-/
  6730. */
  6731. this.listens_ = {};
  6732. }
  6733. reportStats(stats) {
  6734. throw new Error('Method not implemented.');
  6735. }
  6736. static getListenId_(query, tag) {
  6737. if (tag !== undefined) {
  6738. return 'tag$' + tag;
  6739. }
  6740. else {
  6741. assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6742. return query._path.toString();
  6743. }
  6744. }
  6745. /** @inheritDoc */
  6746. listen(query, currentHashFn, tag, onComplete) {
  6747. const pathString = query._path.toString();
  6748. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6749. // Mark this listener so we can tell if it's removed.
  6750. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6751. const thisListen = {};
  6752. this.listens_[listenId] = thisListen;
  6753. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6754. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6755. let data = result;
  6756. if (error === 404) {
  6757. data = null;
  6758. error = null;
  6759. }
  6760. if (error === null) {
  6761. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6762. }
  6763. if (safeGet(this.listens_, listenId) === thisListen) {
  6764. let status;
  6765. if (!error) {
  6766. status = 'ok';
  6767. }
  6768. else if (error === 401) {
  6769. status = 'permission_denied';
  6770. }
  6771. else {
  6772. status = 'rest_error:' + error;
  6773. }
  6774. onComplete(status, null);
  6775. }
  6776. });
  6777. }
  6778. /** @inheritDoc */
  6779. unlisten(query, tag) {
  6780. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6781. delete this.listens_[listenId];
  6782. }
  6783. get(query) {
  6784. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6785. const pathString = query._path.toString();
  6786. const deferred = new Deferred();
  6787. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6788. let data = result;
  6789. if (error === 404) {
  6790. data = null;
  6791. error = null;
  6792. }
  6793. if (error === null) {
  6794. this.onDataUpdate_(pathString, data,
  6795. /*isMerge=*/ false,
  6796. /*tag=*/ null);
  6797. deferred.resolve(data);
  6798. }
  6799. else {
  6800. deferred.reject(new Error(data));
  6801. }
  6802. });
  6803. return deferred.promise;
  6804. }
  6805. /** @inheritDoc */
  6806. refreshAuthToken(token) {
  6807. // no-op since we just always call getToken.
  6808. }
  6809. /**
  6810. * Performs a REST request to the given path, with the provided query string parameters,
  6811. * and any auth credentials we have.
  6812. */
  6813. restRequest_(pathString, queryStringParameters = {}, callback) {
  6814. queryStringParameters['format'] = 'export';
  6815. return Promise.all([
  6816. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6817. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6818. ]).then(([authToken, appCheckToken]) => {
  6819. if (authToken && authToken.accessToken) {
  6820. queryStringParameters['auth'] = authToken.accessToken;
  6821. }
  6822. if (appCheckToken && appCheckToken.token) {
  6823. queryStringParameters['ac'] = appCheckToken.token;
  6824. }
  6825. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6826. this.repoInfo_.host +
  6827. pathString +
  6828. '?' +
  6829. 'ns=' +
  6830. this.repoInfo_.namespace +
  6831. querystring(queryStringParameters);
  6832. this.log_('Sending REST request for ' + url);
  6833. const xhr = new XMLHttpRequest();
  6834. xhr.onreadystatechange = () => {
  6835. if (callback && xhr.readyState === 4) {
  6836. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6837. let res = null;
  6838. if (xhr.status >= 200 && xhr.status < 300) {
  6839. try {
  6840. res = jsonEval(xhr.responseText);
  6841. }
  6842. catch (e) {
  6843. warn('Failed to parse JSON response for ' +
  6844. url +
  6845. ': ' +
  6846. xhr.responseText);
  6847. }
  6848. callback(null, res);
  6849. }
  6850. else {
  6851. // 401 and 404 are expected.
  6852. if (xhr.status !== 401 && xhr.status !== 404) {
  6853. warn('Got unsuccessful REST response for ' +
  6854. url +
  6855. ' Status: ' +
  6856. xhr.status);
  6857. }
  6858. callback(xhr.status);
  6859. }
  6860. callback = null;
  6861. }
  6862. };
  6863. xhr.open('GET', url, /*asynchronous=*/ true);
  6864. xhr.send();
  6865. });
  6866. }
  6867. }
  6868. /**
  6869. * @license
  6870. * Copyright 2017 Google LLC
  6871. *
  6872. * Licensed under the Apache License, Version 2.0 (the "License");
  6873. * you may not use this file except in compliance with the License.
  6874. * You may obtain a copy of the License at
  6875. *
  6876. * http://www.apache.org/licenses/LICENSE-2.0
  6877. *
  6878. * Unless required by applicable law or agreed to in writing, software
  6879. * distributed under the License is distributed on an "AS IS" BASIS,
  6880. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6881. * See the License for the specific language governing permissions and
  6882. * limitations under the License.
  6883. */
  6884. /**
  6885. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6886. */
  6887. class SnapshotHolder {
  6888. constructor() {
  6889. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6890. }
  6891. getNode(path) {
  6892. return this.rootNode_.getChild(path);
  6893. }
  6894. updateSnapshot(path, newSnapshotNode) {
  6895. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6896. }
  6897. }
  6898. /**
  6899. * @license
  6900. * Copyright 2017 Google LLC
  6901. *
  6902. * Licensed under the Apache License, Version 2.0 (the "License");
  6903. * you may not use this file except in compliance with the License.
  6904. * You may obtain a copy of the License at
  6905. *
  6906. * http://www.apache.org/licenses/LICENSE-2.0
  6907. *
  6908. * Unless required by applicable law or agreed to in writing, software
  6909. * distributed under the License is distributed on an "AS IS" BASIS,
  6910. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6911. * See the License for the specific language governing permissions and
  6912. * limitations under the License.
  6913. */
  6914. function newSparseSnapshotTree() {
  6915. return {
  6916. value: null,
  6917. children: new Map()
  6918. };
  6919. }
  6920. /**
  6921. * Stores the given node at the specified path. If there is already a node
  6922. * at a shallower path, it merges the new data into that snapshot node.
  6923. *
  6924. * @param path - Path to look up snapshot for.
  6925. * @param data - The new data, or null.
  6926. */
  6927. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6928. if (pathIsEmpty(path)) {
  6929. sparseSnapshotTree.value = data;
  6930. sparseSnapshotTree.children.clear();
  6931. }
  6932. else if (sparseSnapshotTree.value !== null) {
  6933. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6934. }
  6935. else {
  6936. const childKey = pathGetFront(path);
  6937. if (!sparseSnapshotTree.children.has(childKey)) {
  6938. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6939. }
  6940. const child = sparseSnapshotTree.children.get(childKey);
  6941. path = pathPopFront(path);
  6942. sparseSnapshotTreeRemember(child, path, data);
  6943. }
  6944. }
  6945. /**
  6946. * Purge the data at path from the cache.
  6947. *
  6948. * @param path - Path to look up snapshot for.
  6949. * @returns True if this node should now be removed.
  6950. */
  6951. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6952. if (pathIsEmpty(path)) {
  6953. sparseSnapshotTree.value = null;
  6954. sparseSnapshotTree.children.clear();
  6955. return true;
  6956. }
  6957. else {
  6958. if (sparseSnapshotTree.value !== null) {
  6959. if (sparseSnapshotTree.value.isLeafNode()) {
  6960. // We're trying to forget a node that doesn't exist
  6961. return false;
  6962. }
  6963. else {
  6964. const value = sparseSnapshotTree.value;
  6965. sparseSnapshotTree.value = null;
  6966. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6967. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6968. });
  6969. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6970. }
  6971. }
  6972. else if (sparseSnapshotTree.children.size > 0) {
  6973. const childKey = pathGetFront(path);
  6974. path = pathPopFront(path);
  6975. if (sparseSnapshotTree.children.has(childKey)) {
  6976. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6977. if (safeToRemove) {
  6978. sparseSnapshotTree.children.delete(childKey);
  6979. }
  6980. }
  6981. return sparseSnapshotTree.children.size === 0;
  6982. }
  6983. else {
  6984. return true;
  6985. }
  6986. }
  6987. }
  6988. /**
  6989. * Recursively iterates through all of the stored tree and calls the
  6990. * callback on each one.
  6991. *
  6992. * @param prefixPath - Path to look up node for.
  6993. * @param func - The function to invoke for each tree.
  6994. */
  6995. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  6996. if (sparseSnapshotTree.value !== null) {
  6997. func(prefixPath, sparseSnapshotTree.value);
  6998. }
  6999. else {
  7000. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  7001. const path = new Path(prefixPath.toString() + '/' + key);
  7002. sparseSnapshotTreeForEachTree(tree, path, func);
  7003. });
  7004. }
  7005. }
  7006. /**
  7007. * Iterates through each immediate child and triggers the callback.
  7008. * Only seems to be used in tests.
  7009. *
  7010. * @param func - The function to invoke for each child.
  7011. */
  7012. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7013. sparseSnapshotTree.children.forEach((tree, key) => {
  7014. func(key, tree);
  7015. });
  7016. }
  7017. /**
  7018. * @license
  7019. * Copyright 2017 Google LLC
  7020. *
  7021. * Licensed under the Apache License, Version 2.0 (the "License");
  7022. * you may not use this file except in compliance with the License.
  7023. * You may obtain a copy of the License at
  7024. *
  7025. * http://www.apache.org/licenses/LICENSE-2.0
  7026. *
  7027. * Unless required by applicable law or agreed to in writing, software
  7028. * distributed under the License is distributed on an "AS IS" BASIS,
  7029. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7030. * See the License for the specific language governing permissions and
  7031. * limitations under the License.
  7032. */
  7033. /**
  7034. * Returns the delta from the previous call to get stats.
  7035. *
  7036. * @param collection_ - The collection to "listen" to.
  7037. */
  7038. class StatsListener {
  7039. constructor(collection_) {
  7040. this.collection_ = collection_;
  7041. this.last_ = null;
  7042. }
  7043. get() {
  7044. const newStats = this.collection_.get();
  7045. const delta = Object.assign({}, newStats);
  7046. if (this.last_) {
  7047. each(this.last_, (stat, value) => {
  7048. delta[stat] = delta[stat] - value;
  7049. });
  7050. }
  7051. this.last_ = newStats;
  7052. return delta;
  7053. }
  7054. }
  7055. /**
  7056. * @license
  7057. * Copyright 2017 Google LLC
  7058. *
  7059. * Licensed under the Apache License, Version 2.0 (the "License");
  7060. * you may not use this file except in compliance with the License.
  7061. * You may obtain a copy of the License at
  7062. *
  7063. * http://www.apache.org/licenses/LICENSE-2.0
  7064. *
  7065. * Unless required by applicable law or agreed to in writing, software
  7066. * distributed under the License is distributed on an "AS IS" BASIS,
  7067. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7068. * See the License for the specific language governing permissions and
  7069. * limitations under the License.
  7070. */
  7071. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7072. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7073. // seconds to try to ensure the Firebase connection is established / settled.
  7074. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7075. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7076. // We'll continue to report stats on average every 5 minutes.
  7077. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7078. class StatsReporter {
  7079. constructor(collection, server_) {
  7080. this.server_ = server_;
  7081. this.statsToReport_ = {};
  7082. this.statsListener_ = new StatsListener(collection);
  7083. const timeout = FIRST_STATS_MIN_TIME +
  7084. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7085. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7086. }
  7087. reportStats_() {
  7088. const stats = this.statsListener_.get();
  7089. const reportedStats = {};
  7090. let haveStatsToReport = false;
  7091. each(stats, (stat, value) => {
  7092. if (value > 0 && contains(this.statsToReport_, stat)) {
  7093. reportedStats[stat] = value;
  7094. haveStatsToReport = true;
  7095. }
  7096. });
  7097. if (haveStatsToReport) {
  7098. this.server_.reportStats(reportedStats);
  7099. }
  7100. // queue our next run.
  7101. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7102. }
  7103. }
  7104. /**
  7105. * @license
  7106. * Copyright 2017 Google LLC
  7107. *
  7108. * Licensed under the Apache License, Version 2.0 (the "License");
  7109. * you may not use this file except in compliance with the License.
  7110. * You may obtain a copy of the License at
  7111. *
  7112. * http://www.apache.org/licenses/LICENSE-2.0
  7113. *
  7114. * Unless required by applicable law or agreed to in writing, software
  7115. * distributed under the License is distributed on an "AS IS" BASIS,
  7116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7117. * See the License for the specific language governing permissions and
  7118. * limitations under the License.
  7119. */
  7120. /**
  7121. *
  7122. * @enum
  7123. */
  7124. var OperationType;
  7125. (function (OperationType) {
  7126. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7127. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7128. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7129. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7130. })(OperationType || (OperationType = {}));
  7131. function newOperationSourceUser() {
  7132. return {
  7133. fromUser: true,
  7134. fromServer: false,
  7135. queryId: null,
  7136. tagged: false
  7137. };
  7138. }
  7139. function newOperationSourceServer() {
  7140. return {
  7141. fromUser: false,
  7142. fromServer: true,
  7143. queryId: null,
  7144. tagged: false
  7145. };
  7146. }
  7147. function newOperationSourceServerTaggedQuery(queryId) {
  7148. return {
  7149. fromUser: false,
  7150. fromServer: true,
  7151. queryId,
  7152. tagged: true
  7153. };
  7154. }
  7155. /**
  7156. * @license
  7157. * Copyright 2017 Google LLC
  7158. *
  7159. * Licensed under the Apache License, Version 2.0 (the "License");
  7160. * you may not use this file except in compliance with the License.
  7161. * You may obtain a copy of the License at
  7162. *
  7163. * http://www.apache.org/licenses/LICENSE-2.0
  7164. *
  7165. * Unless required by applicable law or agreed to in writing, software
  7166. * distributed under the License is distributed on an "AS IS" BASIS,
  7167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7168. * See the License for the specific language governing permissions and
  7169. * limitations under the License.
  7170. */
  7171. class AckUserWrite {
  7172. /**
  7173. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7174. */
  7175. constructor(
  7176. /** @inheritDoc */ path,
  7177. /** @inheritDoc */ affectedTree,
  7178. /** @inheritDoc */ revert) {
  7179. this.path = path;
  7180. this.affectedTree = affectedTree;
  7181. this.revert = revert;
  7182. /** @inheritDoc */
  7183. this.type = OperationType.ACK_USER_WRITE;
  7184. /** @inheritDoc */
  7185. this.source = newOperationSourceUser();
  7186. }
  7187. operationForChild(childName) {
  7188. if (!pathIsEmpty(this.path)) {
  7189. assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7190. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7191. }
  7192. else if (this.affectedTree.value != null) {
  7193. assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7194. // All child locations are affected as well; just return same operation.
  7195. return this;
  7196. }
  7197. else {
  7198. const childTree = this.affectedTree.subtree(new Path(childName));
  7199. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7200. }
  7201. }
  7202. }
  7203. /**
  7204. * @license
  7205. * Copyright 2017 Google LLC
  7206. *
  7207. * Licensed under the Apache License, Version 2.0 (the "License");
  7208. * you may not use this file except in compliance with the License.
  7209. * You may obtain a copy of the License at
  7210. *
  7211. * http://www.apache.org/licenses/LICENSE-2.0
  7212. *
  7213. * Unless required by applicable law or agreed to in writing, software
  7214. * distributed under the License is distributed on an "AS IS" BASIS,
  7215. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7216. * See the License for the specific language governing permissions and
  7217. * limitations under the License.
  7218. */
  7219. class ListenComplete {
  7220. constructor(source, path) {
  7221. this.source = source;
  7222. this.path = path;
  7223. /** @inheritDoc */
  7224. this.type = OperationType.LISTEN_COMPLETE;
  7225. }
  7226. operationForChild(childName) {
  7227. if (pathIsEmpty(this.path)) {
  7228. return new ListenComplete(this.source, newEmptyPath());
  7229. }
  7230. else {
  7231. return new ListenComplete(this.source, pathPopFront(this.path));
  7232. }
  7233. }
  7234. }
  7235. /**
  7236. * @license
  7237. * Copyright 2017 Google LLC
  7238. *
  7239. * Licensed under the Apache License, Version 2.0 (the "License");
  7240. * you may not use this file except in compliance with the License.
  7241. * You may obtain a copy of the License at
  7242. *
  7243. * http://www.apache.org/licenses/LICENSE-2.0
  7244. *
  7245. * Unless required by applicable law or agreed to in writing, software
  7246. * distributed under the License is distributed on an "AS IS" BASIS,
  7247. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7248. * See the License for the specific language governing permissions and
  7249. * limitations under the License.
  7250. */
  7251. class Overwrite {
  7252. constructor(source, path, snap) {
  7253. this.source = source;
  7254. this.path = path;
  7255. this.snap = snap;
  7256. /** @inheritDoc */
  7257. this.type = OperationType.OVERWRITE;
  7258. }
  7259. operationForChild(childName) {
  7260. if (pathIsEmpty(this.path)) {
  7261. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7262. }
  7263. else {
  7264. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7265. }
  7266. }
  7267. }
  7268. /**
  7269. * @license
  7270. * Copyright 2017 Google LLC
  7271. *
  7272. * Licensed under the Apache License, Version 2.0 (the "License");
  7273. * you may not use this file except in compliance with the License.
  7274. * You may obtain a copy of the License at
  7275. *
  7276. * http://www.apache.org/licenses/LICENSE-2.0
  7277. *
  7278. * Unless required by applicable law or agreed to in writing, software
  7279. * distributed under the License is distributed on an "AS IS" BASIS,
  7280. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7281. * See the License for the specific language governing permissions and
  7282. * limitations under the License.
  7283. */
  7284. class Merge {
  7285. constructor(
  7286. /** @inheritDoc */ source,
  7287. /** @inheritDoc */ path,
  7288. /** @inheritDoc */ children) {
  7289. this.source = source;
  7290. this.path = path;
  7291. this.children = children;
  7292. /** @inheritDoc */
  7293. this.type = OperationType.MERGE;
  7294. }
  7295. operationForChild(childName) {
  7296. if (pathIsEmpty(this.path)) {
  7297. const childTree = this.children.subtree(new Path(childName));
  7298. if (childTree.isEmpty()) {
  7299. // This child is unaffected
  7300. return null;
  7301. }
  7302. else if (childTree.value) {
  7303. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7304. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7305. }
  7306. else {
  7307. // This is a merge at a deeper level
  7308. return new Merge(this.source, newEmptyPath(), childTree);
  7309. }
  7310. }
  7311. else {
  7312. assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7313. return new Merge(this.source, pathPopFront(this.path), this.children);
  7314. }
  7315. }
  7316. toString() {
  7317. return ('Operation(' +
  7318. this.path +
  7319. ': ' +
  7320. this.source.toString() +
  7321. ' merge: ' +
  7322. this.children.toString() +
  7323. ')');
  7324. }
  7325. }
  7326. /**
  7327. * @license
  7328. * Copyright 2017 Google LLC
  7329. *
  7330. * Licensed under the Apache License, Version 2.0 (the "License");
  7331. * you may not use this file except in compliance with the License.
  7332. * You may obtain a copy of the License at
  7333. *
  7334. * http://www.apache.org/licenses/LICENSE-2.0
  7335. *
  7336. * Unless required by applicable law or agreed to in writing, software
  7337. * distributed under the License is distributed on an "AS IS" BASIS,
  7338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7339. * See the License for the specific language governing permissions and
  7340. * limitations under the License.
  7341. */
  7342. /**
  7343. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7344. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7345. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7346. * whether a node potentially had children removed due to a filter.
  7347. */
  7348. class CacheNode {
  7349. constructor(node_, fullyInitialized_, filtered_) {
  7350. this.node_ = node_;
  7351. this.fullyInitialized_ = fullyInitialized_;
  7352. this.filtered_ = filtered_;
  7353. }
  7354. /**
  7355. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7356. */
  7357. isFullyInitialized() {
  7358. return this.fullyInitialized_;
  7359. }
  7360. /**
  7361. * Returns whether this node is potentially missing children due to a filter applied to the node
  7362. */
  7363. isFiltered() {
  7364. return this.filtered_;
  7365. }
  7366. isCompleteForPath(path) {
  7367. if (pathIsEmpty(path)) {
  7368. return this.isFullyInitialized() && !this.filtered_;
  7369. }
  7370. const childKey = pathGetFront(path);
  7371. return this.isCompleteForChild(childKey);
  7372. }
  7373. isCompleteForChild(key) {
  7374. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7375. }
  7376. getNode() {
  7377. return this.node_;
  7378. }
  7379. }
  7380. /**
  7381. * @license
  7382. * Copyright 2017 Google LLC
  7383. *
  7384. * Licensed under the Apache License, Version 2.0 (the "License");
  7385. * you may not use this file except in compliance with the License.
  7386. * You may obtain a copy of the License at
  7387. *
  7388. * http://www.apache.org/licenses/LICENSE-2.0
  7389. *
  7390. * Unless required by applicable law or agreed to in writing, software
  7391. * distributed under the License is distributed on an "AS IS" BASIS,
  7392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7393. * See the License for the specific language governing permissions and
  7394. * limitations under the License.
  7395. */
  7396. /**
  7397. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7398. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7399. * for details.
  7400. *
  7401. */
  7402. class EventGenerator {
  7403. constructor(query_) {
  7404. this.query_ = query_;
  7405. this.index_ = this.query_._queryParams.getIndex();
  7406. }
  7407. }
  7408. /**
  7409. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7410. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7411. *
  7412. * Notes:
  7413. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7414. * our index.
  7415. * - prevName will be calculated based on the index ordering.
  7416. */
  7417. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7418. const events = [];
  7419. const moves = [];
  7420. changes.forEach(change => {
  7421. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7422. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7423. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7424. }
  7425. });
  7426. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7427. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7428. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7429. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7430. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7431. return events;
  7432. }
  7433. /**
  7434. * Given changes of a single change type, generate the corresponding events.
  7435. */
  7436. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7437. const filteredChanges = changes.filter(change => change.type === eventType);
  7438. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7439. filteredChanges.forEach(change => {
  7440. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7441. registrations.forEach(registration => {
  7442. if (registration.respondsTo(change.type)) {
  7443. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7444. }
  7445. });
  7446. });
  7447. }
  7448. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7449. if (change.type === 'value' || change.type === 'child_removed') {
  7450. return change;
  7451. }
  7452. else {
  7453. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7454. return change;
  7455. }
  7456. }
  7457. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7458. if (a.childName == null || b.childName == null) {
  7459. throw assertionError('Should only compare child_ events.');
  7460. }
  7461. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7462. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7463. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7464. }
  7465. /**
  7466. * @license
  7467. * Copyright 2017 Google LLC
  7468. *
  7469. * Licensed under the Apache License, Version 2.0 (the "License");
  7470. * you may not use this file except in compliance with the License.
  7471. * You may obtain a copy of the License at
  7472. *
  7473. * http://www.apache.org/licenses/LICENSE-2.0
  7474. *
  7475. * Unless required by applicable law or agreed to in writing, software
  7476. * distributed under the License is distributed on an "AS IS" BASIS,
  7477. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7478. * See the License for the specific language governing permissions and
  7479. * limitations under the License.
  7480. */
  7481. function newViewCache(eventCache, serverCache) {
  7482. return { eventCache, serverCache };
  7483. }
  7484. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7485. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7486. }
  7487. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7488. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7489. }
  7490. function viewCacheGetCompleteEventSnap(viewCache) {
  7491. return viewCache.eventCache.isFullyInitialized()
  7492. ? viewCache.eventCache.getNode()
  7493. : null;
  7494. }
  7495. function viewCacheGetCompleteServerSnap(viewCache) {
  7496. return viewCache.serverCache.isFullyInitialized()
  7497. ? viewCache.serverCache.getNode()
  7498. : null;
  7499. }
  7500. /**
  7501. * @license
  7502. * Copyright 2017 Google LLC
  7503. *
  7504. * Licensed under the Apache License, Version 2.0 (the "License");
  7505. * you may not use this file except in compliance with the License.
  7506. * You may obtain a copy of the License at
  7507. *
  7508. * http://www.apache.org/licenses/LICENSE-2.0
  7509. *
  7510. * Unless required by applicable law or agreed to in writing, software
  7511. * distributed under the License is distributed on an "AS IS" BASIS,
  7512. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7513. * See the License for the specific language governing permissions and
  7514. * limitations under the License.
  7515. */
  7516. let emptyChildrenSingleton;
  7517. /**
  7518. * Singleton empty children collection.
  7519. *
  7520. */
  7521. const EmptyChildren = () => {
  7522. if (!emptyChildrenSingleton) {
  7523. emptyChildrenSingleton = new SortedMap(stringCompare);
  7524. }
  7525. return emptyChildrenSingleton;
  7526. };
  7527. /**
  7528. * A tree with immutable elements.
  7529. */
  7530. class ImmutableTree {
  7531. constructor(value, children = EmptyChildren()) {
  7532. this.value = value;
  7533. this.children = children;
  7534. }
  7535. static fromObject(obj) {
  7536. let tree = new ImmutableTree(null);
  7537. each(obj, (childPath, childSnap) => {
  7538. tree = tree.set(new Path(childPath), childSnap);
  7539. });
  7540. return tree;
  7541. }
  7542. /**
  7543. * True if the value is empty and there are no children
  7544. */
  7545. isEmpty() {
  7546. return this.value === null && this.children.isEmpty();
  7547. }
  7548. /**
  7549. * Given a path and predicate, return the first node and the path to that node
  7550. * where the predicate returns true.
  7551. *
  7552. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7553. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7554. *
  7555. * @param relativePath - The remainder of the path
  7556. * @param predicate - The predicate to satisfy to return a node
  7557. */
  7558. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7559. if (this.value != null && predicate(this.value)) {
  7560. return { path: newEmptyPath(), value: this.value };
  7561. }
  7562. else {
  7563. if (pathIsEmpty(relativePath)) {
  7564. return null;
  7565. }
  7566. else {
  7567. const front = pathGetFront(relativePath);
  7568. const child = this.children.get(front);
  7569. if (child !== null) {
  7570. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7571. if (childExistingPathAndValue != null) {
  7572. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7573. return { path: fullPath, value: childExistingPathAndValue.value };
  7574. }
  7575. else {
  7576. return null;
  7577. }
  7578. }
  7579. else {
  7580. return null;
  7581. }
  7582. }
  7583. }
  7584. }
  7585. /**
  7586. * Find, if it exists, the shortest subpath of the given path that points a defined
  7587. * value in the tree
  7588. */
  7589. findRootMostValueAndPath(relativePath) {
  7590. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7591. }
  7592. /**
  7593. * @returns The subtree at the given path
  7594. */
  7595. subtree(relativePath) {
  7596. if (pathIsEmpty(relativePath)) {
  7597. return this;
  7598. }
  7599. else {
  7600. const front = pathGetFront(relativePath);
  7601. const childTree = this.children.get(front);
  7602. if (childTree !== null) {
  7603. return childTree.subtree(pathPopFront(relativePath));
  7604. }
  7605. else {
  7606. return new ImmutableTree(null);
  7607. }
  7608. }
  7609. }
  7610. /**
  7611. * Sets a value at the specified path.
  7612. *
  7613. * @param relativePath - Path to set value at.
  7614. * @param toSet - Value to set.
  7615. * @returns Resulting tree.
  7616. */
  7617. set(relativePath, toSet) {
  7618. if (pathIsEmpty(relativePath)) {
  7619. return new ImmutableTree(toSet, this.children);
  7620. }
  7621. else {
  7622. const front = pathGetFront(relativePath);
  7623. const child = this.children.get(front) || new ImmutableTree(null);
  7624. const newChild = child.set(pathPopFront(relativePath), toSet);
  7625. const newChildren = this.children.insert(front, newChild);
  7626. return new ImmutableTree(this.value, newChildren);
  7627. }
  7628. }
  7629. /**
  7630. * Removes the value at the specified path.
  7631. *
  7632. * @param relativePath - Path to value to remove.
  7633. * @returns Resulting tree.
  7634. */
  7635. remove(relativePath) {
  7636. if (pathIsEmpty(relativePath)) {
  7637. if (this.children.isEmpty()) {
  7638. return new ImmutableTree(null);
  7639. }
  7640. else {
  7641. return new ImmutableTree(null, this.children);
  7642. }
  7643. }
  7644. else {
  7645. const front = pathGetFront(relativePath);
  7646. const child = this.children.get(front);
  7647. if (child) {
  7648. const newChild = child.remove(pathPopFront(relativePath));
  7649. let newChildren;
  7650. if (newChild.isEmpty()) {
  7651. newChildren = this.children.remove(front);
  7652. }
  7653. else {
  7654. newChildren = this.children.insert(front, newChild);
  7655. }
  7656. if (this.value === null && newChildren.isEmpty()) {
  7657. return new ImmutableTree(null);
  7658. }
  7659. else {
  7660. return new ImmutableTree(this.value, newChildren);
  7661. }
  7662. }
  7663. else {
  7664. return this;
  7665. }
  7666. }
  7667. }
  7668. /**
  7669. * Gets a value from the tree.
  7670. *
  7671. * @param relativePath - Path to get value for.
  7672. * @returns Value at path, or null.
  7673. */
  7674. get(relativePath) {
  7675. if (pathIsEmpty(relativePath)) {
  7676. return this.value;
  7677. }
  7678. else {
  7679. const front = pathGetFront(relativePath);
  7680. const child = this.children.get(front);
  7681. if (child) {
  7682. return child.get(pathPopFront(relativePath));
  7683. }
  7684. else {
  7685. return null;
  7686. }
  7687. }
  7688. }
  7689. /**
  7690. * Replace the subtree at the specified path with the given new tree.
  7691. *
  7692. * @param relativePath - Path to replace subtree for.
  7693. * @param newTree - New tree.
  7694. * @returns Resulting tree.
  7695. */
  7696. setTree(relativePath, newTree) {
  7697. if (pathIsEmpty(relativePath)) {
  7698. return newTree;
  7699. }
  7700. else {
  7701. const front = pathGetFront(relativePath);
  7702. const child = this.children.get(front) || new ImmutableTree(null);
  7703. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7704. let newChildren;
  7705. if (newChild.isEmpty()) {
  7706. newChildren = this.children.remove(front);
  7707. }
  7708. else {
  7709. newChildren = this.children.insert(front, newChild);
  7710. }
  7711. return new ImmutableTree(this.value, newChildren);
  7712. }
  7713. }
  7714. /**
  7715. * Performs a depth first fold on this tree. Transforms a tree into a single
  7716. * value, given a function that operates on the path to a node, an optional
  7717. * current value, and a map of child names to folded subtrees
  7718. */
  7719. fold(fn) {
  7720. return this.fold_(newEmptyPath(), fn);
  7721. }
  7722. /**
  7723. * Recursive helper for public-facing fold() method
  7724. */
  7725. fold_(pathSoFar, fn) {
  7726. const accum = {};
  7727. this.children.inorderTraversal((childKey, childTree) => {
  7728. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7729. });
  7730. return fn(pathSoFar, this.value, accum);
  7731. }
  7732. /**
  7733. * Find the first matching value on the given path. Return the result of applying f to it.
  7734. */
  7735. findOnPath(path, f) {
  7736. return this.findOnPath_(path, newEmptyPath(), f);
  7737. }
  7738. findOnPath_(pathToFollow, pathSoFar, f) {
  7739. const result = this.value ? f(pathSoFar, this.value) : false;
  7740. if (result) {
  7741. return result;
  7742. }
  7743. else {
  7744. if (pathIsEmpty(pathToFollow)) {
  7745. return null;
  7746. }
  7747. else {
  7748. const front = pathGetFront(pathToFollow);
  7749. const nextChild = this.children.get(front);
  7750. if (nextChild) {
  7751. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7752. }
  7753. else {
  7754. return null;
  7755. }
  7756. }
  7757. }
  7758. }
  7759. foreachOnPath(path, f) {
  7760. return this.foreachOnPath_(path, newEmptyPath(), f);
  7761. }
  7762. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7763. if (pathIsEmpty(pathToFollow)) {
  7764. return this;
  7765. }
  7766. else {
  7767. if (this.value) {
  7768. f(currentRelativePath, this.value);
  7769. }
  7770. const front = pathGetFront(pathToFollow);
  7771. const nextChild = this.children.get(front);
  7772. if (nextChild) {
  7773. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7774. }
  7775. else {
  7776. return new ImmutableTree(null);
  7777. }
  7778. }
  7779. }
  7780. /**
  7781. * Calls the given function for each node in the tree that has a value.
  7782. *
  7783. * @param f - A function to be called with the path from the root of the tree to
  7784. * a node, and the value at that node. Called in depth-first order.
  7785. */
  7786. foreach(f) {
  7787. this.foreach_(newEmptyPath(), f);
  7788. }
  7789. foreach_(currentRelativePath, f) {
  7790. this.children.inorderTraversal((childName, childTree) => {
  7791. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7792. });
  7793. if (this.value) {
  7794. f(currentRelativePath, this.value);
  7795. }
  7796. }
  7797. foreachChild(f) {
  7798. this.children.inorderTraversal((childName, childTree) => {
  7799. if (childTree.value) {
  7800. f(childName, childTree.value);
  7801. }
  7802. });
  7803. }
  7804. }
  7805. /**
  7806. * @license
  7807. * Copyright 2017 Google LLC
  7808. *
  7809. * Licensed under the Apache License, Version 2.0 (the "License");
  7810. * you may not use this file except in compliance with the License.
  7811. * You may obtain a copy of the License at
  7812. *
  7813. * http://www.apache.org/licenses/LICENSE-2.0
  7814. *
  7815. * Unless required by applicable law or agreed to in writing, software
  7816. * distributed under the License is distributed on an "AS IS" BASIS,
  7817. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7818. * See the License for the specific language governing permissions and
  7819. * limitations under the License.
  7820. */
  7821. /**
  7822. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7823. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7824. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7825. * to reflect the write added.
  7826. */
  7827. class CompoundWrite {
  7828. constructor(writeTree_) {
  7829. this.writeTree_ = writeTree_;
  7830. }
  7831. static empty() {
  7832. return new CompoundWrite(new ImmutableTree(null));
  7833. }
  7834. }
  7835. function compoundWriteAddWrite(compoundWrite, path, node) {
  7836. if (pathIsEmpty(path)) {
  7837. return new CompoundWrite(new ImmutableTree(node));
  7838. }
  7839. else {
  7840. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7841. if (rootmost != null) {
  7842. const rootMostPath = rootmost.path;
  7843. let value = rootmost.value;
  7844. const relativePath = newRelativePath(rootMostPath, path);
  7845. value = value.updateChild(relativePath, node);
  7846. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7847. }
  7848. else {
  7849. const subtree = new ImmutableTree(node);
  7850. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7851. return new CompoundWrite(newWriteTree);
  7852. }
  7853. }
  7854. }
  7855. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7856. let newWrite = compoundWrite;
  7857. each(updates, (childKey, node) => {
  7858. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7859. });
  7860. return newWrite;
  7861. }
  7862. /**
  7863. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7864. * location, which must be removed by calling this method with that path.
  7865. *
  7866. * @param compoundWrite - The CompoundWrite to remove.
  7867. * @param path - The path at which a write and all deeper writes should be removed
  7868. * @returns The new CompoundWrite with the removed path
  7869. */
  7870. function compoundWriteRemoveWrite(compoundWrite, path) {
  7871. if (pathIsEmpty(path)) {
  7872. return CompoundWrite.empty();
  7873. }
  7874. else {
  7875. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7876. return new CompoundWrite(newWriteTree);
  7877. }
  7878. }
  7879. /**
  7880. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7881. * considered "complete".
  7882. *
  7883. * @param compoundWrite - The CompoundWrite to check.
  7884. * @param path - The path to check for
  7885. * @returns Whether there is a complete write at that path
  7886. */
  7887. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7888. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7889. }
  7890. /**
  7891. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7892. * writes from deeper paths, but will return child nodes from a more shallow path.
  7893. *
  7894. * @param compoundWrite - The CompoundWrite to get the node from.
  7895. * @param path - The path to get a complete write
  7896. * @returns The node if complete at that path, or null otherwise.
  7897. */
  7898. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7899. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7900. if (rootmost != null) {
  7901. return compoundWrite.writeTree_
  7902. .get(rootmost.path)
  7903. .getChild(newRelativePath(rootmost.path, path));
  7904. }
  7905. else {
  7906. return null;
  7907. }
  7908. }
  7909. /**
  7910. * Returns all children that are guaranteed to be a complete overwrite.
  7911. *
  7912. * @param compoundWrite - The CompoundWrite to get children from.
  7913. * @returns A list of all complete children.
  7914. */
  7915. function compoundWriteGetCompleteChildren(compoundWrite) {
  7916. const children = [];
  7917. const node = compoundWrite.writeTree_.value;
  7918. if (node != null) {
  7919. // If it's a leaf node, it has no children; so nothing to do.
  7920. if (!node.isLeafNode()) {
  7921. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7922. children.push(new NamedNode(childName, childNode));
  7923. });
  7924. }
  7925. }
  7926. else {
  7927. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7928. if (childTree.value != null) {
  7929. children.push(new NamedNode(childName, childTree.value));
  7930. }
  7931. });
  7932. }
  7933. return children;
  7934. }
  7935. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7936. if (pathIsEmpty(path)) {
  7937. return compoundWrite;
  7938. }
  7939. else {
  7940. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7941. if (shadowingNode != null) {
  7942. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7943. }
  7944. else {
  7945. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7946. }
  7947. }
  7948. }
  7949. /**
  7950. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7951. * @returns Whether this CompoundWrite is empty
  7952. */
  7953. function compoundWriteIsEmpty(compoundWrite) {
  7954. return compoundWrite.writeTree_.isEmpty();
  7955. }
  7956. /**
  7957. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7958. * node
  7959. * @param node - The node to apply this CompoundWrite to
  7960. * @returns The node with all writes applied
  7961. */
  7962. function compoundWriteApply(compoundWrite, node) {
  7963. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7964. }
  7965. function applySubtreeWrite(relativePath, writeTree, node) {
  7966. if (writeTree.value != null) {
  7967. // Since there a write is always a leaf, we're done here
  7968. return node.updateChild(relativePath, writeTree.value);
  7969. }
  7970. else {
  7971. let priorityWrite = null;
  7972. writeTree.children.inorderTraversal((childKey, childTree) => {
  7973. if (childKey === '.priority') {
  7974. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7975. // to apply priorities to empty nodes that are later filled
  7976. assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7977. priorityWrite = childTree.value;
  7978. }
  7979. else {
  7980. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7981. }
  7982. });
  7983. // If there was a priority write, we only apply it if the node is not empty
  7984. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7985. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7986. }
  7987. return node;
  7988. }
  7989. }
  7990. /**
  7991. * @license
  7992. * Copyright 2017 Google LLC
  7993. *
  7994. * Licensed under the Apache License, Version 2.0 (the "License");
  7995. * you may not use this file except in compliance with the License.
  7996. * You may obtain a copy of the License at
  7997. *
  7998. * http://www.apache.org/licenses/LICENSE-2.0
  7999. *
  8000. * Unless required by applicable law or agreed to in writing, software
  8001. * distributed under the License is distributed on an "AS IS" BASIS,
  8002. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8003. * See the License for the specific language governing permissions and
  8004. * limitations under the License.
  8005. */
  8006. /**
  8007. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8008. *
  8009. */
  8010. function writeTreeChildWrites(writeTree, path) {
  8011. return newWriteTreeRef(path, writeTree);
  8012. }
  8013. /**
  8014. * Record a new overwrite from user code.
  8015. *
  8016. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8017. */
  8018. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8019. assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8020. if (visible === undefined) {
  8021. visible = true;
  8022. }
  8023. writeTree.allWrites.push({
  8024. path,
  8025. snap,
  8026. writeId,
  8027. visible
  8028. });
  8029. if (visible) {
  8030. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8031. }
  8032. writeTree.lastWriteId = writeId;
  8033. }
  8034. /**
  8035. * Record a new merge from user code.
  8036. */
  8037. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8038. assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8039. writeTree.allWrites.push({
  8040. path,
  8041. children: changedChildren,
  8042. writeId,
  8043. visible: true
  8044. });
  8045. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8046. writeTree.lastWriteId = writeId;
  8047. }
  8048. function writeTreeGetWrite(writeTree, writeId) {
  8049. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8050. const record = writeTree.allWrites[i];
  8051. if (record.writeId === writeId) {
  8052. return record;
  8053. }
  8054. }
  8055. return null;
  8056. }
  8057. /**
  8058. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8059. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8060. *
  8061. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8062. * events as a result).
  8063. */
  8064. function writeTreeRemoveWrite(writeTree, writeId) {
  8065. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8066. // out of order.
  8067. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8068. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8069. const idx = writeTree.allWrites.findIndex(s => {
  8070. return s.writeId === writeId;
  8071. });
  8072. assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8073. const writeToRemove = writeTree.allWrites[idx];
  8074. writeTree.allWrites.splice(idx, 1);
  8075. let removedWriteWasVisible = writeToRemove.visible;
  8076. let removedWriteOverlapsWithOtherWrites = false;
  8077. let i = writeTree.allWrites.length - 1;
  8078. while (removedWriteWasVisible && i >= 0) {
  8079. const currentWrite = writeTree.allWrites[i];
  8080. if (currentWrite.visible) {
  8081. if (i >= idx &&
  8082. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8083. // The removed write was completely shadowed by a subsequent write.
  8084. removedWriteWasVisible = false;
  8085. }
  8086. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8087. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8088. removedWriteOverlapsWithOtherWrites = true;
  8089. }
  8090. }
  8091. i--;
  8092. }
  8093. if (!removedWriteWasVisible) {
  8094. return false;
  8095. }
  8096. else if (removedWriteOverlapsWithOtherWrites) {
  8097. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8098. writeTreeResetTree_(writeTree);
  8099. return true;
  8100. }
  8101. else {
  8102. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8103. if (writeToRemove.snap) {
  8104. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8105. }
  8106. else {
  8107. const children = writeToRemove.children;
  8108. each(children, (childName) => {
  8109. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8110. });
  8111. }
  8112. return true;
  8113. }
  8114. }
  8115. function writeTreeRecordContainsPath_(writeRecord, path) {
  8116. if (writeRecord.snap) {
  8117. return pathContains(writeRecord.path, path);
  8118. }
  8119. else {
  8120. for (const childName in writeRecord.children) {
  8121. if (writeRecord.children.hasOwnProperty(childName) &&
  8122. pathContains(pathChild(writeRecord.path, childName), path)) {
  8123. return true;
  8124. }
  8125. }
  8126. return false;
  8127. }
  8128. }
  8129. /**
  8130. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8131. */
  8132. function writeTreeResetTree_(writeTree) {
  8133. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8134. if (writeTree.allWrites.length > 0) {
  8135. writeTree.lastWriteId =
  8136. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8137. }
  8138. else {
  8139. writeTree.lastWriteId = -1;
  8140. }
  8141. }
  8142. /**
  8143. * The default filter used when constructing the tree. Keep everything that's visible.
  8144. */
  8145. function writeTreeDefaultFilter_(write) {
  8146. return write.visible;
  8147. }
  8148. /**
  8149. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8150. * event data at that path.
  8151. */
  8152. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8153. let compoundWrite = CompoundWrite.empty();
  8154. for (let i = 0; i < writes.length; ++i) {
  8155. const write = writes[i];
  8156. // Theory, a later set will either:
  8157. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8158. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8159. if (filter(write)) {
  8160. const writePath = write.path;
  8161. let relativePath;
  8162. if (write.snap) {
  8163. if (pathContains(treeRoot, writePath)) {
  8164. relativePath = newRelativePath(treeRoot, writePath);
  8165. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8166. }
  8167. else if (pathContains(writePath, treeRoot)) {
  8168. relativePath = newRelativePath(writePath, treeRoot);
  8169. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8170. }
  8171. else ;
  8172. }
  8173. else if (write.children) {
  8174. if (pathContains(treeRoot, writePath)) {
  8175. relativePath = newRelativePath(treeRoot, writePath);
  8176. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8177. }
  8178. else if (pathContains(writePath, treeRoot)) {
  8179. relativePath = newRelativePath(writePath, treeRoot);
  8180. if (pathIsEmpty(relativePath)) {
  8181. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8182. }
  8183. else {
  8184. const child = safeGet(write.children, pathGetFront(relativePath));
  8185. if (child) {
  8186. // There exists a child in this node that matches the root path
  8187. const deepNode = child.getChild(pathPopFront(relativePath));
  8188. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8189. }
  8190. }
  8191. }
  8192. else ;
  8193. }
  8194. else {
  8195. throw assertionError('WriteRecord should have .snap or .children');
  8196. }
  8197. }
  8198. }
  8199. return compoundWrite;
  8200. }
  8201. /**
  8202. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8203. * writes), attempt to calculate a complete snapshot for the given path
  8204. *
  8205. * @param writeIdsToExclude - An optional set to be excluded
  8206. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8207. */
  8208. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8209. if (!writeIdsToExclude && !includeHiddenWrites) {
  8210. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8211. if (shadowingNode != null) {
  8212. return shadowingNode;
  8213. }
  8214. else {
  8215. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8216. if (compoundWriteIsEmpty(subMerge)) {
  8217. return completeServerCache;
  8218. }
  8219. else if (completeServerCache == null &&
  8220. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8221. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8222. return null;
  8223. }
  8224. else {
  8225. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8226. return compoundWriteApply(subMerge, layeredCache);
  8227. }
  8228. }
  8229. }
  8230. else {
  8231. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8232. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8233. return completeServerCache;
  8234. }
  8235. else {
  8236. // If the server cache is null, and we don't have a complete cache, we need to return null
  8237. if (!includeHiddenWrites &&
  8238. completeServerCache == null &&
  8239. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8240. return null;
  8241. }
  8242. else {
  8243. const filter = function (write) {
  8244. return ((write.visible || includeHiddenWrites) &&
  8245. (!writeIdsToExclude ||
  8246. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8247. (pathContains(write.path, treePath) ||
  8248. pathContains(treePath, write.path)));
  8249. };
  8250. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8251. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8252. return compoundWriteApply(mergeAtPath, layeredCache);
  8253. }
  8254. }
  8255. }
  8256. }
  8257. /**
  8258. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8259. * Used when creating new views, to pre-fill their complete event children snapshot.
  8260. */
  8261. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8262. let completeChildren = ChildrenNode.EMPTY_NODE;
  8263. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8264. if (topLevelSet) {
  8265. if (!topLevelSet.isLeafNode()) {
  8266. // we're shadowing everything. Return the children.
  8267. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8268. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8269. });
  8270. }
  8271. return completeChildren;
  8272. }
  8273. else if (completeServerChildren) {
  8274. // Layer any children we have on top of this
  8275. // We know we don't have a top-level set, so just enumerate existing children
  8276. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8277. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8278. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8279. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8280. });
  8281. // Add any complete children we have from the set
  8282. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8283. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8284. });
  8285. return completeChildren;
  8286. }
  8287. else {
  8288. // We don't have anything to layer on top of. Layer on any children we have
  8289. // Note that we can return an empty snap if we have a defined delete
  8290. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8291. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8292. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8293. });
  8294. return completeChildren;
  8295. }
  8296. }
  8297. /**
  8298. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8299. * applied to the event cache.
  8300. *
  8301. * Possibilities:
  8302. *
  8303. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8304. *
  8305. * 2. Some write is completely shadowing. No events to be raised
  8306. *
  8307. * 3. Is partially shadowed. Events
  8308. *
  8309. * Either existingEventSnap or existingServerSnap must exist
  8310. */
  8311. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8312. assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8313. const path = pathChild(treePath, childPath);
  8314. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8315. // At this point we can probably guarantee that we're in case 2, meaning no events
  8316. // May need to check visibility while doing the findRootMostValueAndPath call
  8317. return null;
  8318. }
  8319. else {
  8320. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8321. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8322. if (compoundWriteIsEmpty(childMerge)) {
  8323. // We're not shadowing at all. Case 1
  8324. return existingServerSnap.getChild(childPath);
  8325. }
  8326. else {
  8327. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8328. // However this is tricky to find out, since user updates don't necessary change the server
  8329. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8330. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8331. // only check if the updates change the serverNode.
  8332. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8333. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8334. }
  8335. }
  8336. }
  8337. /**
  8338. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8339. * complete child for this ChildKey.
  8340. */
  8341. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8342. const path = pathChild(treePath, childKey);
  8343. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8344. if (shadowingNode != null) {
  8345. return shadowingNode;
  8346. }
  8347. else {
  8348. if (existingServerSnap.isCompleteForChild(childKey)) {
  8349. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8350. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8351. }
  8352. else {
  8353. return null;
  8354. }
  8355. }
  8356. }
  8357. /**
  8358. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8359. * a higher path, this will return the child of that write relative to the write and this path.
  8360. * Returns null if there is no write at this path.
  8361. */
  8362. function writeTreeShadowingWrite(writeTree, path) {
  8363. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8364. }
  8365. /**
  8366. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8367. * the window, but may now be in the window.
  8368. */
  8369. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8370. let toIterate;
  8371. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8372. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8373. if (shadowingNode != null) {
  8374. toIterate = shadowingNode;
  8375. }
  8376. else if (completeServerData != null) {
  8377. toIterate = compoundWriteApply(merge, completeServerData);
  8378. }
  8379. else {
  8380. // no children to iterate on
  8381. return [];
  8382. }
  8383. toIterate = toIterate.withIndex(index);
  8384. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8385. const nodes = [];
  8386. const cmp = index.getCompare();
  8387. const iter = reverse
  8388. ? toIterate.getReverseIteratorFrom(startPost, index)
  8389. : toIterate.getIteratorFrom(startPost, index);
  8390. let next = iter.getNext();
  8391. while (next && nodes.length < count) {
  8392. if (cmp(next, startPost) !== 0) {
  8393. nodes.push(next);
  8394. }
  8395. next = iter.getNext();
  8396. }
  8397. return nodes;
  8398. }
  8399. else {
  8400. return [];
  8401. }
  8402. }
  8403. function newWriteTree() {
  8404. return {
  8405. visibleWrites: CompoundWrite.empty(),
  8406. allWrites: [],
  8407. lastWriteId: -1
  8408. };
  8409. }
  8410. /**
  8411. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8412. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8413. * can lead to a more expensive calculation.
  8414. *
  8415. * @param writeIdsToExclude - Optional writes to exclude.
  8416. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8417. */
  8418. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8419. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8420. }
  8421. /**
  8422. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8423. * mix of the given server data and write data.
  8424. *
  8425. */
  8426. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8427. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8428. }
  8429. /**
  8430. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8431. * if anything, needs to be applied to the event cache.
  8432. *
  8433. * Possibilities:
  8434. *
  8435. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8436. *
  8437. * 2. Some write is completely shadowing. No events to be raised
  8438. *
  8439. * 3. Is partially shadowed. Events should be raised
  8440. *
  8441. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8442. *
  8443. *
  8444. */
  8445. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8446. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8447. }
  8448. /**
  8449. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8450. * a higher path, this will return the child of that write relative to the write and this path.
  8451. * Returns null if there is no write at this path.
  8452. *
  8453. */
  8454. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8455. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8456. }
  8457. /**
  8458. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8459. * the window, but may now be in the window
  8460. */
  8461. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8462. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8463. }
  8464. /**
  8465. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8466. * complete child for this ChildKey.
  8467. */
  8468. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8469. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8470. }
  8471. /**
  8472. * Return a WriteTreeRef for a child.
  8473. */
  8474. function writeTreeRefChild(writeTreeRef, childName) {
  8475. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8476. }
  8477. function newWriteTreeRef(path, writeTree) {
  8478. return {
  8479. treePath: path,
  8480. writeTree
  8481. };
  8482. }
  8483. /**
  8484. * @license
  8485. * Copyright 2017 Google LLC
  8486. *
  8487. * Licensed under the Apache License, Version 2.0 (the "License");
  8488. * you may not use this file except in compliance with the License.
  8489. * You may obtain a copy of the License at
  8490. *
  8491. * http://www.apache.org/licenses/LICENSE-2.0
  8492. *
  8493. * Unless required by applicable law or agreed to in writing, software
  8494. * distributed under the License is distributed on an "AS IS" BASIS,
  8495. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8496. * See the License for the specific language governing permissions and
  8497. * limitations under the License.
  8498. */
  8499. class ChildChangeAccumulator {
  8500. constructor() {
  8501. this.changeMap = new Map();
  8502. }
  8503. trackChildChange(change) {
  8504. const type = change.type;
  8505. const childKey = change.childName;
  8506. assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8507. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8508. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8509. assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8510. const oldChange = this.changeMap.get(childKey);
  8511. if (oldChange) {
  8512. const oldType = oldChange.type;
  8513. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8514. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8515. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8516. }
  8517. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8518. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8519. this.changeMap.delete(childKey);
  8520. }
  8521. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8522. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8523. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8524. }
  8525. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8526. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8527. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8528. }
  8529. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8530. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8531. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8532. }
  8533. else {
  8534. throw assertionError('Illegal combination of changes: ' +
  8535. change +
  8536. ' occurred after ' +
  8537. oldChange);
  8538. }
  8539. }
  8540. else {
  8541. this.changeMap.set(childKey, change);
  8542. }
  8543. }
  8544. getChanges() {
  8545. return Array.from(this.changeMap.values());
  8546. }
  8547. }
  8548. /**
  8549. * @license
  8550. * Copyright 2017 Google LLC
  8551. *
  8552. * Licensed under the Apache License, Version 2.0 (the "License");
  8553. * you may not use this file except in compliance with the License.
  8554. * You may obtain a copy of the License at
  8555. *
  8556. * http://www.apache.org/licenses/LICENSE-2.0
  8557. *
  8558. * Unless required by applicable law or agreed to in writing, software
  8559. * distributed under the License is distributed on an "AS IS" BASIS,
  8560. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8561. * See the License for the specific language governing permissions and
  8562. * limitations under the License.
  8563. */
  8564. /**
  8565. * An implementation of CompleteChildSource that never returns any additional children
  8566. */
  8567. // eslint-disable-next-line @typescript-eslint/naming-convention
  8568. class NoCompleteChildSource_ {
  8569. getCompleteChild(childKey) {
  8570. return null;
  8571. }
  8572. getChildAfterChild(index, child, reverse) {
  8573. return null;
  8574. }
  8575. }
  8576. /**
  8577. * Singleton instance.
  8578. */
  8579. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8580. /**
  8581. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8582. * old event caches available to calculate complete children.
  8583. */
  8584. class WriteTreeCompleteChildSource {
  8585. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8586. this.writes_ = writes_;
  8587. this.viewCache_ = viewCache_;
  8588. this.optCompleteServerCache_ = optCompleteServerCache_;
  8589. }
  8590. getCompleteChild(childKey) {
  8591. const node = this.viewCache_.eventCache;
  8592. if (node.isCompleteForChild(childKey)) {
  8593. return node.getNode().getImmediateChild(childKey);
  8594. }
  8595. else {
  8596. const serverNode = this.optCompleteServerCache_ != null
  8597. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8598. : this.viewCache_.serverCache;
  8599. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8600. }
  8601. }
  8602. getChildAfterChild(index, child, reverse) {
  8603. const completeServerData = this.optCompleteServerCache_ != null
  8604. ? this.optCompleteServerCache_
  8605. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8606. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8607. if (nodes.length === 0) {
  8608. return null;
  8609. }
  8610. else {
  8611. return nodes[0];
  8612. }
  8613. }
  8614. }
  8615. /**
  8616. * @license
  8617. * Copyright 2017 Google LLC
  8618. *
  8619. * Licensed under the Apache License, Version 2.0 (the "License");
  8620. * you may not use this file except in compliance with the License.
  8621. * You may obtain a copy of the License at
  8622. *
  8623. * http://www.apache.org/licenses/LICENSE-2.0
  8624. *
  8625. * Unless required by applicable law or agreed to in writing, software
  8626. * distributed under the License is distributed on an "AS IS" BASIS,
  8627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8628. * See the License for the specific language governing permissions and
  8629. * limitations under the License.
  8630. */
  8631. function newViewProcessor(filter) {
  8632. return { filter };
  8633. }
  8634. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8635. assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8636. assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8637. }
  8638. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8639. const accumulator = new ChildChangeAccumulator();
  8640. let newViewCache, filterServerNode;
  8641. if (operation.type === OperationType.OVERWRITE) {
  8642. const overwrite = operation;
  8643. if (overwrite.source.fromUser) {
  8644. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8645. }
  8646. else {
  8647. assert(overwrite.source.fromServer, 'Unknown source.');
  8648. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8649. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8650. // again
  8651. filterServerNode =
  8652. overwrite.source.tagged ||
  8653. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8654. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8655. }
  8656. }
  8657. else if (operation.type === OperationType.MERGE) {
  8658. const merge = operation;
  8659. if (merge.source.fromUser) {
  8660. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8661. }
  8662. else {
  8663. assert(merge.source.fromServer, 'Unknown source.');
  8664. // We filter the node if it's a tagged update or the node has been previously filtered
  8665. filterServerNode =
  8666. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8667. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8668. }
  8669. }
  8670. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8671. const ackUserWrite = operation;
  8672. if (!ackUserWrite.revert) {
  8673. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8674. }
  8675. else {
  8676. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8677. }
  8678. }
  8679. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8680. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8681. }
  8682. else {
  8683. throw assertionError('Unknown operation type: ' + operation.type);
  8684. }
  8685. const changes = accumulator.getChanges();
  8686. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8687. return { viewCache: newViewCache, changes };
  8688. }
  8689. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8690. const eventSnap = newViewCache.eventCache;
  8691. if (eventSnap.isFullyInitialized()) {
  8692. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8693. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8694. if (accumulator.length > 0 ||
  8695. !oldViewCache.eventCache.isFullyInitialized() ||
  8696. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8697. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8698. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8699. }
  8700. }
  8701. }
  8702. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8703. const oldEventSnap = viewCache.eventCache;
  8704. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8705. // we have a shadowing write, ignore changes
  8706. return viewCache;
  8707. }
  8708. else {
  8709. let newEventCache, serverNode;
  8710. if (pathIsEmpty(changePath)) {
  8711. // TODO: figure out how this plays with "sliding ack windows"
  8712. assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8713. if (viewCache.serverCache.isFiltered()) {
  8714. // We need to special case this, because we need to only apply writes to complete children, or
  8715. // we might end up raising events for incomplete children. If the server data is filtered deep
  8716. // writes cannot be guaranteed to be complete
  8717. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8718. const completeChildren = serverCache instanceof ChildrenNode
  8719. ? serverCache
  8720. : ChildrenNode.EMPTY_NODE;
  8721. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8722. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8723. }
  8724. else {
  8725. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8726. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8727. }
  8728. }
  8729. else {
  8730. const childKey = pathGetFront(changePath);
  8731. if (childKey === '.priority') {
  8732. assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8733. const oldEventNode = oldEventSnap.getNode();
  8734. serverNode = viewCache.serverCache.getNode();
  8735. // we might have overwrites for this priority
  8736. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8737. if (updatedPriority != null) {
  8738. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8739. }
  8740. else {
  8741. // priority didn't change, keep old node
  8742. newEventCache = oldEventSnap.getNode();
  8743. }
  8744. }
  8745. else {
  8746. const childChangePath = pathPopFront(changePath);
  8747. // update child
  8748. let newEventChild;
  8749. if (oldEventSnap.isCompleteForChild(childKey)) {
  8750. serverNode = viewCache.serverCache.getNode();
  8751. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8752. if (eventChildUpdate != null) {
  8753. newEventChild = oldEventSnap
  8754. .getNode()
  8755. .getImmediateChild(childKey)
  8756. .updateChild(childChangePath, eventChildUpdate);
  8757. }
  8758. else {
  8759. // Nothing changed, just keep the old child
  8760. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8761. }
  8762. }
  8763. else {
  8764. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8765. }
  8766. if (newEventChild != null) {
  8767. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8768. }
  8769. else {
  8770. // no complete child available or no change
  8771. newEventCache = oldEventSnap.getNode();
  8772. }
  8773. }
  8774. }
  8775. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8776. }
  8777. }
  8778. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8779. const oldServerSnap = oldViewCache.serverCache;
  8780. let newServerCache;
  8781. const serverFilter = filterServerNode
  8782. ? viewProcessor.filter
  8783. : viewProcessor.filter.getIndexedFilter();
  8784. if (pathIsEmpty(changePath)) {
  8785. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8786. }
  8787. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8788. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8789. const newServerNode = oldServerSnap
  8790. .getNode()
  8791. .updateChild(changePath, changedSnap);
  8792. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8793. }
  8794. else {
  8795. const childKey = pathGetFront(changePath);
  8796. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8797. pathGetLength(changePath) > 1) {
  8798. // We don't update incomplete nodes with updates intended for other listeners
  8799. return oldViewCache;
  8800. }
  8801. const childChangePath = pathPopFront(changePath);
  8802. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8803. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8804. if (childKey === '.priority') {
  8805. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8806. }
  8807. else {
  8808. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8809. }
  8810. }
  8811. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8812. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8813. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8814. }
  8815. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8816. const oldEventSnap = oldViewCache.eventCache;
  8817. let newViewCache, newEventCache;
  8818. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8819. if (pathIsEmpty(changePath)) {
  8820. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8821. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8822. }
  8823. else {
  8824. const childKey = pathGetFront(changePath);
  8825. if (childKey === '.priority') {
  8826. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8827. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8828. }
  8829. else {
  8830. const childChangePath = pathPopFront(changePath);
  8831. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8832. let newChild;
  8833. if (pathIsEmpty(childChangePath)) {
  8834. // Child overwrite, we can replace the child
  8835. newChild = changedSnap;
  8836. }
  8837. else {
  8838. const childNode = source.getCompleteChild(childKey);
  8839. if (childNode != null) {
  8840. if (pathGetBack(childChangePath) === '.priority' &&
  8841. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8842. // This is a priority update on an empty node. If this node exists on the server, the
  8843. // server will send down the priority in the update, so ignore for now
  8844. newChild = childNode;
  8845. }
  8846. else {
  8847. newChild = childNode.updateChild(childChangePath, changedSnap);
  8848. }
  8849. }
  8850. else {
  8851. // There is no complete child node available
  8852. newChild = ChildrenNode.EMPTY_NODE;
  8853. }
  8854. }
  8855. if (!oldChild.equals(newChild)) {
  8856. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8857. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8858. }
  8859. else {
  8860. newViewCache = oldViewCache;
  8861. }
  8862. }
  8863. }
  8864. return newViewCache;
  8865. }
  8866. function viewProcessorCacheHasChild(viewCache, childKey) {
  8867. return viewCache.eventCache.isCompleteForChild(childKey);
  8868. }
  8869. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8870. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8871. // window leaving room for new items. It's important we process these changes first, so we
  8872. // iterate the changes twice, first processing any that affect items currently in view.
  8873. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8874. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8875. // not the other.
  8876. let curViewCache = viewCache;
  8877. changedChildren.foreach((relativePath, childNode) => {
  8878. const writePath = pathChild(path, relativePath);
  8879. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8880. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8881. }
  8882. });
  8883. changedChildren.foreach((relativePath, childNode) => {
  8884. const writePath = pathChild(path, relativePath);
  8885. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8886. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8887. }
  8888. });
  8889. return curViewCache;
  8890. }
  8891. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8892. merge.foreach((relativePath, childNode) => {
  8893. node = node.updateChild(relativePath, childNode);
  8894. });
  8895. return node;
  8896. }
  8897. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8898. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8899. // wait for the complete data update coming soon.
  8900. if (viewCache.serverCache.getNode().isEmpty() &&
  8901. !viewCache.serverCache.isFullyInitialized()) {
  8902. return viewCache;
  8903. }
  8904. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8905. // window leaving room for new items. It's important we process these changes first, so we
  8906. // iterate the changes twice, first processing any that affect items currently in view.
  8907. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8908. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8909. // not the other.
  8910. let curViewCache = viewCache;
  8911. let viewMergeTree;
  8912. if (pathIsEmpty(path)) {
  8913. viewMergeTree = changedChildren;
  8914. }
  8915. else {
  8916. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8917. }
  8918. const serverNode = viewCache.serverCache.getNode();
  8919. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8920. if (serverNode.hasChild(childKey)) {
  8921. const serverChild = viewCache.serverCache
  8922. .getNode()
  8923. .getImmediateChild(childKey);
  8924. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8925. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8926. }
  8927. });
  8928. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8929. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8930. childMergeTree.value === null;
  8931. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8932. const serverChild = viewCache.serverCache
  8933. .getNode()
  8934. .getImmediateChild(childKey);
  8935. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8936. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8937. }
  8938. });
  8939. return curViewCache;
  8940. }
  8941. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8942. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8943. return viewCache;
  8944. }
  8945. // Only filter server node if it is currently filtered
  8946. const filterServerNode = viewCache.serverCache.isFiltered();
  8947. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8948. // now that it won't be shadowed.
  8949. const serverCache = viewCache.serverCache;
  8950. if (affectedTree.value != null) {
  8951. // This is an overwrite.
  8952. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8953. serverCache.isCompleteForPath(ackPath)) {
  8954. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8955. }
  8956. else if (pathIsEmpty(ackPath)) {
  8957. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8958. // should just re-apply whatever we have in our cache as a merge.
  8959. let changedChildren = new ImmutableTree(null);
  8960. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8961. changedChildren = changedChildren.set(new Path(name), node);
  8962. });
  8963. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8964. }
  8965. else {
  8966. return viewCache;
  8967. }
  8968. }
  8969. else {
  8970. // This is a merge.
  8971. let changedChildren = new ImmutableTree(null);
  8972. affectedTree.foreach((mergePath, value) => {
  8973. const serverCachePath = pathChild(ackPath, mergePath);
  8974. if (serverCache.isCompleteForPath(serverCachePath)) {
  8975. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8976. }
  8977. });
  8978. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8979. }
  8980. }
  8981. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8982. const oldServerNode = viewCache.serverCache;
  8983. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8984. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8985. }
  8986. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8987. let complete;
  8988. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8989. return viewCache;
  8990. }
  8991. else {
  8992. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  8993. const oldEventCache = viewCache.eventCache.getNode();
  8994. let newEventCache;
  8995. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  8996. let newNode;
  8997. if (viewCache.serverCache.isFullyInitialized()) {
  8998. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8999. }
  9000. else {
  9001. const serverChildren = viewCache.serverCache.getNode();
  9002. assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9003. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9004. }
  9005. newNode = newNode;
  9006. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9007. }
  9008. else {
  9009. const childKey = pathGetFront(path);
  9010. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9011. if (newChild == null &&
  9012. viewCache.serverCache.isCompleteForChild(childKey)) {
  9013. newChild = oldEventCache.getImmediateChild(childKey);
  9014. }
  9015. if (newChild != null) {
  9016. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9017. }
  9018. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9019. // No complete child available, delete the existing one, if any
  9020. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9021. }
  9022. else {
  9023. newEventCache = oldEventCache;
  9024. }
  9025. if (newEventCache.isEmpty() &&
  9026. viewCache.serverCache.isFullyInitialized()) {
  9027. // We might have reverted all child writes. Maybe the old event was a leaf node
  9028. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9029. if (complete.isLeafNode()) {
  9030. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9031. }
  9032. }
  9033. }
  9034. complete =
  9035. viewCache.serverCache.isFullyInitialized() ||
  9036. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9037. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9038. }
  9039. }
  9040. /**
  9041. * @license
  9042. * Copyright 2017 Google LLC
  9043. *
  9044. * Licensed under the Apache License, Version 2.0 (the "License");
  9045. * you may not use this file except in compliance with the License.
  9046. * You may obtain a copy of the License at
  9047. *
  9048. * http://www.apache.org/licenses/LICENSE-2.0
  9049. *
  9050. * Unless required by applicable law or agreed to in writing, software
  9051. * distributed under the License is distributed on an "AS IS" BASIS,
  9052. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9053. * See the License for the specific language governing permissions and
  9054. * limitations under the License.
  9055. */
  9056. /**
  9057. * A view represents a specific location and query that has 1 or more event registrations.
  9058. *
  9059. * It does several things:
  9060. * - Maintains the list of event registrations for this location/query.
  9061. * - Maintains a cache of the data visible for this location/query.
  9062. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9063. * registrations returns the set of events to be raised.
  9064. */
  9065. class View {
  9066. constructor(query_, initialViewCache) {
  9067. this.query_ = query_;
  9068. this.eventRegistrations_ = [];
  9069. const params = this.query_._queryParams;
  9070. const indexFilter = new IndexedFilter(params.getIndex());
  9071. const filter = queryParamsGetNodeFilter(params);
  9072. this.processor_ = newViewProcessor(filter);
  9073. const initialServerCache = initialViewCache.serverCache;
  9074. const initialEventCache = initialViewCache.eventCache;
  9075. // Don't filter server node with other filter than index, wait for tagged listen
  9076. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9077. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9078. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9079. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9080. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9081. this.eventGenerator_ = new EventGenerator(this.query_);
  9082. }
  9083. get query() {
  9084. return this.query_;
  9085. }
  9086. }
  9087. function viewGetServerCache(view) {
  9088. return view.viewCache_.serverCache.getNode();
  9089. }
  9090. function viewGetCompleteNode(view) {
  9091. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9092. }
  9093. function viewGetCompleteServerCache(view, path) {
  9094. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9095. if (cache) {
  9096. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9097. // we need to see if it contains the child we're interested in.
  9098. if (view.query._queryParams.loadsAllData() ||
  9099. (!pathIsEmpty(path) &&
  9100. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9101. return cache.getChild(path);
  9102. }
  9103. }
  9104. return null;
  9105. }
  9106. function viewIsEmpty(view) {
  9107. return view.eventRegistrations_.length === 0;
  9108. }
  9109. function viewAddEventRegistration(view, eventRegistration) {
  9110. view.eventRegistrations_.push(eventRegistration);
  9111. }
  9112. /**
  9113. * @param eventRegistration - If null, remove all callbacks.
  9114. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9115. * @returns Cancel events, if cancelError was provided.
  9116. */
  9117. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9118. const cancelEvents = [];
  9119. if (cancelError) {
  9120. assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9121. const path = view.query._path;
  9122. view.eventRegistrations_.forEach(registration => {
  9123. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9124. if (maybeEvent) {
  9125. cancelEvents.push(maybeEvent);
  9126. }
  9127. });
  9128. }
  9129. if (eventRegistration) {
  9130. let remaining = [];
  9131. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9132. const existing = view.eventRegistrations_[i];
  9133. if (!existing.matches(eventRegistration)) {
  9134. remaining.push(existing);
  9135. }
  9136. else if (eventRegistration.hasAnyCallback()) {
  9137. // We're removing just this one
  9138. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9139. break;
  9140. }
  9141. }
  9142. view.eventRegistrations_ = remaining;
  9143. }
  9144. else {
  9145. view.eventRegistrations_ = [];
  9146. }
  9147. return cancelEvents;
  9148. }
  9149. /**
  9150. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9151. */
  9152. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9153. if (operation.type === OperationType.MERGE &&
  9154. operation.source.queryId !== null) {
  9155. assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9156. assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9157. }
  9158. const oldViewCache = view.viewCache_;
  9159. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9160. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9161. assert(result.viewCache.serverCache.isFullyInitialized() ||
  9162. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9163. view.viewCache_ = result.viewCache;
  9164. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9165. }
  9166. function viewGetInitialEvents(view, registration) {
  9167. const eventSnap = view.viewCache_.eventCache;
  9168. const initialChanges = [];
  9169. if (!eventSnap.getNode().isLeafNode()) {
  9170. const eventNode = eventSnap.getNode();
  9171. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9172. initialChanges.push(changeChildAdded(key, childNode));
  9173. });
  9174. }
  9175. if (eventSnap.isFullyInitialized()) {
  9176. initialChanges.push(changeValue(eventSnap.getNode()));
  9177. }
  9178. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9179. }
  9180. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9181. const registrations = eventRegistration
  9182. ? [eventRegistration]
  9183. : view.eventRegistrations_;
  9184. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9185. }
  9186. /**
  9187. * @license
  9188. * Copyright 2017 Google LLC
  9189. *
  9190. * Licensed under the Apache License, Version 2.0 (the "License");
  9191. * you may not use this file except in compliance with the License.
  9192. * You may obtain a copy of the License at
  9193. *
  9194. * http://www.apache.org/licenses/LICENSE-2.0
  9195. *
  9196. * Unless required by applicable law or agreed to in writing, software
  9197. * distributed under the License is distributed on an "AS IS" BASIS,
  9198. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9199. * See the License for the specific language governing permissions and
  9200. * limitations under the License.
  9201. */
  9202. let referenceConstructor$1;
  9203. /**
  9204. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9205. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9206. * and user writes (set, transaction, update).
  9207. *
  9208. * It's responsible for:
  9209. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9210. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9211. * applyUserOverwrite, etc.)
  9212. */
  9213. class SyncPoint {
  9214. constructor() {
  9215. /**
  9216. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9217. * queryId and the value is the View for that query.
  9218. *
  9219. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9220. */
  9221. this.views = new Map();
  9222. }
  9223. }
  9224. function syncPointSetReferenceConstructor(val) {
  9225. assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9226. referenceConstructor$1 = val;
  9227. }
  9228. function syncPointGetReferenceConstructor() {
  9229. assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9230. return referenceConstructor$1;
  9231. }
  9232. function syncPointIsEmpty(syncPoint) {
  9233. return syncPoint.views.size === 0;
  9234. }
  9235. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9236. const queryId = operation.source.queryId;
  9237. if (queryId !== null) {
  9238. const view = syncPoint.views.get(queryId);
  9239. assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9240. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9241. }
  9242. else {
  9243. let events = [];
  9244. for (const view of syncPoint.views.values()) {
  9245. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9246. }
  9247. return events;
  9248. }
  9249. }
  9250. /**
  9251. * Get a view for the specified query.
  9252. *
  9253. * @param query - The query to return a view for
  9254. * @param writesCache
  9255. * @param serverCache
  9256. * @param serverCacheComplete
  9257. * @returns Events to raise.
  9258. */
  9259. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9260. const queryId = query._queryIdentifier;
  9261. const view = syncPoint.views.get(queryId);
  9262. if (!view) {
  9263. // TODO: make writesCache take flag for complete server node
  9264. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9265. let eventCacheComplete = false;
  9266. if (eventCache) {
  9267. eventCacheComplete = true;
  9268. }
  9269. else if (serverCache instanceof ChildrenNode) {
  9270. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9271. eventCacheComplete = false;
  9272. }
  9273. else {
  9274. eventCache = ChildrenNode.EMPTY_NODE;
  9275. eventCacheComplete = false;
  9276. }
  9277. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9278. return new View(query, viewCache);
  9279. }
  9280. return view;
  9281. }
  9282. /**
  9283. * Add an event callback for the specified query.
  9284. *
  9285. * @param query
  9286. * @param eventRegistration
  9287. * @param writesCache
  9288. * @param serverCache - Complete server cache, if we have it.
  9289. * @param serverCacheComplete
  9290. * @returns Events to raise.
  9291. */
  9292. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9293. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9294. if (!syncPoint.views.has(query._queryIdentifier)) {
  9295. syncPoint.views.set(query._queryIdentifier, view);
  9296. }
  9297. // This is guaranteed to exist now, we just created anything that was missing
  9298. viewAddEventRegistration(view, eventRegistration);
  9299. return viewGetInitialEvents(view, eventRegistration);
  9300. }
  9301. /**
  9302. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9303. *
  9304. * If query is the default query, we'll check all views for the specified eventRegistration.
  9305. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9306. *
  9307. * @param eventRegistration - If null, remove all callbacks.
  9308. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9309. * @returns removed queries and any cancel events
  9310. */
  9311. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9312. const queryId = query._queryIdentifier;
  9313. const removed = [];
  9314. let cancelEvents = [];
  9315. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9316. if (queryId === 'default') {
  9317. // When you do ref.off(...), we search all views for the registration to remove.
  9318. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9319. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9320. if (viewIsEmpty(view)) {
  9321. syncPoint.views.delete(viewQueryId);
  9322. // We'll deal with complete views later.
  9323. if (!view.query._queryParams.loadsAllData()) {
  9324. removed.push(view.query);
  9325. }
  9326. }
  9327. }
  9328. }
  9329. else {
  9330. // remove the callback from the specific view.
  9331. const view = syncPoint.views.get(queryId);
  9332. if (view) {
  9333. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9334. if (viewIsEmpty(view)) {
  9335. syncPoint.views.delete(queryId);
  9336. // We'll deal with complete views later.
  9337. if (!view.query._queryParams.loadsAllData()) {
  9338. removed.push(view.query);
  9339. }
  9340. }
  9341. }
  9342. }
  9343. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9344. // We removed our last complete view.
  9345. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9346. }
  9347. return { removed, events: cancelEvents };
  9348. }
  9349. function syncPointGetQueryViews(syncPoint) {
  9350. const result = [];
  9351. for (const view of syncPoint.views.values()) {
  9352. if (!view.query._queryParams.loadsAllData()) {
  9353. result.push(view);
  9354. }
  9355. }
  9356. return result;
  9357. }
  9358. /**
  9359. * @param path - The path to the desired complete snapshot
  9360. * @returns A complete cache, if it exists
  9361. */
  9362. function syncPointGetCompleteServerCache(syncPoint, path) {
  9363. let serverCache = null;
  9364. for (const view of syncPoint.views.values()) {
  9365. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9366. }
  9367. return serverCache;
  9368. }
  9369. function syncPointViewForQuery(syncPoint, query) {
  9370. const params = query._queryParams;
  9371. if (params.loadsAllData()) {
  9372. return syncPointGetCompleteView(syncPoint);
  9373. }
  9374. else {
  9375. const queryId = query._queryIdentifier;
  9376. return syncPoint.views.get(queryId);
  9377. }
  9378. }
  9379. function syncPointViewExistsForQuery(syncPoint, query) {
  9380. return syncPointViewForQuery(syncPoint, query) != null;
  9381. }
  9382. function syncPointHasCompleteView(syncPoint) {
  9383. return syncPointGetCompleteView(syncPoint) != null;
  9384. }
  9385. function syncPointGetCompleteView(syncPoint) {
  9386. for (const view of syncPoint.views.values()) {
  9387. if (view.query._queryParams.loadsAllData()) {
  9388. return view;
  9389. }
  9390. }
  9391. return null;
  9392. }
  9393. /**
  9394. * @license
  9395. * Copyright 2017 Google LLC
  9396. *
  9397. * Licensed under the Apache License, Version 2.0 (the "License");
  9398. * you may not use this file except in compliance with the License.
  9399. * You may obtain a copy of the License at
  9400. *
  9401. * http://www.apache.org/licenses/LICENSE-2.0
  9402. *
  9403. * Unless required by applicable law or agreed to in writing, software
  9404. * distributed under the License is distributed on an "AS IS" BASIS,
  9405. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9406. * See the License for the specific language governing permissions and
  9407. * limitations under the License.
  9408. */
  9409. let referenceConstructor;
  9410. function syncTreeSetReferenceConstructor(val) {
  9411. assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9412. referenceConstructor = val;
  9413. }
  9414. function syncTreeGetReferenceConstructor() {
  9415. assert(referenceConstructor, 'Reference.ts has not been loaded');
  9416. return referenceConstructor;
  9417. }
  9418. /**
  9419. * Static tracker for next query tag.
  9420. */
  9421. let syncTreeNextQueryTag_ = 1;
  9422. /**
  9423. * SyncTree is the central class for managing event callback registration, data caching, views
  9424. * (query processing), and event generation. There are typically two SyncTree instances for
  9425. * each Repo, one for the normal Firebase data, and one for the .info data.
  9426. *
  9427. * It has a number of responsibilities, including:
  9428. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9429. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9430. * (applyUserOverwrite(), applyUserMerge()).
  9431. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9432. * applyServerMerge()).
  9433. * - Generating user-facing events for server and user changes (all of the apply* methods
  9434. * return the set of events that need to be raised as a result).
  9435. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9436. * to the correct set of paths and queries to satisfy the current set of user event
  9437. * callbacks (listens are started/stopped using the provided listenProvider).
  9438. *
  9439. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9440. * events are returned to the caller rather than raised synchronously.
  9441. *
  9442. */
  9443. class SyncTree {
  9444. /**
  9445. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9446. * to server data.
  9447. */
  9448. constructor(listenProvider_) {
  9449. this.listenProvider_ = listenProvider_;
  9450. /**
  9451. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9452. */
  9453. this.syncPointTree_ = new ImmutableTree(null);
  9454. /**
  9455. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9456. */
  9457. this.pendingWriteTree_ = newWriteTree();
  9458. this.tagToQueryMap = new Map();
  9459. this.queryToTagMap = new Map();
  9460. }
  9461. }
  9462. /**
  9463. * Apply the data changes for a user-generated set() or transaction() call.
  9464. *
  9465. * @returns Events to raise.
  9466. */
  9467. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9468. // Record pending write.
  9469. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9470. if (!visible) {
  9471. return [];
  9472. }
  9473. else {
  9474. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9475. }
  9476. }
  9477. /**
  9478. * Apply the data from a user-generated update() call
  9479. *
  9480. * @returns Events to raise.
  9481. */
  9482. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9483. // Record pending merge.
  9484. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9485. const changeTree = ImmutableTree.fromObject(changedChildren);
  9486. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9487. }
  9488. /**
  9489. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9490. *
  9491. * @param revert - True if the given write failed and needs to be reverted
  9492. * @returns Events to raise.
  9493. */
  9494. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9495. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9496. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9497. if (!needToReevaluate) {
  9498. return [];
  9499. }
  9500. else {
  9501. let affectedTree = new ImmutableTree(null);
  9502. if (write.snap != null) {
  9503. // overwrite
  9504. affectedTree = affectedTree.set(newEmptyPath(), true);
  9505. }
  9506. else {
  9507. each(write.children, (pathString) => {
  9508. affectedTree = affectedTree.set(new Path(pathString), true);
  9509. });
  9510. }
  9511. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9512. }
  9513. }
  9514. /**
  9515. * Apply new server data for the specified path..
  9516. *
  9517. * @returns Events to raise.
  9518. */
  9519. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9520. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9521. }
  9522. /**
  9523. * Apply new server data to be merged in at the specified path.
  9524. *
  9525. * @returns Events to raise.
  9526. */
  9527. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9528. const changeTree = ImmutableTree.fromObject(changedChildren);
  9529. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9530. }
  9531. /**
  9532. * Apply a listen complete for a query
  9533. *
  9534. * @returns Events to raise.
  9535. */
  9536. function syncTreeApplyListenComplete(syncTree, path) {
  9537. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9538. }
  9539. /**
  9540. * Apply a listen complete for a tagged query
  9541. *
  9542. * @returns Events to raise.
  9543. */
  9544. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9545. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9546. if (queryKey) {
  9547. const r = syncTreeParseQueryKey_(queryKey);
  9548. const queryPath = r.path, queryId = r.queryId;
  9549. const relativePath = newRelativePath(queryPath, path);
  9550. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9551. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9552. }
  9553. else {
  9554. // We've already removed the query. No big deal, ignore the update
  9555. return [];
  9556. }
  9557. }
  9558. /**
  9559. * Remove event callback(s).
  9560. *
  9561. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9562. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9563. *
  9564. * @param eventRegistration - If null, all callbacks are removed.
  9565. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9566. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9567. * deduping needs to take place. This flag allows toggling of that behavior
  9568. * @returns Cancel events, if cancelError was provided.
  9569. */
  9570. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9571. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9572. const path = query._path;
  9573. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9574. let cancelEvents = [];
  9575. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9576. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9577. // not loadsAllData().
  9578. if (maybeSyncPoint &&
  9579. (query._queryIdentifier === 'default' ||
  9580. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9581. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9582. if (syncPointIsEmpty(maybeSyncPoint)) {
  9583. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9584. }
  9585. const removed = removedAndEvents.removed;
  9586. cancelEvents = removedAndEvents.events;
  9587. if (!skipListenerDedup) {
  9588. /**
  9589. * We may have just removed one of many listeners and can short-circuit this whole process
  9590. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9591. * properly set up.
  9592. */
  9593. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9594. // queryId === 'default'
  9595. const removingDefault = -1 !==
  9596. removed.findIndex(query => {
  9597. return query._queryParams.loadsAllData();
  9598. });
  9599. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9600. if (removingDefault && !covered) {
  9601. const subtree = syncTree.syncPointTree_.subtree(path);
  9602. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9603. // removal
  9604. if (!subtree.isEmpty()) {
  9605. // We need to fold over our subtree and collect the listeners to send
  9606. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9607. // Ok, we've collected all the listens we need. Set them up.
  9608. for (let i = 0; i < newViews.length; ++i) {
  9609. const view = newViews[i], newQuery = view.query;
  9610. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9611. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9612. }
  9613. }
  9614. // Otherwise there's nothing below us, so nothing we need to start listening on
  9615. }
  9616. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9617. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9618. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9619. if (!covered && removed.length > 0 && !cancelError) {
  9620. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9621. // default. Otherwise, we need to iterate through and cancel each individual query
  9622. if (removingDefault) {
  9623. // We don't tag default listeners
  9624. const defaultTag = null;
  9625. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9626. }
  9627. else {
  9628. removed.forEach((queryToRemove) => {
  9629. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9630. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9631. });
  9632. }
  9633. }
  9634. }
  9635. // Now, clear all of the tags we're tracking for the removed listens
  9636. syncTreeRemoveTags_(syncTree, removed);
  9637. }
  9638. return cancelEvents;
  9639. }
  9640. /**
  9641. * Apply new server data for the specified tagged query.
  9642. *
  9643. * @returns Events to raise.
  9644. */
  9645. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9646. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9647. if (queryKey != null) {
  9648. const r = syncTreeParseQueryKey_(queryKey);
  9649. const queryPath = r.path, queryId = r.queryId;
  9650. const relativePath = newRelativePath(queryPath, path);
  9651. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9652. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9653. }
  9654. else {
  9655. // Query must have been removed already
  9656. return [];
  9657. }
  9658. }
  9659. /**
  9660. * Apply server data to be merged in for the specified tagged query.
  9661. *
  9662. * @returns Events to raise.
  9663. */
  9664. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9665. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9666. if (queryKey) {
  9667. const r = syncTreeParseQueryKey_(queryKey);
  9668. const queryPath = r.path, queryId = r.queryId;
  9669. const relativePath = newRelativePath(queryPath, path);
  9670. const changeTree = ImmutableTree.fromObject(changedChildren);
  9671. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9672. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9673. }
  9674. else {
  9675. // We've already removed the query. No big deal, ignore the update
  9676. return [];
  9677. }
  9678. }
  9679. /**
  9680. * Add an event callback for the specified query.
  9681. *
  9682. * @returns Events to raise.
  9683. */
  9684. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9685. const path = query._path;
  9686. let serverCache = null;
  9687. let foundAncestorDefaultView = false;
  9688. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9689. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9690. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9691. const relativePath = newRelativePath(pathToSyncPoint, path);
  9692. serverCache =
  9693. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9694. foundAncestorDefaultView =
  9695. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9696. });
  9697. let syncPoint = syncTree.syncPointTree_.get(path);
  9698. if (!syncPoint) {
  9699. syncPoint = new SyncPoint();
  9700. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9701. }
  9702. else {
  9703. foundAncestorDefaultView =
  9704. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9705. serverCache =
  9706. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9707. }
  9708. let serverCacheComplete;
  9709. if (serverCache != null) {
  9710. serverCacheComplete = true;
  9711. }
  9712. else {
  9713. serverCacheComplete = false;
  9714. serverCache = ChildrenNode.EMPTY_NODE;
  9715. const subtree = syncTree.syncPointTree_.subtree(path);
  9716. subtree.foreachChild((childName, childSyncPoint) => {
  9717. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9718. if (completeCache) {
  9719. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9720. }
  9721. });
  9722. }
  9723. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9724. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9725. // We need to track a tag for this query
  9726. const queryKey = syncTreeMakeQueryKey_(query);
  9727. assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9728. const tag = syncTreeGetNextQueryTag_();
  9729. syncTree.queryToTagMap.set(queryKey, tag);
  9730. syncTree.tagToQueryMap.set(tag, queryKey);
  9731. }
  9732. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9733. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9734. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9735. const view = syncPointViewForQuery(syncPoint, query);
  9736. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9737. }
  9738. return events;
  9739. }
  9740. /**
  9741. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9742. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9743. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9744. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9745. *
  9746. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9747. *
  9748. * @param path - The path to the data we want
  9749. * @param writeIdsToExclude - A specific set to be excluded
  9750. */
  9751. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9752. const includeHiddenSets = true;
  9753. const writeTree = syncTree.pendingWriteTree_;
  9754. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9755. const relativePath = newRelativePath(pathSoFar, path);
  9756. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9757. if (serverCache) {
  9758. return serverCache;
  9759. }
  9760. });
  9761. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9762. }
  9763. function syncTreeGetServerValue(syncTree, query) {
  9764. const path = query._path;
  9765. let serverCache = null;
  9766. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9767. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9768. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9769. const relativePath = newRelativePath(pathToSyncPoint, path);
  9770. serverCache =
  9771. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9772. });
  9773. let syncPoint = syncTree.syncPointTree_.get(path);
  9774. if (!syncPoint) {
  9775. syncPoint = new SyncPoint();
  9776. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9777. }
  9778. else {
  9779. serverCache =
  9780. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9781. }
  9782. const serverCacheComplete = serverCache != null;
  9783. const serverCacheNode = serverCacheComplete
  9784. ? new CacheNode(serverCache, true, false)
  9785. : null;
  9786. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9787. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9788. return viewGetCompleteNode(view);
  9789. }
  9790. /**
  9791. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9792. *
  9793. * NOTES:
  9794. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9795. *
  9796. * - We call applyOperation() on each SyncPoint passing three things:
  9797. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9798. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9799. * 3. A snapshot Node with cached server data, if we have it.
  9800. *
  9801. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9802. */
  9803. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9804. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9805. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9806. }
  9807. /**
  9808. * Recursive helper for applyOperationToSyncPoints_
  9809. */
  9810. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9811. if (pathIsEmpty(operation.path)) {
  9812. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9813. }
  9814. else {
  9815. const syncPoint = syncPointTree.get(newEmptyPath());
  9816. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9817. if (serverCache == null && syncPoint != null) {
  9818. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9819. }
  9820. let events = [];
  9821. const childName = pathGetFront(operation.path);
  9822. const childOperation = operation.operationForChild(childName);
  9823. const childTree = syncPointTree.children.get(childName);
  9824. if (childTree && childOperation) {
  9825. const childServerCache = serverCache
  9826. ? serverCache.getImmediateChild(childName)
  9827. : null;
  9828. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9829. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9830. }
  9831. if (syncPoint) {
  9832. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9833. }
  9834. return events;
  9835. }
  9836. }
  9837. /**
  9838. * Recursive helper for applyOperationToSyncPoints_
  9839. */
  9840. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9841. const syncPoint = syncPointTree.get(newEmptyPath());
  9842. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9843. if (serverCache == null && syncPoint != null) {
  9844. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9845. }
  9846. let events = [];
  9847. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9848. const childServerCache = serverCache
  9849. ? serverCache.getImmediateChild(childName)
  9850. : null;
  9851. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9852. const childOperation = operation.operationForChild(childName);
  9853. if (childOperation) {
  9854. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9855. }
  9856. });
  9857. if (syncPoint) {
  9858. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9859. }
  9860. return events;
  9861. }
  9862. function syncTreeCreateListenerForView_(syncTree, view) {
  9863. const query = view.query;
  9864. const tag = syncTreeTagForQuery(syncTree, query);
  9865. return {
  9866. hashFn: () => {
  9867. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9868. return cache.hash();
  9869. },
  9870. onComplete: (status) => {
  9871. if (status === 'ok') {
  9872. if (tag) {
  9873. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9874. }
  9875. else {
  9876. return syncTreeApplyListenComplete(syncTree, query._path);
  9877. }
  9878. }
  9879. else {
  9880. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9881. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9882. const error = errorForServerCode(status, query);
  9883. return syncTreeRemoveEventRegistration(syncTree, query,
  9884. /*eventRegistration*/ null, error);
  9885. }
  9886. }
  9887. };
  9888. }
  9889. /**
  9890. * Return the tag associated with the given query.
  9891. */
  9892. function syncTreeTagForQuery(syncTree, query) {
  9893. const queryKey = syncTreeMakeQueryKey_(query);
  9894. return syncTree.queryToTagMap.get(queryKey);
  9895. }
  9896. /**
  9897. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9898. */
  9899. function syncTreeMakeQueryKey_(query) {
  9900. return query._path.toString() + '$' + query._queryIdentifier;
  9901. }
  9902. /**
  9903. * Return the query associated with the given tag, if we have one
  9904. */
  9905. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9906. return syncTree.tagToQueryMap.get(tag);
  9907. }
  9908. /**
  9909. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9910. */
  9911. function syncTreeParseQueryKey_(queryKey) {
  9912. const splitIndex = queryKey.indexOf('$');
  9913. assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9914. return {
  9915. queryId: queryKey.substr(splitIndex + 1),
  9916. path: new Path(queryKey.substr(0, splitIndex))
  9917. };
  9918. }
  9919. /**
  9920. * A helper method to apply tagged operations
  9921. */
  9922. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9923. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9924. assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9925. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9926. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9927. }
  9928. /**
  9929. * This collapses multiple unfiltered views into a single view, since we only need a single
  9930. * listener for them.
  9931. */
  9932. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9933. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9934. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9935. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9936. return [completeView];
  9937. }
  9938. else {
  9939. // No complete view here, flatten any deeper listens into an array
  9940. let views = [];
  9941. if (maybeChildSyncPoint) {
  9942. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9943. }
  9944. each(childMap, (_key, childViews) => {
  9945. views = views.concat(childViews);
  9946. });
  9947. return views;
  9948. }
  9949. });
  9950. }
  9951. /**
  9952. * Normalizes a query to a query we send the server for listening
  9953. *
  9954. * @returns The normalized query
  9955. */
  9956. function syncTreeQueryForListening_(query) {
  9957. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9958. // We treat queries that load all data as default queries
  9959. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9960. // from Query
  9961. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9962. }
  9963. else {
  9964. return query;
  9965. }
  9966. }
  9967. function syncTreeRemoveTags_(syncTree, queries) {
  9968. for (let j = 0; j < queries.length; ++j) {
  9969. const removedQuery = queries[j];
  9970. if (!removedQuery._queryParams.loadsAllData()) {
  9971. // We should have a tag for this
  9972. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9973. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9974. syncTree.queryToTagMap.delete(removedQueryKey);
  9975. syncTree.tagToQueryMap.delete(removedQueryTag);
  9976. }
  9977. }
  9978. }
  9979. /**
  9980. * Static accessor for query tags.
  9981. */
  9982. function syncTreeGetNextQueryTag_() {
  9983. return syncTreeNextQueryTag_++;
  9984. }
  9985. /**
  9986. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9987. *
  9988. * @returns This method can return events to support synchronous data sources
  9989. */
  9990. function syncTreeSetupListener_(syncTree, query, view) {
  9991. const path = query._path;
  9992. const tag = syncTreeTagForQuery(syncTree, query);
  9993. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9994. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  9995. const subtree = syncTree.syncPointTree_.subtree(path);
  9996. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  9997. // may need to shadow other listens as well.
  9998. if (tag) {
  9999. assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10000. }
  10001. else {
  10002. // Shadow everything at or below this location, this is a default listener.
  10003. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  10004. if (!pathIsEmpty(relativePath) &&
  10005. maybeChildSyncPoint &&
  10006. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10007. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10008. }
  10009. else {
  10010. // No default listener here, flatten any deeper queries into an array
  10011. let queries = [];
  10012. if (maybeChildSyncPoint) {
  10013. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10014. }
  10015. each(childMap, (_key, childQueries) => {
  10016. queries = queries.concat(childQueries);
  10017. });
  10018. return queries;
  10019. }
  10020. });
  10021. for (let i = 0; i < queriesToStop.length; ++i) {
  10022. const queryToStop = queriesToStop[i];
  10023. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10024. }
  10025. }
  10026. return events;
  10027. }
  10028. /**
  10029. * @license
  10030. * Copyright 2017 Google LLC
  10031. *
  10032. * Licensed under the Apache License, Version 2.0 (the "License");
  10033. * you may not use this file except in compliance with the License.
  10034. * You may obtain a copy of the License at
  10035. *
  10036. * http://www.apache.org/licenses/LICENSE-2.0
  10037. *
  10038. * Unless required by applicable law or agreed to in writing, software
  10039. * distributed under the License is distributed on an "AS IS" BASIS,
  10040. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10041. * See the License for the specific language governing permissions and
  10042. * limitations under the License.
  10043. */
  10044. class ExistingValueProvider {
  10045. constructor(node_) {
  10046. this.node_ = node_;
  10047. }
  10048. getImmediateChild(childName) {
  10049. const child = this.node_.getImmediateChild(childName);
  10050. return new ExistingValueProvider(child);
  10051. }
  10052. node() {
  10053. return this.node_;
  10054. }
  10055. }
  10056. class DeferredValueProvider {
  10057. constructor(syncTree, path) {
  10058. this.syncTree_ = syncTree;
  10059. this.path_ = path;
  10060. }
  10061. getImmediateChild(childName) {
  10062. const childPath = pathChild(this.path_, childName);
  10063. return new DeferredValueProvider(this.syncTree_, childPath);
  10064. }
  10065. node() {
  10066. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10067. }
  10068. }
  10069. /**
  10070. * Generate placeholders for deferred values.
  10071. */
  10072. const generateWithValues = function (values) {
  10073. values = values || {};
  10074. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10075. return values;
  10076. };
  10077. /**
  10078. * Value to use when firing local events. When writing server values, fire
  10079. * local events with an approximate value, otherwise return value as-is.
  10080. */
  10081. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10082. if (!value || typeof value !== 'object') {
  10083. return value;
  10084. }
  10085. assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10086. if (typeof value['.sv'] === 'string') {
  10087. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10088. }
  10089. else if (typeof value['.sv'] === 'object') {
  10090. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10091. }
  10092. else {
  10093. assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10094. }
  10095. };
  10096. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10097. switch (op) {
  10098. case 'timestamp':
  10099. return serverValues['timestamp'];
  10100. default:
  10101. assert(false, 'Unexpected server value: ' + op);
  10102. }
  10103. };
  10104. const resolveComplexDeferredValue = function (op, existing, unused) {
  10105. if (!op.hasOwnProperty('increment')) {
  10106. assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10107. }
  10108. const delta = op['increment'];
  10109. if (typeof delta !== 'number') {
  10110. assert(false, 'Unexpected increment value: ' + delta);
  10111. }
  10112. const existingNode = existing.node();
  10113. assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10114. // Incrementing a non-number sets the value to the incremented amount
  10115. if (!existingNode.isLeafNode()) {
  10116. return delta;
  10117. }
  10118. const leaf = existingNode;
  10119. const existingVal = leaf.getValue();
  10120. if (typeof existingVal !== 'number') {
  10121. return delta;
  10122. }
  10123. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10124. return existingVal + delta;
  10125. };
  10126. /**
  10127. * Recursively replace all deferred values and priorities in the tree with the
  10128. * specified generated replacement values.
  10129. * @param path - path to which write is relative
  10130. * @param node - new data written at path
  10131. * @param syncTree - current data
  10132. */
  10133. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10134. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10135. };
  10136. /**
  10137. * Recursively replace all deferred values and priorities in the node with the
  10138. * specified generated replacement values. If there are no server values in the node,
  10139. * it'll be returned as-is.
  10140. */
  10141. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10142. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10143. };
  10144. function resolveDeferredValue(node, existingVal, serverValues) {
  10145. const rawPri = node.getPriority().val();
  10146. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10147. let newNode;
  10148. if (node.isLeafNode()) {
  10149. const leafNode = node;
  10150. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10151. if (value !== leafNode.getValue() ||
  10152. priority !== leafNode.getPriority().val()) {
  10153. return new LeafNode(value, nodeFromJSON(priority));
  10154. }
  10155. else {
  10156. return node;
  10157. }
  10158. }
  10159. else {
  10160. const childrenNode = node;
  10161. newNode = childrenNode;
  10162. if (priority !== childrenNode.getPriority().val()) {
  10163. newNode = newNode.updatePriority(new LeafNode(priority));
  10164. }
  10165. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10166. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10167. if (newChildNode !== childNode) {
  10168. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10169. }
  10170. });
  10171. return newNode;
  10172. }
  10173. }
  10174. /**
  10175. * @license
  10176. * Copyright 2017 Google LLC
  10177. *
  10178. * Licensed under the Apache License, Version 2.0 (the "License");
  10179. * you may not use this file except in compliance with the License.
  10180. * You may obtain a copy of the License at
  10181. *
  10182. * http://www.apache.org/licenses/LICENSE-2.0
  10183. *
  10184. * Unless required by applicable law or agreed to in writing, software
  10185. * distributed under the License is distributed on an "AS IS" BASIS,
  10186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10187. * See the License for the specific language governing permissions and
  10188. * limitations under the License.
  10189. */
  10190. /**
  10191. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10192. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10193. * children.
  10194. */
  10195. class Tree {
  10196. /**
  10197. * @param name - Optional name of the node.
  10198. * @param parent - Optional parent node.
  10199. * @param node - Optional node to wrap.
  10200. */
  10201. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10202. this.name = name;
  10203. this.parent = parent;
  10204. this.node = node;
  10205. }
  10206. }
  10207. /**
  10208. * Returns a sub-Tree for the given path.
  10209. *
  10210. * @param pathObj - Path to look up.
  10211. * @returns Tree for path.
  10212. */
  10213. function treeSubTree(tree, pathObj) {
  10214. // TODO: Require pathObj to be Path?
  10215. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10216. let child = tree, next = pathGetFront(path);
  10217. while (next !== null) {
  10218. const childNode = safeGet(child.node.children, next) || {
  10219. children: {},
  10220. childCount: 0
  10221. };
  10222. child = new Tree(next, child, childNode);
  10223. path = pathPopFront(path);
  10224. next = pathGetFront(path);
  10225. }
  10226. return child;
  10227. }
  10228. /**
  10229. * Returns the data associated with this tree node.
  10230. *
  10231. * @returns The data or null if no data exists.
  10232. */
  10233. function treeGetValue(tree) {
  10234. return tree.node.value;
  10235. }
  10236. /**
  10237. * Sets data to this tree node.
  10238. *
  10239. * @param value - Value to set.
  10240. */
  10241. function treeSetValue(tree, value) {
  10242. tree.node.value = value;
  10243. treeUpdateParents(tree);
  10244. }
  10245. /**
  10246. * @returns Whether the tree has any children.
  10247. */
  10248. function treeHasChildren(tree) {
  10249. return tree.node.childCount > 0;
  10250. }
  10251. /**
  10252. * @returns Whether the tree is empty (no value or children).
  10253. */
  10254. function treeIsEmpty(tree) {
  10255. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10256. }
  10257. /**
  10258. * Calls action for each child of this tree node.
  10259. *
  10260. * @param action - Action to be called for each child.
  10261. */
  10262. function treeForEachChild(tree, action) {
  10263. each(tree.node.children, (child, childTree) => {
  10264. action(new Tree(child, tree, childTree));
  10265. });
  10266. }
  10267. /**
  10268. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10269. *
  10270. * @param action - Action to be called for each child.
  10271. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10272. * false.
  10273. * @param childrenFirst - Whether to call action on children before calling it on
  10274. * parent.
  10275. */
  10276. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10277. if (includeSelf && !childrenFirst) {
  10278. action(tree);
  10279. }
  10280. treeForEachChild(tree, child => {
  10281. treeForEachDescendant(child, action, true, childrenFirst);
  10282. });
  10283. if (includeSelf && childrenFirst) {
  10284. action(tree);
  10285. }
  10286. }
  10287. /**
  10288. * Calls action on each ancestor node.
  10289. *
  10290. * @param action - Action to be called on each parent; return
  10291. * true to abort.
  10292. * @param includeSelf - Whether to call action on this node as well.
  10293. * @returns true if the action callback returned true.
  10294. */
  10295. function treeForEachAncestor(tree, action, includeSelf) {
  10296. let node = includeSelf ? tree : tree.parent;
  10297. while (node !== null) {
  10298. if (action(node)) {
  10299. return true;
  10300. }
  10301. node = node.parent;
  10302. }
  10303. return false;
  10304. }
  10305. /**
  10306. * @returns The path of this tree node, as a Path.
  10307. */
  10308. function treeGetPath(tree) {
  10309. return new Path(tree.parent === null
  10310. ? tree.name
  10311. : treeGetPath(tree.parent) + '/' + tree.name);
  10312. }
  10313. /**
  10314. * Adds or removes this child from its parent based on whether it's empty or not.
  10315. */
  10316. function treeUpdateParents(tree) {
  10317. if (tree.parent !== null) {
  10318. treeUpdateChild(tree.parent, tree.name, tree);
  10319. }
  10320. }
  10321. /**
  10322. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10323. *
  10324. * @param childName - The name of the child to update.
  10325. * @param child - The child to update.
  10326. */
  10327. function treeUpdateChild(tree, childName, child) {
  10328. const childEmpty = treeIsEmpty(child);
  10329. const childExists = contains(tree.node.children, childName);
  10330. if (childEmpty && childExists) {
  10331. delete tree.node.children[childName];
  10332. tree.node.childCount--;
  10333. treeUpdateParents(tree);
  10334. }
  10335. else if (!childEmpty && !childExists) {
  10336. tree.node.children[childName] = child.node;
  10337. tree.node.childCount++;
  10338. treeUpdateParents(tree);
  10339. }
  10340. }
  10341. /**
  10342. * @license
  10343. * Copyright 2017 Google LLC
  10344. *
  10345. * Licensed under the Apache License, Version 2.0 (the "License");
  10346. * you may not use this file except in compliance with the License.
  10347. * You may obtain a copy of the License at
  10348. *
  10349. * http://www.apache.org/licenses/LICENSE-2.0
  10350. *
  10351. * Unless required by applicable law or agreed to in writing, software
  10352. * distributed under the License is distributed on an "AS IS" BASIS,
  10353. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10354. * See the License for the specific language governing permissions and
  10355. * limitations under the License.
  10356. */
  10357. /**
  10358. * True for invalid Firebase keys
  10359. */
  10360. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10361. /**
  10362. * True for invalid Firebase paths.
  10363. * Allows '/' in paths.
  10364. */
  10365. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10366. /**
  10367. * Maximum number of characters to allow in leaf value
  10368. */
  10369. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10370. const isValidKey = function (key) {
  10371. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10372. };
  10373. const isValidPathString = function (pathString) {
  10374. return (typeof pathString === 'string' &&
  10375. pathString.length !== 0 &&
  10376. !INVALID_PATH_REGEX_.test(pathString));
  10377. };
  10378. const isValidRootPathString = function (pathString) {
  10379. if (pathString) {
  10380. // Allow '/.info/' at the beginning.
  10381. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10382. }
  10383. return isValidPathString(pathString);
  10384. };
  10385. const isValidPriority = function (priority) {
  10386. return (priority === null ||
  10387. typeof priority === 'string' ||
  10388. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10389. (priority &&
  10390. typeof priority === 'object' &&
  10391. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10392. contains(priority, '.sv')));
  10393. };
  10394. /**
  10395. * Pre-validate a datum passed as an argument to Firebase function.
  10396. */
  10397. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10398. if (optional && value === undefined) {
  10399. return;
  10400. }
  10401. validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
  10402. };
  10403. /**
  10404. * Validate a data object client-side before sending to server.
  10405. */
  10406. const validateFirebaseData = function (errorPrefix, data, path_) {
  10407. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10408. if (data === undefined) {
  10409. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10410. }
  10411. if (typeof data === 'function') {
  10412. throw new Error(errorPrefix +
  10413. 'contains a function ' +
  10414. validationPathToErrorString(path) +
  10415. ' with contents = ' +
  10416. data.toString());
  10417. }
  10418. if (isInvalidJSONNumber(data)) {
  10419. throw new Error(errorPrefix +
  10420. 'contains ' +
  10421. data.toString() +
  10422. ' ' +
  10423. validationPathToErrorString(path));
  10424. }
  10425. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10426. if (typeof data === 'string' &&
  10427. data.length > MAX_LEAF_SIZE_ / 3 &&
  10428. stringLength(data) > MAX_LEAF_SIZE_) {
  10429. throw new Error(errorPrefix +
  10430. 'contains a string greater than ' +
  10431. MAX_LEAF_SIZE_ +
  10432. ' utf8 bytes ' +
  10433. validationPathToErrorString(path) +
  10434. " ('" +
  10435. data.substring(0, 50) +
  10436. "...')");
  10437. }
  10438. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10439. // to save extra walking of large objects.
  10440. if (data && typeof data === 'object') {
  10441. let hasDotValue = false;
  10442. let hasActualChild = false;
  10443. each(data, (key, value) => {
  10444. if (key === '.value') {
  10445. hasDotValue = true;
  10446. }
  10447. else if (key !== '.priority' && key !== '.sv') {
  10448. hasActualChild = true;
  10449. if (!isValidKey(key)) {
  10450. throw new Error(errorPrefix +
  10451. ' contains an invalid key (' +
  10452. key +
  10453. ') ' +
  10454. validationPathToErrorString(path) +
  10455. '. Keys must be non-empty strings ' +
  10456. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10457. }
  10458. }
  10459. validationPathPush(path, key);
  10460. validateFirebaseData(errorPrefix, value, path);
  10461. validationPathPop(path);
  10462. });
  10463. if (hasDotValue && hasActualChild) {
  10464. throw new Error(errorPrefix +
  10465. ' contains ".value" child ' +
  10466. validationPathToErrorString(path) +
  10467. ' in addition to actual children.');
  10468. }
  10469. }
  10470. };
  10471. /**
  10472. * Pre-validate paths passed in the firebase function.
  10473. */
  10474. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10475. let i, curPath;
  10476. for (i = 0; i < mergePaths.length; i++) {
  10477. curPath = mergePaths[i];
  10478. const keys = pathSlice(curPath);
  10479. for (let j = 0; j < keys.length; j++) {
  10480. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10481. else if (!isValidKey(keys[j])) {
  10482. throw new Error(errorPrefix +
  10483. 'contains an invalid key (' +
  10484. keys[j] +
  10485. ') in path ' +
  10486. curPath.toString() +
  10487. '. Keys must be non-empty strings ' +
  10488. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10489. }
  10490. }
  10491. }
  10492. // Check that update keys are not descendants of each other.
  10493. // We rely on the property that sorting guarantees that ancestors come
  10494. // right before descendants.
  10495. mergePaths.sort(pathCompare);
  10496. let prevPath = null;
  10497. for (i = 0; i < mergePaths.length; i++) {
  10498. curPath = mergePaths[i];
  10499. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10500. throw new Error(errorPrefix +
  10501. 'contains a path ' +
  10502. prevPath.toString() +
  10503. ' that is ancestor of another path ' +
  10504. curPath.toString());
  10505. }
  10506. prevPath = curPath;
  10507. }
  10508. };
  10509. /**
  10510. * pre-validate an object passed as an argument to firebase function (
  10511. * must be an object - e.g. for firebase.update()).
  10512. */
  10513. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10514. if (optional && data === undefined) {
  10515. return;
  10516. }
  10517. const errorPrefix$1 = errorPrefix(fnName, 'values');
  10518. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10519. throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
  10520. }
  10521. const mergePaths = [];
  10522. each(data, (key, value) => {
  10523. const curPath = new Path(key);
  10524. validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
  10525. if (pathGetBack(curPath) === '.priority') {
  10526. if (!isValidPriority(value)) {
  10527. throw new Error(errorPrefix$1 +
  10528. "contains an invalid value for '" +
  10529. curPath.toString() +
  10530. "', which must be a valid " +
  10531. 'Firebase priority (a string, finite number, server value, or null).');
  10532. }
  10533. }
  10534. mergePaths.push(curPath);
  10535. });
  10536. validateFirebaseMergePaths(errorPrefix$1, mergePaths);
  10537. };
  10538. const validatePriority = function (fnName, priority, optional) {
  10539. if (optional && priority === undefined) {
  10540. return;
  10541. }
  10542. if (isInvalidJSONNumber(priority)) {
  10543. throw new Error(errorPrefix(fnName, 'priority') +
  10544. 'is ' +
  10545. priority.toString() +
  10546. ', but must be a valid Firebase priority (a string, finite number, ' +
  10547. 'server value, or null).');
  10548. }
  10549. // Special case to allow importing data with a .sv.
  10550. if (!isValidPriority(priority)) {
  10551. throw new Error(errorPrefix(fnName, 'priority') +
  10552. 'must be a valid Firebase priority ' +
  10553. '(a string, finite number, server value, or null).');
  10554. }
  10555. };
  10556. const validateKey = function (fnName, argumentName, key, optional) {
  10557. if (optional && key === undefined) {
  10558. return;
  10559. }
  10560. if (!isValidKey(key)) {
  10561. throw new Error(errorPrefix(fnName, argumentName) +
  10562. 'was an invalid key = "' +
  10563. key +
  10564. '". Firebase keys must be non-empty strings and ' +
  10565. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10566. }
  10567. };
  10568. /**
  10569. * @internal
  10570. */
  10571. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10572. if (optional && pathString === undefined) {
  10573. return;
  10574. }
  10575. if (!isValidPathString(pathString)) {
  10576. throw new Error(errorPrefix(fnName, argumentName) +
  10577. 'was an invalid path = "' +
  10578. pathString +
  10579. '". Paths must be non-empty strings and ' +
  10580. 'can\'t contain ".", "#", "$", "[", or "]"');
  10581. }
  10582. };
  10583. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10584. if (pathString) {
  10585. // Allow '/.info/' at the beginning.
  10586. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10587. }
  10588. validatePathString(fnName, argumentName, pathString, optional);
  10589. };
  10590. /**
  10591. * @internal
  10592. */
  10593. const validateWritablePath = function (fnName, path) {
  10594. if (pathGetFront(path) === '.info') {
  10595. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10596. }
  10597. };
  10598. const validateUrl = function (fnName, parsedUrl) {
  10599. // TODO = Validate server better.
  10600. const pathString = parsedUrl.path.toString();
  10601. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10602. parsedUrl.repoInfo.host.length === 0 ||
  10603. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10604. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10605. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10606. throw new Error(errorPrefix(fnName, 'url') +
  10607. 'must be a valid firebase URL and ' +
  10608. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10609. }
  10610. };
  10611. /**
  10612. * @license
  10613. * Copyright 2017 Google LLC
  10614. *
  10615. * Licensed under the Apache License, Version 2.0 (the "License");
  10616. * you may not use this file except in compliance with the License.
  10617. * You may obtain a copy of the License at
  10618. *
  10619. * http://www.apache.org/licenses/LICENSE-2.0
  10620. *
  10621. * Unless required by applicable law or agreed to in writing, software
  10622. * distributed under the License is distributed on an "AS IS" BASIS,
  10623. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10624. * See the License for the specific language governing permissions and
  10625. * limitations under the License.
  10626. */
  10627. /**
  10628. * The event queue serves a few purposes:
  10629. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10630. * events being queued.
  10631. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10632. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10633. * left off, ensuring that the events are still raised synchronously and in order.
  10634. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10635. * events are raised synchronously.
  10636. *
  10637. * NOTE: This can all go away if/when we move to async events.
  10638. *
  10639. */
  10640. class EventQueue {
  10641. constructor() {
  10642. this.eventLists_ = [];
  10643. /**
  10644. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10645. */
  10646. this.recursionDepth_ = 0;
  10647. }
  10648. }
  10649. /**
  10650. * @param eventDataList - The new events to queue.
  10651. */
  10652. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10653. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10654. let currList = null;
  10655. for (let i = 0; i < eventDataList.length; i++) {
  10656. const data = eventDataList[i];
  10657. const path = data.getPath();
  10658. if (currList !== null && !pathEquals(path, currList.path)) {
  10659. eventQueue.eventLists_.push(currList);
  10660. currList = null;
  10661. }
  10662. if (currList === null) {
  10663. currList = { events: [], path };
  10664. }
  10665. currList.events.push(data);
  10666. }
  10667. if (currList) {
  10668. eventQueue.eventLists_.push(currList);
  10669. }
  10670. }
  10671. /**
  10672. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10673. * for the specified path.
  10674. *
  10675. * It is assumed that the new events are all for the specified path.
  10676. *
  10677. * @param path - The path to raise events for.
  10678. * @param eventDataList - The new events to raise.
  10679. */
  10680. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10681. eventQueueQueueEvents(eventQueue, eventDataList);
  10682. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10683. }
  10684. /**
  10685. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10686. * locations related to the specified change path (i.e. all ancestors and descendants).
  10687. *
  10688. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10689. *
  10690. * @param changedPath - The path to raise events for.
  10691. * @param eventDataList - The events to raise
  10692. */
  10693. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10694. eventQueueQueueEvents(eventQueue, eventDataList);
  10695. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10696. pathContains(changedPath, eventPath));
  10697. }
  10698. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10699. eventQueue.recursionDepth_++;
  10700. let sentAll = true;
  10701. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10702. const eventList = eventQueue.eventLists_[i];
  10703. if (eventList) {
  10704. const eventPath = eventList.path;
  10705. if (predicate(eventPath)) {
  10706. eventListRaise(eventQueue.eventLists_[i]);
  10707. eventQueue.eventLists_[i] = null;
  10708. }
  10709. else {
  10710. sentAll = false;
  10711. }
  10712. }
  10713. }
  10714. if (sentAll) {
  10715. eventQueue.eventLists_ = [];
  10716. }
  10717. eventQueue.recursionDepth_--;
  10718. }
  10719. /**
  10720. * Iterates through the list and raises each event
  10721. */
  10722. function eventListRaise(eventList) {
  10723. for (let i = 0; i < eventList.events.length; i++) {
  10724. const eventData = eventList.events[i];
  10725. if (eventData !== null) {
  10726. eventList.events[i] = null;
  10727. const eventFn = eventData.getEventRunner();
  10728. if (logger) {
  10729. log('event: ' + eventData.toString());
  10730. }
  10731. exceptionGuard(eventFn);
  10732. }
  10733. }
  10734. }
  10735. /**
  10736. * @license
  10737. * Copyright 2017 Google LLC
  10738. *
  10739. * Licensed under the Apache License, Version 2.0 (the "License");
  10740. * you may not use this file except in compliance with the License.
  10741. * You may obtain a copy of the License at
  10742. *
  10743. * http://www.apache.org/licenses/LICENSE-2.0
  10744. *
  10745. * Unless required by applicable law or agreed to in writing, software
  10746. * distributed under the License is distributed on an "AS IS" BASIS,
  10747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10748. * See the License for the specific language governing permissions and
  10749. * limitations under the License.
  10750. */
  10751. const INTERRUPT_REASON = 'repo_interrupt';
  10752. /**
  10753. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10754. * things this ensure that if there's ever a bug causing a mismatch between
  10755. * client / server hashes for some data, we won't retry indefinitely.
  10756. */
  10757. const MAX_TRANSACTION_RETRIES = 25;
  10758. /**
  10759. * A connection to a single data repository.
  10760. */
  10761. class Repo {
  10762. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10763. this.repoInfo_ = repoInfo_;
  10764. this.forceRestClient_ = forceRestClient_;
  10765. this.authTokenProvider_ = authTokenProvider_;
  10766. this.appCheckProvider_ = appCheckProvider_;
  10767. this.dataUpdateCount = 0;
  10768. this.statsListener_ = null;
  10769. this.eventQueue_ = new EventQueue();
  10770. this.nextWriteId_ = 1;
  10771. this.interceptServerDataCallback_ = null;
  10772. /** A list of data pieces and paths to be set when this client disconnects. */
  10773. this.onDisconnect_ = newSparseSnapshotTree();
  10774. /** Stores queues of outstanding transactions for Firebase locations. */
  10775. this.transactionQueueTree_ = new Tree();
  10776. // TODO: This should be @private but it's used by test_access.js and internal.js
  10777. this.persistentConnection_ = null;
  10778. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10779. this.key = this.repoInfo_.toURLString();
  10780. }
  10781. /**
  10782. * @returns The URL corresponding to the root of this Firebase.
  10783. */
  10784. toString() {
  10785. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10786. }
  10787. }
  10788. function repoStart(repo, appId, authOverride) {
  10789. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10790. if (repo.forceRestClient_ || beingCrawled()) {
  10791. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10792. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10793. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10794. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10795. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10796. }
  10797. else {
  10798. // Validate authOverride
  10799. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10800. if (typeof authOverride !== 'object') {
  10801. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10802. }
  10803. try {
  10804. stringify(authOverride);
  10805. }
  10806. catch (e) {
  10807. throw new Error('Invalid authOverride provided: ' + e);
  10808. }
  10809. }
  10810. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10811. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10812. }, (connectStatus) => {
  10813. repoOnConnectStatus(repo, connectStatus);
  10814. }, (updates) => {
  10815. repoOnServerInfoUpdate(repo, updates);
  10816. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10817. repo.server_ = repo.persistentConnection_;
  10818. }
  10819. repo.authTokenProvider_.addTokenChangeListener(token => {
  10820. repo.server_.refreshAuthToken(token);
  10821. });
  10822. repo.appCheckProvider_.addTokenChangeListener(result => {
  10823. repo.server_.refreshAppCheckToken(result.token);
  10824. });
  10825. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10826. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10827. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10828. // Used for .info.
  10829. repo.infoData_ = new SnapshotHolder();
  10830. repo.infoSyncTree_ = new SyncTree({
  10831. startListening: (query, tag, currentHashFn, onComplete) => {
  10832. let infoEvents = [];
  10833. const node = repo.infoData_.getNode(query._path);
  10834. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10835. // on initial data...
  10836. if (!node.isEmpty()) {
  10837. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10838. setTimeout(() => {
  10839. onComplete('ok');
  10840. }, 0);
  10841. }
  10842. return infoEvents;
  10843. },
  10844. stopListening: () => { }
  10845. });
  10846. repoUpdateInfo(repo, 'connected', false);
  10847. repo.serverSyncTree_ = new SyncTree({
  10848. startListening: (query, tag, currentHashFn, onComplete) => {
  10849. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10850. const events = onComplete(status, data);
  10851. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10852. });
  10853. // No synchronous events for network-backed sync trees
  10854. return [];
  10855. },
  10856. stopListening: (query, tag) => {
  10857. repo.server_.unlisten(query, tag);
  10858. }
  10859. });
  10860. }
  10861. /**
  10862. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10863. */
  10864. function repoServerTime(repo) {
  10865. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10866. const offset = offsetNode.val() || 0;
  10867. return new Date().getTime() + offset;
  10868. }
  10869. /**
  10870. * Generate ServerValues using some variables from the repo object.
  10871. */
  10872. function repoGenerateServerValues(repo) {
  10873. return generateWithValues({
  10874. timestamp: repoServerTime(repo)
  10875. });
  10876. }
  10877. /**
  10878. * Called by realtime when we get new messages from the server.
  10879. */
  10880. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10881. // For testing.
  10882. repo.dataUpdateCount++;
  10883. const path = new Path(pathString);
  10884. data = repo.interceptServerDataCallback_
  10885. ? repo.interceptServerDataCallback_(pathString, data)
  10886. : data;
  10887. let events = [];
  10888. if (tag) {
  10889. if (isMerge) {
  10890. const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
  10891. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10892. }
  10893. else {
  10894. const taggedSnap = nodeFromJSON(data);
  10895. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10896. }
  10897. }
  10898. else if (isMerge) {
  10899. const changedChildren = map(data, (raw) => nodeFromJSON(raw));
  10900. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10901. }
  10902. else {
  10903. const snap = nodeFromJSON(data);
  10904. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10905. }
  10906. let affectedPath = path;
  10907. if (events.length > 0) {
  10908. // Since we have a listener outstanding for each transaction, receiving any events
  10909. // is a proxy for some change having occurred.
  10910. affectedPath = repoRerunTransactions(repo, path);
  10911. }
  10912. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10913. }
  10914. function repoOnConnectStatus(repo, connectStatus) {
  10915. repoUpdateInfo(repo, 'connected', connectStatus);
  10916. if (connectStatus === false) {
  10917. repoRunOnDisconnectEvents(repo);
  10918. }
  10919. }
  10920. function repoOnServerInfoUpdate(repo, updates) {
  10921. each(updates, (key, value) => {
  10922. repoUpdateInfo(repo, key, value);
  10923. });
  10924. }
  10925. function repoUpdateInfo(repo, pathString, value) {
  10926. const path = new Path('/.info/' + pathString);
  10927. const newNode = nodeFromJSON(value);
  10928. repo.infoData_.updateSnapshot(path, newNode);
  10929. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10930. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10931. }
  10932. function repoGetNextWriteId(repo) {
  10933. return repo.nextWriteId_++;
  10934. }
  10935. /**
  10936. * The purpose of `getValue` is to return the latest known value
  10937. * satisfying `query`.
  10938. *
  10939. * This method will first check for in-memory cached values
  10940. * belonging to active listeners. If they are found, such values
  10941. * are considered to be the most up-to-date.
  10942. *
  10943. * If the client is not connected, this method will wait until the
  10944. * repo has established a connection and then request the value for `query`.
  10945. * If the client is not able to retrieve the query result for another reason,
  10946. * it reports an error.
  10947. *
  10948. * @param query - The query to surface a value for.
  10949. */
  10950. function repoGetValue(repo, query, eventRegistration) {
  10951. // Only active queries are cached. There is no persisted cache.
  10952. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10953. if (cached != null) {
  10954. return Promise.resolve(cached);
  10955. }
  10956. return repo.server_.get(query).then(payload => {
  10957. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10958. /**
  10959. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10960. * Add an event registration,
  10961. * Update data at the path,
  10962. * Raise any events,
  10963. * Cleanup the SyncTree
  10964. */
  10965. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10966. let events;
  10967. if (query._queryParams.loadsAllData()) {
  10968. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10969. }
  10970. else {
  10971. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10972. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10973. }
  10974. /*
  10975. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10976. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10977. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10978. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10979. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10980. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10981. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10982. * ensure the corresponding child events will get fired.
  10983. */
  10984. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10985. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10986. return node;
  10987. }, err => {
  10988. repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
  10989. return Promise.reject(new Error(err));
  10990. });
  10991. }
  10992. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  10993. repoLog(repo, 'set', {
  10994. path: path.toString(),
  10995. value: newVal,
  10996. priority: newPriority
  10997. });
  10998. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  10999. // (b) store unresolved paths on JSON parse
  11000. const serverValues = repoGenerateServerValues(repo);
  11001. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11002. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11003. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11004. const writeId = repoGetNextWriteId(repo);
  11005. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11006. eventQueueQueueEvents(repo.eventQueue_, events);
  11007. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11008. const success = status === 'ok';
  11009. if (!success) {
  11010. warn('set at ' + path + ' failed: ' + status);
  11011. }
  11012. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11013. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11014. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11015. });
  11016. const affectedPath = repoAbortTransactions(repo, path);
  11017. repoRerunTransactions(repo, affectedPath);
  11018. // We queued the events above, so just flush the queue here
  11019. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11020. }
  11021. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11022. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11023. // Start with our existing data and merge each child into it.
  11024. let empty = true;
  11025. const serverValues = repoGenerateServerValues(repo);
  11026. const changedChildren = {};
  11027. each(childrenToMerge, (changedKey, changedValue) => {
  11028. empty = false;
  11029. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11030. });
  11031. if (!empty) {
  11032. const writeId = repoGetNextWriteId(repo);
  11033. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11034. eventQueueQueueEvents(repo.eventQueue_, events);
  11035. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11036. const success = status === 'ok';
  11037. if (!success) {
  11038. warn('update at ' + path + ' failed: ' + status);
  11039. }
  11040. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11041. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11042. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11043. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11044. });
  11045. each(childrenToMerge, (changedPath) => {
  11046. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11047. repoRerunTransactions(repo, affectedPath);
  11048. });
  11049. // We queued the events above, so just flush the queue here
  11050. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11051. }
  11052. else {
  11053. log("update() called with empty data. Don't do anything.");
  11054. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11055. }
  11056. }
  11057. /**
  11058. * Applies all of the changes stored up in the onDisconnect_ tree.
  11059. */
  11060. function repoRunOnDisconnectEvents(repo) {
  11061. repoLog(repo, 'onDisconnectEvents');
  11062. const serverValues = repoGenerateServerValues(repo);
  11063. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11064. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11065. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11066. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11067. });
  11068. let events = [];
  11069. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11070. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11071. const affectedPath = repoAbortTransactions(repo, path);
  11072. repoRerunTransactions(repo, affectedPath);
  11073. });
  11074. repo.onDisconnect_ = newSparseSnapshotTree();
  11075. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11076. }
  11077. function repoOnDisconnectCancel(repo, path, onComplete) {
  11078. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11079. if (status === 'ok') {
  11080. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11081. }
  11082. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11083. });
  11084. }
  11085. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11086. const newNode = nodeFromJSON(value);
  11087. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11088. if (status === 'ok') {
  11089. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11090. }
  11091. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11092. });
  11093. }
  11094. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11095. const newNode = nodeFromJSON(value, priority);
  11096. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11097. if (status === 'ok') {
  11098. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11099. }
  11100. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11101. });
  11102. }
  11103. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11104. if (isEmpty(childrenToMerge)) {
  11105. log("onDisconnect().update() called with empty data. Don't do anything.");
  11106. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11107. return;
  11108. }
  11109. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11110. if (status === 'ok') {
  11111. each(childrenToMerge, (childName, childNode) => {
  11112. const newChildNode = nodeFromJSON(childNode);
  11113. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11114. });
  11115. }
  11116. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11117. });
  11118. }
  11119. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11120. let events;
  11121. if (pathGetFront(query._path) === '.info') {
  11122. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11123. }
  11124. else {
  11125. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11126. }
  11127. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11128. }
  11129. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11130. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11131. // a little bit by handling the return values anyways.
  11132. let events;
  11133. if (pathGetFront(query._path) === '.info') {
  11134. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11135. }
  11136. else {
  11137. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11138. }
  11139. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11140. }
  11141. function repoInterrupt(repo) {
  11142. if (repo.persistentConnection_) {
  11143. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11144. }
  11145. }
  11146. function repoResume(repo) {
  11147. if (repo.persistentConnection_) {
  11148. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11149. }
  11150. }
  11151. function repoLog(repo, ...varArgs) {
  11152. let prefix = '';
  11153. if (repo.persistentConnection_) {
  11154. prefix = repo.persistentConnection_.id + ':';
  11155. }
  11156. log(prefix, ...varArgs);
  11157. }
  11158. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11159. if (callback) {
  11160. exceptionGuard(() => {
  11161. if (status === 'ok') {
  11162. callback(null);
  11163. }
  11164. else {
  11165. const code = (status || 'error').toUpperCase();
  11166. let message = code;
  11167. if (errorReason) {
  11168. message += ': ' + errorReason;
  11169. }
  11170. const error = new Error(message);
  11171. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11172. error.code = code;
  11173. callback(error);
  11174. }
  11175. });
  11176. }
  11177. }
  11178. /**
  11179. * Creates a new transaction, adds it to the transactions we're tracking, and
  11180. * sends it to the server if possible.
  11181. *
  11182. * @param path - Path at which to do transaction.
  11183. * @param transactionUpdate - Update callback.
  11184. * @param onComplete - Completion callback.
  11185. * @param unwatcher - Function that will be called when the transaction no longer
  11186. * need data updates for `path`.
  11187. * @param applyLocally - Whether or not to make intermediate results visible
  11188. */
  11189. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11190. repoLog(repo, 'transaction on ' + path);
  11191. // Initialize transaction.
  11192. const transaction = {
  11193. path,
  11194. update: transactionUpdate,
  11195. onComplete,
  11196. // One of TransactionStatus enums.
  11197. status: null,
  11198. // Used when combining transactions at different locations to figure out
  11199. // which one goes first.
  11200. order: LUIDGenerator(),
  11201. // Whether to raise local events for this transaction.
  11202. applyLocally,
  11203. // Count of how many times we've retried the transaction.
  11204. retryCount: 0,
  11205. // Function to call to clean up our .on() listener.
  11206. unwatcher,
  11207. // Stores why a transaction was aborted.
  11208. abortReason: null,
  11209. currentWriteId: null,
  11210. currentInputSnapshot: null,
  11211. currentOutputSnapshotRaw: null,
  11212. currentOutputSnapshotResolved: null
  11213. };
  11214. // Run transaction initially.
  11215. const currentState = repoGetLatestState(repo, path, undefined);
  11216. transaction.currentInputSnapshot = currentState;
  11217. const newVal = transaction.update(currentState.val());
  11218. if (newVal === undefined) {
  11219. // Abort transaction.
  11220. transaction.unwatcher();
  11221. transaction.currentOutputSnapshotRaw = null;
  11222. transaction.currentOutputSnapshotResolved = null;
  11223. if (transaction.onComplete) {
  11224. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11225. }
  11226. }
  11227. else {
  11228. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11229. // Mark as run and add to our queue.
  11230. transaction.status = 0 /* TransactionStatus.RUN */;
  11231. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11232. const nodeQueue = treeGetValue(queueNode) || [];
  11233. nodeQueue.push(transaction);
  11234. treeSetValue(queueNode, nodeQueue);
  11235. // Update visibleData and raise events
  11236. // Note: We intentionally raise events after updating all of our
  11237. // transaction state, since the user could start new transactions from the
  11238. // event callbacks.
  11239. let priorityForNode;
  11240. if (typeof newVal === 'object' &&
  11241. newVal !== null &&
  11242. contains(newVal, '.priority')) {
  11243. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11244. priorityForNode = safeGet(newVal, '.priority');
  11245. assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11246. 'Priority must be a valid string, finite number, server value, or null.');
  11247. }
  11248. else {
  11249. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11250. ChildrenNode.EMPTY_NODE;
  11251. priorityForNode = currentNode.getPriority().val();
  11252. }
  11253. const serverValues = repoGenerateServerValues(repo);
  11254. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11255. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11256. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11257. transaction.currentOutputSnapshotResolved = newNode;
  11258. transaction.currentWriteId = repoGetNextWriteId(repo);
  11259. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11260. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11261. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11262. }
  11263. }
  11264. /**
  11265. * @param excludeSets - A specific set to exclude
  11266. */
  11267. function repoGetLatestState(repo, path, excludeSets) {
  11268. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11269. ChildrenNode.EMPTY_NODE);
  11270. }
  11271. /**
  11272. * Sends any already-run transactions that aren't waiting for outstanding
  11273. * transactions to complete.
  11274. *
  11275. * Externally it's called with no arguments, but it calls itself recursively
  11276. * with a particular transactionQueueTree node to recurse through the tree.
  11277. *
  11278. * @param node - transactionQueueTree node to start at.
  11279. */
  11280. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11281. // Before recursing, make sure any completed transactions are removed.
  11282. if (!node) {
  11283. repoPruneCompletedTransactionsBelowNode(repo, node);
  11284. }
  11285. if (treeGetValue(node)) {
  11286. const queue = repoBuildTransactionQueue(repo, node);
  11287. assert(queue.length > 0, 'Sending zero length transaction queue');
  11288. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11289. // If they're all run (and not sent), we can send them. Else, we must wait.
  11290. if (allRun) {
  11291. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11292. }
  11293. }
  11294. else if (treeHasChildren(node)) {
  11295. treeForEachChild(node, childNode => {
  11296. repoSendReadyTransactions(repo, childNode);
  11297. });
  11298. }
  11299. }
  11300. /**
  11301. * Given a list of run transactions, send them to the server and then handle
  11302. * the result (success or failure).
  11303. *
  11304. * @param path - The location of the queue.
  11305. * @param queue - Queue of transactions under the specified location.
  11306. */
  11307. function repoSendTransactionQueue(repo, path, queue) {
  11308. // Mark transactions as sent and increment retry count!
  11309. const setsToIgnore = queue.map(txn => {
  11310. return txn.currentWriteId;
  11311. });
  11312. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11313. let snapToSend = latestState;
  11314. const latestHash = latestState.hash();
  11315. for (let i = 0; i < queue.length; i++) {
  11316. const txn = queue[i];
  11317. assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11318. txn.status = 1 /* TransactionStatus.SENT */;
  11319. txn.retryCount++;
  11320. const relativePath = newRelativePath(path, txn.path);
  11321. // If we've gotten to this point, the output snapshot must be defined.
  11322. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11323. }
  11324. const dataToSend = snapToSend.val(true);
  11325. const pathToSend = path;
  11326. // Send the put.
  11327. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11328. repoLog(repo, 'transaction put response', {
  11329. path: pathToSend.toString(),
  11330. status
  11331. });
  11332. let events = [];
  11333. if (status === 'ok') {
  11334. // Queue up the callbacks and fire them after cleaning up all of our
  11335. // transaction state, since the callback could trigger more
  11336. // transactions or sets.
  11337. const callbacks = [];
  11338. for (let i = 0; i < queue.length; i++) {
  11339. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11340. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11341. if (queue[i].onComplete) {
  11342. // We never unset the output snapshot, and given that this
  11343. // transaction is complete, it should be set
  11344. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11345. }
  11346. queue[i].unwatcher();
  11347. }
  11348. // Now remove the completed transactions.
  11349. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11350. // There may be pending transactions that we can now send.
  11351. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11352. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11353. // Finally, trigger onComplete callbacks.
  11354. for (let i = 0; i < callbacks.length; i++) {
  11355. exceptionGuard(callbacks[i]);
  11356. }
  11357. }
  11358. else {
  11359. // transactions are no longer sent. Update their status appropriately.
  11360. if (status === 'datastale') {
  11361. for (let i = 0; i < queue.length; i++) {
  11362. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11363. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11364. }
  11365. else {
  11366. queue[i].status = 0 /* TransactionStatus.RUN */;
  11367. }
  11368. }
  11369. }
  11370. else {
  11371. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11372. for (let i = 0; i < queue.length; i++) {
  11373. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11374. queue[i].abortReason = status;
  11375. }
  11376. }
  11377. repoRerunTransactions(repo, path);
  11378. }
  11379. }, latestHash);
  11380. }
  11381. /**
  11382. * Finds all transactions dependent on the data at changedPath and reruns them.
  11383. *
  11384. * Should be called any time cached data changes.
  11385. *
  11386. * Return the highest path that was affected by rerunning transactions. This
  11387. * is the path at which events need to be raised for.
  11388. *
  11389. * @param changedPath - The path in mergedData that changed.
  11390. * @returns The rootmost path that was affected by rerunning transactions.
  11391. */
  11392. function repoRerunTransactions(repo, changedPath) {
  11393. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11394. const path = treeGetPath(rootMostTransactionNode);
  11395. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11396. repoRerunTransactionQueue(repo, queue, path);
  11397. return path;
  11398. }
  11399. /**
  11400. * Does all the work of rerunning transactions (as well as cleans up aborted
  11401. * transactions and whatnot).
  11402. *
  11403. * @param queue - The queue of transactions to run.
  11404. * @param path - The path the queue is for.
  11405. */
  11406. function repoRerunTransactionQueue(repo, queue, path) {
  11407. if (queue.length === 0) {
  11408. return; // Nothing to do!
  11409. }
  11410. // Queue up the callbacks and fire them after cleaning up all of our
  11411. // transaction state, since the callback could trigger more transactions or
  11412. // sets.
  11413. const callbacks = [];
  11414. let events = [];
  11415. // Ignore all of the sets we're going to re-run.
  11416. const txnsToRerun = queue.filter(q => {
  11417. return q.status === 0 /* TransactionStatus.RUN */;
  11418. });
  11419. const setsToIgnore = txnsToRerun.map(q => {
  11420. return q.currentWriteId;
  11421. });
  11422. for (let i = 0; i < queue.length; i++) {
  11423. const transaction = queue[i];
  11424. const relativePath = newRelativePath(path, transaction.path);
  11425. let abortTransaction = false, abortReason;
  11426. assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11427. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11428. abortTransaction = true;
  11429. abortReason = transaction.abortReason;
  11430. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11431. }
  11432. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11433. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11434. abortTransaction = true;
  11435. abortReason = 'maxretry';
  11436. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11437. }
  11438. else {
  11439. // This code reruns a transaction
  11440. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11441. transaction.currentInputSnapshot = currentNode;
  11442. const newData = queue[i].update(currentNode.val());
  11443. if (newData !== undefined) {
  11444. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11445. let newDataNode = nodeFromJSON(newData);
  11446. const hasExplicitPriority = typeof newData === 'object' &&
  11447. newData != null &&
  11448. contains(newData, '.priority');
  11449. if (!hasExplicitPriority) {
  11450. // Keep the old priority if there wasn't a priority explicitly specified.
  11451. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11452. }
  11453. const oldWriteId = transaction.currentWriteId;
  11454. const serverValues = repoGenerateServerValues(repo);
  11455. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11456. transaction.currentOutputSnapshotRaw = newDataNode;
  11457. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11458. transaction.currentWriteId = repoGetNextWriteId(repo);
  11459. // Mutates setsToIgnore in place
  11460. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11461. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11462. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11463. }
  11464. else {
  11465. abortTransaction = true;
  11466. abortReason = 'nodata';
  11467. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11468. }
  11469. }
  11470. }
  11471. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11472. events = [];
  11473. if (abortTransaction) {
  11474. // Abort.
  11475. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11476. // Removing a listener can trigger pruning which can muck with
  11477. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11478. // until we're done.
  11479. (function (unwatcher) {
  11480. setTimeout(unwatcher, Math.floor(0));
  11481. })(queue[i].unwatcher);
  11482. if (queue[i].onComplete) {
  11483. if (abortReason === 'nodata') {
  11484. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11485. }
  11486. else {
  11487. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11488. }
  11489. }
  11490. }
  11491. }
  11492. // Clean up completed transactions.
  11493. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11494. // Now fire callbacks, now that we're in a good, known state.
  11495. for (let i = 0; i < callbacks.length; i++) {
  11496. exceptionGuard(callbacks[i]);
  11497. }
  11498. // Try to send the transaction result to the server.
  11499. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11500. }
  11501. /**
  11502. * Returns the rootmost ancestor node of the specified path that has a pending
  11503. * transaction on it, or just returns the node for the given path if there are
  11504. * no pending transactions on any ancestor.
  11505. *
  11506. * @param path - The location to start at.
  11507. * @returns The rootmost node with a transaction.
  11508. */
  11509. function repoGetAncestorTransactionNode(repo, path) {
  11510. let front;
  11511. // Start at the root and walk deeper into the tree towards path until we
  11512. // find a node with pending transactions.
  11513. let transactionNode = repo.transactionQueueTree_;
  11514. front = pathGetFront(path);
  11515. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11516. transactionNode = treeSubTree(transactionNode, front);
  11517. path = pathPopFront(path);
  11518. front = pathGetFront(path);
  11519. }
  11520. return transactionNode;
  11521. }
  11522. /**
  11523. * Builds the queue of all transactions at or below the specified
  11524. * transactionNode.
  11525. *
  11526. * @param transactionNode
  11527. * @returns The generated queue.
  11528. */
  11529. function repoBuildTransactionQueue(repo, transactionNode) {
  11530. // Walk any child transaction queues and aggregate them into a single queue.
  11531. const transactionQueue = [];
  11532. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11533. // Sort them by the order the transactions were created.
  11534. transactionQueue.sort((a, b) => a.order - b.order);
  11535. return transactionQueue;
  11536. }
  11537. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11538. const nodeQueue = treeGetValue(node);
  11539. if (nodeQueue) {
  11540. for (let i = 0; i < nodeQueue.length; i++) {
  11541. queue.push(nodeQueue[i]);
  11542. }
  11543. }
  11544. treeForEachChild(node, child => {
  11545. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11546. });
  11547. }
  11548. /**
  11549. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11550. */
  11551. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11552. const queue = treeGetValue(node);
  11553. if (queue) {
  11554. let to = 0;
  11555. for (let from = 0; from < queue.length; from++) {
  11556. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11557. queue[to] = queue[from];
  11558. to++;
  11559. }
  11560. }
  11561. queue.length = to;
  11562. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11563. }
  11564. treeForEachChild(node, childNode => {
  11565. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11566. });
  11567. }
  11568. /**
  11569. * Aborts all transactions on ancestors or descendants of the specified path.
  11570. * Called when doing a set() or update() since we consider them incompatible
  11571. * with transactions.
  11572. *
  11573. * @param path - Path for which we want to abort related transactions.
  11574. */
  11575. function repoAbortTransactions(repo, path) {
  11576. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11577. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11578. treeForEachAncestor(transactionNode, (node) => {
  11579. repoAbortTransactionsOnNode(repo, node);
  11580. });
  11581. repoAbortTransactionsOnNode(repo, transactionNode);
  11582. treeForEachDescendant(transactionNode, (node) => {
  11583. repoAbortTransactionsOnNode(repo, node);
  11584. });
  11585. return affectedPath;
  11586. }
  11587. /**
  11588. * Abort transactions stored in this transaction queue node.
  11589. *
  11590. * @param node - Node to abort transactions for.
  11591. */
  11592. function repoAbortTransactionsOnNode(repo, node) {
  11593. const queue = treeGetValue(node);
  11594. if (queue) {
  11595. // Queue up the callbacks and fire them after cleaning up all of our
  11596. // transaction state, since the callback could trigger more transactions
  11597. // or sets.
  11598. const callbacks = [];
  11599. // Go through queue. Any already-sent transactions must be marked for
  11600. // abort, while the unsent ones can be immediately aborted and removed.
  11601. let events = [];
  11602. let lastSent = -1;
  11603. for (let i = 0; i < queue.length; i++) {
  11604. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11605. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11606. assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11607. lastSent = i;
  11608. // Mark transaction for abort when it comes back.
  11609. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11610. queue[i].abortReason = 'set';
  11611. }
  11612. else {
  11613. assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11614. // We can abort it immediately.
  11615. queue[i].unwatcher();
  11616. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11617. if (queue[i].onComplete) {
  11618. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11619. }
  11620. }
  11621. }
  11622. if (lastSent === -1) {
  11623. // We're not waiting for any sent transactions. We can clear the queue.
  11624. treeSetValue(node, undefined);
  11625. }
  11626. else {
  11627. // Remove the transactions we aborted.
  11628. queue.length = lastSent + 1;
  11629. }
  11630. // Now fire the callbacks.
  11631. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11632. for (let i = 0; i < callbacks.length; i++) {
  11633. exceptionGuard(callbacks[i]);
  11634. }
  11635. }
  11636. }
  11637. /**
  11638. * @license
  11639. * Copyright 2017 Google LLC
  11640. *
  11641. * Licensed under the Apache License, Version 2.0 (the "License");
  11642. * you may not use this file except in compliance with the License.
  11643. * You may obtain a copy of the License at
  11644. *
  11645. * http://www.apache.org/licenses/LICENSE-2.0
  11646. *
  11647. * Unless required by applicable law or agreed to in writing, software
  11648. * distributed under the License is distributed on an "AS IS" BASIS,
  11649. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11650. * See the License for the specific language governing permissions and
  11651. * limitations under the License.
  11652. */
  11653. function decodePath(pathString) {
  11654. let pathStringDecoded = '';
  11655. const pieces = pathString.split('/');
  11656. for (let i = 0; i < pieces.length; i++) {
  11657. if (pieces[i].length > 0) {
  11658. let piece = pieces[i];
  11659. try {
  11660. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11661. }
  11662. catch (e) { }
  11663. pathStringDecoded += '/' + piece;
  11664. }
  11665. }
  11666. return pathStringDecoded;
  11667. }
  11668. /**
  11669. * @returns key value hash
  11670. */
  11671. function decodeQuery(queryString) {
  11672. const results = {};
  11673. if (queryString.charAt(0) === '?') {
  11674. queryString = queryString.substring(1);
  11675. }
  11676. for (const segment of queryString.split('&')) {
  11677. if (segment.length === 0) {
  11678. continue;
  11679. }
  11680. const kv = segment.split('=');
  11681. if (kv.length === 2) {
  11682. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11683. }
  11684. else {
  11685. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11686. }
  11687. }
  11688. return results;
  11689. }
  11690. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11691. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11692. if (parsedUrl.domain === 'firebase.com') {
  11693. fatal(parsedUrl.host +
  11694. ' is no longer supported. ' +
  11695. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11696. }
  11697. // Catch common error of uninitialized namespace value.
  11698. if ((!namespace || namespace === 'undefined') &&
  11699. parsedUrl.domain !== 'localhost') {
  11700. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11701. }
  11702. if (!parsedUrl.secure) {
  11703. warnIfPageIsSecure();
  11704. }
  11705. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11706. return {
  11707. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11708. /*persistenceKey=*/ '',
  11709. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11710. path: new Path(parsedUrl.pathString)
  11711. };
  11712. };
  11713. const parseDatabaseURL = function (dataURL) {
  11714. // Default to empty strings in the event of a malformed string.
  11715. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11716. // Always default to SSL, unless otherwise specified.
  11717. let secure = true, scheme = 'https', port = 443;
  11718. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11719. if (typeof dataURL === 'string') {
  11720. // Parse scheme.
  11721. let colonInd = dataURL.indexOf('//');
  11722. if (colonInd >= 0) {
  11723. scheme = dataURL.substring(0, colonInd - 1);
  11724. dataURL = dataURL.substring(colonInd + 2);
  11725. }
  11726. // Parse host, path, and query string.
  11727. let slashInd = dataURL.indexOf('/');
  11728. if (slashInd === -1) {
  11729. slashInd = dataURL.length;
  11730. }
  11731. let questionMarkInd = dataURL.indexOf('?');
  11732. if (questionMarkInd === -1) {
  11733. questionMarkInd = dataURL.length;
  11734. }
  11735. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11736. if (slashInd < questionMarkInd) {
  11737. // For pathString, questionMarkInd will always come after slashInd
  11738. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11739. }
  11740. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11741. // If we have a port, use scheme for determining if it's secure.
  11742. colonInd = host.indexOf(':');
  11743. if (colonInd >= 0) {
  11744. secure = scheme === 'https' || scheme === 'wss';
  11745. port = parseInt(host.substring(colonInd + 1), 10);
  11746. }
  11747. else {
  11748. colonInd = host.length;
  11749. }
  11750. const hostWithoutPort = host.slice(0, colonInd);
  11751. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11752. domain = 'localhost';
  11753. }
  11754. else if (hostWithoutPort.split('.').length <= 2) {
  11755. domain = hostWithoutPort;
  11756. }
  11757. else {
  11758. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11759. const dotInd = host.indexOf('.');
  11760. subdomain = host.substring(0, dotInd).toLowerCase();
  11761. domain = host.substring(dotInd + 1);
  11762. // Normalize namespaces to lowercase to share storage / connection.
  11763. namespace = subdomain;
  11764. }
  11765. // Always treat the value of the `ns` as the namespace name if it is present.
  11766. if ('ns' in queryParams) {
  11767. namespace = queryParams['ns'];
  11768. }
  11769. }
  11770. return {
  11771. host,
  11772. port,
  11773. domain,
  11774. subdomain,
  11775. secure,
  11776. scheme,
  11777. pathString,
  11778. namespace
  11779. };
  11780. };
  11781. /**
  11782. * @license
  11783. * Copyright 2017 Google LLC
  11784. *
  11785. * Licensed under the Apache License, Version 2.0 (the "License");
  11786. * you may not use this file except in compliance with the License.
  11787. * You may obtain a copy of the License at
  11788. *
  11789. * http://www.apache.org/licenses/LICENSE-2.0
  11790. *
  11791. * Unless required by applicable law or agreed to in writing, software
  11792. * distributed under the License is distributed on an "AS IS" BASIS,
  11793. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11794. * See the License for the specific language governing permissions and
  11795. * limitations under the License.
  11796. */
  11797. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11798. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11799. /**
  11800. * Fancy ID generator that creates 20-character string identifiers with the
  11801. * following properties:
  11802. *
  11803. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11804. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11805. * collide with other clients' IDs.
  11806. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11807. * that will sort properly).
  11808. * 4. They're monotonically increasing. Even if you generate more than one in
  11809. * the same timestamp, the latter ones will sort after the former ones. We do
  11810. * this by using the previous random bits but "incrementing" them by 1 (only
  11811. * in the case of a timestamp collision).
  11812. */
  11813. const nextPushId = (function () {
  11814. // Timestamp of last push, used to prevent local collisions if you push twice
  11815. // in one ms.
  11816. let lastPushTime = 0;
  11817. // We generate 72-bits of randomness which get turned into 12 characters and
  11818. // appended to the timestamp to prevent collisions with other clients. We
  11819. // store the last characters we generated because in the event of a collision,
  11820. // we'll use those same characters except "incremented" by one.
  11821. const lastRandChars = [];
  11822. return function (now) {
  11823. const duplicateTime = now === lastPushTime;
  11824. lastPushTime = now;
  11825. let i;
  11826. const timeStampChars = new Array(8);
  11827. for (i = 7; i >= 0; i--) {
  11828. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11829. // NOTE: Can't use << here because javascript will convert to int and lose
  11830. // the upper bits.
  11831. now = Math.floor(now / 64);
  11832. }
  11833. assert(now === 0, 'Cannot push at time == 0');
  11834. let id = timeStampChars.join('');
  11835. if (!duplicateTime) {
  11836. for (i = 0; i < 12; i++) {
  11837. lastRandChars[i] = Math.floor(Math.random() * 64);
  11838. }
  11839. }
  11840. else {
  11841. // If the timestamp hasn't changed since last push, use the same random
  11842. // number, except incremented by 1.
  11843. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11844. lastRandChars[i] = 0;
  11845. }
  11846. lastRandChars[i]++;
  11847. }
  11848. for (i = 0; i < 12; i++) {
  11849. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11850. }
  11851. assert(id.length === 20, 'nextPushId: Length should be 20.');
  11852. return id;
  11853. };
  11854. })();
  11855. /**
  11856. * @license
  11857. * Copyright 2017 Google LLC
  11858. *
  11859. * Licensed under the Apache License, Version 2.0 (the "License");
  11860. * you may not use this file except in compliance with the License.
  11861. * You may obtain a copy of the License at
  11862. *
  11863. * http://www.apache.org/licenses/LICENSE-2.0
  11864. *
  11865. * Unless required by applicable law or agreed to in writing, software
  11866. * distributed under the License is distributed on an "AS IS" BASIS,
  11867. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11868. * See the License for the specific language governing permissions and
  11869. * limitations under the License.
  11870. */
  11871. /**
  11872. * Encapsulates the data needed to raise an event
  11873. */
  11874. class DataEvent {
  11875. /**
  11876. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11877. * @param eventRegistration - The function to call to with the event data. User provided
  11878. * @param snapshot - The data backing the event
  11879. * @param prevName - Optional, the name of the previous child for child_* events.
  11880. */
  11881. constructor(eventType, eventRegistration, snapshot, prevName) {
  11882. this.eventType = eventType;
  11883. this.eventRegistration = eventRegistration;
  11884. this.snapshot = snapshot;
  11885. this.prevName = prevName;
  11886. }
  11887. getPath() {
  11888. const ref = this.snapshot.ref;
  11889. if (this.eventType === 'value') {
  11890. return ref._path;
  11891. }
  11892. else {
  11893. return ref.parent._path;
  11894. }
  11895. }
  11896. getEventType() {
  11897. return this.eventType;
  11898. }
  11899. getEventRunner() {
  11900. return this.eventRegistration.getEventRunner(this);
  11901. }
  11902. toString() {
  11903. return (this.getPath().toString() +
  11904. ':' +
  11905. this.eventType +
  11906. ':' +
  11907. stringify(this.snapshot.exportVal()));
  11908. }
  11909. }
  11910. class CancelEvent {
  11911. constructor(eventRegistration, error, path) {
  11912. this.eventRegistration = eventRegistration;
  11913. this.error = error;
  11914. this.path = path;
  11915. }
  11916. getPath() {
  11917. return this.path;
  11918. }
  11919. getEventType() {
  11920. return 'cancel';
  11921. }
  11922. getEventRunner() {
  11923. return this.eventRegistration.getEventRunner(this);
  11924. }
  11925. toString() {
  11926. return this.path.toString() + ':cancel';
  11927. }
  11928. }
  11929. /**
  11930. * @license
  11931. * Copyright 2017 Google LLC
  11932. *
  11933. * Licensed under the Apache License, Version 2.0 (the "License");
  11934. * you may not use this file except in compliance with the License.
  11935. * You may obtain a copy of the License at
  11936. *
  11937. * http://www.apache.org/licenses/LICENSE-2.0
  11938. *
  11939. * Unless required by applicable law or agreed to in writing, software
  11940. * distributed under the License is distributed on an "AS IS" BASIS,
  11941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11942. * See the License for the specific language governing permissions and
  11943. * limitations under the License.
  11944. */
  11945. /**
  11946. * A wrapper class that converts events from the database@exp SDK to the legacy
  11947. * Database SDK. Events are not converted directly as event registration relies
  11948. * on reference comparison of the original user callback (see `matches()`) and
  11949. * relies on equality of the legacy SDK's `context` object.
  11950. */
  11951. class CallbackContext {
  11952. constructor(snapshotCallback, cancelCallback) {
  11953. this.snapshotCallback = snapshotCallback;
  11954. this.cancelCallback = cancelCallback;
  11955. }
  11956. onValue(expDataSnapshot, previousChildName) {
  11957. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11958. }
  11959. onCancel(error) {
  11960. assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11961. return this.cancelCallback.call(null, error);
  11962. }
  11963. get hasCancelCallback() {
  11964. return !!this.cancelCallback;
  11965. }
  11966. matches(other) {
  11967. return (this.snapshotCallback === other.snapshotCallback ||
  11968. (this.snapshotCallback.userCallback !== undefined &&
  11969. this.snapshotCallback.userCallback ===
  11970. other.snapshotCallback.userCallback &&
  11971. this.snapshotCallback.context === other.snapshotCallback.context));
  11972. }
  11973. }
  11974. /**
  11975. * @license
  11976. * Copyright 2021 Google LLC
  11977. *
  11978. * Licensed under the Apache License, Version 2.0 (the "License");
  11979. * you may not use this file except in compliance with the License.
  11980. * You may obtain a copy of the License at
  11981. *
  11982. * http://www.apache.org/licenses/LICENSE-2.0
  11983. *
  11984. * Unless required by applicable law or agreed to in writing, software
  11985. * distributed under the License is distributed on an "AS IS" BASIS,
  11986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11987. * See the License for the specific language governing permissions and
  11988. * limitations under the License.
  11989. */
  11990. /**
  11991. * The `onDisconnect` class allows you to write or clear data when your client
  11992. * disconnects from the Database server. These updates occur whether your
  11993. * client disconnects cleanly or not, so you can rely on them to clean up data
  11994. * even if a connection is dropped or a client crashes.
  11995. *
  11996. * The `onDisconnect` class is most commonly used to manage presence in
  11997. * applications where it is useful to detect how many clients are connected and
  11998. * when other clients disconnect. See
  11999. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12000. * for more information.
  12001. *
  12002. * To avoid problems when a connection is dropped before the requests can be
  12003. * transferred to the Database server, these functions should be called before
  12004. * writing any data.
  12005. *
  12006. * Note that `onDisconnect` operations are only triggered once. If you want an
  12007. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12008. * the `onDisconnect` operations each time you reconnect.
  12009. */
  12010. class OnDisconnect {
  12011. /** @hideconstructor */
  12012. constructor(_repo, _path) {
  12013. this._repo = _repo;
  12014. this._path = _path;
  12015. }
  12016. /**
  12017. * Cancels all previously queued `onDisconnect()` set or update events for this
  12018. * location and all children.
  12019. *
  12020. * If a write has been queued for this location via a `set()` or `update()` at a
  12021. * parent location, the write at this location will be canceled, though writes
  12022. * to sibling locations will still occur.
  12023. *
  12024. * @returns Resolves when synchronization to the server is complete.
  12025. */
  12026. cancel() {
  12027. const deferred = new Deferred();
  12028. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12029. return deferred.promise;
  12030. }
  12031. /**
  12032. * Ensures the data at this location is deleted when the client is disconnected
  12033. * (due to closing the browser, navigating to a new page, or network issues).
  12034. *
  12035. * @returns Resolves when synchronization to the server is complete.
  12036. */
  12037. remove() {
  12038. validateWritablePath('OnDisconnect.remove', this._path);
  12039. const deferred = new Deferred();
  12040. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12041. return deferred.promise;
  12042. }
  12043. /**
  12044. * Ensures the data at this location is set to the specified value when the
  12045. * client is disconnected (due to closing the browser, navigating to a new page,
  12046. * or network issues).
  12047. *
  12048. * `set()` is especially useful for implementing "presence" systems, where a
  12049. * value should be changed or cleared when a user disconnects so that they
  12050. * appear "offline" to other users. See
  12051. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12052. * for more information.
  12053. *
  12054. * Note that `onDisconnect` operations are only triggered once. If you want an
  12055. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12056. * the `onDisconnect` operations each time.
  12057. *
  12058. * @param value - The value to be written to this location on disconnect (can
  12059. * be an object, array, string, number, boolean, or null).
  12060. * @returns Resolves when synchronization to the Database is complete.
  12061. */
  12062. set(value) {
  12063. validateWritablePath('OnDisconnect.set', this._path);
  12064. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12065. const deferred = new Deferred();
  12066. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12067. return deferred.promise;
  12068. }
  12069. /**
  12070. * Ensures the data at this location is set to the specified value and priority
  12071. * when the client is disconnected (due to closing the browser, navigating to a
  12072. * new page, or network issues).
  12073. *
  12074. * @param value - The value to be written to this location on disconnect (can
  12075. * be an object, array, string, number, boolean, or null).
  12076. * @param priority - The priority to be written (string, number, or null).
  12077. * @returns Resolves when synchronization to the Database is complete.
  12078. */
  12079. setWithPriority(value, priority) {
  12080. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12081. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12082. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12083. const deferred = new Deferred();
  12084. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12085. return deferred.promise;
  12086. }
  12087. /**
  12088. * Writes multiple values at this location when the client is disconnected (due
  12089. * to closing the browser, navigating to a new page, or network issues).
  12090. *
  12091. * The `values` argument contains multiple property-value pairs that will be
  12092. * written to the Database together. Each child property can either be a simple
  12093. * property (for example, "name") or a relative path (for example, "name/first")
  12094. * from the current location to the data to update.
  12095. *
  12096. * As opposed to the `set()` method, `update()` can be use to selectively update
  12097. * only the referenced properties at the current location (instead of replacing
  12098. * all the child properties at the current location).
  12099. *
  12100. * @param values - Object containing multiple values.
  12101. * @returns Resolves when synchronization to the Database is complete.
  12102. */
  12103. update(values) {
  12104. validateWritablePath('OnDisconnect.update', this._path);
  12105. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12106. const deferred = new Deferred();
  12107. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12108. return deferred.promise;
  12109. }
  12110. }
  12111. /**
  12112. * @license
  12113. * Copyright 2020 Google LLC
  12114. *
  12115. * Licensed under the Apache License, Version 2.0 (the "License");
  12116. * you may not use this file except in compliance with the License.
  12117. * You may obtain a copy of the License at
  12118. *
  12119. * http://www.apache.org/licenses/LICENSE-2.0
  12120. *
  12121. * Unless required by applicable law or agreed to in writing, software
  12122. * distributed under the License is distributed on an "AS IS" BASIS,
  12123. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12124. * See the License for the specific language governing permissions and
  12125. * limitations under the License.
  12126. */
  12127. /**
  12128. * @internal
  12129. */
  12130. class QueryImpl {
  12131. /**
  12132. * @hideconstructor
  12133. */
  12134. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12135. this._repo = _repo;
  12136. this._path = _path;
  12137. this._queryParams = _queryParams;
  12138. this._orderByCalled = _orderByCalled;
  12139. }
  12140. get key() {
  12141. if (pathIsEmpty(this._path)) {
  12142. return null;
  12143. }
  12144. else {
  12145. return pathGetBack(this._path);
  12146. }
  12147. }
  12148. get ref() {
  12149. return new ReferenceImpl(this._repo, this._path);
  12150. }
  12151. get _queryIdentifier() {
  12152. const obj = queryParamsGetQueryObject(this._queryParams);
  12153. const id = ObjectToUniqueKey(obj);
  12154. return id === '{}' ? 'default' : id;
  12155. }
  12156. /**
  12157. * An object representation of the query parameters used by this Query.
  12158. */
  12159. get _queryObject() {
  12160. return queryParamsGetQueryObject(this._queryParams);
  12161. }
  12162. isEqual(other) {
  12163. other = getModularInstance(other);
  12164. if (!(other instanceof QueryImpl)) {
  12165. return false;
  12166. }
  12167. const sameRepo = this._repo === other._repo;
  12168. const samePath = pathEquals(this._path, other._path);
  12169. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12170. return sameRepo && samePath && sameQueryIdentifier;
  12171. }
  12172. toJSON() {
  12173. return this.toString();
  12174. }
  12175. toString() {
  12176. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12177. }
  12178. }
  12179. /**
  12180. * Validates that no other order by call has been made
  12181. */
  12182. function validateNoPreviousOrderByCall(query, fnName) {
  12183. if (query._orderByCalled === true) {
  12184. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12185. }
  12186. }
  12187. /**
  12188. * Validates start/end values for queries.
  12189. */
  12190. function validateQueryEndpoints(params) {
  12191. let startNode = null;
  12192. let endNode = null;
  12193. if (params.hasStart()) {
  12194. startNode = params.getIndexStartValue();
  12195. }
  12196. if (params.hasEnd()) {
  12197. endNode = params.getIndexEndValue();
  12198. }
  12199. if (params.getIndex() === KEY_INDEX) {
  12200. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12201. 'startAt(), endAt(), or equalTo().';
  12202. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12203. 'endAt(), endBefore(), or equalTo() must be a string.';
  12204. if (params.hasStart()) {
  12205. const startName = params.getIndexStartName();
  12206. if (startName !== MIN_NAME) {
  12207. throw new Error(tooManyArgsError);
  12208. }
  12209. else if (typeof startNode !== 'string') {
  12210. throw new Error(wrongArgTypeError);
  12211. }
  12212. }
  12213. if (params.hasEnd()) {
  12214. const endName = params.getIndexEndName();
  12215. if (endName !== MAX_NAME) {
  12216. throw new Error(tooManyArgsError);
  12217. }
  12218. else if (typeof endNode !== 'string') {
  12219. throw new Error(wrongArgTypeError);
  12220. }
  12221. }
  12222. }
  12223. else if (params.getIndex() === PRIORITY_INDEX) {
  12224. if ((startNode != null && !isValidPriority(startNode)) ||
  12225. (endNode != null && !isValidPriority(endNode))) {
  12226. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12227. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12228. '(null, a number, or a string).');
  12229. }
  12230. }
  12231. else {
  12232. assert(params.getIndex() instanceof PathIndex ||
  12233. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12234. if ((startNode != null && typeof startNode === 'object') ||
  12235. (endNode != null && typeof endNode === 'object')) {
  12236. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12237. 'equalTo() cannot be an object.');
  12238. }
  12239. }
  12240. }
  12241. /**
  12242. * Validates that limit* has been called with the correct combination of parameters
  12243. */
  12244. function validateLimit(params) {
  12245. if (params.hasStart() &&
  12246. params.hasEnd() &&
  12247. params.hasLimit() &&
  12248. !params.hasAnchoredLimit()) {
  12249. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12250. 'limitToFirst() or limitToLast() instead.');
  12251. }
  12252. }
  12253. /**
  12254. * @internal
  12255. */
  12256. class ReferenceImpl extends QueryImpl {
  12257. /** @hideconstructor */
  12258. constructor(repo, path) {
  12259. super(repo, path, new QueryParams(), false);
  12260. }
  12261. get parent() {
  12262. const parentPath = pathParent(this._path);
  12263. return parentPath === null
  12264. ? null
  12265. : new ReferenceImpl(this._repo, parentPath);
  12266. }
  12267. get root() {
  12268. let ref = this;
  12269. while (ref.parent !== null) {
  12270. ref = ref.parent;
  12271. }
  12272. return ref;
  12273. }
  12274. }
  12275. /**
  12276. * A `DataSnapshot` contains data from a Database location.
  12277. *
  12278. * Any time you read data from the Database, you receive the data as a
  12279. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12280. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12281. * JavaScript object by calling the `val()` method. Alternatively, you can
  12282. * traverse into the snapshot by calling `child()` to return child snapshots
  12283. * (which you could then call `val()` on).
  12284. *
  12285. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12286. * a Database location. It cannot be modified and will never change (to modify
  12287. * data, you always call the `set()` method on a `Reference` directly).
  12288. */
  12289. class DataSnapshot {
  12290. /**
  12291. * @param _node - A SnapshotNode to wrap.
  12292. * @param ref - The location this snapshot came from.
  12293. * @param _index - The iteration order for this snapshot
  12294. * @hideconstructor
  12295. */
  12296. constructor(_node,
  12297. /**
  12298. * The location of this DataSnapshot.
  12299. */
  12300. ref, _index) {
  12301. this._node = _node;
  12302. this.ref = ref;
  12303. this._index = _index;
  12304. }
  12305. /**
  12306. * Gets the priority value of the data in this `DataSnapshot`.
  12307. *
  12308. * Applications need not use priority but can order collections by
  12309. * ordinary properties (see
  12310. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12311. * ).
  12312. */
  12313. get priority() {
  12314. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12315. return this._node.getPriority().val();
  12316. }
  12317. /**
  12318. * The key (last part of the path) of the location of this `DataSnapshot`.
  12319. *
  12320. * The last token in a Database location is considered its key. For example,
  12321. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12322. * `DataSnapshot` will return the key for the location that generated it.
  12323. * However, accessing the key on the root URL of a Database will return
  12324. * `null`.
  12325. */
  12326. get key() {
  12327. return this.ref.key;
  12328. }
  12329. /** Returns the number of child properties of this `DataSnapshot`. */
  12330. get size() {
  12331. return this._node.numChildren();
  12332. }
  12333. /**
  12334. * Gets another `DataSnapshot` for the location at the specified relative path.
  12335. *
  12336. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12337. * another `DataSnapshot` for the location at the specified relative path. The
  12338. * relative path can either be a simple child name (for example, "ada") or a
  12339. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12340. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12341. * whose value is `null`) is returned.
  12342. *
  12343. * @param path - A relative path to the location of child data.
  12344. */
  12345. child(path) {
  12346. const childPath = new Path(path);
  12347. const childRef = child(this.ref, path);
  12348. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12349. }
  12350. /**
  12351. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12352. * efficient than using `snapshot.val() !== null`.
  12353. */
  12354. exists() {
  12355. return !this._node.isEmpty();
  12356. }
  12357. /**
  12358. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12359. *
  12360. * The `exportVal()` method is similar to `val()`, except priority information
  12361. * is included (if available), making it suitable for backing up your data.
  12362. *
  12363. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12364. * Array, string, number, boolean, or `null`).
  12365. */
  12366. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12367. exportVal() {
  12368. return this._node.val(true);
  12369. }
  12370. /**
  12371. * Enumerates the top-level children in the `IteratedDataSnapshot`.
  12372. *
  12373. * Because of the way JavaScript objects work, the ordering of data in the
  12374. * JavaScript object returned by `val()` is not guaranteed to match the
  12375. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12376. * where `forEach()` comes in handy. It guarantees the children of a
  12377. * `DataSnapshot` will be iterated in their query order.
  12378. *
  12379. * If no explicit `orderBy*()` method is used, results are returned
  12380. * ordered by key (unless priorities are used, in which case, results are
  12381. * returned by priority).
  12382. *
  12383. * @param action - A function that will be called for each child DataSnapshot.
  12384. * The callback can return true to cancel further enumeration.
  12385. * @returns true if enumeration was canceled due to your callback returning
  12386. * true.
  12387. */
  12388. forEach(action) {
  12389. if (this._node.isLeafNode()) {
  12390. return false;
  12391. }
  12392. const childrenNode = this._node;
  12393. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12394. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12395. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12396. });
  12397. }
  12398. /**
  12399. * Returns true if the specified child path has (non-null) data.
  12400. *
  12401. * @param path - A relative path to the location of a potential child.
  12402. * @returns `true` if data exists at the specified child path; else
  12403. * `false`.
  12404. */
  12405. hasChild(path) {
  12406. const childPath = new Path(path);
  12407. return !this._node.getChild(childPath).isEmpty();
  12408. }
  12409. /**
  12410. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12411. * properties.
  12412. *
  12413. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12414. * children. If it does, you can enumerate them using `forEach()`. If it
  12415. * doesn't, then either this snapshot contains a primitive value (which can be
  12416. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12417. * `null`).
  12418. *
  12419. * @returns true if this snapshot has any children; else false.
  12420. */
  12421. hasChildren() {
  12422. if (this._node.isLeafNode()) {
  12423. return false;
  12424. }
  12425. else {
  12426. return !this._node.isEmpty();
  12427. }
  12428. }
  12429. /**
  12430. * Returns a JSON-serializable representation of this object.
  12431. */
  12432. toJSON() {
  12433. return this.exportVal();
  12434. }
  12435. /**
  12436. * Extracts a JavaScript value from a `DataSnapshot`.
  12437. *
  12438. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12439. * scalar type (string, number, or boolean), an array, or an object. It may
  12440. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12441. * data).
  12442. *
  12443. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12444. * Array, string, number, boolean, or `null`).
  12445. */
  12446. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12447. val() {
  12448. return this._node.val();
  12449. }
  12450. }
  12451. /**
  12452. *
  12453. * Returns a `Reference` representing the location in the Database
  12454. * corresponding to the provided path. If no path is provided, the `Reference`
  12455. * will point to the root of the Database.
  12456. *
  12457. * @param db - The database instance to obtain a reference for.
  12458. * @param path - Optional path representing the location the returned
  12459. * `Reference` will point. If not provided, the returned `Reference` will
  12460. * point to the root of the Database.
  12461. * @returns If a path is provided, a `Reference`
  12462. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12463. * root of the Database.
  12464. */
  12465. function ref(db, path) {
  12466. db = getModularInstance(db);
  12467. db._checkNotDeleted('ref');
  12468. return path !== undefined ? child(db._root, path) : db._root;
  12469. }
  12470. /**
  12471. * Returns a `Reference` representing the location in the Database
  12472. * corresponding to the provided Firebase URL.
  12473. *
  12474. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12475. * has a different domain than the current `Database` instance.
  12476. *
  12477. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12478. * and are not applied to the returned `Reference`.
  12479. *
  12480. * @param db - The database instance to obtain a reference for.
  12481. * @param url - The Firebase URL at which the returned `Reference` will
  12482. * point.
  12483. * @returns A `Reference` pointing to the provided
  12484. * Firebase URL.
  12485. */
  12486. function refFromURL(db, url) {
  12487. db = getModularInstance(db);
  12488. db._checkNotDeleted('refFromURL');
  12489. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12490. validateUrl('refFromURL', parsedURL);
  12491. const repoInfo = parsedURL.repoInfo;
  12492. if (!db._repo.repoInfo_.isCustomHost() &&
  12493. repoInfo.host !== db._repo.repoInfo_.host) {
  12494. fatal('refFromURL' +
  12495. ': Host name does not match the current database: ' +
  12496. '(found ' +
  12497. repoInfo.host +
  12498. ' but expected ' +
  12499. db._repo.repoInfo_.host +
  12500. ')');
  12501. }
  12502. return ref(db, parsedURL.path.toString());
  12503. }
  12504. /**
  12505. * Gets a `Reference` for the location at the specified relative path.
  12506. *
  12507. * The relative path can either be a simple child name (for example, "ada") or
  12508. * a deeper slash-separated path (for example, "ada/name/first").
  12509. *
  12510. * @param parent - The parent location.
  12511. * @param path - A relative path from this location to the desired child
  12512. * location.
  12513. * @returns The specified child location.
  12514. */
  12515. function child(parent, path) {
  12516. parent = getModularInstance(parent);
  12517. if (pathGetFront(parent._path) === null) {
  12518. validateRootPathString('child', 'path', path, false);
  12519. }
  12520. else {
  12521. validatePathString('child', 'path', path, false);
  12522. }
  12523. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12524. }
  12525. /**
  12526. * Returns an `OnDisconnect` object - see
  12527. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12528. * for more information on how to use it.
  12529. *
  12530. * @param ref - The reference to add OnDisconnect triggers for.
  12531. */
  12532. function onDisconnect(ref) {
  12533. ref = getModularInstance(ref);
  12534. return new OnDisconnect(ref._repo, ref._path);
  12535. }
  12536. /**
  12537. * Generates a new child location using a unique key and returns its
  12538. * `Reference`.
  12539. *
  12540. * This is the most common pattern for adding data to a collection of items.
  12541. *
  12542. * If you provide a value to `push()`, the value is written to the
  12543. * generated location. If you don't pass a value, nothing is written to the
  12544. * database and the child remains empty (but you can use the `Reference`
  12545. * elsewhere).
  12546. *
  12547. * The unique keys generated by `push()` are ordered by the current time, so the
  12548. * resulting list of items is chronologically sorted. The keys are also
  12549. * designed to be unguessable (they contain 72 random bits of entropy).
  12550. *
  12551. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12552. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12553. *
  12554. * @param parent - The parent location.
  12555. * @param value - Optional value to be written at the generated location.
  12556. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12557. * but can be used immediately as the `Reference` to the child location.
  12558. */
  12559. function push(parent, value) {
  12560. parent = getModularInstance(parent);
  12561. validateWritablePath('push', parent._path);
  12562. validateFirebaseDataArg('push', value, parent._path, true);
  12563. const now = repoServerTime(parent._repo);
  12564. const name = nextPushId(now);
  12565. // push() returns a ThennableReference whose promise is fulfilled with a
  12566. // regular Reference. We use child() to create handles to two different
  12567. // references. The first is turned into a ThennableReference below by adding
  12568. // then() and catch() methods and is used as the return value of push(). The
  12569. // second remains a regular Reference and is used as the fulfilled value of
  12570. // the first ThennableReference.
  12571. const thenablePushRef = child(parent, name);
  12572. const pushRef = child(parent, name);
  12573. let promise;
  12574. if (value != null) {
  12575. promise = set(pushRef, value).then(() => pushRef);
  12576. }
  12577. else {
  12578. promise = Promise.resolve(pushRef);
  12579. }
  12580. thenablePushRef.then = promise.then.bind(promise);
  12581. thenablePushRef.catch = promise.then.bind(promise, undefined);
  12582. return thenablePushRef;
  12583. }
  12584. /**
  12585. * Removes the data at this Database location.
  12586. *
  12587. * Any data at child locations will also be deleted.
  12588. *
  12589. * The effect of the remove will be visible immediately and the corresponding
  12590. * event 'value' will be triggered. Synchronization of the remove to the
  12591. * Firebase servers will also be started, and the returned Promise will resolve
  12592. * when complete. If provided, the onComplete callback will be called
  12593. * asynchronously after synchronization has finished.
  12594. *
  12595. * @param ref - The location to remove.
  12596. * @returns Resolves when remove on server is complete.
  12597. */
  12598. function remove(ref) {
  12599. validateWritablePath('remove', ref._path);
  12600. return set(ref, null);
  12601. }
  12602. /**
  12603. * Writes data to this Database location.
  12604. *
  12605. * This will overwrite any data at this location and all child locations.
  12606. *
  12607. * The effect of the write will be visible immediately, and the corresponding
  12608. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12609. * the data to the Firebase servers will also be started, and the returned
  12610. * Promise will resolve when complete. If provided, the `onComplete` callback
  12611. * will be called asynchronously after synchronization has finished.
  12612. *
  12613. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12614. * all data at this location and all child locations will be deleted.
  12615. *
  12616. * `set()` will remove any priority stored at this location, so if priority is
  12617. * meant to be preserved, you need to use `setWithPriority()` instead.
  12618. *
  12619. * Note that modifying data with `set()` will cancel any pending transactions
  12620. * at that location, so extreme care should be taken if mixing `set()` and
  12621. * `transaction()` to modify the same data.
  12622. *
  12623. * A single `set()` will generate a single "value" event at the location where
  12624. * the `set()` was performed.
  12625. *
  12626. * @param ref - The location to write to.
  12627. * @param value - The value to be written (string, number, boolean, object,
  12628. * array, or null).
  12629. * @returns Resolves when write to server is complete.
  12630. */
  12631. function set(ref, value) {
  12632. ref = getModularInstance(ref);
  12633. validateWritablePath('set', ref._path);
  12634. validateFirebaseDataArg('set', value, ref._path, false);
  12635. const deferred = new Deferred();
  12636. repoSetWithPriority(ref._repo, ref._path, value,
  12637. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12638. return deferred.promise;
  12639. }
  12640. /**
  12641. * Sets a priority for the data at this Database location.
  12642. *
  12643. * Applications need not use priority but can order collections by
  12644. * ordinary properties (see
  12645. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12646. * ).
  12647. *
  12648. * @param ref - The location to write to.
  12649. * @param priority - The priority to be written (string, number, or null).
  12650. * @returns Resolves when write to server is complete.
  12651. */
  12652. function setPriority(ref, priority) {
  12653. ref = getModularInstance(ref);
  12654. validateWritablePath('setPriority', ref._path);
  12655. validatePriority('setPriority', priority, false);
  12656. const deferred = new Deferred();
  12657. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12658. return deferred.promise;
  12659. }
  12660. /**
  12661. * Writes data the Database location. Like `set()` but also specifies the
  12662. * priority for that data.
  12663. *
  12664. * Applications need not use priority but can order collections by
  12665. * ordinary properties (see
  12666. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12667. * ).
  12668. *
  12669. * @param ref - The location to write to.
  12670. * @param value - The value to be written (string, number, boolean, object,
  12671. * array, or null).
  12672. * @param priority - The priority to be written (string, number, or null).
  12673. * @returns Resolves when write to server is complete.
  12674. */
  12675. function setWithPriority(ref, value, priority) {
  12676. validateWritablePath('setWithPriority', ref._path);
  12677. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12678. validatePriority('setWithPriority', priority, false);
  12679. if (ref.key === '.length' || ref.key === '.keys') {
  12680. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12681. }
  12682. const deferred = new Deferred();
  12683. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12684. return deferred.promise;
  12685. }
  12686. /**
  12687. * Writes multiple values to the Database at once.
  12688. *
  12689. * The `values` argument contains multiple property-value pairs that will be
  12690. * written to the Database together. Each child property can either be a simple
  12691. * property (for example, "name") or a relative path (for example,
  12692. * "name/first") from the current location to the data to update.
  12693. *
  12694. * As opposed to the `set()` method, `update()` can be use to selectively update
  12695. * only the referenced properties at the current location (instead of replacing
  12696. * all the child properties at the current location).
  12697. *
  12698. * The effect of the write will be visible immediately, and the corresponding
  12699. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12700. * the data to the Firebase servers will also be started, and the returned
  12701. * Promise will resolve when complete. If provided, the `onComplete` callback
  12702. * will be called asynchronously after synchronization has finished.
  12703. *
  12704. * A single `update()` will generate a single "value" event at the location
  12705. * where the `update()` was performed, regardless of how many children were
  12706. * modified.
  12707. *
  12708. * Note that modifying data with `update()` will cancel any pending
  12709. * transactions at that location, so extreme care should be taken if mixing
  12710. * `update()` and `transaction()` to modify the same data.
  12711. *
  12712. * Passing `null` to `update()` will remove the data at this location.
  12713. *
  12714. * See
  12715. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12716. *
  12717. * @param ref - The location to write to.
  12718. * @param values - Object containing multiple values.
  12719. * @returns Resolves when update on server is complete.
  12720. */
  12721. function update(ref, values) {
  12722. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12723. const deferred = new Deferred();
  12724. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12725. return deferred.promise;
  12726. }
  12727. /**
  12728. * Gets the most up-to-date result for this query.
  12729. *
  12730. * @param query - The query to run.
  12731. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12732. * available, or rejects if the client is unable to return a value (e.g., if the
  12733. * server is unreachable and there is nothing cached).
  12734. */
  12735. function get(query) {
  12736. query = getModularInstance(query);
  12737. const callbackContext = new CallbackContext(() => { });
  12738. const container = new ValueEventRegistration(callbackContext);
  12739. return repoGetValue(query._repo, query, container).then(node => {
  12740. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12741. });
  12742. }
  12743. /**
  12744. * Represents registration for 'value' events.
  12745. */
  12746. class ValueEventRegistration {
  12747. constructor(callbackContext) {
  12748. this.callbackContext = callbackContext;
  12749. }
  12750. respondsTo(eventType) {
  12751. return eventType === 'value';
  12752. }
  12753. createEvent(change, query) {
  12754. const index = query._queryParams.getIndex();
  12755. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12756. }
  12757. getEventRunner(eventData) {
  12758. if (eventData.getEventType() === 'cancel') {
  12759. return () => this.callbackContext.onCancel(eventData.error);
  12760. }
  12761. else {
  12762. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12763. }
  12764. }
  12765. createCancelEvent(error, path) {
  12766. if (this.callbackContext.hasCancelCallback) {
  12767. return new CancelEvent(this, error, path);
  12768. }
  12769. else {
  12770. return null;
  12771. }
  12772. }
  12773. matches(other) {
  12774. if (!(other instanceof ValueEventRegistration)) {
  12775. return false;
  12776. }
  12777. else if (!other.callbackContext || !this.callbackContext) {
  12778. // If no callback specified, we consider it to match any callback.
  12779. return true;
  12780. }
  12781. else {
  12782. return other.callbackContext.matches(this.callbackContext);
  12783. }
  12784. }
  12785. hasAnyCallback() {
  12786. return this.callbackContext !== null;
  12787. }
  12788. }
  12789. /**
  12790. * Represents the registration of a child_x event.
  12791. */
  12792. class ChildEventRegistration {
  12793. constructor(eventType, callbackContext) {
  12794. this.eventType = eventType;
  12795. this.callbackContext = callbackContext;
  12796. }
  12797. respondsTo(eventType) {
  12798. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12799. eventToCheck =
  12800. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12801. return this.eventType === eventToCheck;
  12802. }
  12803. createCancelEvent(error, path) {
  12804. if (this.callbackContext.hasCancelCallback) {
  12805. return new CancelEvent(this, error, path);
  12806. }
  12807. else {
  12808. return null;
  12809. }
  12810. }
  12811. createEvent(change, query) {
  12812. assert(change.childName != null, 'Child events should have a childName.');
  12813. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12814. const index = query._queryParams.getIndex();
  12815. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12816. }
  12817. getEventRunner(eventData) {
  12818. if (eventData.getEventType() === 'cancel') {
  12819. return () => this.callbackContext.onCancel(eventData.error);
  12820. }
  12821. else {
  12822. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12823. }
  12824. }
  12825. matches(other) {
  12826. if (other instanceof ChildEventRegistration) {
  12827. return (this.eventType === other.eventType &&
  12828. (!this.callbackContext ||
  12829. !other.callbackContext ||
  12830. this.callbackContext.matches(other.callbackContext)));
  12831. }
  12832. return false;
  12833. }
  12834. hasAnyCallback() {
  12835. return !!this.callbackContext;
  12836. }
  12837. }
  12838. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12839. let cancelCallback;
  12840. if (typeof cancelCallbackOrListenOptions === 'object') {
  12841. cancelCallback = undefined;
  12842. options = cancelCallbackOrListenOptions;
  12843. }
  12844. if (typeof cancelCallbackOrListenOptions === 'function') {
  12845. cancelCallback = cancelCallbackOrListenOptions;
  12846. }
  12847. if (options && options.onlyOnce) {
  12848. const userCallback = callback;
  12849. const onceCallback = (dataSnapshot, previousChildName) => {
  12850. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12851. userCallback(dataSnapshot, previousChildName);
  12852. };
  12853. onceCallback.userCallback = callback.userCallback;
  12854. onceCallback.context = callback.context;
  12855. callback = onceCallback;
  12856. }
  12857. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12858. const container = eventType === 'value'
  12859. ? new ValueEventRegistration(callbackContext)
  12860. : new ChildEventRegistration(eventType, callbackContext);
  12861. repoAddEventCallbackForQuery(query._repo, query, container);
  12862. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12863. }
  12864. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12865. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12866. }
  12867. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12868. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12869. }
  12870. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12871. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12872. }
  12873. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12874. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12875. }
  12876. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12877. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12878. }
  12879. /**
  12880. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12881. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12882. * the respective `on*` callbacks.
  12883. *
  12884. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12885. * will not automatically remove listeners registered on child nodes, `off()`
  12886. * must also be called on any child listeners to remove the callback.
  12887. *
  12888. * If a callback is not specified, all callbacks for the specified eventType
  12889. * will be removed. Similarly, if no eventType is specified, all callbacks
  12890. * for the `Reference` will be removed.
  12891. *
  12892. * Individual listeners can also be removed by invoking their unsubscribe
  12893. * callbacks.
  12894. *
  12895. * @param query - The query that the listener was registered with.
  12896. * @param eventType - One of the following strings: "value", "child_added",
  12897. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12898. * for the `Reference` will be removed.
  12899. * @param callback - The callback function that was passed to `on()` or
  12900. * `undefined` to remove all callbacks.
  12901. */
  12902. function off(query, eventType, callback) {
  12903. let container = null;
  12904. const expCallback = callback ? new CallbackContext(callback) : null;
  12905. if (eventType === 'value') {
  12906. container = new ValueEventRegistration(expCallback);
  12907. }
  12908. else if (eventType) {
  12909. container = new ChildEventRegistration(eventType, expCallback);
  12910. }
  12911. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12912. }
  12913. /**
  12914. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12915. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12916. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12917. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12918. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12919. * {@link orderByValue} or {@link equalTo} and
  12920. * can then be passed to {@link query} to create a new query instance that
  12921. * also contains this `QueryConstraint`.
  12922. */
  12923. class QueryConstraint {
  12924. }
  12925. class QueryEndAtConstraint extends QueryConstraint {
  12926. constructor(_value, _key) {
  12927. super();
  12928. this._value = _value;
  12929. this._key = _key;
  12930. this.type = 'endAt';
  12931. }
  12932. _apply(query) {
  12933. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12934. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12935. validateLimit(newParams);
  12936. validateQueryEndpoints(newParams);
  12937. if (query._queryParams.hasEnd()) {
  12938. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12939. 'endBefore or equalTo).');
  12940. }
  12941. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12942. }
  12943. }
  12944. /**
  12945. * Creates a `QueryConstraint` with the specified ending point.
  12946. *
  12947. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12948. * allows you to choose arbitrary starting and ending points for your queries.
  12949. *
  12950. * The ending point is inclusive, so children with exactly the specified value
  12951. * will be included in the query. The optional key argument can be used to
  12952. * further limit the range of the query. If it is specified, then children that
  12953. * have exactly the specified value must also have a key name less than or equal
  12954. * to the specified key.
  12955. *
  12956. * You can read more about `endAt()` in
  12957. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12958. *
  12959. * @param value - The value to end at. The argument type depends on which
  12960. * `orderBy*()` function was used in this query. Specify a value that matches
  12961. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12962. * value must be a string.
  12963. * @param key - The child key to end at, among the children with the previously
  12964. * specified priority. This argument is only allowed if ordering by child,
  12965. * value, or priority.
  12966. */
  12967. function endAt(value, key) {
  12968. validateKey('endAt', 'key', key, true);
  12969. return new QueryEndAtConstraint(value, key);
  12970. }
  12971. class QueryEndBeforeConstraint extends QueryConstraint {
  12972. constructor(_value, _key) {
  12973. super();
  12974. this._value = _value;
  12975. this._key = _key;
  12976. this.type = 'endBefore';
  12977. }
  12978. _apply(query) {
  12979. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12980. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12981. validateLimit(newParams);
  12982. validateQueryEndpoints(newParams);
  12983. if (query._queryParams.hasEnd()) {
  12984. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12985. 'endBefore or equalTo).');
  12986. }
  12987. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12988. }
  12989. }
  12990. /**
  12991. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  12992. *
  12993. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12994. * allows you to choose arbitrary starting and ending points for your queries.
  12995. *
  12996. * The ending point is exclusive. If only a value is provided, children
  12997. * with a value less than the specified value will be included in the query.
  12998. * If a key is specified, then children must have a value less than or equal
  12999. * to the specified value and a key name less than the specified key.
  13000. *
  13001. * @param value - The value to end before. The argument type depends on which
  13002. * `orderBy*()` function was used in this query. Specify a value that matches
  13003. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13004. * value must be a string.
  13005. * @param key - The child key to end before, among the children with the
  13006. * previously specified priority. This argument is only allowed if ordering by
  13007. * child, value, or priority.
  13008. */
  13009. function endBefore(value, key) {
  13010. validateKey('endBefore', 'key', key, true);
  13011. return new QueryEndBeforeConstraint(value, key);
  13012. }
  13013. class QueryStartAtConstraint extends QueryConstraint {
  13014. constructor(_value, _key) {
  13015. super();
  13016. this._value = _value;
  13017. this._key = _key;
  13018. this.type = 'startAt';
  13019. }
  13020. _apply(query) {
  13021. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13022. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13023. validateLimit(newParams);
  13024. validateQueryEndpoints(newParams);
  13025. if (query._queryParams.hasStart()) {
  13026. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13027. 'startBefore or equalTo).');
  13028. }
  13029. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13030. }
  13031. }
  13032. /**
  13033. * Creates a `QueryConstraint` with the specified starting point.
  13034. *
  13035. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13036. * allows you to choose arbitrary starting and ending points for your queries.
  13037. *
  13038. * The starting point is inclusive, so children with exactly the specified value
  13039. * will be included in the query. The optional key argument can be used to
  13040. * further limit the range of the query. If it is specified, then children that
  13041. * have exactly the specified value must also have a key name greater than or
  13042. * equal to the specified key.
  13043. *
  13044. * You can read more about `startAt()` in
  13045. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13046. *
  13047. * @param value - The value to start at. The argument type depends on which
  13048. * `orderBy*()` function was used in this query. Specify a value that matches
  13049. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13050. * value must be a string.
  13051. * @param key - The child key to start at. This argument is only allowed if
  13052. * ordering by child, value, or priority.
  13053. */
  13054. function startAt(value = null, key) {
  13055. validateKey('startAt', 'key', key, true);
  13056. return new QueryStartAtConstraint(value, key);
  13057. }
  13058. class QueryStartAfterConstraint extends QueryConstraint {
  13059. constructor(_value, _key) {
  13060. super();
  13061. this._value = _value;
  13062. this._key = _key;
  13063. this.type = 'startAfter';
  13064. }
  13065. _apply(query) {
  13066. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13067. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13068. validateLimit(newParams);
  13069. validateQueryEndpoints(newParams);
  13070. if (query._queryParams.hasStart()) {
  13071. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13072. 'startAfter, or equalTo).');
  13073. }
  13074. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13075. }
  13076. }
  13077. /**
  13078. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13079. *
  13080. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13081. * allows you to choose arbitrary starting and ending points for your queries.
  13082. *
  13083. * The starting point is exclusive. If only a value is provided, children
  13084. * with a value greater than the specified value will be included in the query.
  13085. * If a key is specified, then children must have a value greater than or equal
  13086. * to the specified value and a a key name greater than the specified key.
  13087. *
  13088. * @param value - The value to start after. The argument type depends on which
  13089. * `orderBy*()` function was used in this query. Specify a value that matches
  13090. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13091. * value must be a string.
  13092. * @param key - The child key to start after. This argument is only allowed if
  13093. * ordering by child, value, or priority.
  13094. */
  13095. function startAfter(value, key) {
  13096. validateKey('startAfter', 'key', key, true);
  13097. return new QueryStartAfterConstraint(value, key);
  13098. }
  13099. class QueryLimitToFirstConstraint extends QueryConstraint {
  13100. constructor(_limit) {
  13101. super();
  13102. this._limit = _limit;
  13103. this.type = 'limitToFirst';
  13104. }
  13105. _apply(query) {
  13106. if (query._queryParams.hasLimit()) {
  13107. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13108. 'or limitToLast).');
  13109. }
  13110. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13111. }
  13112. }
  13113. /**
  13114. * Creates a new `QueryConstraint` that if limited to the first specific number
  13115. * of children.
  13116. *
  13117. * The `limitToFirst()` method is used to set a maximum number of children to be
  13118. * synced for a given callback. If we set a limit of 100, we will initially only
  13119. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13120. * stored in our Database, a `child_added` event will fire for each message.
  13121. * However, if we have over 100 messages, we will only receive a `child_added`
  13122. * event for the first 100 ordered messages. As items change, we will receive
  13123. * `child_removed` events for each item that drops out of the active list so
  13124. * that the total number stays at 100.
  13125. *
  13126. * You can read more about `limitToFirst()` in
  13127. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13128. *
  13129. * @param limit - The maximum number of nodes to include in this query.
  13130. */
  13131. function limitToFirst(limit) {
  13132. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13133. throw new Error('limitToFirst: First argument must be a positive integer.');
  13134. }
  13135. return new QueryLimitToFirstConstraint(limit);
  13136. }
  13137. class QueryLimitToLastConstraint extends QueryConstraint {
  13138. constructor(_limit) {
  13139. super();
  13140. this._limit = _limit;
  13141. this.type = 'limitToLast';
  13142. }
  13143. _apply(query) {
  13144. if (query._queryParams.hasLimit()) {
  13145. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13146. 'or limitToLast).');
  13147. }
  13148. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13149. }
  13150. }
  13151. /**
  13152. * Creates a new `QueryConstraint` that is limited to return only the last
  13153. * specified number of children.
  13154. *
  13155. * The `limitToLast()` method is used to set a maximum number of children to be
  13156. * synced for a given callback. If we set a limit of 100, we will initially only
  13157. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13158. * stored in our Database, a `child_added` event will fire for each message.
  13159. * However, if we have over 100 messages, we will only receive a `child_added`
  13160. * event for the last 100 ordered messages. As items change, we will receive
  13161. * `child_removed` events for each item that drops out of the active list so
  13162. * that the total number stays at 100.
  13163. *
  13164. * You can read more about `limitToLast()` in
  13165. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13166. *
  13167. * @param limit - The maximum number of nodes to include in this query.
  13168. */
  13169. function limitToLast(limit) {
  13170. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13171. throw new Error('limitToLast: First argument must be a positive integer.');
  13172. }
  13173. return new QueryLimitToLastConstraint(limit);
  13174. }
  13175. class QueryOrderByChildConstraint extends QueryConstraint {
  13176. constructor(_path) {
  13177. super();
  13178. this._path = _path;
  13179. this.type = 'orderByChild';
  13180. }
  13181. _apply(query) {
  13182. validateNoPreviousOrderByCall(query, 'orderByChild');
  13183. const parsedPath = new Path(this._path);
  13184. if (pathIsEmpty(parsedPath)) {
  13185. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13186. }
  13187. const index = new PathIndex(parsedPath);
  13188. const newParams = queryParamsOrderBy(query._queryParams, index);
  13189. validateQueryEndpoints(newParams);
  13190. return new QueryImpl(query._repo, query._path, newParams,
  13191. /*orderByCalled=*/ true);
  13192. }
  13193. }
  13194. /**
  13195. * Creates a new `QueryConstraint` that orders by the specified child key.
  13196. *
  13197. * Queries can only order by one key at a time. Calling `orderByChild()`
  13198. * multiple times on the same query is an error.
  13199. *
  13200. * Firebase queries allow you to order your data by any child key on the fly.
  13201. * However, if you know in advance what your indexes will be, you can define
  13202. * them via the .indexOn rule in your Security Rules for better performance. See
  13203. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13204. * rule for more information.
  13205. *
  13206. * You can read more about `orderByChild()` in
  13207. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13208. *
  13209. * @param path - The path to order by.
  13210. */
  13211. function orderByChild(path) {
  13212. if (path === '$key') {
  13213. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13214. }
  13215. else if (path === '$priority') {
  13216. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13217. }
  13218. else if (path === '$value') {
  13219. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13220. }
  13221. validatePathString('orderByChild', 'path', path, false);
  13222. return new QueryOrderByChildConstraint(path);
  13223. }
  13224. class QueryOrderByKeyConstraint extends QueryConstraint {
  13225. constructor() {
  13226. super(...arguments);
  13227. this.type = 'orderByKey';
  13228. }
  13229. _apply(query) {
  13230. validateNoPreviousOrderByCall(query, 'orderByKey');
  13231. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13232. validateQueryEndpoints(newParams);
  13233. return new QueryImpl(query._repo, query._path, newParams,
  13234. /*orderByCalled=*/ true);
  13235. }
  13236. }
  13237. /**
  13238. * Creates a new `QueryConstraint` that orders by the key.
  13239. *
  13240. * Sorts the results of a query by their (ascending) key values.
  13241. *
  13242. * You can read more about `orderByKey()` in
  13243. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13244. */
  13245. function orderByKey() {
  13246. return new QueryOrderByKeyConstraint();
  13247. }
  13248. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13249. constructor() {
  13250. super(...arguments);
  13251. this.type = 'orderByPriority';
  13252. }
  13253. _apply(query) {
  13254. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13255. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13256. validateQueryEndpoints(newParams);
  13257. return new QueryImpl(query._repo, query._path, newParams,
  13258. /*orderByCalled=*/ true);
  13259. }
  13260. }
  13261. /**
  13262. * Creates a new `QueryConstraint` that orders by priority.
  13263. *
  13264. * Applications need not use priority but can order collections by
  13265. * ordinary properties (see
  13266. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13267. * for alternatives to priority.
  13268. */
  13269. function orderByPriority() {
  13270. return new QueryOrderByPriorityConstraint();
  13271. }
  13272. class QueryOrderByValueConstraint extends QueryConstraint {
  13273. constructor() {
  13274. super(...arguments);
  13275. this.type = 'orderByValue';
  13276. }
  13277. _apply(query) {
  13278. validateNoPreviousOrderByCall(query, 'orderByValue');
  13279. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13280. validateQueryEndpoints(newParams);
  13281. return new QueryImpl(query._repo, query._path, newParams,
  13282. /*orderByCalled=*/ true);
  13283. }
  13284. }
  13285. /**
  13286. * Creates a new `QueryConstraint` that orders by value.
  13287. *
  13288. * If the children of a query are all scalar values (string, number, or
  13289. * boolean), you can order the results by their (ascending) values.
  13290. *
  13291. * You can read more about `orderByValue()` in
  13292. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13293. */
  13294. function orderByValue() {
  13295. return new QueryOrderByValueConstraint();
  13296. }
  13297. class QueryEqualToValueConstraint extends QueryConstraint {
  13298. constructor(_value, _key) {
  13299. super();
  13300. this._value = _value;
  13301. this._key = _key;
  13302. this.type = 'equalTo';
  13303. }
  13304. _apply(query) {
  13305. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13306. if (query._queryParams.hasStart()) {
  13307. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13308. 'equalTo).');
  13309. }
  13310. if (query._queryParams.hasEnd()) {
  13311. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13312. 'equalTo).');
  13313. }
  13314. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13315. }
  13316. }
  13317. /**
  13318. * Creates a `QueryConstraint` that includes children that match the specified
  13319. * value.
  13320. *
  13321. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13322. * allows you to choose arbitrary starting and ending points for your queries.
  13323. *
  13324. * The optional key argument can be used to further limit the range of the
  13325. * query. If it is specified, then children that have exactly the specified
  13326. * value must also have exactly the specified key as their key name. This can be
  13327. * used to filter result sets with many matches for the same value.
  13328. *
  13329. * You can read more about `equalTo()` in
  13330. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13331. *
  13332. * @param value - The value to match for. The argument type depends on which
  13333. * `orderBy*()` function was used in this query. Specify a value that matches
  13334. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13335. * value must be a string.
  13336. * @param key - The child key to start at, among the children with the
  13337. * previously specified priority. This argument is only allowed if ordering by
  13338. * child, value, or priority.
  13339. */
  13340. function equalTo(value, key) {
  13341. validateKey('equalTo', 'key', key, true);
  13342. return new QueryEqualToValueConstraint(value, key);
  13343. }
  13344. /**
  13345. * Creates a new immutable instance of `Query` that is extended to also include
  13346. * additional query constraints.
  13347. *
  13348. * @param query - The Query instance to use as a base for the new constraints.
  13349. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13350. * @throws if any of the provided query constraints cannot be combined with the
  13351. * existing or new constraints.
  13352. */
  13353. function query(query, ...queryConstraints) {
  13354. let queryImpl = getModularInstance(query);
  13355. for (const constraint of queryConstraints) {
  13356. queryImpl = constraint._apply(queryImpl);
  13357. }
  13358. return queryImpl;
  13359. }
  13360. /**
  13361. * Define reference constructor in various modules
  13362. *
  13363. * We are doing this here to avoid several circular
  13364. * dependency issues
  13365. */
  13366. syncPointSetReferenceConstructor(ReferenceImpl);
  13367. syncTreeSetReferenceConstructor(ReferenceImpl);
  13368. /**
  13369. * @license
  13370. * Copyright 2020 Google LLC
  13371. *
  13372. * Licensed under the Apache License, Version 2.0 (the "License");
  13373. * you may not use this file except in compliance with the License.
  13374. * You may obtain a copy of the License at
  13375. *
  13376. * http://www.apache.org/licenses/LICENSE-2.0
  13377. *
  13378. * Unless required by applicable law or agreed to in writing, software
  13379. * distributed under the License is distributed on an "AS IS" BASIS,
  13380. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13381. * See the License for the specific language governing permissions and
  13382. * limitations under the License.
  13383. */
  13384. /**
  13385. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13386. * modifying this definition, consult the definition in:
  13387. *
  13388. * https://github.com/firebase/firebase-admin-node
  13389. *
  13390. * and make sure the two are consistent.
  13391. */
  13392. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13393. /**
  13394. * Creates and caches `Repo` instances.
  13395. */
  13396. const repos = {};
  13397. /**
  13398. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13399. */
  13400. let useRestClient = false;
  13401. /**
  13402. * Update an existing `Repo` in place to point to a new host/port.
  13403. */
  13404. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13405. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13406. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13407. /*isUsingEmulator=*/ true);
  13408. if (tokenProvider) {
  13409. repo.authTokenProvider_ = tokenProvider;
  13410. }
  13411. }
  13412. /**
  13413. * This function should only ever be called to CREATE a new database instance.
  13414. * @internal
  13415. */
  13416. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13417. let dbUrl = url || app.options.databaseURL;
  13418. if (dbUrl === undefined) {
  13419. if (!app.options.projectId) {
  13420. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13421. ' a Project ID when calling firebase.initializeApp().');
  13422. }
  13423. log('Using default host for project ', app.options.projectId);
  13424. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13425. }
  13426. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13427. let repoInfo = parsedUrl.repoInfo;
  13428. let isEmulator;
  13429. let dbEmulatorHost = undefined;
  13430. if (typeof process !== 'undefined' && process.env) {
  13431. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13432. }
  13433. if (dbEmulatorHost) {
  13434. isEmulator = true;
  13435. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13436. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13437. repoInfo = parsedUrl.repoInfo;
  13438. }
  13439. else {
  13440. isEmulator = !parsedUrl.repoInfo.secure;
  13441. }
  13442. const authTokenProvider = nodeAdmin && isEmulator
  13443. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13444. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13445. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13446. if (!pathIsEmpty(parsedUrl.path)) {
  13447. fatal('Database URL must point to the root of a Firebase Database ' +
  13448. '(not including a child path).');
  13449. }
  13450. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13451. return new Database(repo, app);
  13452. }
  13453. /**
  13454. * Remove the repo and make sure it is disconnected.
  13455. *
  13456. */
  13457. function repoManagerDeleteRepo(repo, appName) {
  13458. const appRepos = repos[appName];
  13459. // This should never happen...
  13460. if (!appRepos || appRepos[repo.key] !== repo) {
  13461. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13462. }
  13463. repoInterrupt(repo);
  13464. delete appRepos[repo.key];
  13465. }
  13466. /**
  13467. * Ensures a repo doesn't already exist and then creates one using the
  13468. * provided app.
  13469. *
  13470. * @param repoInfo - The metadata about the Repo
  13471. * @returns The Repo object for the specified server / repoName.
  13472. */
  13473. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13474. let appRepos = repos[app.name];
  13475. if (!appRepos) {
  13476. appRepos = {};
  13477. repos[app.name] = appRepos;
  13478. }
  13479. let repo = appRepos[repoInfo.toURLString()];
  13480. if (repo) {
  13481. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13482. }
  13483. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13484. appRepos[repoInfo.toURLString()] = repo;
  13485. return repo;
  13486. }
  13487. /**
  13488. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13489. */
  13490. function repoManagerForceRestClient(forceRestClient) {
  13491. useRestClient = forceRestClient;
  13492. }
  13493. /**
  13494. * Class representing a Firebase Realtime Database.
  13495. */
  13496. class Database {
  13497. /** @hideconstructor */
  13498. constructor(_repoInternal,
  13499. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13500. app) {
  13501. this._repoInternal = _repoInternal;
  13502. this.app = app;
  13503. /** Represents a `Database` instance. */
  13504. this['type'] = 'database';
  13505. /** Track if the instance has been used (root or repo accessed) */
  13506. this._instanceStarted = false;
  13507. }
  13508. get _repo() {
  13509. if (!this._instanceStarted) {
  13510. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13511. this._instanceStarted = true;
  13512. }
  13513. return this._repoInternal;
  13514. }
  13515. get _root() {
  13516. if (!this._rootInternal) {
  13517. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13518. }
  13519. return this._rootInternal;
  13520. }
  13521. _delete() {
  13522. if (this._rootInternal !== null) {
  13523. repoManagerDeleteRepo(this._repo, this.app.name);
  13524. this._repoInternal = null;
  13525. this._rootInternal = null;
  13526. }
  13527. return Promise.resolve();
  13528. }
  13529. _checkNotDeleted(apiName) {
  13530. if (this._rootInternal === null) {
  13531. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13532. }
  13533. }
  13534. }
  13535. function checkTransportInit() {
  13536. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13537. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13538. }
  13539. }
  13540. /**
  13541. * Force the use of websockets instead of longPolling.
  13542. */
  13543. function forceWebSockets() {
  13544. checkTransportInit();
  13545. BrowserPollConnection.forceDisallow();
  13546. }
  13547. /**
  13548. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13549. */
  13550. function forceLongPolling() {
  13551. checkTransportInit();
  13552. WebSocketConnection.forceDisallow();
  13553. BrowserPollConnection.forceAllow();
  13554. }
  13555. /**
  13556. * Returns the instance of the Realtime Database SDK that is associated with the provided
  13557. * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if
  13558. * no instance exists or if the existing instance uses a custom database URL.
  13559. *
  13560. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  13561. * Database instance is associated with.
  13562. * @param url - The URL of the Realtime Database instance to connect to. If not
  13563. * provided, the SDK connects to the default instance of the Firebase App.
  13564. * @returns The `Database` instance of the provided app.
  13565. */
  13566. function getDatabase(app = getApp(), url) {
  13567. const db = _getProvider(app, 'database').getImmediate({
  13568. identifier: url
  13569. });
  13570. if (!db._instanceStarted) {
  13571. const emulator = getDefaultEmulatorHostnameAndPort('database');
  13572. if (emulator) {
  13573. connectDatabaseEmulator(db, ...emulator);
  13574. }
  13575. }
  13576. return db;
  13577. }
  13578. /**
  13579. * Modify the provided instance to communicate with the Realtime Database
  13580. * emulator.
  13581. *
  13582. * <p>Note: This method must be called before performing any other operation.
  13583. *
  13584. * @param db - The instance to modify.
  13585. * @param host - The emulator host (ex: localhost)
  13586. * @param port - The emulator port (ex: 8080)
  13587. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13588. */
  13589. function connectDatabaseEmulator(db, host, port, options = {}) {
  13590. db = getModularInstance(db);
  13591. db._checkNotDeleted('useEmulator');
  13592. if (db._instanceStarted) {
  13593. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13594. }
  13595. const repo = db._repoInternal;
  13596. let tokenProvider = undefined;
  13597. if (repo.repoInfo_.nodeAdmin) {
  13598. if (options.mockUserToken) {
  13599. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13600. }
  13601. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13602. }
  13603. else if (options.mockUserToken) {
  13604. const token = typeof options.mockUserToken === 'string'
  13605. ? options.mockUserToken
  13606. : createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13607. tokenProvider = new EmulatorTokenProvider(token);
  13608. }
  13609. // Modify the repo to apply emulator settings
  13610. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13611. }
  13612. /**
  13613. * Disconnects from the server (all Database operations will be completed
  13614. * offline).
  13615. *
  13616. * The client automatically maintains a persistent connection to the Database
  13617. * server, which will remain active indefinitely and reconnect when
  13618. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13619. * to control the client connection in cases where a persistent connection is
  13620. * undesirable.
  13621. *
  13622. * While offline, the client will no longer receive data updates from the
  13623. * Database. However, all Database operations performed locally will continue to
  13624. * immediately fire events, allowing your application to continue behaving
  13625. * normally. Additionally, each operation performed locally will automatically
  13626. * be queued and retried upon reconnection to the Database server.
  13627. *
  13628. * To reconnect to the Database and begin receiving remote events, see
  13629. * `goOnline()`.
  13630. *
  13631. * @param db - The instance to disconnect.
  13632. */
  13633. function goOffline(db) {
  13634. db = getModularInstance(db);
  13635. db._checkNotDeleted('goOffline');
  13636. repoInterrupt(db._repo);
  13637. }
  13638. /**
  13639. * Reconnects to the server and synchronizes the offline Database state
  13640. * with the server state.
  13641. *
  13642. * This method should be used after disabling the active connection with
  13643. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13644. * and fire the appropriate events so that your client "catches up"
  13645. * automatically.
  13646. *
  13647. * @param db - The instance to reconnect.
  13648. */
  13649. function goOnline(db) {
  13650. db = getModularInstance(db);
  13651. db._checkNotDeleted('goOnline');
  13652. repoResume(db._repo);
  13653. }
  13654. function enableLogging(logger, persistent) {
  13655. enableLogging$1(logger, persistent);
  13656. }
  13657. /**
  13658. * @license
  13659. * Copyright 2021 Google LLC
  13660. *
  13661. * Licensed under the Apache License, Version 2.0 (the "License");
  13662. * you may not use this file except in compliance with the License.
  13663. * You may obtain a copy of the License at
  13664. *
  13665. * http://www.apache.org/licenses/LICENSE-2.0
  13666. *
  13667. * Unless required by applicable law or agreed to in writing, software
  13668. * distributed under the License is distributed on an "AS IS" BASIS,
  13669. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13670. * See the License for the specific language governing permissions and
  13671. * limitations under the License.
  13672. */
  13673. function registerDatabase(variant) {
  13674. setSDKVersion(SDK_VERSION$1);
  13675. _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {
  13676. const app = container.getProvider('app').getImmediate();
  13677. const authProvider = container.getProvider('auth-internal');
  13678. const appCheckProvider = container.getProvider('app-check-internal');
  13679. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  13680. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  13681. registerVersion(name, version, variant);
  13682. // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
  13683. registerVersion(name, version, 'esm2017');
  13684. }
  13685. /**
  13686. * @license
  13687. * Copyright 2020 Google LLC
  13688. *
  13689. * Licensed under the Apache License, Version 2.0 (the "License");
  13690. * you may not use this file except in compliance with the License.
  13691. * You may obtain a copy of the License at
  13692. *
  13693. * http://www.apache.org/licenses/LICENSE-2.0
  13694. *
  13695. * Unless required by applicable law or agreed to in writing, software
  13696. * distributed under the License is distributed on an "AS IS" BASIS,
  13697. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13698. * See the License for the specific language governing permissions and
  13699. * limitations under the License.
  13700. */
  13701. const SERVER_TIMESTAMP = {
  13702. '.sv': 'timestamp'
  13703. };
  13704. /**
  13705. * Returns a placeholder value for auto-populating the current timestamp (time
  13706. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13707. * servers.
  13708. */
  13709. function serverTimestamp() {
  13710. return SERVER_TIMESTAMP;
  13711. }
  13712. /**
  13713. * Returns a placeholder value that can be used to atomically increment the
  13714. * current database value by the provided delta.
  13715. *
  13716. * @param delta - the amount to modify the current value atomically.
  13717. * @returns A placeholder value for modifying data atomically server-side.
  13718. */
  13719. function increment(delta) {
  13720. return {
  13721. '.sv': {
  13722. 'increment': delta
  13723. }
  13724. };
  13725. }
  13726. /**
  13727. * @license
  13728. * Copyright 2020 Google LLC
  13729. *
  13730. * Licensed under the Apache License, Version 2.0 (the "License");
  13731. * you may not use this file except in compliance with the License.
  13732. * You may obtain a copy of the License at
  13733. *
  13734. * http://www.apache.org/licenses/LICENSE-2.0
  13735. *
  13736. * Unless required by applicable law or agreed to in writing, software
  13737. * distributed under the License is distributed on an "AS IS" BASIS,
  13738. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13739. * See the License for the specific language governing permissions and
  13740. * limitations under the License.
  13741. */
  13742. /**
  13743. * A type for the resolve value of {@link runTransaction}.
  13744. */
  13745. class TransactionResult {
  13746. /** @hideconstructor */
  13747. constructor(
  13748. /** Whether the transaction was successfully committed. */
  13749. committed,
  13750. /** The resulting data snapshot. */
  13751. snapshot) {
  13752. this.committed = committed;
  13753. this.snapshot = snapshot;
  13754. }
  13755. /** Returns a JSON-serializable representation of this object. */
  13756. toJSON() {
  13757. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13758. }
  13759. }
  13760. /**
  13761. * Atomically modifies the data at this location.
  13762. *
  13763. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13764. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13765. * used to modify the existing value to a new value, ensuring there are no
  13766. * conflicts with other clients writing to the same location at the same time.
  13767. *
  13768. * To accomplish this, you pass `runTransaction()` an update function which is
  13769. * used to transform the current value into a new value. If another client
  13770. * writes to the location before your new value is successfully written, your
  13771. * update function will be called again with the new current value, and the
  13772. * write will be retried. This will happen repeatedly until your write succeeds
  13773. * without conflict or you abort the transaction by not returning a value from
  13774. * your update function.
  13775. *
  13776. * Note: Modifying data with `set()` will cancel any pending transactions at
  13777. * that location, so extreme care should be taken if mixing `set()` and
  13778. * `runTransaction()` to update the same data.
  13779. *
  13780. * Note: When using transactions with Security and Firebase Rules in place, be
  13781. * aware that a client needs `.read` access in addition to `.write` access in
  13782. * order to perform a transaction. This is because the client-side nature of
  13783. * transactions requires the client to read the data in order to transactionally
  13784. * update it.
  13785. *
  13786. * @param ref - The location to atomically modify.
  13787. * @param transactionUpdate - A developer-supplied function which will be passed
  13788. * the current data stored at this location (as a JavaScript object). The
  13789. * function should return the new value it would like written (as a JavaScript
  13790. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13791. * transaction will be aborted and the data at this location will not be
  13792. * modified.
  13793. * @param options - An options object to configure transactions.
  13794. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13795. * callback to handle success and failure.
  13796. */
  13797. function runTransaction(ref,
  13798. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13799. transactionUpdate, options) {
  13800. var _a;
  13801. ref = getModularInstance(ref);
  13802. validateWritablePath('Reference.transaction', ref._path);
  13803. if (ref.key === '.length' || ref.key === '.keys') {
  13804. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13805. }
  13806. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13807. const deferred = new Deferred();
  13808. const promiseComplete = (error, committed, node) => {
  13809. let dataSnapshot = null;
  13810. if (error) {
  13811. deferred.reject(error);
  13812. }
  13813. else {
  13814. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13815. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13816. }
  13817. };
  13818. // Add a watch to make sure we get server updates.
  13819. const unwatcher = onValue(ref, () => { });
  13820. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13821. return deferred.promise;
  13822. }
  13823. /**
  13824. * @license
  13825. * Copyright 2017 Google LLC
  13826. *
  13827. * Licensed under the Apache License, Version 2.0 (the "License");
  13828. * you may not use this file except in compliance with the License.
  13829. * You may obtain a copy of the License at
  13830. *
  13831. * http://www.apache.org/licenses/LICENSE-2.0
  13832. *
  13833. * Unless required by applicable law or agreed to in writing, software
  13834. * distributed under the License is distributed on an "AS IS" BASIS,
  13835. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13836. * See the License for the specific language governing permissions and
  13837. * limitations under the License.
  13838. */
  13839. PersistentConnection;
  13840. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13841. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13842. this.sendRequest('q', { p: pathString }, onComplete);
  13843. };
  13844. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13845. PersistentConnection.prototype.echo = function (data, onEcho) {
  13846. this.sendRequest('echo', { d: data }, onEcho);
  13847. };
  13848. // RealTimeConnection properties that we use in tests.
  13849. Connection;
  13850. /**
  13851. * @internal
  13852. */
  13853. const hijackHash = function (newHash) {
  13854. const oldPut = PersistentConnection.prototype.put;
  13855. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13856. if (hash !== undefined) {
  13857. hash = newHash();
  13858. }
  13859. oldPut.call(this, pathString, data, onComplete, hash);
  13860. };
  13861. return function () {
  13862. PersistentConnection.prototype.put = oldPut;
  13863. };
  13864. };
  13865. RepoInfo;
  13866. /**
  13867. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13868. * @internal
  13869. */
  13870. const forceRestClient = function (forceRestClient) {
  13871. repoManagerForceRestClient(forceRestClient);
  13872. };
  13873. /**
  13874. * @license
  13875. * Copyright 2023 Google LLC
  13876. *
  13877. * Licensed under the Apache License, Version 2.0 (the "License");
  13878. * you may not use this file except in compliance with the License.
  13879. * You may obtain a copy of the License at
  13880. *
  13881. * http://www.apache.org/licenses/LICENSE-2.0
  13882. *
  13883. * Unless required by applicable law or agreed to in writing, software
  13884. * distributed under the License is distributed on an "AS IS" BASIS,
  13885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13886. * See the License for the specific language governing permissions and
  13887. * limitations under the License.
  13888. */
  13889. /**
  13890. * Used by console to create a database based on the app,
  13891. * passed database URL and a custom auth implementation.
  13892. * @internal
  13893. * @param app - A valid FirebaseApp-like object
  13894. * @param url - A valid Firebase databaseURL
  13895. * @param version - custom version e.g. firebase-admin version
  13896. * @param customAppCheckImpl - custom app check implementation
  13897. * @param customAuthImpl - custom auth implementation
  13898. */
  13899. function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {
  13900. setSDKVersion(version);
  13901. /**
  13902. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  13903. * any actual function.
  13904. */
  13905. const componentContainer = new ComponentContainer('database-standalone');
  13906. const authProvider = new Provider('auth-internal', componentContainer);
  13907. let appCheckProvider;
  13908. if (customAppCheckImpl) {
  13909. appCheckProvider = new Provider('app-check-internal', componentContainer);
  13910. appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13911. }
  13912. authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13913. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);
  13914. }
  13915. /**
  13916. * Firebase Realtime Database
  13917. *
  13918. * @packageDocumentation
  13919. */
  13920. registerDatabase();
  13921. 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, _initStandalone, 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 };
  13922. //# sourceMappingURL=index.esm2017.js.map