index.webworker.esm5.js 382 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661
  1. import { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';
  2. import { ErrorFactory, deepEqual, getUA, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, createSubscribe, querystringDecode, extractQuerystring } from '@firebase/util';
  3. import { __spreadArray, __assign, __awaiter, __generator, __rest, __extends } from 'tslib';
  4. import { Logger, LogLevel } from '@firebase/logger';
  5. import { Component } from '@firebase/component';
  6. /**
  7. * @license
  8. * Copyright 2020 Google LLC
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. */
  22. function _debugErrorMap() {
  23. var _a;
  24. return _a = {},
  25. _a["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
  26. _a["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */] = '',
  27. _a["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
  28. 'authorized to use Firebase Authentication with the provided API key. ' +
  29. 'Review your key configuration in the Google API console.',
  30. _a["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
  31. 'Android package name or iOS bundle ID) provided is not installed on ' +
  32. 'this device.',
  33. _a["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
  34. 'already used or the domain associated with it does not match the list ' +
  35. 'of whitelisted domains.',
  36. _a["code-expired" /* AuthErrorCode.CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
  37. 'again.',
  38. _a["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
  39. _a["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */] = 'This browser is not supported.',
  40. _a["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
  41. _a["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
  42. _a["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
  43. 'again before retrying this request.',
  44. _a["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  45. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  46. 'starting any other Firebase SDK.',
  47. _a["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  48. 'conditions.',
  49. _a["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
  50. _a["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */] = 'The email address is already in use by another account.',
  51. _a["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
  52. 'no longer be configured to use the emulator. Try calling ' +
  53. '"connectAuthEmulator()" sooner.',
  54. _a["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */] = 'The action code has expired.',
  55. _a["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
  56. _a["internal-error" /* AuthErrorCode.INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
  57. _a["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
  58. ' The reCAPTCHA token response is either invalid or expired.',
  59. _a["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
  60. _a["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
  61. "if the user's token has been tampered with, or if the user isn't for " +
  62. 'the project associated with this API key.',
  63. _a["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  64. _a["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
  65. 'invalid. Please resend the verification code sms and be sure to use the ' +
  66. 'verification code provided by the user.',
  67. _a["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
  68. _a["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  69. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  70. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  71. 'cordova-plugin-customurlscheme.',
  72. _a["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
  73. _a["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
  74. _a["invalid-email" /* AuthErrorCode.INVALID_EMAIL */] = 'The email address is badly formatted.',
  75. _a["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
  76. _a["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
  77. _a["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
  78. _a["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
  79. _a["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
  80. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  81. _a["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
  82. _a["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
  83. 'only supports OAuth providers.',
  84. _a["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
  85. 'specified API key.',
  86. _a["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
  87. 'project. Edit the list of authorized domains from the Firebase console.',
  88. _a["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
  89. 'expired, or has already been used.',
  90. _a["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
  91. _a["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
  92. _a["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
  93. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  94. 'phone numbers are written in the format [+][country code][subscriber ' +
  95. 'number including area code].',
  96. _a["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
  97. _a["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
  98. 'recipient email address is invalid.',
  99. _a["invalid-sender" /* AuthErrorCode.INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
  100. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  101. _a["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
  102. _a["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
  103. _a["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */] = 'Login blocked by user-provided method: {$originalMessage}',
  104. _a["missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */] = 'An Android Package Name must be provided if the Android App is required to be installed.',
  105. _a["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  106. 'by following the instructions in the Firebase console.',
  107. _a["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
  108. 'assertion. A reCAPTCHA response token needs to be provided.',
  109. _a["missing-verification-code" /* AuthErrorCode.MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
  110. _a["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
  111. _a["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
  112. _a["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  113. _a["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
  114. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  115. 'in the ID token payload.',
  116. _a["missing-password" /* AuthErrorCode.MISSING_PASSWORD */] = 'A non-empty password must be provided',
  117. _a["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
  118. _a["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
  119. _a["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
  120. _a["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
  121. _a["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
  122. _a["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
  123. _a["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
  124. _a["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
  125. 'sign-in credentials. Sign in using a provider associated with this ' +
  126. 'email address.',
  127. _a["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  128. _a["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  129. _a["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
  130. _a["null-user" /* AuthErrorCode.NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
  131. 'requires a non-null user object.',
  132. _a["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
  133. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  134. 'Auth section.',
  135. _a["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
  136. 'running on. "location.protocol" must be http, https or chrome-extension' +
  137. ' and web storage must be enabled.',
  138. _a["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  139. _a["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
  140. _a["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
  141. _a["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
  142. _a["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
  143. _a["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
  144. _a["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
  145. _a["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
  146. _a["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
  147. _a["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
  148. _a["timeout" /* AuthErrorCode.TIMEOUT */] = 'The operation has timed out.',
  149. _a["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
  150. _a["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
  151. 'Try again later.',
  152. _a["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  153. 'the domain in the Firebase console.',
  154. _a["unsupported-first-factor" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */] = 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
  155. _a["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
  156. _a["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
  157. _a["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
  158. _a["user-cancelled" /* AuthErrorCode.USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
  159. _a["user-not-found" /* AuthErrorCode.USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
  160. 'have been deleted.',
  161. _a["user-disabled" /* AuthErrorCode.USER_DISABLED */] = 'The user account has been disabled by an administrator.',
  162. _a["user-mismatch" /* AuthErrorCode.USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
  163. _a["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */] = '',
  164. _a["weak-password" /* AuthErrorCode.WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
  165. _a["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
  166. _a["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
  167. 'different options. To avoid this error, call initializeAuth() with the ' +
  168. 'same options as when it was originally called, or call getAuth() to return the' +
  169. ' already initialized instance.',
  170. _a["missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */] = 'The reCAPTCHA token is missing when sending request to the backend.',
  171. _a["invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */] = 'The reCAPTCHA token is invalid when sending request to the backend.',
  172. _a["invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */] = 'The reCAPTCHA action is invalid when sending request to the backend.',
  173. _a["recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */] = 'reCAPTCHA Enterprise integration is not enabled for this project.',
  174. _a["missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */] = 'The reCAPTCHA client type is missing when sending request to the backend.',
  175. _a["missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */] = 'The reCAPTCHA version is missing when sending request to the backend.',
  176. _a["invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */] = 'Invalid request parameters.',
  177. _a["invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */] = 'The reCAPTCHA version is invalid when sending request to the backend.',
  178. _a;
  179. }
  180. function _prodErrorMap() {
  181. var _a;
  182. // We will include this one message in the prod error map since by the very
  183. // nature of this error, developers will never be able to see the message
  184. // using the debugErrorMap (which is installed during auth initialization).
  185. return _a = {},
  186. _a["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  187. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  188. 'starting any other Firebase SDK.',
  189. _a;
  190. }
  191. /**
  192. * A verbose error map with detailed descriptions for most error codes.
  193. *
  194. * See discussion at {@link AuthErrorMap}
  195. *
  196. * @public
  197. */
  198. var debugErrorMap = _debugErrorMap;
  199. /**
  200. * A minimal error map with all verbose error messages stripped.
  201. *
  202. * See discussion at {@link AuthErrorMap}
  203. *
  204. * @public
  205. */
  206. var prodErrorMap = _prodErrorMap;
  207. var _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
  208. /**
  209. * A map of potential `Auth` error codes, for easier comparison with errors
  210. * thrown by the SDK.
  211. *
  212. * @remarks
  213. * Note that you can't tree-shake individual keys
  214. * in the map, so by using the map you might substantially increase your
  215. * bundle size.
  216. *
  217. * @public
  218. */
  219. var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  220. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  221. ARGUMENT_ERROR: 'auth/argument-error',
  222. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  223. APP_NOT_INSTALLED: 'auth/app-not-installed',
  224. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  225. CODE_EXPIRED: 'auth/code-expired',
  226. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  227. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  228. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  229. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  230. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  231. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  232. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  233. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  234. EMAIL_EXISTS: 'auth/email-already-in-use',
  235. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  236. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  237. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  238. INTERNAL_ERROR: 'auth/internal-error',
  239. INVALID_API_KEY: 'auth/invalid-api-key',
  240. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  241. INVALID_APP_ID: 'auth/invalid-app-id',
  242. INVALID_AUTH: 'auth/invalid-user-token',
  243. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  244. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  245. INVALID_CODE: 'auth/invalid-verification-code',
  246. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  247. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  248. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  249. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  250. INVALID_EMAIL: 'auth/invalid-email',
  251. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  252. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  253. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  254. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  255. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  256. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  257. INVALID_OOB_CODE: 'auth/invalid-action-code',
  258. INVALID_ORIGIN: 'auth/unauthorized-domain',
  259. INVALID_PASSWORD: 'auth/wrong-password',
  260. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  261. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  262. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  263. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  264. INVALID_SENDER: 'auth/invalid-sender',
  265. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  266. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  267. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  268. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  269. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  270. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  271. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  272. MISSING_CODE: 'auth/missing-verification-code',
  273. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  274. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  275. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  276. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  277. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  278. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  279. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  280. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  281. MODULE_DESTROYED: 'auth/app-deleted',
  282. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  283. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  284. NULL_USER: 'auth/null-user',
  285. NO_AUTH_EVENT: 'auth/no-auth-event',
  286. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  287. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  288. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  289. POPUP_BLOCKED: 'auth/popup-blocked',
  290. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  291. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  292. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  293. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  294. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  295. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  296. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  297. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  298. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  299. TIMEOUT: 'auth/timeout',
  300. TOKEN_EXPIRED: 'auth/user-token-expired',
  301. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  302. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  303. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  304. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  305. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  306. UNVERIFIED_EMAIL: 'auth/unverified-email',
  307. USER_CANCELLED: 'auth/user-cancelled',
  308. USER_DELETED: 'auth/user-not-found',
  309. USER_DISABLED: 'auth/user-disabled',
  310. USER_MISMATCH: 'auth/user-mismatch',
  311. USER_SIGNED_OUT: 'auth/user-signed-out',
  312. WEAK_PASSWORD: 'auth/weak-password',
  313. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  314. ALREADY_INITIALIZED: 'auth/already-initialized',
  315. RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',
  316. MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',
  317. INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',
  318. INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',
  319. MISSING_CLIENT_TYPE: 'auth/missing-client-type',
  320. MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',
  321. INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',
  322. INVALID_REQ_TYPE: 'auth/invalid-req-type'
  323. };
  324. /**
  325. * @license
  326. * Copyright 2020 Google LLC
  327. *
  328. * Licensed under the Apache License, Version 2.0 (the "License");
  329. * you may not use this file except in compliance with the License.
  330. * You may obtain a copy of the License at
  331. *
  332. * http://www.apache.org/licenses/LICENSE-2.0
  333. *
  334. * Unless required by applicable law or agreed to in writing, software
  335. * distributed under the License is distributed on an "AS IS" BASIS,
  336. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  337. * See the License for the specific language governing permissions and
  338. * limitations under the License.
  339. */
  340. var logClient = new Logger('@firebase/auth');
  341. function _logWarn(msg) {
  342. var args = [];
  343. for (var _i = 1; _i < arguments.length; _i++) {
  344. args[_i - 1] = arguments[_i];
  345. }
  346. if (logClient.logLevel <= LogLevel.WARN) {
  347. logClient.warn.apply(logClient, __spreadArray(["Auth (".concat(SDK_VERSION, "): ").concat(msg)], args, false));
  348. }
  349. }
  350. function _logError(msg) {
  351. var args = [];
  352. for (var _i = 1; _i < arguments.length; _i++) {
  353. args[_i - 1] = arguments[_i];
  354. }
  355. if (logClient.logLevel <= LogLevel.ERROR) {
  356. logClient.error.apply(logClient, __spreadArray(["Auth (".concat(SDK_VERSION, "): ").concat(msg)], args, false));
  357. }
  358. }
  359. /**
  360. * @license
  361. * Copyright 2020 Google LLC
  362. *
  363. * Licensed under the Apache License, Version 2.0 (the "License");
  364. * you may not use this file except in compliance with the License.
  365. * You may obtain a copy of the License at
  366. *
  367. * http://www.apache.org/licenses/LICENSE-2.0
  368. *
  369. * Unless required by applicable law or agreed to in writing, software
  370. * distributed under the License is distributed on an "AS IS" BASIS,
  371. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  372. * See the License for the specific language governing permissions and
  373. * limitations under the License.
  374. */
  375. function _fail(authOrCode) {
  376. var rest = [];
  377. for (var _i = 1; _i < arguments.length; _i++) {
  378. rest[_i - 1] = arguments[_i];
  379. }
  380. throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  381. }
  382. function _createError(authOrCode) {
  383. var rest = [];
  384. for (var _i = 1; _i < arguments.length; _i++) {
  385. rest[_i - 1] = arguments[_i];
  386. }
  387. return createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  388. }
  389. function _errorWithCustomMessage(auth, code, message) {
  390. var _a;
  391. var errorMap = __assign(__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
  392. var factory = new ErrorFactory('auth', 'Firebase', errorMap);
  393. return factory.create(code, {
  394. appName: auth.name
  395. });
  396. }
  397. function createErrorInternal(authOrCode) {
  398. var _a;
  399. var rest = [];
  400. for (var _i = 1; _i < arguments.length; _i++) {
  401. rest[_i - 1] = arguments[_i];
  402. }
  403. if (typeof authOrCode !== 'string') {
  404. var code = rest[0];
  405. var fullParams = __spreadArray([], rest.slice(1), true);
  406. if (fullParams[0]) {
  407. fullParams[0].appName = authOrCode.name;
  408. }
  409. return (_a = authOrCode._errorFactory).create.apply(_a, __spreadArray([code], fullParams, false));
  410. }
  411. return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, __spreadArray([authOrCode], rest, false));
  412. }
  413. function _assert(assertion, authOrCode) {
  414. var rest = [];
  415. for (var _i = 2; _i < arguments.length; _i++) {
  416. rest[_i - 2] = arguments[_i];
  417. }
  418. if (!assertion) {
  419. throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  420. }
  421. }
  422. /**
  423. * Unconditionally fails, throwing an internal error with the given message.
  424. *
  425. * @param failure type of failure encountered
  426. * @throws Error
  427. */
  428. function debugFail(failure) {
  429. // Log the failure in addition to throw an exception, just in case the
  430. // exception is swallowed.
  431. var message = "INTERNAL ASSERTION FAILED: " + failure;
  432. _logError(message);
  433. // NOTE: We don't use FirebaseError here because these are internal failures
  434. // that cannot be handled by the user. (Also it would create a circular
  435. // dependency between the error and assert modules which doesn't work.)
  436. throw new Error(message);
  437. }
  438. /**
  439. * Fails if the given assertion condition is false, throwing an Error with the
  440. * given message if it did.
  441. *
  442. * @param assertion
  443. * @param message
  444. */
  445. function debugAssert(assertion, message) {
  446. if (!assertion) {
  447. debugFail(message);
  448. }
  449. }
  450. /**
  451. * @license
  452. * Copyright 2020 Google LLC
  453. *
  454. * Licensed under the Apache License, Version 2.0 (the "License");
  455. * you may not use this file except in compliance with the License.
  456. * You may obtain a copy of the License at
  457. *
  458. * http://www.apache.org/licenses/LICENSE-2.0
  459. *
  460. * Unless required by applicable law or agreed to in writing, software
  461. * distributed under the License is distributed on an "AS IS" BASIS,
  462. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  463. * See the License for the specific language governing permissions and
  464. * limitations under the License.
  465. */
  466. var instanceCache = new Map();
  467. function _getInstance(cls) {
  468. debugAssert(cls instanceof Function, 'Expected a class definition');
  469. var instance = instanceCache.get(cls);
  470. if (instance) {
  471. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  472. return instance;
  473. }
  474. instance = new cls();
  475. instanceCache.set(cls, instance);
  476. return instance;
  477. }
  478. /**
  479. * @license
  480. * Copyright 2020 Google LLC
  481. *
  482. * Licensed under the Apache License, Version 2.0 (the "License");
  483. * you may not use this file except in compliance with the License.
  484. * You may obtain a copy of the License at
  485. *
  486. * http://www.apache.org/licenses/LICENSE-2.0
  487. *
  488. * Unless required by applicable law or agreed to in writing, software
  489. * distributed under the License is distributed on an "AS IS" BASIS,
  490. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  491. * See the License for the specific language governing permissions and
  492. * limitations under the License.
  493. */
  494. /**
  495. * Initializes an {@link Auth} instance with fine-grained control over
  496. * {@link Dependencies}.
  497. *
  498. * @remarks
  499. *
  500. * This function allows more control over the {@link Auth} instance than
  501. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  502. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  503. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  504. * need control over which persistence layer is used, or to minimize bundle
  505. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  506. *
  507. * For example, if your app only uses anonymous accounts and you only want
  508. * accounts saved for the current session, initialize `Auth` with:
  509. *
  510. * ```js
  511. * const auth = initializeAuth(app, {
  512. * persistence: browserSessionPersistence,
  513. * popupRedirectResolver: undefined,
  514. * });
  515. * ```
  516. *
  517. * @public
  518. */
  519. function initializeAuth(app, deps) {
  520. var provider = _getProvider(app, 'auth');
  521. if (provider.isInitialized()) {
  522. var auth_1 = provider.getImmediate();
  523. var initialOptions = provider.getOptions();
  524. if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  525. return auth_1;
  526. }
  527. else {
  528. _fail(auth_1, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  529. }
  530. }
  531. var auth = provider.initialize({ options: deps });
  532. return auth;
  533. }
  534. function _initializeAuthInstance(auth, deps) {
  535. var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  536. var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  537. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  538. auth._updateErrorMap(deps.errorMap);
  539. }
  540. // This promise is intended to float; auth initialization happens in the
  541. // background, meanwhile the auth object may be used by the app.
  542. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  543. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  544. }
  545. var name = "@firebase/auth";
  546. var version = "0.23.2";
  547. /**
  548. * @license
  549. * Copyright 2020 Google LLC
  550. *
  551. * Licensed under the Apache License, Version 2.0 (the "License");
  552. * you may not use this file except in compliance with the License.
  553. * You may obtain a copy of the License at
  554. *
  555. * http://www.apache.org/licenses/LICENSE-2.0
  556. *
  557. * Unless required by applicable law or agreed to in writing, software
  558. * distributed under the License is distributed on an "AS IS" BASIS,
  559. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  560. * See the License for the specific language governing permissions and
  561. * limitations under the License.
  562. */
  563. /**
  564. * Determine the browser for the purposes of reporting usage to the API
  565. */
  566. function _getBrowserName(userAgent) {
  567. var ua = userAgent.toLowerCase();
  568. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  569. return "Opera" /* BrowserName.OPERA */;
  570. }
  571. else if (_isIEMobile(ua)) {
  572. // Windows phone IEMobile browser.
  573. return "IEMobile" /* BrowserName.IEMOBILE */;
  574. }
  575. else if (ua.includes('msie') || ua.includes('trident/')) {
  576. return "IE" /* BrowserName.IE */;
  577. }
  578. else if (ua.includes('edge/')) {
  579. return "Edge" /* BrowserName.EDGE */;
  580. }
  581. else if (_isFirefox(ua)) {
  582. return "Firefox" /* BrowserName.FIREFOX */;
  583. }
  584. else if (ua.includes('silk/')) {
  585. return "Silk" /* BrowserName.SILK */;
  586. }
  587. else if (_isBlackBerry(ua)) {
  588. // Blackberry browser.
  589. return "Blackberry" /* BrowserName.BLACKBERRY */;
  590. }
  591. else if (_isWebOS(ua)) {
  592. // WebOS default browser.
  593. return "Webos" /* BrowserName.WEBOS */;
  594. }
  595. else if (_isSafari(ua)) {
  596. return "Safari" /* BrowserName.SAFARI */;
  597. }
  598. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  599. !ua.includes('edge/')) {
  600. return "Chrome" /* BrowserName.CHROME */;
  601. }
  602. else if (_isAndroid(ua)) {
  603. // Android stock browser.
  604. return "Android" /* BrowserName.ANDROID */;
  605. }
  606. else {
  607. // Most modern browsers have name/version at end of user agent string.
  608. var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  609. var matches = userAgent.match(re);
  610. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  611. return matches[1];
  612. }
  613. }
  614. return "Other" /* BrowserName.OTHER */;
  615. }
  616. function _isFirefox(ua) {
  617. if (ua === void 0) { ua = getUA(); }
  618. return /firefox\//i.test(ua);
  619. }
  620. function _isSafari(userAgent) {
  621. if (userAgent === void 0) { userAgent = getUA(); }
  622. var ua = userAgent.toLowerCase();
  623. return (ua.includes('safari/') &&
  624. !ua.includes('chrome/') &&
  625. !ua.includes('crios/') &&
  626. !ua.includes('android'));
  627. }
  628. function _isChromeIOS(ua) {
  629. if (ua === void 0) { ua = getUA(); }
  630. return /crios\//i.test(ua);
  631. }
  632. function _isIEMobile(ua) {
  633. if (ua === void 0) { ua = getUA(); }
  634. return /iemobile/i.test(ua);
  635. }
  636. function _isAndroid(ua) {
  637. if (ua === void 0) { ua = getUA(); }
  638. return /android/i.test(ua);
  639. }
  640. function _isBlackBerry(ua) {
  641. if (ua === void 0) { ua = getUA(); }
  642. return /blackberry/i.test(ua);
  643. }
  644. function _isWebOS(ua) {
  645. if (ua === void 0) { ua = getUA(); }
  646. return /webos/i.test(ua);
  647. }
  648. /**
  649. * @license
  650. * Copyright 2020 Google LLC
  651. *
  652. * Licensed under the Apache License, Version 2.0 (the "License");
  653. * you may not use this file except in compliance with the License.
  654. * You may obtain a copy of the License at
  655. *
  656. * http://www.apache.org/licenses/LICENSE-2.0
  657. *
  658. * Unless required by applicable law or agreed to in writing, software
  659. * distributed under the License is distributed on an "AS IS" BASIS,
  660. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  661. * See the License for the specific language governing permissions and
  662. * limitations under the License.
  663. */
  664. /*
  665. * Determine the SDK version string
  666. */
  667. function _getClientVersion(clientPlatform, frameworks) {
  668. if (frameworks === void 0) { frameworks = []; }
  669. var reportedPlatform;
  670. switch (clientPlatform) {
  671. case "Browser" /* ClientPlatform.BROWSER */:
  672. // In a browser environment, report the browser name.
  673. reportedPlatform = _getBrowserName(getUA());
  674. break;
  675. case "Worker" /* ClientPlatform.WORKER */:
  676. // Technically a worker runs from a browser but we need to differentiate a
  677. // worker from a browser.
  678. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  679. reportedPlatform = "".concat(_getBrowserName(getUA()), "-").concat(clientPlatform);
  680. break;
  681. default:
  682. reportedPlatform = clientPlatform;
  683. }
  684. var reportedFrameworks = frameworks.length
  685. ? frameworks.join(',')
  686. : 'FirebaseCore-web'; /* default value if no other framework is used */
  687. return "".concat(reportedPlatform, "/").concat("JsCore" /* ClientImplementation.CORE */, "/").concat(SDK_VERSION, "/").concat(reportedFrameworks);
  688. }
  689. /**
  690. * @license
  691. * Copyright 2020 Google LLC
  692. *
  693. * Licensed under the Apache License, Version 2.0 (the "License");
  694. * you may not use this file except in compliance with the License.
  695. * You may obtain a copy of the License at
  696. *
  697. * http://www.apache.org/licenses/LICENSE-2.0
  698. *
  699. * Unless required by applicable law or agreed to in writing, software
  700. * distributed under the License is distributed on an "AS IS" BASIS,
  701. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  702. * See the License for the specific language governing permissions and
  703. * limitations under the License.
  704. */
  705. function _getCurrentUrl() {
  706. var _a;
  707. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  708. }
  709. function _isHttpOrHttps() {
  710. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  711. }
  712. function _getCurrentScheme() {
  713. var _a;
  714. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  715. }
  716. /**
  717. * @license
  718. * Copyright 2020 Google LLC
  719. *
  720. * Licensed under the Apache License, Version 2.0 (the "License");
  721. * you may not use this file except in compliance with the License.
  722. * You may obtain a copy of the License at
  723. *
  724. * http://www.apache.org/licenses/LICENSE-2.0
  725. *
  726. * Unless required by applicable law or agreed to in writing, software
  727. * distributed under the License is distributed on an "AS IS" BASIS,
  728. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  729. * See the License for the specific language governing permissions and
  730. * limitations under the License.
  731. */
  732. /**
  733. * Determine whether the browser is working online
  734. */
  735. function _isOnline() {
  736. if (typeof navigator !== 'undefined' &&
  737. navigator &&
  738. 'onLine' in navigator &&
  739. typeof navigator.onLine === 'boolean' &&
  740. // Apply only for traditional web apps and Chrome extensions.
  741. // This is especially true for Cordova apps which have unreliable
  742. // navigator.onLine behavior unless cordova-plugin-network-information is
  743. // installed which overwrites the native navigator.onLine value and
  744. // defines navigator.connection.
  745. (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
  746. return navigator.onLine;
  747. }
  748. // If we can't determine the state, assume it is online.
  749. return true;
  750. }
  751. function _getUserLanguage() {
  752. if (typeof navigator === 'undefined') {
  753. return null;
  754. }
  755. var navigatorLanguage = navigator;
  756. return (
  757. // Most reliable, but only supported in Chrome/Firefox.
  758. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  759. // Supported in most browsers, but returns the language of the browser
  760. // UI, not the language set in browser settings.
  761. navigatorLanguage.language ||
  762. // Couldn't determine language.
  763. null);
  764. }
  765. /**
  766. * @license
  767. * Copyright 2020 Google LLC
  768. *
  769. * Licensed under the Apache License, Version 2.0 (the "License");
  770. * you may not use this file except in compliance with the License.
  771. * You may obtain a copy of the License at
  772. *
  773. * http://www.apache.org/licenses/LICENSE-2.0
  774. *
  775. * Unless required by applicable law or agreed to in writing, software
  776. * distributed under the License is distributed on an "AS IS" BASIS,
  777. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  778. * See the License for the specific language governing permissions and
  779. * limitations under the License.
  780. */
  781. /**
  782. * A structure to help pick between a range of long and short delay durations
  783. * depending on the current environment. In general, the long delay is used for
  784. * mobile environments whereas short delays are used for desktop environments.
  785. */
  786. var Delay = /** @class */ (function () {
  787. function Delay(shortDelay, longDelay) {
  788. this.shortDelay = shortDelay;
  789. this.longDelay = longDelay;
  790. // Internal error when improperly initialized.
  791. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  792. this.isMobile = isMobileCordova() || isReactNative();
  793. }
  794. Delay.prototype.get = function () {
  795. if (!_isOnline()) {
  796. // Pick the shorter timeout.
  797. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  798. }
  799. // If running in a mobile environment, return the long delay, otherwise
  800. // return the short delay.
  801. // This could be improved in the future to dynamically change based on other
  802. // variables instead of just reading the current environment.
  803. return this.isMobile ? this.longDelay : this.shortDelay;
  804. };
  805. return Delay;
  806. }());
  807. /**
  808. * @license
  809. * Copyright 2020 Google LLC
  810. *
  811. * Licensed under the Apache License, Version 2.0 (the "License");
  812. * you may not use this file except in compliance with the License.
  813. * You may obtain a copy of the License at
  814. *
  815. * http://www.apache.org/licenses/LICENSE-2.0
  816. *
  817. * Unless required by applicable law or agreed to in writing, software
  818. * distributed under the License is distributed on an "AS IS" BASIS,
  819. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  820. * See the License for the specific language governing permissions and
  821. * limitations under the License.
  822. */
  823. function _emulatorUrl(config, path) {
  824. debugAssert(config.emulator, 'Emulator should always be set here');
  825. var url = config.emulator.url;
  826. if (!path) {
  827. return url;
  828. }
  829. return "".concat(url).concat(path.startsWith('/') ? path.slice(1) : path);
  830. }
  831. /**
  832. * @license
  833. * Copyright 2020 Google LLC
  834. *
  835. * Licensed under the Apache License, Version 2.0 (the "License");
  836. * you may not use this file except in compliance with the License.
  837. * You may obtain a copy of the License at
  838. *
  839. * http://www.apache.org/licenses/LICENSE-2.0
  840. *
  841. * Unless required by applicable law or agreed to in writing, software
  842. * distributed under the License is distributed on an "AS IS" BASIS,
  843. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  844. * See the License for the specific language governing permissions and
  845. * limitations under the License.
  846. */
  847. var FetchProvider = /** @class */ (function () {
  848. function FetchProvider() {
  849. }
  850. FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
  851. this.fetchImpl = fetchImpl;
  852. if (headersImpl) {
  853. this.headersImpl = headersImpl;
  854. }
  855. if (responseImpl) {
  856. this.responseImpl = responseImpl;
  857. }
  858. };
  859. FetchProvider.fetch = function () {
  860. if (this.fetchImpl) {
  861. return this.fetchImpl;
  862. }
  863. if (typeof self !== 'undefined' && 'fetch' in self) {
  864. return self.fetch;
  865. }
  866. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  867. };
  868. FetchProvider.headers = function () {
  869. if (this.headersImpl) {
  870. return this.headersImpl;
  871. }
  872. if (typeof self !== 'undefined' && 'Headers' in self) {
  873. return self.Headers;
  874. }
  875. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  876. };
  877. FetchProvider.response = function () {
  878. if (this.responseImpl) {
  879. return this.responseImpl;
  880. }
  881. if (typeof self !== 'undefined' && 'Response' in self) {
  882. return self.Response;
  883. }
  884. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  885. };
  886. return FetchProvider;
  887. }());
  888. /**
  889. * @license
  890. * Copyright 2020 Google LLC
  891. *
  892. * Licensed under the Apache License, Version 2.0 (the "License");
  893. * you may not use this file except in compliance with the License.
  894. * You may obtain a copy of the License at
  895. *
  896. * http://www.apache.org/licenses/LICENSE-2.0
  897. *
  898. * Unless required by applicable law or agreed to in writing, software
  899. * distributed under the License is distributed on an "AS IS" BASIS,
  900. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  901. * See the License for the specific language governing permissions and
  902. * limitations under the License.
  903. */
  904. var _a$1;
  905. /**
  906. * Map from errors returned by the server to errors to developer visible errors
  907. */
  908. var SERVER_ERROR_MAP = (_a$1 = {},
  909. // Custom token errors.
  910. _a$1["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  911. // This can only happen if the SDK sends a bad request.
  912. _a$1["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  913. // Create Auth URI errors.
  914. _a$1["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */] = "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  915. // This can only happen if the SDK sends a bad request.
  916. _a$1["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  917. // Sign in with email and password errors (some apply to sign up too).
  918. _a$1["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */] = "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  919. // This can only happen if the SDK sends a bad request.
  920. _a$1["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */] = "missing-password" /* AuthErrorCode.MISSING_PASSWORD */,
  921. // Sign up with email and password errors.
  922. _a$1["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */] = "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  923. _a$1["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  924. // Verify assertion for sign in with credential errors:
  925. _a$1["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  926. _a$1["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  927. _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  928. // This can only happen if the SDK sends a bad request.
  929. _a$1["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  930. // Send Password reset email errors:
  931. _a$1["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  932. _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  933. _a$1["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */] = "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  934. _a$1["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */] = "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  935. // This can only happen if the SDK sends a bad request.
  936. _a$1["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  937. // Operations that require ID token in request:
  938. _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  939. _a$1["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */] = "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  940. _a$1["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  941. _a$1["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  942. // Other errors.
  943. _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  944. // Phone Auth related errors.
  945. _a$1["INVALID_CODE" /* ServerError.INVALID_CODE */] = "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  946. _a$1["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */] = "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  947. _a$1["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  948. _a$1["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */] = "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  949. _a$1["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */] = "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  950. // Other action code errors when additional settings passed.
  951. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  952. // This is OK as this error will be caught by client side validation.
  953. _a$1["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  954. _a$1["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  955. // getProjectConfig errors when clientId is passed.
  956. _a$1["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  957. // User actions (sign-up or deletion) disabled errors.
  958. _a$1["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  959. // Multi factor related errors.
  960. _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  961. _a$1["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  962. _a$1["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  963. _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  964. _a$1["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  965. _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  966. // Blocking functions related errors.
  967. _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  968. // Recaptcha related errors.
  969. _a$1["RECAPTCHA_NOT_ENABLED" /* ServerError.RECAPTCHA_NOT_ENABLED */] = "recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,
  970. _a$1["MISSING_RECAPTCHA_TOKEN" /* ServerError.MISSING_RECAPTCHA_TOKEN */] = "missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,
  971. _a$1["INVALID_RECAPTCHA_TOKEN" /* ServerError.INVALID_RECAPTCHA_TOKEN */] = "invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,
  972. _a$1["INVALID_RECAPTCHA_ACTION" /* ServerError.INVALID_RECAPTCHA_ACTION */] = "invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,
  973. _a$1["MISSING_CLIENT_TYPE" /* ServerError.MISSING_CLIENT_TYPE */] = "missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */,
  974. _a$1["MISSING_RECAPTCHA_VERSION" /* ServerError.MISSING_RECAPTCHA_VERSION */] = "missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,
  975. _a$1["INVALID_RECAPTCHA_VERSION" /* ServerError.INVALID_RECAPTCHA_VERSION */] = "invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,
  976. _a$1["INVALID_REQ_TYPE" /* ServerError.INVALID_REQ_TYPE */] = "invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */,
  977. _a$1);
  978. /**
  979. * @license
  980. * Copyright 2020 Google LLC
  981. *
  982. * Licensed under the Apache License, Version 2.0 (the "License");
  983. * you may not use this file except in compliance with the License.
  984. * You may obtain a copy of the License at
  985. *
  986. * http://www.apache.org/licenses/LICENSE-2.0
  987. *
  988. * Unless required by applicable law or agreed to in writing, software
  989. * distributed under the License is distributed on an "AS IS" BASIS,
  990. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  991. * See the License for the specific language governing permissions and
  992. * limitations under the License.
  993. */
  994. var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  995. function _addTidIfNecessary(auth, request) {
  996. if (auth.tenantId && !request.tenantId) {
  997. return __assign(__assign({}, request), { tenantId: auth.tenantId });
  998. }
  999. return request;
  1000. }
  1001. function _performApiRequest(auth, method, path, request, customErrorMap) {
  1002. if (customErrorMap === void 0) { customErrorMap = {}; }
  1003. return __awaiter(this, void 0, void 0, function () {
  1004. var _this = this;
  1005. return __generator(this, function (_a) {
  1006. return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return __awaiter(_this, void 0, void 0, function () {
  1007. var body, params, query, headers;
  1008. return __generator(this, function (_a) {
  1009. switch (_a.label) {
  1010. case 0:
  1011. body = {};
  1012. params = {};
  1013. if (request) {
  1014. if (method === "GET" /* HttpMethod.GET */) {
  1015. params = request;
  1016. }
  1017. else {
  1018. body = {
  1019. body: JSON.stringify(request)
  1020. };
  1021. }
  1022. }
  1023. query = querystring(__assign({ key: auth.config.apiKey }, params)).slice(1);
  1024. return [4 /*yield*/, auth._getAdditionalHeaders()];
  1025. case 1:
  1026. headers = _a.sent();
  1027. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  1028. if (auth.languageCode) {
  1029. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  1030. }
  1031. return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), __assign({ method: method, headers: headers, referrerPolicy: 'no-referrer' }, body))];
  1032. }
  1033. });
  1034. }); })];
  1035. });
  1036. });
  1037. }
  1038. function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  1039. return __awaiter(this, void 0, void 0, function () {
  1040. var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
  1041. return __generator(this, function (_b) {
  1042. switch (_b.label) {
  1043. case 0:
  1044. auth._canInitEmulator = false;
  1045. errorMap = __assign(__assign({}, SERVER_ERROR_MAP), customErrorMap);
  1046. _b.label = 1;
  1047. case 1:
  1048. _b.trys.push([1, 4, , 5]);
  1049. networkTimeout = new NetworkTimeout(auth);
  1050. return [4 /*yield*/, Promise.race([
  1051. fetchFn(),
  1052. networkTimeout.promise
  1053. ])];
  1054. case 2:
  1055. response = _b.sent();
  1056. // If we've reached this point, the fetch succeeded and the networkTimeout
  1057. // didn't throw; clear the network timeout delay so that Node won't hang
  1058. networkTimeout.clearNetworkTimeout();
  1059. return [4 /*yield*/, response.json()];
  1060. case 3:
  1061. json = _b.sent();
  1062. if ('needConfirmation' in json) {
  1063. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  1064. }
  1065. if (response.ok && !('errorMessage' in json)) {
  1066. return [2 /*return*/, json];
  1067. }
  1068. else {
  1069. errorMessage = response.ok ? json.errorMessage : json.error.message;
  1070. _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
  1071. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  1072. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  1073. }
  1074. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  1075. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  1076. }
  1077. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  1078. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  1079. }
  1080. authError = errorMap[serverErrorCode] ||
  1081. serverErrorCode
  1082. .toLowerCase()
  1083. .replace(/[_\s]+/g, '-');
  1084. if (serverErrorMessage) {
  1085. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  1086. }
  1087. else {
  1088. _fail(auth, authError);
  1089. }
  1090. }
  1091. return [3 /*break*/, 5];
  1092. case 4:
  1093. e_1 = _b.sent();
  1094. if (e_1 instanceof FirebaseError) {
  1095. throw e_1;
  1096. }
  1097. // Changing this to a different error code will log user out when there is a network error
  1098. // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.
  1099. // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316
  1100. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e_1) });
  1101. return [3 /*break*/, 5];
  1102. case 5: return [2 /*return*/];
  1103. }
  1104. });
  1105. });
  1106. }
  1107. function _performSignInRequest(auth, method, path, request, customErrorMap) {
  1108. if (customErrorMap === void 0) { customErrorMap = {}; }
  1109. return __awaiter(this, void 0, void 0, function () {
  1110. var serverResponse;
  1111. return __generator(this, function (_a) {
  1112. switch (_a.label) {
  1113. case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
  1114. case 1:
  1115. serverResponse = (_a.sent());
  1116. if ('mfaPendingCredential' in serverResponse) {
  1117. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  1118. _serverResponse: serverResponse
  1119. });
  1120. }
  1121. return [2 /*return*/, serverResponse];
  1122. }
  1123. });
  1124. });
  1125. }
  1126. function _getFinalTarget(auth, host, path, query) {
  1127. var base = "".concat(host).concat(path, "?").concat(query);
  1128. if (!auth.config.emulator) {
  1129. return "".concat(auth.config.apiScheme, "://").concat(base);
  1130. }
  1131. return _emulatorUrl(auth.config, base);
  1132. }
  1133. var NetworkTimeout = /** @class */ (function () {
  1134. function NetworkTimeout(auth) {
  1135. var _this = this;
  1136. this.auth = auth;
  1137. // Node timers and browser timers are fundamentally incompatible, but we
  1138. // don't care about the value here
  1139. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1140. this.timer = null;
  1141. this.promise = new Promise(function (_, reject) {
  1142. _this.timer = setTimeout(function () {
  1143. return reject(_createError(_this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  1144. }, DEFAULT_API_TIMEOUT_MS.get());
  1145. });
  1146. }
  1147. NetworkTimeout.prototype.clearNetworkTimeout = function () {
  1148. clearTimeout(this.timer);
  1149. };
  1150. return NetworkTimeout;
  1151. }());
  1152. function _makeTaggedError(auth, code, response) {
  1153. var errorParams = {
  1154. appName: auth.name
  1155. };
  1156. if (response.email) {
  1157. errorParams.email = response.email;
  1158. }
  1159. if (response.phoneNumber) {
  1160. errorParams.phoneNumber = response.phoneNumber;
  1161. }
  1162. var error = _createError(auth, code, errorParams);
  1163. // We know customData is defined on error because errorParams is defined
  1164. error.customData._tokenResponse = response;
  1165. return error;
  1166. }
  1167. /**
  1168. * @license
  1169. * Copyright 2020 Google LLC
  1170. *
  1171. * Licensed under the Apache License, Version 2.0 (the "License");
  1172. * you may not use this file except in compliance with the License.
  1173. * You may obtain a copy of the License at
  1174. *
  1175. * http://www.apache.org/licenses/LICENSE-2.0
  1176. *
  1177. * Unless required by applicable law or agreed to in writing, software
  1178. * distributed under the License is distributed on an "AS IS" BASIS,
  1179. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1180. * See the License for the specific language governing permissions and
  1181. * limitations under the License.
  1182. */
  1183. function deleteAccount(auth, request) {
  1184. return __awaiter(this, void 0, void 0, function () {
  1185. return __generator(this, function (_a) {
  1186. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request)];
  1187. });
  1188. });
  1189. }
  1190. function deleteLinkedAccounts(auth, request) {
  1191. return __awaiter(this, void 0, void 0, function () {
  1192. return __generator(this, function (_a) {
  1193. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  1194. });
  1195. });
  1196. }
  1197. function getAccountInfo(auth, request) {
  1198. return __awaiter(this, void 0, void 0, function () {
  1199. return __generator(this, function (_a) {
  1200. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request)];
  1201. });
  1202. });
  1203. }
  1204. /**
  1205. * @license
  1206. * Copyright 2020 Google LLC
  1207. *
  1208. * Licensed under the Apache License, Version 2.0 (the "License");
  1209. * you may not use this file except in compliance with the License.
  1210. * You may obtain a copy of the License at
  1211. *
  1212. * http://www.apache.org/licenses/LICENSE-2.0
  1213. *
  1214. * Unless required by applicable law or agreed to in writing, software
  1215. * distributed under the License is distributed on an "AS IS" BASIS,
  1216. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1217. * See the License for the specific language governing permissions and
  1218. * limitations under the License.
  1219. */
  1220. function utcTimestampToDateString(utcTimestamp) {
  1221. if (!utcTimestamp) {
  1222. return undefined;
  1223. }
  1224. try {
  1225. // Convert to date object.
  1226. var date = new Date(Number(utcTimestamp));
  1227. // Test date is valid.
  1228. if (!isNaN(date.getTime())) {
  1229. // Convert to UTC date string.
  1230. return date.toUTCString();
  1231. }
  1232. }
  1233. catch (e) {
  1234. // Do nothing. undefined will be returned.
  1235. }
  1236. return undefined;
  1237. }
  1238. /**
  1239. * @license
  1240. * Copyright 2020 Google LLC
  1241. *
  1242. * Licensed under the Apache License, Version 2.0 (the "License");
  1243. * you may not use this file except in compliance with the License.
  1244. * You may obtain a copy of the License at
  1245. *
  1246. * http://www.apache.org/licenses/LICENSE-2.0
  1247. *
  1248. * Unless required by applicable law or agreed to in writing, software
  1249. * distributed under the License is distributed on an "AS IS" BASIS,
  1250. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1251. * See the License for the specific language governing permissions and
  1252. * limitations under the License.
  1253. */
  1254. /**
  1255. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1256. *
  1257. * @remarks
  1258. * Returns the current token if it has not expired or if it will not expire in the next five
  1259. * minutes. Otherwise, this will refresh the token and return a new one.
  1260. *
  1261. * @param user - The user.
  1262. * @param forceRefresh - Force refresh regardless of token expiration.
  1263. *
  1264. * @public
  1265. */
  1266. function getIdToken(user, forceRefresh) {
  1267. if (forceRefresh === void 0) { forceRefresh = false; }
  1268. return getModularInstance(user).getIdToken(forceRefresh);
  1269. }
  1270. /**
  1271. * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.
  1272. *
  1273. * @remarks
  1274. * Returns the current token if it has not expired or if it will not expire in the next five
  1275. * minutes. Otherwise, this will refresh the token and return a new one.
  1276. *
  1277. * @param user - The user.
  1278. * @param forceRefresh - Force refresh regardless of token expiration.
  1279. *
  1280. * @public
  1281. */
  1282. function getIdTokenResult(user, forceRefresh) {
  1283. if (forceRefresh === void 0) { forceRefresh = false; }
  1284. return __awaiter(this, void 0, void 0, function () {
  1285. var userInternal, token, claims, firebase, signInProvider;
  1286. return __generator(this, function (_a) {
  1287. switch (_a.label) {
  1288. case 0:
  1289. userInternal = getModularInstance(user);
  1290. return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
  1291. case 1:
  1292. token = _a.sent();
  1293. claims = _parseToken(token);
  1294. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1295. firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1296. signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1297. return [2 /*return*/, {
  1298. claims: claims,
  1299. token: token,
  1300. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1301. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1302. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1303. signInProvider: signInProvider || null,
  1304. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1305. }];
  1306. }
  1307. });
  1308. });
  1309. }
  1310. function secondsStringToMilliseconds(seconds) {
  1311. return Number(seconds) * 1000;
  1312. }
  1313. function _parseToken(token) {
  1314. var _a = token.split('.'), algorithm = _a[0], payload = _a[1], signature = _a[2];
  1315. if (algorithm === undefined ||
  1316. payload === undefined ||
  1317. signature === undefined) {
  1318. _logError('JWT malformed, contained fewer than 3 sections');
  1319. return null;
  1320. }
  1321. try {
  1322. var decoded = base64Decode(payload);
  1323. if (!decoded) {
  1324. _logError('Failed to decode base64 JWT payload');
  1325. return null;
  1326. }
  1327. return JSON.parse(decoded);
  1328. }
  1329. catch (e) {
  1330. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1331. return null;
  1332. }
  1333. }
  1334. /**
  1335. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1336. */
  1337. function _tokenExpiresIn(token) {
  1338. var parsedToken = _parseToken(token);
  1339. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1340. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1341. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1342. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1343. }
  1344. /**
  1345. * @license
  1346. * Copyright 2020 Google LLC
  1347. *
  1348. * Licensed under the Apache License, Version 2.0 (the "License");
  1349. * you may not use this file except in compliance with the License.
  1350. * You may obtain a copy of the License at
  1351. *
  1352. * http://www.apache.org/licenses/LICENSE-2.0
  1353. *
  1354. * Unless required by applicable law or agreed to in writing, software
  1355. * distributed under the License is distributed on an "AS IS" BASIS,
  1356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1357. * See the License for the specific language governing permissions and
  1358. * limitations under the License.
  1359. */
  1360. function _logoutIfInvalidated(user, promise, bypassAuthState) {
  1361. if (bypassAuthState === void 0) { bypassAuthState = false; }
  1362. return __awaiter(this, void 0, void 0, function () {
  1363. var e_1;
  1364. return __generator(this, function (_a) {
  1365. switch (_a.label) {
  1366. case 0:
  1367. if (bypassAuthState) {
  1368. return [2 /*return*/, promise];
  1369. }
  1370. _a.label = 1;
  1371. case 1:
  1372. _a.trys.push([1, 3, , 6]);
  1373. return [4 /*yield*/, promise];
  1374. case 2: return [2 /*return*/, _a.sent()];
  1375. case 3:
  1376. e_1 = _a.sent();
  1377. if (!(e_1 instanceof FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
  1378. if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
  1379. return [4 /*yield*/, user.auth.signOut()];
  1380. case 4:
  1381. _a.sent();
  1382. _a.label = 5;
  1383. case 5: throw e_1;
  1384. case 6: return [2 /*return*/];
  1385. }
  1386. });
  1387. });
  1388. }
  1389. function isUserInvalidated(_a) {
  1390. var code = _a.code;
  1391. return (code === "auth/".concat("user-disabled" /* AuthErrorCode.USER_DISABLED */) ||
  1392. code === "auth/".concat("user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */));
  1393. }
  1394. /**
  1395. * @license
  1396. * Copyright 2020 Google LLC
  1397. *
  1398. * Licensed under the Apache License, Version 2.0 (the "License");
  1399. * you may not use this file except in compliance with the License.
  1400. * You may obtain a copy of the License at
  1401. *
  1402. * http://www.apache.org/licenses/LICENSE-2.0
  1403. *
  1404. * Unless required by applicable law or agreed to in writing, software
  1405. * distributed under the License is distributed on an "AS IS" BASIS,
  1406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1407. * See the License for the specific language governing permissions and
  1408. * limitations under the License.
  1409. */
  1410. var ProactiveRefresh = /** @class */ (function () {
  1411. function ProactiveRefresh(user) {
  1412. this.user = user;
  1413. this.isRunning = false;
  1414. // Node timers and browser timers return fundamentally different types.
  1415. // We don't actually care what the value is but TS won't accept unknown and
  1416. // we can't cast properly in both environments.
  1417. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1418. this.timerId = null;
  1419. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1420. }
  1421. ProactiveRefresh.prototype._start = function () {
  1422. if (this.isRunning) {
  1423. return;
  1424. }
  1425. this.isRunning = true;
  1426. this.schedule();
  1427. };
  1428. ProactiveRefresh.prototype._stop = function () {
  1429. if (!this.isRunning) {
  1430. return;
  1431. }
  1432. this.isRunning = false;
  1433. if (this.timerId !== null) {
  1434. clearTimeout(this.timerId);
  1435. }
  1436. };
  1437. ProactiveRefresh.prototype.getInterval = function (wasError) {
  1438. var _a;
  1439. if (wasError) {
  1440. var interval = this.errorBackoff;
  1441. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1442. return interval;
  1443. }
  1444. else {
  1445. // Reset the error backoff
  1446. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1447. var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1448. var interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1449. return Math.max(0, interval);
  1450. }
  1451. };
  1452. ProactiveRefresh.prototype.schedule = function (wasError) {
  1453. var _this = this;
  1454. if (wasError === void 0) { wasError = false; }
  1455. if (!this.isRunning) {
  1456. // Just in case...
  1457. return;
  1458. }
  1459. var interval = this.getInterval(wasError);
  1460. this.timerId = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
  1461. return __generator(this, function (_a) {
  1462. switch (_a.label) {
  1463. case 0: return [4 /*yield*/, this.iteration()];
  1464. case 1:
  1465. _a.sent();
  1466. return [2 /*return*/];
  1467. }
  1468. });
  1469. }); }, interval);
  1470. };
  1471. ProactiveRefresh.prototype.iteration = function () {
  1472. return __awaiter(this, void 0, void 0, function () {
  1473. var e_1;
  1474. return __generator(this, function (_a) {
  1475. switch (_a.label) {
  1476. case 0:
  1477. _a.trys.push([0, 2, , 3]);
  1478. return [4 /*yield*/, this.user.getIdToken(true)];
  1479. case 1:
  1480. _a.sent();
  1481. return [3 /*break*/, 3];
  1482. case 2:
  1483. e_1 = _a.sent();
  1484. // Only retry on network errors
  1485. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) ===
  1486. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  1487. this.schedule(/* wasError */ true);
  1488. }
  1489. return [2 /*return*/];
  1490. case 3:
  1491. this.schedule();
  1492. return [2 /*return*/];
  1493. }
  1494. });
  1495. });
  1496. };
  1497. return ProactiveRefresh;
  1498. }());
  1499. /**
  1500. * @license
  1501. * Copyright 2020 Google LLC
  1502. *
  1503. * Licensed under the Apache License, Version 2.0 (the "License");
  1504. * you may not use this file except in compliance with the License.
  1505. * You may obtain a copy of the License at
  1506. *
  1507. * http://www.apache.org/licenses/LICENSE-2.0
  1508. *
  1509. * Unless required by applicable law or agreed to in writing, software
  1510. * distributed under the License is distributed on an "AS IS" BASIS,
  1511. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1512. * See the License for the specific language governing permissions and
  1513. * limitations under the License.
  1514. */
  1515. var UserMetadata = /** @class */ (function () {
  1516. function UserMetadata(createdAt, lastLoginAt) {
  1517. this.createdAt = createdAt;
  1518. this.lastLoginAt = lastLoginAt;
  1519. this._initializeTime();
  1520. }
  1521. UserMetadata.prototype._initializeTime = function () {
  1522. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1523. this.creationTime = utcTimestampToDateString(this.createdAt);
  1524. };
  1525. UserMetadata.prototype._copy = function (metadata) {
  1526. this.createdAt = metadata.createdAt;
  1527. this.lastLoginAt = metadata.lastLoginAt;
  1528. this._initializeTime();
  1529. };
  1530. UserMetadata.prototype.toJSON = function () {
  1531. return {
  1532. createdAt: this.createdAt,
  1533. lastLoginAt: this.lastLoginAt
  1534. };
  1535. };
  1536. return UserMetadata;
  1537. }());
  1538. /**
  1539. * @license
  1540. * Copyright 2019 Google LLC
  1541. *
  1542. * Licensed under the Apache License, Version 2.0 (the "License");
  1543. * you may not use this file except in compliance with the License.
  1544. * You may obtain a copy of the License at
  1545. *
  1546. * http://www.apache.org/licenses/LICENSE-2.0
  1547. *
  1548. * Unless required by applicable law or agreed to in writing, software
  1549. * distributed under the License is distributed on an "AS IS" BASIS,
  1550. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1551. * See the License for the specific language governing permissions and
  1552. * limitations under the License.
  1553. */
  1554. function _reloadWithoutSaving(user) {
  1555. var _a;
  1556. return __awaiter(this, void 0, void 0, function () {
  1557. var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
  1558. return __generator(this, function (_b) {
  1559. switch (_b.label) {
  1560. case 0:
  1561. auth = user.auth;
  1562. return [4 /*yield*/, user.getIdToken()];
  1563. case 1:
  1564. idToken = _b.sent();
  1565. return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
  1566. case 2:
  1567. response = _b.sent();
  1568. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1569. coreAccount = response.users[0];
  1570. user._notifyReloadListener(coreAccount);
  1571. newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1572. ? extractProviderData(coreAccount.providerUserInfo)
  1573. : [];
  1574. providerData = mergeProviderData(user.providerData, newProviderData);
  1575. oldIsAnonymous = user.isAnonymous;
  1576. newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1577. isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1578. updates = {
  1579. uid: coreAccount.localId,
  1580. displayName: coreAccount.displayName || null,
  1581. photoURL: coreAccount.photoUrl || null,
  1582. email: coreAccount.email || null,
  1583. emailVerified: coreAccount.emailVerified || false,
  1584. phoneNumber: coreAccount.phoneNumber || null,
  1585. tenantId: coreAccount.tenantId || null,
  1586. providerData: providerData,
  1587. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1588. isAnonymous: isAnonymous
  1589. };
  1590. Object.assign(user, updates);
  1591. return [2 /*return*/];
  1592. }
  1593. });
  1594. });
  1595. }
  1596. /**
  1597. * Reloads user account data, if signed in.
  1598. *
  1599. * @param user - The user.
  1600. *
  1601. * @public
  1602. */
  1603. function reload(user) {
  1604. return __awaiter(this, void 0, void 0, function () {
  1605. var userInternal;
  1606. return __generator(this, function (_a) {
  1607. switch (_a.label) {
  1608. case 0:
  1609. userInternal = getModularInstance(user);
  1610. return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
  1611. case 1:
  1612. _a.sent();
  1613. // Even though the current user hasn't changed, update
  1614. // current user will trigger a persistence update w/ the
  1615. // new info.
  1616. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  1617. case 2:
  1618. // Even though the current user hasn't changed, update
  1619. // current user will trigger a persistence update w/ the
  1620. // new info.
  1621. _a.sent();
  1622. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1623. return [2 /*return*/];
  1624. }
  1625. });
  1626. });
  1627. }
  1628. function mergeProviderData(original, newData) {
  1629. var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
  1630. return __spreadArray(__spreadArray([], deduped, true), newData, true);
  1631. }
  1632. function extractProviderData(providers) {
  1633. return providers.map(function (_a) {
  1634. var providerId = _a.providerId, provider = __rest(_a, ["providerId"]);
  1635. return {
  1636. providerId: providerId,
  1637. uid: provider.rawId || '',
  1638. displayName: provider.displayName || null,
  1639. email: provider.email || null,
  1640. phoneNumber: provider.phoneNumber || null,
  1641. photoURL: provider.photoUrl || null
  1642. };
  1643. });
  1644. }
  1645. /**
  1646. * @license
  1647. * Copyright 2020 Google LLC
  1648. *
  1649. * Licensed under the Apache License, Version 2.0 (the "License");
  1650. * you may not use this file except in compliance with the License.
  1651. * You may obtain a copy of the License at
  1652. *
  1653. * http://www.apache.org/licenses/LICENSE-2.0
  1654. *
  1655. * Unless required by applicable law or agreed to in writing, software
  1656. * distributed under the License is distributed on an "AS IS" BASIS,
  1657. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1658. * See the License for the specific language governing permissions and
  1659. * limitations under the License.
  1660. */
  1661. function requestStsToken(auth, refreshToken) {
  1662. return __awaiter(this, void 0, void 0, function () {
  1663. var response;
  1664. var _this = this;
  1665. return __generator(this, function (_a) {
  1666. switch (_a.label) {
  1667. case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return __awaiter(_this, void 0, void 0, function () {
  1668. var body, _a, tokenApiHost, apiKey, url, headers;
  1669. return __generator(this, function (_b) {
  1670. switch (_b.label) {
  1671. case 0:
  1672. body = querystring({
  1673. 'grant_type': 'refresh_token',
  1674. 'refresh_token': refreshToken
  1675. }).slice(1);
  1676. _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
  1677. url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, "key=".concat(apiKey));
  1678. return [4 /*yield*/, auth._getAdditionalHeaders()];
  1679. case 1:
  1680. headers = _b.sent();
  1681. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1682. return [2 /*return*/, FetchProvider.fetch()(url, {
  1683. method: "POST" /* HttpMethod.POST */,
  1684. headers: headers,
  1685. body: body
  1686. })];
  1687. }
  1688. });
  1689. }); })];
  1690. case 1:
  1691. response = _a.sent();
  1692. // The response comes back in snake_case. Convert to camel:
  1693. return [2 /*return*/, {
  1694. accessToken: response.access_token,
  1695. expiresIn: response.expires_in,
  1696. refreshToken: response.refresh_token
  1697. }];
  1698. }
  1699. });
  1700. });
  1701. }
  1702. /**
  1703. * @license
  1704. * Copyright 2020 Google LLC
  1705. *
  1706. * Licensed under the Apache License, Version 2.0 (the "License");
  1707. * you may not use this file except in compliance with the License.
  1708. * You may obtain a copy of the License at
  1709. *
  1710. * http://www.apache.org/licenses/LICENSE-2.0
  1711. *
  1712. * Unless required by applicable law or agreed to in writing, software
  1713. * distributed under the License is distributed on an "AS IS" BASIS,
  1714. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1715. * See the License for the specific language governing permissions and
  1716. * limitations under the License.
  1717. */
  1718. /**
  1719. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1720. * it references AuthInternal which has a circular dependency with UserInternal.
  1721. *
  1722. * @internal
  1723. */
  1724. var StsTokenManager = /** @class */ (function () {
  1725. function StsTokenManager() {
  1726. this.refreshToken = null;
  1727. this.accessToken = null;
  1728. this.expirationTime = null;
  1729. }
  1730. Object.defineProperty(StsTokenManager.prototype, "isExpired", {
  1731. get: function () {
  1732. return (!this.expirationTime ||
  1733. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1734. },
  1735. enumerable: false,
  1736. configurable: true
  1737. });
  1738. StsTokenManager.prototype.updateFromServerResponse = function (response) {
  1739. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1740. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1741. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1742. var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1743. ? Number(response.expiresIn)
  1744. : _tokenExpiresIn(response.idToken);
  1745. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1746. };
  1747. StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
  1748. if (forceRefresh === void 0) { forceRefresh = false; }
  1749. return __awaiter(this, void 0, void 0, function () {
  1750. return __generator(this, function (_a) {
  1751. switch (_a.label) {
  1752. case 0:
  1753. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1754. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1755. return [2 /*return*/, this.accessToken];
  1756. }
  1757. if (!this.refreshToken) return [3 /*break*/, 2];
  1758. return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
  1759. case 1:
  1760. _a.sent();
  1761. return [2 /*return*/, this.accessToken];
  1762. case 2: return [2 /*return*/, null];
  1763. }
  1764. });
  1765. });
  1766. };
  1767. StsTokenManager.prototype.clearRefreshToken = function () {
  1768. this.refreshToken = null;
  1769. };
  1770. StsTokenManager.prototype.refresh = function (auth, oldToken) {
  1771. return __awaiter(this, void 0, void 0, function () {
  1772. var _a, accessToken, refreshToken, expiresIn;
  1773. return __generator(this, function (_b) {
  1774. switch (_b.label) {
  1775. case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
  1776. case 1:
  1777. _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
  1778. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1779. return [2 /*return*/];
  1780. }
  1781. });
  1782. });
  1783. };
  1784. StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
  1785. this.refreshToken = refreshToken || null;
  1786. this.accessToken = accessToken || null;
  1787. this.expirationTime = Date.now() + expiresInSec * 1000;
  1788. };
  1789. StsTokenManager.fromJSON = function (appName, object) {
  1790. var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
  1791. var manager = new StsTokenManager();
  1792. if (refreshToken) {
  1793. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1794. appName: appName
  1795. });
  1796. manager.refreshToken = refreshToken;
  1797. }
  1798. if (accessToken) {
  1799. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1800. appName: appName
  1801. });
  1802. manager.accessToken = accessToken;
  1803. }
  1804. if (expirationTime) {
  1805. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1806. appName: appName
  1807. });
  1808. manager.expirationTime = expirationTime;
  1809. }
  1810. return manager;
  1811. };
  1812. StsTokenManager.prototype.toJSON = function () {
  1813. return {
  1814. refreshToken: this.refreshToken,
  1815. accessToken: this.accessToken,
  1816. expirationTime: this.expirationTime
  1817. };
  1818. };
  1819. StsTokenManager.prototype._assign = function (stsTokenManager) {
  1820. this.accessToken = stsTokenManager.accessToken;
  1821. this.refreshToken = stsTokenManager.refreshToken;
  1822. this.expirationTime = stsTokenManager.expirationTime;
  1823. };
  1824. StsTokenManager.prototype._clone = function () {
  1825. return Object.assign(new StsTokenManager(), this.toJSON());
  1826. };
  1827. StsTokenManager.prototype._performRefresh = function () {
  1828. return debugFail('not implemented');
  1829. };
  1830. return StsTokenManager;
  1831. }());
  1832. /**
  1833. * @license
  1834. * Copyright 2020 Google LLC
  1835. *
  1836. * Licensed under the Apache License, Version 2.0 (the "License");
  1837. * you may not use this file except in compliance with the License.
  1838. * You may obtain a copy of the License at
  1839. *
  1840. * http://www.apache.org/licenses/LICENSE-2.0
  1841. *
  1842. * Unless required by applicable law or agreed to in writing, software
  1843. * distributed under the License is distributed on an "AS IS" BASIS,
  1844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1845. * See the License for the specific language governing permissions and
  1846. * limitations under the License.
  1847. */
  1848. function assertStringOrUndefined(assertion, appName) {
  1849. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName: appName });
  1850. }
  1851. var UserImpl = /** @class */ (function () {
  1852. function UserImpl(_a) {
  1853. var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
  1854. // For the user object, provider is always Firebase.
  1855. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1856. this.proactiveRefresh = new ProactiveRefresh(this);
  1857. this.reloadUserInfo = null;
  1858. this.reloadListener = null;
  1859. this.uid = uid;
  1860. this.auth = auth;
  1861. this.stsTokenManager = stsTokenManager;
  1862. this.accessToken = stsTokenManager.accessToken;
  1863. this.displayName = opt.displayName || null;
  1864. this.email = opt.email || null;
  1865. this.emailVerified = opt.emailVerified || false;
  1866. this.phoneNumber = opt.phoneNumber || null;
  1867. this.photoURL = opt.photoURL || null;
  1868. this.isAnonymous = opt.isAnonymous || false;
  1869. this.tenantId = opt.tenantId || null;
  1870. this.providerData = opt.providerData ? __spreadArray([], opt.providerData, true) : [];
  1871. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1872. }
  1873. UserImpl.prototype.getIdToken = function (forceRefresh) {
  1874. return __awaiter(this, void 0, void 0, function () {
  1875. var accessToken;
  1876. return __generator(this, function (_a) {
  1877. switch (_a.label) {
  1878. case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
  1879. case 1:
  1880. accessToken = _a.sent();
  1881. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1882. if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
  1883. this.accessToken = accessToken;
  1884. return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1885. case 2:
  1886. _a.sent();
  1887. this.auth._notifyListenersIfCurrent(this);
  1888. _a.label = 3;
  1889. case 3: return [2 /*return*/, accessToken];
  1890. }
  1891. });
  1892. });
  1893. };
  1894. UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
  1895. return getIdTokenResult(this, forceRefresh);
  1896. };
  1897. UserImpl.prototype.reload = function () {
  1898. return reload(this);
  1899. };
  1900. UserImpl.prototype._assign = function (user) {
  1901. if (this === user) {
  1902. return;
  1903. }
  1904. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1905. this.displayName = user.displayName;
  1906. this.photoURL = user.photoURL;
  1907. this.email = user.email;
  1908. this.emailVerified = user.emailVerified;
  1909. this.phoneNumber = user.phoneNumber;
  1910. this.isAnonymous = user.isAnonymous;
  1911. this.tenantId = user.tenantId;
  1912. this.providerData = user.providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
  1913. this.metadata._copy(user.metadata);
  1914. this.stsTokenManager._assign(user.stsTokenManager);
  1915. };
  1916. UserImpl.prototype._clone = function (auth) {
  1917. var newUser = new UserImpl(__assign(__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
  1918. newUser.metadata._copy(this.metadata);
  1919. return newUser;
  1920. };
  1921. UserImpl.prototype._onReload = function (callback) {
  1922. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1923. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1924. this.reloadListener = callback;
  1925. if (this.reloadUserInfo) {
  1926. this._notifyReloadListener(this.reloadUserInfo);
  1927. this.reloadUserInfo = null;
  1928. }
  1929. };
  1930. UserImpl.prototype._notifyReloadListener = function (userInfo) {
  1931. if (this.reloadListener) {
  1932. this.reloadListener(userInfo);
  1933. }
  1934. else {
  1935. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1936. this.reloadUserInfo = userInfo;
  1937. }
  1938. };
  1939. UserImpl.prototype._startProactiveRefresh = function () {
  1940. this.proactiveRefresh._start();
  1941. };
  1942. UserImpl.prototype._stopProactiveRefresh = function () {
  1943. this.proactiveRefresh._stop();
  1944. };
  1945. UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
  1946. if (reload === void 0) { reload = false; }
  1947. return __awaiter(this, void 0, void 0, function () {
  1948. var tokensRefreshed;
  1949. return __generator(this, function (_a) {
  1950. switch (_a.label) {
  1951. case 0:
  1952. tokensRefreshed = false;
  1953. if (response.idToken &&
  1954. response.idToken !== this.stsTokenManager.accessToken) {
  1955. this.stsTokenManager.updateFromServerResponse(response);
  1956. tokensRefreshed = true;
  1957. }
  1958. if (!reload) return [3 /*break*/, 2];
  1959. return [4 /*yield*/, _reloadWithoutSaving(this)];
  1960. case 1:
  1961. _a.sent();
  1962. _a.label = 2;
  1963. case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1964. case 3:
  1965. _a.sent();
  1966. if (tokensRefreshed) {
  1967. this.auth._notifyListenersIfCurrent(this);
  1968. }
  1969. return [2 /*return*/];
  1970. }
  1971. });
  1972. });
  1973. };
  1974. UserImpl.prototype.delete = function () {
  1975. return __awaiter(this, void 0, void 0, function () {
  1976. var idToken;
  1977. return __generator(this, function (_a) {
  1978. switch (_a.label) {
  1979. case 0: return [4 /*yield*/, this.getIdToken()];
  1980. case 1:
  1981. idToken = _a.sent();
  1982. return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
  1983. case 2:
  1984. _a.sent();
  1985. this.stsTokenManager.clearRefreshToken();
  1986. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1987. // cancels pending actions...
  1988. return [2 /*return*/, this.auth.signOut()];
  1989. }
  1990. });
  1991. });
  1992. };
  1993. UserImpl.prototype.toJSON = function () {
  1994. return __assign(__assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(function (userInfo) { return (__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
  1995. // Redirect event ID must be maintained in case there is a pending
  1996. // redirect event.
  1997. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1998. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1999. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  2000. };
  2001. Object.defineProperty(UserImpl.prototype, "refreshToken", {
  2002. get: function () {
  2003. return this.stsTokenManager.refreshToken || '';
  2004. },
  2005. enumerable: false,
  2006. configurable: true
  2007. });
  2008. UserImpl._fromJSON = function (auth, object) {
  2009. var _a, _b, _c, _d, _e, _f, _g, _h;
  2010. var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  2011. var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  2012. var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  2013. var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  2014. var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  2015. var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  2016. var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  2017. var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  2018. var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
  2019. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2020. var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  2021. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2022. assertStringOrUndefined(displayName, auth.name);
  2023. assertStringOrUndefined(email, auth.name);
  2024. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2025. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2026. assertStringOrUndefined(phoneNumber, auth.name);
  2027. assertStringOrUndefined(photoURL, auth.name);
  2028. assertStringOrUndefined(tenantId, auth.name);
  2029. assertStringOrUndefined(_redirectEventId, auth.name);
  2030. assertStringOrUndefined(createdAt, auth.name);
  2031. assertStringOrUndefined(lastLoginAt, auth.name);
  2032. var user = new UserImpl({
  2033. uid: uid,
  2034. auth: auth,
  2035. email: email,
  2036. emailVerified: emailVerified,
  2037. displayName: displayName,
  2038. isAnonymous: isAnonymous,
  2039. photoURL: photoURL,
  2040. phoneNumber: phoneNumber,
  2041. tenantId: tenantId,
  2042. stsTokenManager: stsTokenManager,
  2043. createdAt: createdAt,
  2044. lastLoginAt: lastLoginAt
  2045. });
  2046. if (providerData && Array.isArray(providerData)) {
  2047. user.providerData = providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
  2048. }
  2049. if (_redirectEventId) {
  2050. user._redirectEventId = _redirectEventId;
  2051. }
  2052. return user;
  2053. };
  2054. /**
  2055. * Initialize a User from an idToken server response
  2056. * @param auth
  2057. * @param idTokenResponse
  2058. */
  2059. UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
  2060. if (isAnonymous === void 0) { isAnonymous = false; }
  2061. return __awaiter(this, void 0, void 0, function () {
  2062. var stsTokenManager, user;
  2063. return __generator(this, function (_a) {
  2064. switch (_a.label) {
  2065. case 0:
  2066. stsTokenManager = new StsTokenManager();
  2067. stsTokenManager.updateFromServerResponse(idTokenResponse);
  2068. user = new UserImpl({
  2069. uid: idTokenResponse.localId,
  2070. auth: auth,
  2071. stsTokenManager: stsTokenManager,
  2072. isAnonymous: isAnonymous
  2073. });
  2074. // Updates the user info and data and resolves with a user instance.
  2075. return [4 /*yield*/, _reloadWithoutSaving(user)];
  2076. case 1:
  2077. // Updates the user info and data and resolves with a user instance.
  2078. _a.sent();
  2079. return [2 /*return*/, user];
  2080. }
  2081. });
  2082. });
  2083. };
  2084. return UserImpl;
  2085. }());
  2086. /**
  2087. * @license
  2088. * Copyright 2019 Google LLC
  2089. *
  2090. * Licensed under the Apache License, Version 2.0 (the "License");
  2091. * you may not use this file except in compliance with the License.
  2092. * You may obtain a copy of the License at
  2093. *
  2094. * http://www.apache.org/licenses/LICENSE-2.0
  2095. *
  2096. * Unless required by applicable law or agreed to in writing, software
  2097. * distributed under the License is distributed on an "AS IS" BASIS,
  2098. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2099. * See the License for the specific language governing permissions and
  2100. * limitations under the License.
  2101. */
  2102. var InMemoryPersistence = /** @class */ (function () {
  2103. function InMemoryPersistence() {
  2104. this.type = "NONE" /* PersistenceType.NONE */;
  2105. this.storage = {};
  2106. }
  2107. InMemoryPersistence.prototype._isAvailable = function () {
  2108. return __awaiter(this, void 0, void 0, function () {
  2109. return __generator(this, function (_a) {
  2110. return [2 /*return*/, true];
  2111. });
  2112. });
  2113. };
  2114. InMemoryPersistence.prototype._set = function (key, value) {
  2115. return __awaiter(this, void 0, void 0, function () {
  2116. return __generator(this, function (_a) {
  2117. this.storage[key] = value;
  2118. return [2 /*return*/];
  2119. });
  2120. });
  2121. };
  2122. InMemoryPersistence.prototype._get = function (key) {
  2123. return __awaiter(this, void 0, void 0, function () {
  2124. var value;
  2125. return __generator(this, function (_a) {
  2126. value = this.storage[key];
  2127. return [2 /*return*/, value === undefined ? null : value];
  2128. });
  2129. });
  2130. };
  2131. InMemoryPersistence.prototype._remove = function (key) {
  2132. return __awaiter(this, void 0, void 0, function () {
  2133. return __generator(this, function (_a) {
  2134. delete this.storage[key];
  2135. return [2 /*return*/];
  2136. });
  2137. });
  2138. };
  2139. InMemoryPersistence.prototype._addListener = function (_key, _listener) {
  2140. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2141. return;
  2142. };
  2143. InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
  2144. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2145. return;
  2146. };
  2147. InMemoryPersistence.type = 'NONE';
  2148. return InMemoryPersistence;
  2149. }());
  2150. /**
  2151. * An implementation of {@link Persistence} of type 'NONE'.
  2152. *
  2153. * @public
  2154. */
  2155. var inMemoryPersistence = InMemoryPersistence;
  2156. /**
  2157. * @license
  2158. * Copyright 2019 Google LLC
  2159. *
  2160. * Licensed under the Apache License, Version 2.0 (the "License");
  2161. * you may not use this file except in compliance with the License.
  2162. * You may obtain a copy of the License at
  2163. *
  2164. * http://www.apache.org/licenses/LICENSE-2.0
  2165. *
  2166. * Unless required by applicable law or agreed to in writing, software
  2167. * distributed under the License is distributed on an "AS IS" BASIS,
  2168. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2169. * See the License for the specific language governing permissions and
  2170. * limitations under the License.
  2171. */
  2172. function _persistenceKeyName(key, apiKey, appName) {
  2173. return "".concat("firebase" /* Namespace.PERSISTENCE */, ":").concat(key, ":").concat(apiKey, ":").concat(appName);
  2174. }
  2175. var PersistenceUserManager = /** @class */ (function () {
  2176. function PersistenceUserManager(persistence, auth, userKey) {
  2177. this.persistence = persistence;
  2178. this.auth = auth;
  2179. this.userKey = userKey;
  2180. var _a = this.auth, config = _a.config, name = _a.name;
  2181. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  2182. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  2183. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  2184. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  2185. }
  2186. PersistenceUserManager.prototype.setCurrentUser = function (user) {
  2187. return this.persistence._set(this.fullUserKey, user.toJSON());
  2188. };
  2189. PersistenceUserManager.prototype.getCurrentUser = function () {
  2190. return __awaiter(this, void 0, void 0, function () {
  2191. var blob;
  2192. return __generator(this, function (_a) {
  2193. switch (_a.label) {
  2194. case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
  2195. case 1:
  2196. blob = _a.sent();
  2197. return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
  2198. }
  2199. });
  2200. });
  2201. };
  2202. PersistenceUserManager.prototype.removeCurrentUser = function () {
  2203. return this.persistence._remove(this.fullUserKey);
  2204. };
  2205. PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
  2206. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  2207. };
  2208. PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
  2209. return __awaiter(this, void 0, void 0, function () {
  2210. var currentUser;
  2211. return __generator(this, function (_a) {
  2212. switch (_a.label) {
  2213. case 0:
  2214. if (this.persistence === newPersistence) {
  2215. return [2 /*return*/];
  2216. }
  2217. return [4 /*yield*/, this.getCurrentUser()];
  2218. case 1:
  2219. currentUser = _a.sent();
  2220. return [4 /*yield*/, this.removeCurrentUser()];
  2221. case 2:
  2222. _a.sent();
  2223. this.persistence = newPersistence;
  2224. if (currentUser) {
  2225. return [2 /*return*/, this.setCurrentUser(currentUser)];
  2226. }
  2227. return [2 /*return*/];
  2228. }
  2229. });
  2230. });
  2231. };
  2232. PersistenceUserManager.prototype.delete = function () {
  2233. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  2234. };
  2235. PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
  2236. if (userKey === void 0) { userKey = "authUser" /* KeyName.AUTH_USER */; }
  2237. return __awaiter(this, void 0, void 0, function () {
  2238. var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
  2239. var _this = this;
  2240. return __generator(this, function (_b) {
  2241. switch (_b.label) {
  2242. case 0:
  2243. if (!persistenceHierarchy.length) {
  2244. return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
  2245. }
  2246. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
  2247. return __generator(this, function (_a) {
  2248. switch (_a.label) {
  2249. case 0: return [4 /*yield*/, persistence._isAvailable()];
  2250. case 1:
  2251. if (_a.sent()) {
  2252. return [2 /*return*/, persistence];
  2253. }
  2254. return [2 /*return*/, undefined];
  2255. }
  2256. });
  2257. }); }))];
  2258. case 1:
  2259. availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
  2260. selectedPersistence = availablePersistences[0] ||
  2261. _getInstance(inMemoryPersistence);
  2262. key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  2263. userToMigrate = null;
  2264. _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
  2265. _b.label = 2;
  2266. case 2:
  2267. if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
  2268. persistence = persistenceHierarchy_1[_i];
  2269. _b.label = 3;
  2270. case 3:
  2271. _b.trys.push([3, 5, , 6]);
  2272. return [4 /*yield*/, persistence._get(key)];
  2273. case 4:
  2274. blob = _b.sent();
  2275. if (blob) {
  2276. user = UserImpl._fromJSON(auth, blob);
  2277. if (persistence !== selectedPersistence) {
  2278. userToMigrate = user;
  2279. }
  2280. selectedPersistence = persistence;
  2281. return [3 /*break*/, 7];
  2282. }
  2283. return [3 /*break*/, 6];
  2284. case 5:
  2285. _b.sent();
  2286. return [3 /*break*/, 6];
  2287. case 6:
  2288. _i++;
  2289. return [3 /*break*/, 2];
  2290. case 7:
  2291. migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
  2292. // If the persistence does _not_ allow migration, just finish off here
  2293. if (!selectedPersistence._shouldAllowMigration ||
  2294. !migrationHierarchy.length) {
  2295. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2296. }
  2297. selectedPersistence = migrationHierarchy[0];
  2298. if (!userToMigrate) return [3 /*break*/, 9];
  2299. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2300. // we'll just let it bubble to surface the error.
  2301. return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
  2302. case 8:
  2303. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2304. // we'll just let it bubble to surface the error.
  2305. _b.sent();
  2306. _b.label = 9;
  2307. case 9:
  2308. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2309. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2310. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
  2311. return __generator(this, function (_b) {
  2312. switch (_b.label) {
  2313. case 0:
  2314. if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
  2315. _b.label = 1;
  2316. case 1:
  2317. _b.trys.push([1, 3, , 4]);
  2318. return [4 /*yield*/, persistence._remove(key)];
  2319. case 2:
  2320. _b.sent();
  2321. return [3 /*break*/, 4];
  2322. case 3:
  2323. _b.sent();
  2324. return [3 /*break*/, 4];
  2325. case 4: return [2 /*return*/];
  2326. }
  2327. });
  2328. }); }))];
  2329. case 10:
  2330. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2331. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2332. _b.sent();
  2333. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2334. }
  2335. });
  2336. });
  2337. };
  2338. return PersistenceUserManager;
  2339. }());
  2340. /**
  2341. * @license
  2342. * Copyright 2020 Google LLC
  2343. *
  2344. * Licensed under the Apache License, Version 2.0 (the "License");
  2345. * you may not use this file except in compliance with the License.
  2346. * You may obtain a copy of the License at
  2347. *
  2348. * http://www.apache.org/licenses/LICENSE-2.0
  2349. *
  2350. * Unless required by applicable law or agreed to in writing, software
  2351. * distributed under the License is distributed on an "AS IS" BASIS,
  2352. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2353. * See the License for the specific language governing permissions and
  2354. * limitations under the License.
  2355. */
  2356. function getRecaptchaConfig(auth, request) {
  2357. return __awaiter(this, void 0, void 0, function () {
  2358. return __generator(this, function (_a) {
  2359. return [2 /*return*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v2/recaptchaConfig" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request))];
  2360. });
  2361. });
  2362. }
  2363. /**
  2364. * @license
  2365. * Copyright 2020 Google LLC
  2366. *
  2367. * Licensed under the Apache License, Version 2.0 (the "License");
  2368. * you may not use this file except in compliance with the License.
  2369. * You may obtain a copy of the License at
  2370. *
  2371. * http://www.apache.org/licenses/LICENSE-2.0
  2372. *
  2373. * Unless required by applicable law or agreed to in writing, software
  2374. * distributed under the License is distributed on an "AS IS" BASIS,
  2375. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2376. * See the License for the specific language governing permissions and
  2377. * limitations under the License.
  2378. */
  2379. function isEnterprise(grecaptcha) {
  2380. return (grecaptcha !== undefined &&
  2381. grecaptcha.enterprise !== undefined);
  2382. }
  2383. var RecaptchaConfig = /** @class */ (function () {
  2384. function RecaptchaConfig(response) {
  2385. /**
  2386. * The reCAPTCHA site key.
  2387. */
  2388. this.siteKey = '';
  2389. /**
  2390. * The reCAPTCHA enablement status of the {@link EmailAuthProvider} for the current tenant.
  2391. */
  2392. this.emailPasswordEnabled = false;
  2393. if (response.recaptchaKey === undefined) {
  2394. throw new Error('recaptchaKey undefined');
  2395. }
  2396. // Example response.recaptchaKey: "projects/proj123/keys/sitekey123"
  2397. this.siteKey = response.recaptchaKey.split('/')[3];
  2398. this.emailPasswordEnabled = response.recaptchaEnforcementState.some(function (enforcementState) {
  2399. return enforcementState.provider === 'EMAIL_PASSWORD_PROVIDER' &&
  2400. enforcementState.enforcementState !== 'OFF';
  2401. });
  2402. }
  2403. return RecaptchaConfig;
  2404. }());
  2405. /**
  2406. * @license
  2407. * Copyright 2020 Google LLC
  2408. *
  2409. * Licensed under the Apache License, Version 2.0 (the "License");
  2410. * you may not use this file except in compliance with the License.
  2411. * You may obtain a copy of the License at
  2412. *
  2413. * http://www.apache.org/licenses/LICENSE-2.0
  2414. *
  2415. * Unless required by applicable law or agreed to in writing, software
  2416. * distributed under the License is distributed on an "AS IS" BASIS,
  2417. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2418. * See the License for the specific language governing permissions and
  2419. * limitations under the License.
  2420. */
  2421. function getScriptParentElement() {
  2422. var _a, _b;
  2423. return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
  2424. }
  2425. function _loadJS(url) {
  2426. // TODO: consider adding timeout support & cancellation
  2427. return new Promise(function (resolve, reject) {
  2428. var el = document.createElement('script');
  2429. el.setAttribute('src', url);
  2430. el.onload = resolve;
  2431. el.onerror = function (e) {
  2432. var error = _createError("internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2433. error.customData = e;
  2434. reject(error);
  2435. };
  2436. el.type = 'text/javascript';
  2437. el.charset = 'UTF-8';
  2438. getScriptParentElement().appendChild(el);
  2439. });
  2440. }
  2441. /* eslint-disable @typescript-eslint/no-require-imports */
  2442. var RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js?render=';
  2443. var RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';
  2444. var FAKE_TOKEN = 'NO_RECAPTCHA';
  2445. var RecaptchaEnterpriseVerifier = /** @class */ (function () {
  2446. /**
  2447. *
  2448. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  2449. *
  2450. */
  2451. function RecaptchaEnterpriseVerifier(authExtern) {
  2452. /**
  2453. * Identifies the type of application verifier (e.g. "recaptcha-enterprise").
  2454. */
  2455. this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;
  2456. this.auth = _castAuth(authExtern);
  2457. }
  2458. /**
  2459. * Executes the verification process.
  2460. *
  2461. * @returns A Promise for a token that can be used to assert the validity of a request.
  2462. */
  2463. RecaptchaEnterpriseVerifier.prototype.verify = function (action, forceRefresh) {
  2464. if (action === void 0) { action = 'verify'; }
  2465. if (forceRefresh === void 0) { forceRefresh = false; }
  2466. return __awaiter(this, void 0, void 0, function () {
  2467. function retrieveSiteKey(auth) {
  2468. return __awaiter(this, void 0, void 0, function () {
  2469. var _this = this;
  2470. return __generator(this, function (_a) {
  2471. if (!forceRefresh) {
  2472. if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {
  2473. return [2 /*return*/, auth._agentRecaptchaConfig.siteKey];
  2474. }
  2475. if (auth.tenantId != null &&
  2476. auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {
  2477. return [2 /*return*/, auth._tenantRecaptchaConfigs[auth.tenantId].siteKey];
  2478. }
  2479. }
  2480. return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  2481. return __generator(this, function (_a) {
  2482. getRecaptchaConfig(auth, {
  2483. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  2484. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2485. })
  2486. .then(function (response) {
  2487. if (response.recaptchaKey === undefined) {
  2488. reject(new Error('recaptcha Enterprise site key undefined'));
  2489. }
  2490. else {
  2491. var config = new RecaptchaConfig(response);
  2492. if (auth.tenantId == null) {
  2493. auth._agentRecaptchaConfig = config;
  2494. }
  2495. else {
  2496. auth._tenantRecaptchaConfigs[auth.tenantId] = config;
  2497. }
  2498. return resolve(config.siteKey);
  2499. }
  2500. })
  2501. .catch(function (error) {
  2502. reject(error);
  2503. });
  2504. return [2 /*return*/];
  2505. });
  2506. }); })];
  2507. });
  2508. });
  2509. }
  2510. function retrieveRecaptchaToken(siteKey, resolve, reject) {
  2511. var grecaptcha = window.grecaptcha;
  2512. if (isEnterprise(grecaptcha)) {
  2513. grecaptcha.enterprise.ready(function () {
  2514. grecaptcha.enterprise
  2515. .execute(siteKey, { action: action })
  2516. .then(function (token) {
  2517. resolve(token);
  2518. })
  2519. .catch(function () {
  2520. resolve(FAKE_TOKEN);
  2521. });
  2522. });
  2523. }
  2524. else {
  2525. reject(Error('No reCAPTCHA enterprise script loaded.'));
  2526. }
  2527. }
  2528. var _this = this;
  2529. return __generator(this, function (_a) {
  2530. return [2 /*return*/, new Promise(function (resolve, reject) {
  2531. retrieveSiteKey(_this.auth)
  2532. .then(function (siteKey) {
  2533. if (!forceRefresh && isEnterprise(window.grecaptcha)) {
  2534. retrieveRecaptchaToken(siteKey, resolve, reject);
  2535. }
  2536. else {
  2537. if (typeof window === 'undefined') {
  2538. reject(new Error('RecaptchaVerifier is only supported in browser'));
  2539. return;
  2540. }
  2541. _loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)
  2542. .then(function () {
  2543. retrieveRecaptchaToken(siteKey, resolve, reject);
  2544. })
  2545. .catch(function (error) {
  2546. reject(error);
  2547. });
  2548. }
  2549. })
  2550. .catch(function (error) {
  2551. reject(error);
  2552. });
  2553. })];
  2554. });
  2555. });
  2556. };
  2557. return RecaptchaEnterpriseVerifier;
  2558. }());
  2559. function injectRecaptchaFields(auth, request, action, captchaResp) {
  2560. if (captchaResp === void 0) { captchaResp = false; }
  2561. return __awaiter(this, void 0, void 0, function () {
  2562. var verifier, captchaResponse, newRequest;
  2563. return __generator(this, function (_a) {
  2564. switch (_a.label) {
  2565. case 0:
  2566. verifier = new RecaptchaEnterpriseVerifier(auth);
  2567. _a.label = 1;
  2568. case 1:
  2569. _a.trys.push([1, 3, , 5]);
  2570. return [4 /*yield*/, verifier.verify(action)];
  2571. case 2:
  2572. captchaResponse = _a.sent();
  2573. return [3 /*break*/, 5];
  2574. case 3:
  2575. _a.sent();
  2576. return [4 /*yield*/, verifier.verify(action, true)];
  2577. case 4:
  2578. captchaResponse = _a.sent();
  2579. return [3 /*break*/, 5];
  2580. case 5:
  2581. newRequest = __assign({}, request);
  2582. if (!captchaResp) {
  2583. Object.assign(newRequest, { captchaResponse: captchaResponse });
  2584. }
  2585. else {
  2586. Object.assign(newRequest, { 'captchaResp': captchaResponse });
  2587. }
  2588. Object.assign(newRequest, { 'clientType': "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */ });
  2589. Object.assign(newRequest, {
  2590. 'recaptchaVersion': "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2591. });
  2592. return [2 /*return*/, newRequest];
  2593. }
  2594. });
  2595. });
  2596. }
  2597. /**
  2598. * @license
  2599. * Copyright 2022 Google LLC
  2600. *
  2601. * Licensed under the Apache License, Version 2.0 (the "License");
  2602. * you may not use this file except in compliance with the License.
  2603. * You may obtain a copy of the License at
  2604. *
  2605. * http://www.apache.org/licenses/LICENSE-2.0
  2606. *
  2607. * Unless required by applicable law or agreed to in writing, software
  2608. * distributed under the License is distributed on an "AS IS" BASIS,
  2609. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2610. * See the License for the specific language governing permissions and
  2611. * limitations under the License.
  2612. */
  2613. var AuthMiddlewareQueue = /** @class */ (function () {
  2614. function AuthMiddlewareQueue(auth) {
  2615. this.auth = auth;
  2616. this.queue = [];
  2617. }
  2618. AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
  2619. var _this = this;
  2620. // The callback could be sync or async. Wrap it into a
  2621. // function that is always async.
  2622. var wrappedCallback = function (user) {
  2623. return new Promise(function (resolve, reject) {
  2624. try {
  2625. var result = callback(user);
  2626. // Either resolve with existing promise or wrap a non-promise
  2627. // return value into a promise.
  2628. resolve(result);
  2629. }
  2630. catch (e) {
  2631. // Sync callback throws.
  2632. reject(e);
  2633. }
  2634. });
  2635. };
  2636. // Attach the onAbort if present
  2637. wrappedCallback.onAbort = onAbort;
  2638. this.queue.push(wrappedCallback);
  2639. var index = this.queue.length - 1;
  2640. return function () {
  2641. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2642. // indexing of other elements.
  2643. _this.queue[index] = function () { return Promise.resolve(); };
  2644. };
  2645. };
  2646. AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
  2647. return __awaiter(this, void 0, void 0, function () {
  2648. var onAbortStack, _i, _a, beforeStateCallback, e_1, _b, onAbortStack_1, onAbort;
  2649. return __generator(this, function (_c) {
  2650. switch (_c.label) {
  2651. case 0:
  2652. if (this.auth.currentUser === nextUser) {
  2653. return [2 /*return*/];
  2654. }
  2655. onAbortStack = [];
  2656. _c.label = 1;
  2657. case 1:
  2658. _c.trys.push([1, 6, , 7]);
  2659. _i = 0, _a = this.queue;
  2660. _c.label = 2;
  2661. case 2:
  2662. if (!(_i < _a.length)) return [3 /*break*/, 5];
  2663. beforeStateCallback = _a[_i];
  2664. return [4 /*yield*/, beforeStateCallback(nextUser)];
  2665. case 3:
  2666. _c.sent();
  2667. // Only push the onAbort if the callback succeeds
  2668. if (beforeStateCallback.onAbort) {
  2669. onAbortStack.push(beforeStateCallback.onAbort);
  2670. }
  2671. _c.label = 4;
  2672. case 4:
  2673. _i++;
  2674. return [3 /*break*/, 2];
  2675. case 5: return [3 /*break*/, 7];
  2676. case 6:
  2677. e_1 = _c.sent();
  2678. // Run all onAbort, with separate try/catch to ignore any errors and
  2679. // continue
  2680. onAbortStack.reverse();
  2681. for (_b = 0, onAbortStack_1 = onAbortStack; _b < onAbortStack_1.length; _b++) {
  2682. onAbort = onAbortStack_1[_b];
  2683. try {
  2684. onAbort();
  2685. }
  2686. catch (_) {
  2687. /* swallow error */
  2688. }
  2689. }
  2690. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2691. originalMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message
  2692. });
  2693. case 7: return [2 /*return*/];
  2694. }
  2695. });
  2696. });
  2697. };
  2698. return AuthMiddlewareQueue;
  2699. }());
  2700. /**
  2701. * @license
  2702. * Copyright 2020 Google LLC
  2703. *
  2704. * Licensed under the Apache License, Version 2.0 (the "License");
  2705. * you may not use this file except in compliance with the License.
  2706. * You may obtain a copy of the License at
  2707. *
  2708. * http://www.apache.org/licenses/LICENSE-2.0
  2709. *
  2710. * Unless required by applicable law or agreed to in writing, software
  2711. * distributed under the License is distributed on an "AS IS" BASIS,
  2712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2713. * See the License for the specific language governing permissions and
  2714. * limitations under the License.
  2715. */
  2716. var AuthImpl = /** @class */ (function () {
  2717. function AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config) {
  2718. this.app = app;
  2719. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2720. this.appCheckServiceProvider = appCheckServiceProvider;
  2721. this.config = config;
  2722. this.currentUser = null;
  2723. this.emulatorConfig = null;
  2724. this.operations = Promise.resolve();
  2725. this.authStateSubscription = new Subscription(this);
  2726. this.idTokenSubscription = new Subscription(this);
  2727. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2728. this.redirectUser = null;
  2729. this.isProactiveRefreshEnabled = false;
  2730. // Any network calls will set this to true and prevent subsequent emulator
  2731. // initialization
  2732. this._canInitEmulator = true;
  2733. this._isInitialized = false;
  2734. this._deleted = false;
  2735. this._initializationPromise = null;
  2736. this._popupRedirectResolver = null;
  2737. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2738. this._agentRecaptchaConfig = null;
  2739. this._tenantRecaptchaConfigs = {};
  2740. // Tracks the last notified UID for state change listeners to prevent
  2741. // repeated calls to the callbacks. Undefined means it's never been
  2742. // called, whereas null means it's been called with a signed out user
  2743. this.lastNotifiedUid = undefined;
  2744. this.languageCode = null;
  2745. this.tenantId = null;
  2746. this.settings = { appVerificationDisabledForTesting: false };
  2747. this.frameworks = [];
  2748. this.name = app.name;
  2749. this.clientVersion = config.sdkClientVersion;
  2750. }
  2751. AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
  2752. var _this = this;
  2753. if (popupRedirectResolver) {
  2754. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2755. }
  2756. // Have to check for app deletion throughout initialization (after each
  2757. // promise resolution)
  2758. this._initializationPromise = this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  2759. var _a;
  2760. var _b, _c;
  2761. return __generator(this, function (_d) {
  2762. switch (_d.label) {
  2763. case 0:
  2764. if (this._deleted) {
  2765. return [2 /*return*/];
  2766. }
  2767. _a = this;
  2768. return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
  2769. case 1:
  2770. _a.persistenceManager = _d.sent();
  2771. if (this._deleted) {
  2772. return [2 /*return*/];
  2773. }
  2774. if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
  2775. _d.label = 2;
  2776. case 2:
  2777. _d.trys.push([2, 4, , 5]);
  2778. return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
  2779. case 3:
  2780. _d.sent();
  2781. return [3 /*break*/, 5];
  2782. case 4:
  2783. _d.sent();
  2784. return [3 /*break*/, 5];
  2785. case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
  2786. case 6:
  2787. _d.sent();
  2788. this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
  2789. if (this._deleted) {
  2790. return [2 /*return*/];
  2791. }
  2792. this._isInitialized = true;
  2793. return [2 /*return*/];
  2794. }
  2795. });
  2796. }); });
  2797. return this._initializationPromise;
  2798. };
  2799. /**
  2800. * If the persistence is changed in another window, the user manager will let us know
  2801. */
  2802. AuthImpl.prototype._onStorageEvent = function () {
  2803. return __awaiter(this, void 0, void 0, function () {
  2804. var user;
  2805. return __generator(this, function (_a) {
  2806. switch (_a.label) {
  2807. case 0:
  2808. if (this._deleted) {
  2809. return [2 /*return*/];
  2810. }
  2811. return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2812. case 1:
  2813. user = _a.sent();
  2814. if (!this.currentUser && !user) {
  2815. // No change, do nothing (was signed out and remained signed out).
  2816. return [2 /*return*/];
  2817. }
  2818. if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
  2819. // Data update, simply copy data changes.
  2820. this._currentUser._assign(user);
  2821. // If tokens changed from previous user tokens, this will trigger
  2822. // notifyAuthListeners_.
  2823. return [4 /*yield*/, this.currentUser.getIdToken()];
  2824. case 2:
  2825. // If tokens changed from previous user tokens, this will trigger
  2826. // notifyAuthListeners_.
  2827. _a.sent();
  2828. return [2 /*return*/];
  2829. case 3:
  2830. // Update current Auth state. Either a new login or logout.
  2831. // Skip blocking callbacks, they should not apply to a change in another tab.
  2832. return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
  2833. case 4:
  2834. // Update current Auth state. Either a new login or logout.
  2835. // Skip blocking callbacks, they should not apply to a change in another tab.
  2836. _a.sent();
  2837. return [2 /*return*/];
  2838. }
  2839. });
  2840. });
  2841. };
  2842. AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
  2843. var _a;
  2844. return __awaiter(this, void 0, void 0, function () {
  2845. var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
  2846. return __generator(this, function (_b) {
  2847. switch (_b.label) {
  2848. case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2849. case 1:
  2850. previouslyStoredUser = (_b.sent());
  2851. futureCurrentUser = previouslyStoredUser;
  2852. needsTocheckMiddleware = false;
  2853. if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
  2854. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2855. case 2:
  2856. _b.sent();
  2857. redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2858. storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2859. return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
  2860. case 3:
  2861. result = _b.sent();
  2862. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2863. // matches the redirect user, then we want to initially sign in with the
  2864. // new user object from result.
  2865. // TODO(samgho): More thoroughly test all of this
  2866. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2867. (result === null || result === void 0 ? void 0 : result.user)) {
  2868. futureCurrentUser = result.user;
  2869. needsTocheckMiddleware = true;
  2870. }
  2871. _b.label = 4;
  2872. case 4:
  2873. // If no user in persistence, there is no current user. Set to null.
  2874. if (!futureCurrentUser) {
  2875. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2876. }
  2877. if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
  2878. if (!needsTocheckMiddleware) return [3 /*break*/, 8];
  2879. _b.label = 5;
  2880. case 5:
  2881. _b.trys.push([5, 7, , 8]);
  2882. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
  2883. case 6:
  2884. _b.sent();
  2885. return [3 /*break*/, 8];
  2886. case 7:
  2887. e_2 = _b.sent();
  2888. futureCurrentUser = previouslyStoredUser;
  2889. // We know this is available since the bit is only set when the
  2890. // resolver is available
  2891. this._popupRedirectResolver._overrideRedirectResult(this, function () {
  2892. return Promise.reject(e_2);
  2893. });
  2894. return [3 /*break*/, 8];
  2895. case 8:
  2896. if (futureCurrentUser) {
  2897. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2898. }
  2899. else {
  2900. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2901. }
  2902. case 9:
  2903. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2904. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2905. case 10:
  2906. _b.sent();
  2907. // If the redirect user's event ID matches the current user's event ID,
  2908. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  2909. // This is important for the reauthenticateWithRedirect() flow.
  2910. if (this.redirectUser &&
  2911. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  2912. return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
  2913. }
  2914. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2915. }
  2916. });
  2917. });
  2918. };
  2919. AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
  2920. return __awaiter(this, void 0, void 0, function () {
  2921. var result;
  2922. return __generator(this, function (_a) {
  2923. switch (_a.label) {
  2924. case 0:
  2925. result = null;
  2926. _a.label = 1;
  2927. case 1:
  2928. _a.trys.push([1, 3, , 5]);
  2929. return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
  2930. case 2:
  2931. // We know this._popupRedirectResolver is set since redirectResolver
  2932. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  2933. result = _a.sent();
  2934. return [3 /*break*/, 5];
  2935. case 3:
  2936. _a.sent();
  2937. // Swallow any errors here; the code can retrieve them in
  2938. // getRedirectResult().
  2939. return [4 /*yield*/, this._setRedirectUser(null)];
  2940. case 4:
  2941. // Swallow any errors here; the code can retrieve them in
  2942. // getRedirectResult().
  2943. _a.sent();
  2944. return [3 /*break*/, 5];
  2945. case 5: return [2 /*return*/, result];
  2946. }
  2947. });
  2948. });
  2949. };
  2950. AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
  2951. return __awaiter(this, void 0, void 0, function () {
  2952. var e_4;
  2953. return __generator(this, function (_a) {
  2954. switch (_a.label) {
  2955. case 0:
  2956. _a.trys.push([0, 2, , 3]);
  2957. return [4 /*yield*/, _reloadWithoutSaving(user)];
  2958. case 1:
  2959. _a.sent();
  2960. return [3 /*break*/, 3];
  2961. case 2:
  2962. e_4 = _a.sent();
  2963. if ((e_4 === null || e_4 === void 0 ? void 0 : e_4.code) !==
  2964. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  2965. // Something's wrong with the user's token. Log them out and remove
  2966. // them from storage
  2967. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2968. }
  2969. return [3 /*break*/, 3];
  2970. case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
  2971. }
  2972. });
  2973. });
  2974. };
  2975. AuthImpl.prototype.useDeviceLanguage = function () {
  2976. this.languageCode = _getUserLanguage();
  2977. };
  2978. AuthImpl.prototype._delete = function () {
  2979. return __awaiter(this, void 0, void 0, function () {
  2980. return __generator(this, function (_a) {
  2981. this._deleted = true;
  2982. return [2 /*return*/];
  2983. });
  2984. });
  2985. };
  2986. AuthImpl.prototype.updateCurrentUser = function (userExtern) {
  2987. return __awaiter(this, void 0, void 0, function () {
  2988. var user;
  2989. return __generator(this, function (_a) {
  2990. user = userExtern
  2991. ? getModularInstance(userExtern)
  2992. : null;
  2993. if (user) {
  2994. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  2995. }
  2996. return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
  2997. });
  2998. });
  2999. };
  3000. AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
  3001. if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
  3002. return __awaiter(this, void 0, void 0, function () {
  3003. var _this = this;
  3004. return __generator(this, function (_a) {
  3005. switch (_a.label) {
  3006. case 0:
  3007. if (this._deleted) {
  3008. return [2 /*return*/];
  3009. }
  3010. if (user) {
  3011. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  3012. }
  3013. if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
  3014. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
  3015. case 1:
  3016. _a.sent();
  3017. _a.label = 2;
  3018. case 2: return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  3019. return __generator(this, function (_a) {
  3020. switch (_a.label) {
  3021. case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
  3022. case 1:
  3023. _a.sent();
  3024. this.notifyAuthListeners();
  3025. return [2 /*return*/];
  3026. }
  3027. });
  3028. }); })];
  3029. }
  3030. });
  3031. });
  3032. };
  3033. AuthImpl.prototype.signOut = function () {
  3034. return __awaiter(this, void 0, void 0, function () {
  3035. return __generator(this, function (_a) {
  3036. switch (_a.label) {
  3037. case 0:
  3038. // Run first, to block _setRedirectUser() if any callbacks fail.
  3039. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
  3040. case 1:
  3041. // Run first, to block _setRedirectUser() if any callbacks fail.
  3042. _a.sent();
  3043. if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
  3044. return [4 /*yield*/, this._setRedirectUser(null)];
  3045. case 2:
  3046. _a.sent();
  3047. _a.label = 3;
  3048. case 3:
  3049. // Prevent callbacks from being called again in _updateCurrentUser, as
  3050. // they were already called in the first line.
  3051. return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
  3052. }
  3053. });
  3054. });
  3055. };
  3056. AuthImpl.prototype.setPersistence = function (persistence) {
  3057. var _this = this;
  3058. return this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  3059. return __generator(this, function (_a) {
  3060. switch (_a.label) {
  3061. case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
  3062. case 1:
  3063. _a.sent();
  3064. return [2 /*return*/];
  3065. }
  3066. });
  3067. }); });
  3068. };
  3069. AuthImpl.prototype.initializeRecaptchaConfig = function () {
  3070. return __awaiter(this, void 0, void 0, function () {
  3071. var response, config, verifier;
  3072. return __generator(this, function (_a) {
  3073. switch (_a.label) {
  3074. case 0: return [4 /*yield*/, getRecaptchaConfig(this, {
  3075. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  3076. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  3077. })];
  3078. case 1:
  3079. response = _a.sent();
  3080. config = new RecaptchaConfig(response);
  3081. if (this.tenantId == null) {
  3082. this._agentRecaptchaConfig = config;
  3083. }
  3084. else {
  3085. this._tenantRecaptchaConfigs[this.tenantId] = config;
  3086. }
  3087. if (config.emailPasswordEnabled) {
  3088. verifier = new RecaptchaEnterpriseVerifier(this);
  3089. void verifier.verify();
  3090. }
  3091. return [2 /*return*/];
  3092. }
  3093. });
  3094. });
  3095. };
  3096. AuthImpl.prototype._getRecaptchaConfig = function () {
  3097. if (this.tenantId == null) {
  3098. return this._agentRecaptchaConfig;
  3099. }
  3100. else {
  3101. return this._tenantRecaptchaConfigs[this.tenantId];
  3102. }
  3103. };
  3104. AuthImpl.prototype._getPersistence = function () {
  3105. return this.assertedPersistence.persistence.type;
  3106. };
  3107. AuthImpl.prototype._updateErrorMap = function (errorMap) {
  3108. this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
  3109. };
  3110. AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
  3111. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  3112. };
  3113. AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
  3114. return this.beforeStateQueue.pushCallback(callback, onAbort);
  3115. };
  3116. AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
  3117. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  3118. };
  3119. AuthImpl.prototype.toJSON = function () {
  3120. var _a;
  3121. return {
  3122. apiKey: this.config.apiKey,
  3123. authDomain: this.config.authDomain,
  3124. appName: this.name,
  3125. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  3126. };
  3127. };
  3128. AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
  3129. return __awaiter(this, void 0, void 0, function () {
  3130. var redirectManager;
  3131. return __generator(this, function (_a) {
  3132. switch (_a.label) {
  3133. case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
  3134. case 1:
  3135. redirectManager = _a.sent();
  3136. return [2 /*return*/, user === null
  3137. ? redirectManager.removeCurrentUser()
  3138. : redirectManager.setCurrentUser(user)];
  3139. }
  3140. });
  3141. });
  3142. };
  3143. AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
  3144. return __awaiter(this, void 0, void 0, function () {
  3145. var resolver, _a, _b;
  3146. return __generator(this, function (_c) {
  3147. switch (_c.label) {
  3148. case 0:
  3149. if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
  3150. resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  3151. this._popupRedirectResolver;
  3152. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3153. _a = this;
  3154. return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */)];
  3155. case 1:
  3156. _a.redirectPersistenceManager = _c.sent();
  3157. _b = this;
  3158. return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
  3159. case 2:
  3160. _b.redirectUser =
  3161. _c.sent();
  3162. _c.label = 3;
  3163. case 3: return [2 /*return*/, this.redirectPersistenceManager];
  3164. }
  3165. });
  3166. });
  3167. };
  3168. AuthImpl.prototype._redirectUserForId = function (id) {
  3169. var _a, _b;
  3170. return __awaiter(this, void 0, void 0, function () {
  3171. var _this = this;
  3172. return __generator(this, function (_c) {
  3173. switch (_c.label) {
  3174. case 0:
  3175. if (!this._isInitialized) return [3 /*break*/, 2];
  3176. return [4 /*yield*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  3177. return [2 /*return*/];
  3178. }); }); })];
  3179. case 1:
  3180. _c.sent();
  3181. _c.label = 2;
  3182. case 2:
  3183. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  3184. return [2 /*return*/, this._currentUser];
  3185. }
  3186. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  3187. return [2 /*return*/, this.redirectUser];
  3188. }
  3189. return [2 /*return*/, null];
  3190. }
  3191. });
  3192. });
  3193. };
  3194. AuthImpl.prototype._persistUserIfCurrent = function (user) {
  3195. return __awaiter(this, void 0, void 0, function () {
  3196. var _this = this;
  3197. return __generator(this, function (_a) {
  3198. if (user === this.currentUser) {
  3199. return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  3200. return [2 /*return*/, this.directlySetCurrentUser(user)];
  3201. }); }); })];
  3202. }
  3203. return [2 /*return*/];
  3204. });
  3205. });
  3206. };
  3207. /** Notifies listeners only if the user is current */
  3208. AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
  3209. if (user === this.currentUser) {
  3210. this.notifyAuthListeners();
  3211. }
  3212. };
  3213. AuthImpl.prototype._key = function () {
  3214. return "".concat(this.config.authDomain, ":").concat(this.config.apiKey, ":").concat(this.name);
  3215. };
  3216. AuthImpl.prototype._startProactiveRefresh = function () {
  3217. this.isProactiveRefreshEnabled = true;
  3218. if (this.currentUser) {
  3219. this._currentUser._startProactiveRefresh();
  3220. }
  3221. };
  3222. AuthImpl.prototype._stopProactiveRefresh = function () {
  3223. this.isProactiveRefreshEnabled = false;
  3224. if (this.currentUser) {
  3225. this._currentUser._stopProactiveRefresh();
  3226. }
  3227. };
  3228. Object.defineProperty(AuthImpl.prototype, "_currentUser", {
  3229. /** Returns the current user cast as the internal type */
  3230. get: function () {
  3231. return this.currentUser;
  3232. },
  3233. enumerable: false,
  3234. configurable: true
  3235. });
  3236. AuthImpl.prototype.notifyAuthListeners = function () {
  3237. var _a, _b;
  3238. if (!this._isInitialized) {
  3239. return;
  3240. }
  3241. this.idTokenSubscription.next(this.currentUser);
  3242. var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  3243. if (this.lastNotifiedUid !== currentUid) {
  3244. this.lastNotifiedUid = currentUid;
  3245. this.authStateSubscription.next(this.currentUser);
  3246. }
  3247. };
  3248. AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
  3249. var _this = this;
  3250. if (this._deleted) {
  3251. return function () { };
  3252. }
  3253. var cb = typeof nextOrObserver === 'function'
  3254. ? nextOrObserver
  3255. : nextOrObserver.next.bind(nextOrObserver);
  3256. var promise = this._isInitialized
  3257. ? Promise.resolve()
  3258. : this._initializationPromise;
  3259. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3260. // The callback needs to be called asynchronously per the spec.
  3261. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  3262. promise.then(function () { return cb(_this.currentUser); });
  3263. if (typeof nextOrObserver === 'function') {
  3264. return subscription.addObserver(nextOrObserver, error, completed);
  3265. }
  3266. else {
  3267. return subscription.addObserver(nextOrObserver);
  3268. }
  3269. };
  3270. /**
  3271. * Unprotected (from race conditions) method to set the current user. This
  3272. * should only be called from within a queued callback. This is necessary
  3273. * because the queue shouldn't rely on another queued callback.
  3274. */
  3275. AuthImpl.prototype.directlySetCurrentUser = function (user) {
  3276. return __awaiter(this, void 0, void 0, function () {
  3277. return __generator(this, function (_a) {
  3278. switch (_a.label) {
  3279. case 0:
  3280. if (this.currentUser && this.currentUser !== user) {
  3281. this._currentUser._stopProactiveRefresh();
  3282. }
  3283. if (user && this.isProactiveRefreshEnabled) {
  3284. user._startProactiveRefresh();
  3285. }
  3286. this.currentUser = user;
  3287. if (!user) return [3 /*break*/, 2];
  3288. return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
  3289. case 1:
  3290. _a.sent();
  3291. return [3 /*break*/, 4];
  3292. case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
  3293. case 3:
  3294. _a.sent();
  3295. _a.label = 4;
  3296. case 4: return [2 /*return*/];
  3297. }
  3298. });
  3299. });
  3300. };
  3301. AuthImpl.prototype.queue = function (action) {
  3302. // In case something errors, the callback still should be called in order
  3303. // to keep the promise chain alive
  3304. this.operations = this.operations.then(action, action);
  3305. return this.operations;
  3306. };
  3307. Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
  3308. get: function () {
  3309. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3310. return this.persistenceManager;
  3311. },
  3312. enumerable: false,
  3313. configurable: true
  3314. });
  3315. AuthImpl.prototype._logFramework = function (framework) {
  3316. if (!framework || this.frameworks.includes(framework)) {
  3317. return;
  3318. }
  3319. this.frameworks.push(framework);
  3320. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  3321. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  3322. this.frameworks.sort();
  3323. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  3324. };
  3325. AuthImpl.prototype._getFrameworks = function () {
  3326. return this.frameworks;
  3327. };
  3328. AuthImpl.prototype._getAdditionalHeaders = function () {
  3329. var _a;
  3330. return __awaiter(this, void 0, void 0, function () {
  3331. var headers, heartbeatsHeader, appCheckToken;
  3332. var _b;
  3333. return __generator(this, function (_c) {
  3334. switch (_c.label) {
  3335. case 0:
  3336. headers = (_b = {},
  3337. _b["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */] = this.clientVersion,
  3338. _b);
  3339. if (this.app.options.appId) {
  3340. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  3341. }
  3342. return [4 /*yield*/, ((_a = this.heartbeatServiceProvider
  3343. .getImmediate({
  3344. optional: true
  3345. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
  3346. case 1:
  3347. heartbeatsHeader = _c.sent();
  3348. if (heartbeatsHeader) {
  3349. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  3350. }
  3351. return [4 /*yield*/, this._getAppCheckToken()];
  3352. case 2:
  3353. appCheckToken = _c.sent();
  3354. if (appCheckToken) {
  3355. headers["X-Firebase-AppCheck" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;
  3356. }
  3357. return [2 /*return*/, headers];
  3358. }
  3359. });
  3360. });
  3361. };
  3362. AuthImpl.prototype._getAppCheckToken = function () {
  3363. var _a;
  3364. return __awaiter(this, void 0, void 0, function () {
  3365. var appCheckTokenResult;
  3366. return __generator(this, function (_b) {
  3367. switch (_b.label) {
  3368. case 0: return [4 /*yield*/, ((_a = this.appCheckServiceProvider
  3369. .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken())];
  3370. case 1:
  3371. appCheckTokenResult = _b.sent();
  3372. if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {
  3373. // Context: appCheck.getToken() will never throw even if an error happened.
  3374. // In the error case, a dummy token will be returned along with an error field describing
  3375. // the error. In general, we shouldn't care about the error condition and just use
  3376. // the token (actual or dummy) to send requests.
  3377. _logWarn("Error while retrieving App Check token: ".concat(appCheckTokenResult.error));
  3378. }
  3379. return [2 /*return*/, appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token];
  3380. }
  3381. });
  3382. });
  3383. };
  3384. return AuthImpl;
  3385. }());
  3386. /**
  3387. * Method to be used to cast down to our private implmentation of Auth.
  3388. * It will also handle unwrapping from the compat type if necessary
  3389. *
  3390. * @param auth Auth object passed in from developer
  3391. */
  3392. function _castAuth(auth) {
  3393. return getModularInstance(auth);
  3394. }
  3395. /** Helper class to wrap subscriber logic */
  3396. var Subscription = /** @class */ (function () {
  3397. function Subscription(auth) {
  3398. var _this = this;
  3399. this.auth = auth;
  3400. this.observer = null;
  3401. this.addObserver = createSubscribe(function (observer) { return (_this.observer = observer); });
  3402. }
  3403. Object.defineProperty(Subscription.prototype, "next", {
  3404. get: function () {
  3405. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3406. return this.observer.next.bind(this.observer);
  3407. },
  3408. enumerable: false,
  3409. configurable: true
  3410. });
  3411. return Subscription;
  3412. }());
  3413. /**
  3414. * @license
  3415. * Copyright 2020 Google LLC
  3416. *
  3417. * Licensed under the Apache License, Version 2.0 (the "License");
  3418. * you may not use this file except in compliance with the License.
  3419. * You may obtain a copy of the License at
  3420. *
  3421. * http://www.apache.org/licenses/LICENSE-2.0
  3422. *
  3423. * Unless required by applicable law or agreed to in writing, software
  3424. * distributed under the License is distributed on an "AS IS" BASIS,
  3425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3426. * See the License for the specific language governing permissions and
  3427. * limitations under the License.
  3428. */
  3429. var AuthInterop = /** @class */ (function () {
  3430. function AuthInterop(auth) {
  3431. this.auth = auth;
  3432. this.internalListeners = new Map();
  3433. }
  3434. AuthInterop.prototype.getUid = function () {
  3435. var _a;
  3436. this.assertAuthConfigured();
  3437. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  3438. };
  3439. AuthInterop.prototype.getToken = function (forceRefresh) {
  3440. return __awaiter(this, void 0, void 0, function () {
  3441. var accessToken;
  3442. return __generator(this, function (_a) {
  3443. switch (_a.label) {
  3444. case 0:
  3445. this.assertAuthConfigured();
  3446. return [4 /*yield*/, this.auth._initializationPromise];
  3447. case 1:
  3448. _a.sent();
  3449. if (!this.auth.currentUser) {
  3450. return [2 /*return*/, null];
  3451. }
  3452. return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
  3453. case 2:
  3454. accessToken = _a.sent();
  3455. return [2 /*return*/, { accessToken: accessToken }];
  3456. }
  3457. });
  3458. });
  3459. };
  3460. AuthInterop.prototype.addAuthTokenListener = function (listener) {
  3461. this.assertAuthConfigured();
  3462. if (this.internalListeners.has(listener)) {
  3463. return;
  3464. }
  3465. var unsubscribe = this.auth.onIdTokenChanged(function (user) {
  3466. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  3467. });
  3468. this.internalListeners.set(listener, unsubscribe);
  3469. this.updateProactiveRefresh();
  3470. };
  3471. AuthInterop.prototype.removeAuthTokenListener = function (listener) {
  3472. this.assertAuthConfigured();
  3473. var unsubscribe = this.internalListeners.get(listener);
  3474. if (!unsubscribe) {
  3475. return;
  3476. }
  3477. this.internalListeners.delete(listener);
  3478. unsubscribe();
  3479. this.updateProactiveRefresh();
  3480. };
  3481. AuthInterop.prototype.assertAuthConfigured = function () {
  3482. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  3483. };
  3484. AuthInterop.prototype.updateProactiveRefresh = function () {
  3485. if (this.internalListeners.size > 0) {
  3486. this.auth._startProactiveRefresh();
  3487. }
  3488. else {
  3489. this.auth._stopProactiveRefresh();
  3490. }
  3491. };
  3492. return AuthInterop;
  3493. }());
  3494. /**
  3495. * @license
  3496. * Copyright 2020 Google LLC
  3497. *
  3498. * Licensed under the Apache License, Version 2.0 (the "License");
  3499. * you may not use this file except in compliance with the License.
  3500. * You may obtain a copy of the License at
  3501. *
  3502. * http://www.apache.org/licenses/LICENSE-2.0
  3503. *
  3504. * Unless required by applicable law or agreed to in writing, software
  3505. * distributed under the License is distributed on an "AS IS" BASIS,
  3506. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3507. * See the License for the specific language governing permissions and
  3508. * limitations under the License.
  3509. */
  3510. function getVersionForPlatform(clientPlatform) {
  3511. switch (clientPlatform) {
  3512. case "Node" /* ClientPlatform.NODE */:
  3513. return 'node';
  3514. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  3515. return 'rn';
  3516. case "Worker" /* ClientPlatform.WORKER */:
  3517. return 'webworker';
  3518. case "Cordova" /* ClientPlatform.CORDOVA */:
  3519. return 'cordova';
  3520. default:
  3521. return undefined;
  3522. }
  3523. }
  3524. /** @internal */
  3525. function registerAuth(clientPlatform) {
  3526. _registerComponent(new Component("auth" /* _ComponentName.AUTH */, function (container, _a) {
  3527. var deps = _a.options;
  3528. var app = container.getProvider('app').getImmediate();
  3529. var heartbeatServiceProvider = container.getProvider('heartbeat');
  3530. var appCheckServiceProvider = container.getProvider('app-check-internal');
  3531. var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
  3532. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  3533. var config = {
  3534. apiKey: apiKey,
  3535. authDomain: authDomain,
  3536. clientPlatform: clientPlatform,
  3537. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  3538. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  3539. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  3540. sdkClientVersion: _getClientVersion(clientPlatform)
  3541. };
  3542. var authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);
  3543. _initializeAuthInstance(authInstance, deps);
  3544. return authInstance;
  3545. }, "PUBLIC" /* ComponentType.PUBLIC */)
  3546. /**
  3547. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  3548. * For why we do this, See go/firebase-next-auth-init
  3549. */
  3550. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  3551. /**
  3552. * Because all firebase products that depend on auth depend on auth-internal directly,
  3553. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  3554. */
  3555. .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
  3556. var authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  3557. authInternalProvider.initialize();
  3558. }));
  3559. _registerComponent(new Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, function (container) {
  3560. var auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  3561. return (function (auth) { return new AuthInterop(auth); })(auth);
  3562. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  3563. registerVersion(name, version, getVersionForPlatform(clientPlatform));
  3564. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  3565. registerVersion(name, version, 'esm5');
  3566. }
  3567. var STORAGE_AVAILABLE_KEY = '__sak';
  3568. /**
  3569. * @license
  3570. * Copyright 2019 Google LLC
  3571. *
  3572. * Licensed under the Apache License, Version 2.0 (the "License");
  3573. * you may not use this file except in compliance with the License.
  3574. * You may obtain a copy of the License at
  3575. *
  3576. * http://www.apache.org/licenses/LICENSE-2.0
  3577. *
  3578. * Unless required by applicable law or agreed to in writing, software
  3579. * distributed under the License is distributed on an "AS IS" BASIS,
  3580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3581. * See the License for the specific language governing permissions and
  3582. * limitations under the License.
  3583. */
  3584. /**
  3585. * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
  3586. *
  3587. * @param promises - Array of promises to wait on.
  3588. */
  3589. function _allSettled(promises) {
  3590. var _this = this;
  3591. return Promise.all(promises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
  3592. var value, reason_1;
  3593. return __generator(this, function (_a) {
  3594. switch (_a.label) {
  3595. case 0:
  3596. _a.trys.push([0, 2, , 3]);
  3597. return [4 /*yield*/, promise];
  3598. case 1:
  3599. value = _a.sent();
  3600. return [2 /*return*/, {
  3601. fulfilled: true,
  3602. value: value
  3603. }];
  3604. case 2:
  3605. reason_1 = _a.sent();
  3606. return [2 /*return*/, {
  3607. fulfilled: false,
  3608. reason: reason_1
  3609. }];
  3610. case 3: return [2 /*return*/];
  3611. }
  3612. });
  3613. }); }));
  3614. }
  3615. /**
  3616. * @license
  3617. * Copyright 2019 Google LLC
  3618. *
  3619. * Licensed under the Apache License, Version 2.0 (the "License");
  3620. * you may not use this file except in compliance with the License.
  3621. * You may obtain a copy of the License at
  3622. *
  3623. * http://www.apache.org/licenses/LICENSE-2.0
  3624. *
  3625. * Unless required by applicable law or agreed to in writing, software
  3626. * distributed under the License is distributed on an "AS IS" BASIS,
  3627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3628. * See the License for the specific language governing permissions and
  3629. * limitations under the License.
  3630. */
  3631. /**
  3632. * Interface class for receiving messages.
  3633. *
  3634. */
  3635. var Receiver = /** @class */ (function () {
  3636. function Receiver(eventTarget) {
  3637. this.eventTarget = eventTarget;
  3638. this.handlersMap = {};
  3639. this.boundEventHandler = this.handleEvent.bind(this);
  3640. }
  3641. /**
  3642. * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
  3643. *
  3644. * @param eventTarget - An event target (such as window or self) through which the underlying
  3645. * messages will be received.
  3646. */
  3647. Receiver._getInstance = function (eventTarget) {
  3648. // The results are stored in an array since objects can't be keys for other
  3649. // objects. In addition, setting a unique property on an event target as a
  3650. // hash map key may not be allowed due to CORS restrictions.
  3651. var existingInstance = this.receivers.find(function (receiver) {
  3652. return receiver.isListeningto(eventTarget);
  3653. });
  3654. if (existingInstance) {
  3655. return existingInstance;
  3656. }
  3657. var newInstance = new Receiver(eventTarget);
  3658. this.receivers.push(newInstance);
  3659. return newInstance;
  3660. };
  3661. Receiver.prototype.isListeningto = function (eventTarget) {
  3662. return this.eventTarget === eventTarget;
  3663. };
  3664. /**
  3665. * Fans out a MessageEvent to the appropriate listeners.
  3666. *
  3667. * @remarks
  3668. * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
  3669. * finished processing.
  3670. *
  3671. * @param event - The MessageEvent.
  3672. *
  3673. */
  3674. Receiver.prototype.handleEvent = function (event) {
  3675. return __awaiter(this, void 0, void 0, function () {
  3676. var messageEvent, _a, eventId, eventType, data, handlers, promises, response;
  3677. var _this = this;
  3678. return __generator(this, function (_b) {
  3679. switch (_b.label) {
  3680. case 0:
  3681. messageEvent = event;
  3682. _a = messageEvent.data, eventId = _a.eventId, eventType = _a.eventType, data = _a.data;
  3683. handlers = this.handlersMap[eventType];
  3684. if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
  3685. return [2 /*return*/];
  3686. }
  3687. messageEvent.ports[0].postMessage({
  3688. status: "ack" /* _Status.ACK */,
  3689. eventId: eventId,
  3690. eventType: eventType
  3691. });
  3692. promises = Array.from(handlers).map(function (handler) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  3693. return [2 /*return*/, handler(messageEvent.origin, data)];
  3694. }); }); });
  3695. return [4 /*yield*/, _allSettled(promises)];
  3696. case 1:
  3697. response = _b.sent();
  3698. messageEvent.ports[0].postMessage({
  3699. status: "done" /* _Status.DONE */,
  3700. eventId: eventId,
  3701. eventType: eventType,
  3702. response: response
  3703. });
  3704. return [2 /*return*/];
  3705. }
  3706. });
  3707. });
  3708. };
  3709. /**
  3710. * Subscribe an event handler for a particular event.
  3711. *
  3712. * @param eventType - Event name to subscribe to.
  3713. * @param eventHandler - The event handler which should receive the events.
  3714. *
  3715. */
  3716. Receiver.prototype._subscribe = function (eventType, eventHandler) {
  3717. if (Object.keys(this.handlersMap).length === 0) {
  3718. this.eventTarget.addEventListener('message', this.boundEventHandler);
  3719. }
  3720. if (!this.handlersMap[eventType]) {
  3721. this.handlersMap[eventType] = new Set();
  3722. }
  3723. this.handlersMap[eventType].add(eventHandler);
  3724. };
  3725. /**
  3726. * Unsubscribe an event handler from a particular event.
  3727. *
  3728. * @param eventType - Event name to unsubscribe from.
  3729. * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
  3730. *
  3731. */
  3732. Receiver.prototype._unsubscribe = function (eventType, eventHandler) {
  3733. if (this.handlersMap[eventType] && eventHandler) {
  3734. this.handlersMap[eventType].delete(eventHandler);
  3735. }
  3736. if (!eventHandler || this.handlersMap[eventType].size === 0) {
  3737. delete this.handlersMap[eventType];
  3738. }
  3739. if (Object.keys(this.handlersMap).length === 0) {
  3740. this.eventTarget.removeEventListener('message', this.boundEventHandler);
  3741. }
  3742. };
  3743. Receiver.receivers = [];
  3744. return Receiver;
  3745. }());
  3746. /**
  3747. * @license
  3748. * Copyright 2020 Google LLC
  3749. *
  3750. * Licensed under the Apache License, Version 2.0 (the "License");
  3751. * you may not use this file except in compliance with the License.
  3752. * You may obtain a copy of the License at
  3753. *
  3754. * http://www.apache.org/licenses/LICENSE-2.0
  3755. *
  3756. * Unless required by applicable law or agreed to in writing, software
  3757. * distributed under the License is distributed on an "AS IS" BASIS,
  3758. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3759. * See the License for the specific language governing permissions and
  3760. * limitations under the License.
  3761. */
  3762. function _generateEventId(prefix, digits) {
  3763. if (prefix === void 0) { prefix = ''; }
  3764. if (digits === void 0) { digits = 10; }
  3765. var random = '';
  3766. for (var i = 0; i < digits; i++) {
  3767. random += Math.floor(Math.random() * 10);
  3768. }
  3769. return prefix + random;
  3770. }
  3771. /**
  3772. * @license
  3773. * Copyright 2019 Google LLC
  3774. *
  3775. * Licensed under the Apache License, Version 2.0 (the "License");
  3776. * you may not use this file except in compliance with the License.
  3777. * You may obtain a copy of the License at
  3778. *
  3779. * http://www.apache.org/licenses/LICENSE-2.0
  3780. *
  3781. * Unless required by applicable law or agreed to in writing, software
  3782. * distributed under the License is distributed on an "AS IS" BASIS,
  3783. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3784. * See the License for the specific language governing permissions and
  3785. * limitations under the License.
  3786. */
  3787. /**
  3788. * Interface for sending messages and waiting for a completion response.
  3789. *
  3790. */
  3791. var Sender = /** @class */ (function () {
  3792. function Sender(target) {
  3793. this.target = target;
  3794. this.handlers = new Set();
  3795. }
  3796. /**
  3797. * Unsubscribe the handler and remove it from our tracking Set.
  3798. *
  3799. * @param handler - The handler to unsubscribe.
  3800. */
  3801. Sender.prototype.removeMessageHandler = function (handler) {
  3802. if (handler.messageChannel) {
  3803. handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
  3804. handler.messageChannel.port1.close();
  3805. }
  3806. this.handlers.delete(handler);
  3807. };
  3808. /**
  3809. * Send a message to the Receiver located at {@link target}.
  3810. *
  3811. * @remarks
  3812. * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
  3813. * receiver has had a chance to fully process the event.
  3814. *
  3815. * @param eventType - Type of event to send.
  3816. * @param data - The payload of the event.
  3817. * @param timeout - Timeout for waiting on an ACK from the receiver.
  3818. *
  3819. * @returns An array of settled promises from all the handlers that were listening on the receiver.
  3820. */
  3821. Sender.prototype._send = function (eventType, data, timeout) {
  3822. if (timeout === void 0) { timeout = 50 /* _TimeoutDuration.ACK */; }
  3823. return __awaiter(this, void 0, void 0, function () {
  3824. var messageChannel, completionTimer, handler;
  3825. var _this = this;
  3826. return __generator(this, function (_a) {
  3827. messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
  3828. if (!messageChannel) {
  3829. throw new Error("connection_unavailable" /* _MessageError.CONNECTION_UNAVAILABLE */);
  3830. }
  3831. return [2 /*return*/, new Promise(function (resolve, reject) {
  3832. var eventId = _generateEventId('', 20);
  3833. messageChannel.port1.start();
  3834. var ackTimer = setTimeout(function () {
  3835. reject(new Error("unsupported_event" /* _MessageError.UNSUPPORTED_EVENT */));
  3836. }, timeout);
  3837. handler = {
  3838. messageChannel: messageChannel,
  3839. onMessage: function (event) {
  3840. var messageEvent = event;
  3841. if (messageEvent.data.eventId !== eventId) {
  3842. return;
  3843. }
  3844. switch (messageEvent.data.status) {
  3845. case "ack" /* _Status.ACK */:
  3846. // The receiver should ACK first.
  3847. clearTimeout(ackTimer);
  3848. completionTimer = setTimeout(function () {
  3849. reject(new Error("timeout" /* _MessageError.TIMEOUT */));
  3850. }, 3000 /* _TimeoutDuration.COMPLETION */);
  3851. break;
  3852. case "done" /* _Status.DONE */:
  3853. // Once the receiver's handlers are finished we will get the results.
  3854. clearTimeout(completionTimer);
  3855. resolve(messageEvent.data.response);
  3856. break;
  3857. default:
  3858. clearTimeout(ackTimer);
  3859. clearTimeout(completionTimer);
  3860. reject(new Error("invalid_response" /* _MessageError.INVALID_RESPONSE */));
  3861. break;
  3862. }
  3863. }
  3864. };
  3865. _this.handlers.add(handler);
  3866. messageChannel.port1.addEventListener('message', handler.onMessage);
  3867. _this.target.postMessage({
  3868. eventType: eventType,
  3869. eventId: eventId,
  3870. data: data
  3871. }, [messageChannel.port2]);
  3872. }).finally(function () {
  3873. if (handler) {
  3874. _this.removeMessageHandler(handler);
  3875. }
  3876. })];
  3877. });
  3878. });
  3879. };
  3880. return Sender;
  3881. }());
  3882. /**
  3883. * @license
  3884. * Copyright 2020 Google LLC
  3885. *
  3886. * Licensed under the Apache License, Version 2.0 (the "License");
  3887. * you may not use this file except in compliance with the License.
  3888. * You may obtain a copy of the License at
  3889. *
  3890. * http://www.apache.org/licenses/LICENSE-2.0
  3891. *
  3892. * Unless required by applicable law or agreed to in writing, software
  3893. * distributed under the License is distributed on an "AS IS" BASIS,
  3894. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3895. * See the License for the specific language governing permissions and
  3896. * limitations under the License.
  3897. */
  3898. /**
  3899. * Lazy accessor for window, since the compat layer won't tree shake this out,
  3900. * we need to make sure not to mess with window unless we have to
  3901. */
  3902. function _window() {
  3903. return window;
  3904. }
  3905. /**
  3906. * @license
  3907. * Copyright 2020 Google LLC.
  3908. *
  3909. * Licensed under the Apache License, Version 2.0 (the "License");
  3910. * you may not use this file except in compliance with the License.
  3911. * You may obtain a copy of the License at
  3912. *
  3913. * http://www.apache.org/licenses/LICENSE-2.0
  3914. *
  3915. * Unless required by applicable law or agreed to in writing, software
  3916. * distributed under the License is distributed on an "AS IS" BASIS,
  3917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3918. * See the License for the specific language governing permissions and
  3919. * limitations under the License.
  3920. */
  3921. function _isWorker() {
  3922. return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
  3923. typeof _window()['importScripts'] === 'function');
  3924. }
  3925. function _getActiveServiceWorker() {
  3926. return __awaiter(this, void 0, void 0, function () {
  3927. var registration;
  3928. return __generator(this, function (_b) {
  3929. switch (_b.label) {
  3930. case 0:
  3931. if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
  3932. return [2 /*return*/, null];
  3933. }
  3934. _b.label = 1;
  3935. case 1:
  3936. _b.trys.push([1, 3, , 4]);
  3937. return [4 /*yield*/, navigator.serviceWorker.ready];
  3938. case 2:
  3939. registration = _b.sent();
  3940. return [2 /*return*/, registration.active];
  3941. case 3:
  3942. _b.sent();
  3943. return [2 /*return*/, null];
  3944. case 4: return [2 /*return*/];
  3945. }
  3946. });
  3947. });
  3948. }
  3949. function _getServiceWorkerController() {
  3950. var _a;
  3951. return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
  3952. }
  3953. function _getWorkerGlobalScope() {
  3954. return _isWorker() ? self : null;
  3955. }
  3956. /**
  3957. * @license
  3958. * Copyright 2019 Google LLC
  3959. *
  3960. * Licensed under the Apache License, Version 2.0 (the "License");
  3961. * you may not use this file except in compliance with the License.
  3962. * You may obtain a copy of the License at
  3963. *
  3964. * http://www.apache.org/licenses/LICENSE-2.0
  3965. *
  3966. * Unless required by applicable law or agreed to in writing, software
  3967. * distributed under the License is distributed on an "AS IS" BASIS,
  3968. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3969. * See the License for the specific language governing permissions and
  3970. * limitations under the License.
  3971. */
  3972. var DB_NAME = 'firebaseLocalStorageDb';
  3973. var DB_VERSION = 1;
  3974. var DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
  3975. var DB_DATA_KEYPATH = 'fbase_key';
  3976. /**
  3977. * Promise wrapper for IDBRequest
  3978. *
  3979. * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
  3980. *
  3981. */
  3982. var DBPromise = /** @class */ (function () {
  3983. function DBPromise(request) {
  3984. this.request = request;
  3985. }
  3986. DBPromise.prototype.toPromise = function () {
  3987. var _this = this;
  3988. return new Promise(function (resolve, reject) {
  3989. _this.request.addEventListener('success', function () {
  3990. resolve(_this.request.result);
  3991. });
  3992. _this.request.addEventListener('error', function () {
  3993. reject(_this.request.error);
  3994. });
  3995. });
  3996. };
  3997. return DBPromise;
  3998. }());
  3999. function getObjectStore(db, isReadWrite) {
  4000. return db
  4001. .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
  4002. .objectStore(DB_OBJECTSTORE_NAME);
  4003. }
  4004. function _deleteDatabase() {
  4005. var request = indexedDB.deleteDatabase(DB_NAME);
  4006. return new DBPromise(request).toPromise();
  4007. }
  4008. function _openDatabase() {
  4009. var _this = this;
  4010. var request = indexedDB.open(DB_NAME, DB_VERSION);
  4011. return new Promise(function (resolve, reject) {
  4012. request.addEventListener('error', function () {
  4013. reject(request.error);
  4014. });
  4015. request.addEventListener('upgradeneeded', function () {
  4016. var db = request.result;
  4017. try {
  4018. db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
  4019. }
  4020. catch (e) {
  4021. reject(e);
  4022. }
  4023. });
  4024. request.addEventListener('success', function () { return __awaiter(_this, void 0, void 0, function () {
  4025. var db, _a;
  4026. return __generator(this, function (_b) {
  4027. switch (_b.label) {
  4028. case 0:
  4029. db = request.result;
  4030. if (!!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) return [3 /*break*/, 3];
  4031. // Need to close the database or else you get a `blocked` event
  4032. db.close();
  4033. return [4 /*yield*/, _deleteDatabase()];
  4034. case 1:
  4035. _b.sent();
  4036. _a = resolve;
  4037. return [4 /*yield*/, _openDatabase()];
  4038. case 2:
  4039. _a.apply(void 0, [_b.sent()]);
  4040. return [3 /*break*/, 4];
  4041. case 3:
  4042. resolve(db);
  4043. _b.label = 4;
  4044. case 4: return [2 /*return*/];
  4045. }
  4046. });
  4047. }); });
  4048. });
  4049. }
  4050. function _putObject(db, key, value) {
  4051. return __awaiter(this, void 0, void 0, function () {
  4052. var request;
  4053. var _a;
  4054. return __generator(this, function (_b) {
  4055. request = getObjectStore(db, true).put((_a = {},
  4056. _a[DB_DATA_KEYPATH] = key,
  4057. _a.value = value,
  4058. _a));
  4059. return [2 /*return*/, new DBPromise(request).toPromise()];
  4060. });
  4061. });
  4062. }
  4063. function getObject(db, key) {
  4064. return __awaiter(this, void 0, void 0, function () {
  4065. var request, data;
  4066. return __generator(this, function (_a) {
  4067. switch (_a.label) {
  4068. case 0:
  4069. request = getObjectStore(db, false).get(key);
  4070. return [4 /*yield*/, new DBPromise(request).toPromise()];
  4071. case 1:
  4072. data = _a.sent();
  4073. return [2 /*return*/, data === undefined ? null : data.value];
  4074. }
  4075. });
  4076. });
  4077. }
  4078. function _deleteObject(db, key) {
  4079. var request = getObjectStore(db, true).delete(key);
  4080. return new DBPromise(request).toPromise();
  4081. }
  4082. var _POLLING_INTERVAL_MS = 800;
  4083. var _TRANSACTION_RETRY_COUNT = 3;
  4084. var IndexedDBLocalPersistence = /** @class */ (function () {
  4085. function IndexedDBLocalPersistence() {
  4086. this.type = "LOCAL" /* PersistenceType.LOCAL */;
  4087. this._shouldAllowMigration = true;
  4088. this.listeners = {};
  4089. this.localCache = {};
  4090. // setTimeout return value is platform specific
  4091. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4092. this.pollTimer = null;
  4093. this.pendingWrites = 0;
  4094. this.receiver = null;
  4095. this.sender = null;
  4096. this.serviceWorkerReceiverAvailable = false;
  4097. this.activeServiceWorker = null;
  4098. // Fire & forget the service worker registration as it may never resolve
  4099. this._workerInitializationPromise =
  4100. this.initializeServiceWorkerMessaging().then(function () { }, function () { });
  4101. }
  4102. IndexedDBLocalPersistence.prototype._openDb = function () {
  4103. return __awaiter(this, void 0, void 0, function () {
  4104. var _a;
  4105. return __generator(this, function (_b) {
  4106. switch (_b.label) {
  4107. case 0:
  4108. if (this.db) {
  4109. return [2 /*return*/, this.db];
  4110. }
  4111. _a = this;
  4112. return [4 /*yield*/, _openDatabase()];
  4113. case 1:
  4114. _a.db = _b.sent();
  4115. return [2 /*return*/, this.db];
  4116. }
  4117. });
  4118. });
  4119. };
  4120. IndexedDBLocalPersistence.prototype._withRetries = function (op) {
  4121. return __awaiter(this, void 0, void 0, function () {
  4122. var numAttempts, db, e_1;
  4123. return __generator(this, function (_a) {
  4124. switch (_a.label) {
  4125. case 0:
  4126. numAttempts = 0;
  4127. _a.label = 1;
  4128. case 1:
  4129. _a.label = 2;
  4130. case 2:
  4131. _a.trys.push([2, 5, , 6]);
  4132. return [4 /*yield*/, this._openDb()];
  4133. case 3:
  4134. db = _a.sent();
  4135. return [4 /*yield*/, op(db)];
  4136. case 4: return [2 /*return*/, _a.sent()];
  4137. case 5:
  4138. e_1 = _a.sent();
  4139. if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
  4140. throw e_1;
  4141. }
  4142. if (this.db) {
  4143. this.db.close();
  4144. this.db = undefined;
  4145. }
  4146. return [3 /*break*/, 6];
  4147. case 6: return [3 /*break*/, 1];
  4148. case 7: return [2 /*return*/];
  4149. }
  4150. });
  4151. });
  4152. };
  4153. /**
  4154. * IndexedDB events do not propagate from the main window to the worker context. We rely on a
  4155. * postMessage interface to send these events to the worker ourselves.
  4156. */
  4157. IndexedDBLocalPersistence.prototype.initializeServiceWorkerMessaging = function () {
  4158. return __awaiter(this, void 0, void 0, function () {
  4159. return __generator(this, function (_a) {
  4160. return [2 /*return*/, _isWorker() ? this.initializeReceiver() : this.initializeSender()];
  4161. });
  4162. });
  4163. };
  4164. /**
  4165. * As the worker we should listen to events from the main window.
  4166. */
  4167. IndexedDBLocalPersistence.prototype.initializeReceiver = function () {
  4168. return __awaiter(this, void 0, void 0, function () {
  4169. var _this = this;
  4170. return __generator(this, function (_a) {
  4171. this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
  4172. // Refresh from persistence if we receive a KeyChanged message.
  4173. this.receiver._subscribe("keyChanged" /* _EventType.KEY_CHANGED */, function (_origin, data) { return __awaiter(_this, void 0, void 0, function () {
  4174. var keys;
  4175. return __generator(this, function (_a) {
  4176. switch (_a.label) {
  4177. case 0: return [4 /*yield*/, this._poll()];
  4178. case 1:
  4179. keys = _a.sent();
  4180. return [2 /*return*/, {
  4181. keyProcessed: keys.includes(data.key)
  4182. }];
  4183. }
  4184. });
  4185. }); });
  4186. // Let the sender know that we are listening so they give us more timeout.
  4187. this.receiver._subscribe("ping" /* _EventType.PING */, function (_origin, _data) { return __awaiter(_this, void 0, void 0, function () {
  4188. return __generator(this, function (_a) {
  4189. return [2 /*return*/, ["keyChanged" /* _EventType.KEY_CHANGED */]];
  4190. });
  4191. }); });
  4192. return [2 /*return*/];
  4193. });
  4194. });
  4195. };
  4196. /**
  4197. * As the main window, we should let the worker know when keys change (set and remove).
  4198. *
  4199. * @remarks
  4200. * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
  4201. * may not resolve.
  4202. */
  4203. IndexedDBLocalPersistence.prototype.initializeSender = function () {
  4204. var _a, _b;
  4205. return __awaiter(this, void 0, void 0, function () {
  4206. var _c, results;
  4207. return __generator(this, function (_d) {
  4208. switch (_d.label) {
  4209. case 0:
  4210. // Check to see if there's an active service worker.
  4211. _c = this;
  4212. return [4 /*yield*/, _getActiveServiceWorker()];
  4213. case 1:
  4214. // Check to see if there's an active service worker.
  4215. _c.activeServiceWorker = _d.sent();
  4216. if (!this.activeServiceWorker) {
  4217. return [2 /*return*/];
  4218. }
  4219. this.sender = new Sender(this.activeServiceWorker);
  4220. return [4 /*yield*/, this.sender._send("ping" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */)];
  4221. case 2:
  4222. results = _d.sent();
  4223. if (!results) {
  4224. return [2 /*return*/];
  4225. }
  4226. if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
  4227. ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* _EventType.KEY_CHANGED */))) {
  4228. this.serviceWorkerReceiverAvailable = true;
  4229. }
  4230. return [2 /*return*/];
  4231. }
  4232. });
  4233. });
  4234. };
  4235. /**
  4236. * Let the worker know about a changed key, the exact key doesn't technically matter since the
  4237. * worker will just trigger a full sync anyway.
  4238. *
  4239. * @remarks
  4240. * For now, we only support one service worker per page.
  4241. *
  4242. * @param key - Storage key which changed.
  4243. */
  4244. IndexedDBLocalPersistence.prototype.notifyServiceWorker = function (key) {
  4245. return __awaiter(this, void 0, void 0, function () {
  4246. return __generator(this, function (_b) {
  4247. switch (_b.label) {
  4248. case 0:
  4249. if (!this.sender ||
  4250. !this.activeServiceWorker ||
  4251. _getServiceWorkerController() !== this.activeServiceWorker) {
  4252. return [2 /*return*/];
  4253. }
  4254. _b.label = 1;
  4255. case 1:
  4256. _b.trys.push([1, 3, , 4]);
  4257. return [4 /*yield*/, this.sender._send("keyChanged" /* _EventType.KEY_CHANGED */, { key: key },
  4258. // Use long timeout if receiver has previously responded to a ping from us.
  4259. this.serviceWorkerReceiverAvailable
  4260. ? 800 /* _TimeoutDuration.LONG_ACK */
  4261. : 50 /* _TimeoutDuration.ACK */)];
  4262. case 2:
  4263. _b.sent();
  4264. return [3 /*break*/, 4];
  4265. case 3:
  4266. _b.sent();
  4267. return [3 /*break*/, 4];
  4268. case 4: return [2 /*return*/];
  4269. }
  4270. });
  4271. });
  4272. };
  4273. IndexedDBLocalPersistence.prototype._isAvailable = function () {
  4274. return __awaiter(this, void 0, void 0, function () {
  4275. var db;
  4276. return __generator(this, function (_b) {
  4277. switch (_b.label) {
  4278. case 0:
  4279. _b.trys.push([0, 4, , 5]);
  4280. if (!indexedDB) {
  4281. return [2 /*return*/, false];
  4282. }
  4283. return [4 /*yield*/, _openDatabase()];
  4284. case 1:
  4285. db = _b.sent();
  4286. return [4 /*yield*/, _putObject(db, STORAGE_AVAILABLE_KEY, '1')];
  4287. case 2:
  4288. _b.sent();
  4289. return [4 /*yield*/, _deleteObject(db, STORAGE_AVAILABLE_KEY)];
  4290. case 3:
  4291. _b.sent();
  4292. return [2 /*return*/, true];
  4293. case 4:
  4294. _b.sent();
  4295. return [3 /*break*/, 5];
  4296. case 5: return [2 /*return*/, false];
  4297. }
  4298. });
  4299. });
  4300. };
  4301. IndexedDBLocalPersistence.prototype._withPendingWrite = function (write) {
  4302. return __awaiter(this, void 0, void 0, function () {
  4303. return __generator(this, function (_a) {
  4304. switch (_a.label) {
  4305. case 0:
  4306. this.pendingWrites++;
  4307. _a.label = 1;
  4308. case 1:
  4309. _a.trys.push([1, , 3, 4]);
  4310. return [4 /*yield*/, write()];
  4311. case 2:
  4312. _a.sent();
  4313. return [3 /*break*/, 4];
  4314. case 3:
  4315. this.pendingWrites--;
  4316. return [7 /*endfinally*/];
  4317. case 4: return [2 /*return*/];
  4318. }
  4319. });
  4320. });
  4321. };
  4322. IndexedDBLocalPersistence.prototype._set = function (key, value) {
  4323. return __awaiter(this, void 0, void 0, function () {
  4324. var _this = this;
  4325. return __generator(this, function (_a) {
  4326. return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
  4327. return __generator(this, function (_a) {
  4328. switch (_a.label) {
  4329. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _putObject(db, key, value); })];
  4330. case 1:
  4331. _a.sent();
  4332. this.localCache[key] = value;
  4333. return [2 /*return*/, this.notifyServiceWorker(key)];
  4334. }
  4335. });
  4336. }); })];
  4337. });
  4338. });
  4339. };
  4340. IndexedDBLocalPersistence.prototype._get = function (key) {
  4341. return __awaiter(this, void 0, void 0, function () {
  4342. var obj;
  4343. return __generator(this, function (_a) {
  4344. switch (_a.label) {
  4345. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  4346. return getObject(db, key);
  4347. })];
  4348. case 1:
  4349. obj = (_a.sent());
  4350. this.localCache[key] = obj;
  4351. return [2 /*return*/, obj];
  4352. }
  4353. });
  4354. });
  4355. };
  4356. IndexedDBLocalPersistence.prototype._remove = function (key) {
  4357. return __awaiter(this, void 0, void 0, function () {
  4358. var _this = this;
  4359. return __generator(this, function (_a) {
  4360. return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
  4361. return __generator(this, function (_a) {
  4362. switch (_a.label) {
  4363. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _deleteObject(db, key); })];
  4364. case 1:
  4365. _a.sent();
  4366. delete this.localCache[key];
  4367. return [2 /*return*/, this.notifyServiceWorker(key)];
  4368. }
  4369. });
  4370. }); })];
  4371. });
  4372. });
  4373. };
  4374. IndexedDBLocalPersistence.prototype._poll = function () {
  4375. return __awaiter(this, void 0, void 0, function () {
  4376. var result, keys, keysInResult, _i, result_1, _a, key, value, _b, _c, localKey;
  4377. return __generator(this, function (_d) {
  4378. switch (_d.label) {
  4379. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  4380. var getAllRequest = getObjectStore(db, false).getAll();
  4381. return new DBPromise(getAllRequest).toPromise();
  4382. })];
  4383. case 1:
  4384. result = _d.sent();
  4385. if (!result) {
  4386. return [2 /*return*/, []];
  4387. }
  4388. // If we have pending writes in progress abort, we'll get picked up on the next poll
  4389. if (this.pendingWrites !== 0) {
  4390. return [2 /*return*/, []];
  4391. }
  4392. keys = [];
  4393. keysInResult = new Set();
  4394. for (_i = 0, result_1 = result; _i < result_1.length; _i++) {
  4395. _a = result_1[_i], key = _a.fbase_key, value = _a.value;
  4396. keysInResult.add(key);
  4397. if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
  4398. this.notifyListeners(key, value);
  4399. keys.push(key);
  4400. }
  4401. }
  4402. for (_b = 0, _c = Object.keys(this.localCache); _b < _c.length; _b++) {
  4403. localKey = _c[_b];
  4404. if (this.localCache[localKey] && !keysInResult.has(localKey)) {
  4405. // Deleted
  4406. this.notifyListeners(localKey, null);
  4407. keys.push(localKey);
  4408. }
  4409. }
  4410. return [2 /*return*/, keys];
  4411. }
  4412. });
  4413. });
  4414. };
  4415. IndexedDBLocalPersistence.prototype.notifyListeners = function (key, newValue) {
  4416. this.localCache[key] = newValue;
  4417. var listeners = this.listeners[key];
  4418. if (listeners) {
  4419. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  4420. var listener = _a[_i];
  4421. listener(newValue);
  4422. }
  4423. }
  4424. };
  4425. IndexedDBLocalPersistence.prototype.startPolling = function () {
  4426. var _this = this;
  4427. this.stopPolling();
  4428. this.pollTimer = setInterval(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  4429. return [2 /*return*/, this._poll()];
  4430. }); }); }, _POLLING_INTERVAL_MS);
  4431. };
  4432. IndexedDBLocalPersistence.prototype.stopPolling = function () {
  4433. if (this.pollTimer) {
  4434. clearInterval(this.pollTimer);
  4435. this.pollTimer = null;
  4436. }
  4437. };
  4438. IndexedDBLocalPersistence.prototype._addListener = function (key, listener) {
  4439. if (Object.keys(this.listeners).length === 0) {
  4440. this.startPolling();
  4441. }
  4442. if (!this.listeners[key]) {
  4443. this.listeners[key] = new Set();
  4444. // Populate the cache to avoid spuriously triggering on first poll.
  4445. void this._get(key); // This can happen in the background async and we can return immediately.
  4446. }
  4447. this.listeners[key].add(listener);
  4448. };
  4449. IndexedDBLocalPersistence.prototype._removeListener = function (key, listener) {
  4450. if (this.listeners[key]) {
  4451. this.listeners[key].delete(listener);
  4452. if (this.listeners[key].size === 0) {
  4453. delete this.listeners[key];
  4454. }
  4455. }
  4456. if (Object.keys(this.listeners).length === 0) {
  4457. this.stopPolling();
  4458. }
  4459. };
  4460. IndexedDBLocalPersistence.type = 'LOCAL';
  4461. return IndexedDBLocalPersistence;
  4462. }());
  4463. /**
  4464. * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
  4465. * for the underlying storage.
  4466. *
  4467. * @public
  4468. */
  4469. var indexedDBLocalPersistence = IndexedDBLocalPersistence;
  4470. /**
  4471. * @license
  4472. * Copyright 2021 Google LLC
  4473. *
  4474. * Licensed under the Apache License, Version 2.0 (the "License");
  4475. * you may not use this file except in compliance with the License.
  4476. * You may obtain a copy of the License at
  4477. *
  4478. * http://www.apache.org/licenses/LICENSE-2.0
  4479. *
  4480. * Unless required by applicable law or agreed to in writing, software
  4481. * distributed under the License is distributed on an "AS IS" BASIS,
  4482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4483. * See the License for the specific language governing permissions and
  4484. * limitations under the License.
  4485. */
  4486. /**
  4487. * An enum of factors that may be used for multifactor authentication.
  4488. *
  4489. * @public
  4490. */
  4491. var FactorId = {
  4492. /** Phone as second factor */
  4493. PHONE: 'phone',
  4494. TOTP: 'totp'
  4495. };
  4496. /**
  4497. * Enumeration of supported providers.
  4498. *
  4499. * @public
  4500. */
  4501. var ProviderId = {
  4502. /** Facebook provider ID */
  4503. FACEBOOK: 'facebook.com',
  4504. /** GitHub provider ID */
  4505. GITHUB: 'github.com',
  4506. /** Google provider ID */
  4507. GOOGLE: 'google.com',
  4508. /** Password provider */
  4509. PASSWORD: 'password',
  4510. /** Phone provider */
  4511. PHONE: 'phone',
  4512. /** Twitter provider ID */
  4513. TWITTER: 'twitter.com'
  4514. };
  4515. /**
  4516. * Enumeration of supported sign-in methods.
  4517. *
  4518. * @public
  4519. */
  4520. var SignInMethod = {
  4521. /** Email link sign in method */
  4522. EMAIL_LINK: 'emailLink',
  4523. /** Email/password sign in method */
  4524. EMAIL_PASSWORD: 'password',
  4525. /** Facebook sign in method */
  4526. FACEBOOK: 'facebook.com',
  4527. /** GitHub sign in method */
  4528. GITHUB: 'github.com',
  4529. /** Google sign in method */
  4530. GOOGLE: 'google.com',
  4531. /** Phone sign in method */
  4532. PHONE: 'phone',
  4533. /** Twitter sign in method */
  4534. TWITTER: 'twitter.com'
  4535. };
  4536. /**
  4537. * Enumeration of supported operation types.
  4538. *
  4539. * @public
  4540. */
  4541. var OperationType = {
  4542. /** Operation involving linking an additional provider to an already signed-in user. */
  4543. LINK: 'link',
  4544. /** Operation involving using a provider to reauthenticate an already signed-in user. */
  4545. REAUTHENTICATE: 'reauthenticate',
  4546. /** Operation involving signing in a user. */
  4547. SIGN_IN: 'signIn'
  4548. };
  4549. /**
  4550. * An enumeration of the possible email action types.
  4551. *
  4552. * @public
  4553. */
  4554. var ActionCodeOperation = {
  4555. /** The email link sign-in action. */
  4556. EMAIL_SIGNIN: 'EMAIL_SIGNIN',
  4557. /** The password reset action. */
  4558. PASSWORD_RESET: 'PASSWORD_RESET',
  4559. /** The email revocation action. */
  4560. RECOVER_EMAIL: 'RECOVER_EMAIL',
  4561. /** The revert second factor addition email action. */
  4562. REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
  4563. /** The revert second factor addition email action. */
  4564. VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
  4565. /** The email verification action. */
  4566. VERIFY_EMAIL: 'VERIFY_EMAIL'
  4567. };
  4568. /**
  4569. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  4570. * Firebase Auth services.
  4571. *
  4572. * @remarks
  4573. * This must be called synchronously immediately following the first call to
  4574. * {@link initializeAuth}. Do not use with production credentials as emulator
  4575. * traffic is not encrypted.
  4576. *
  4577. *
  4578. * @example
  4579. * ```javascript
  4580. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  4581. * ```
  4582. *
  4583. * @param auth - The {@link Auth} instance.
  4584. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  4585. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  4586. * `true` to disable the warning banner attached to the DOM.
  4587. *
  4588. * @public
  4589. */
  4590. function connectAuthEmulator(auth, url, options) {
  4591. var authInternal = _castAuth(auth);
  4592. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  4593. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  4594. var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  4595. var protocol = extractProtocol(url);
  4596. var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
  4597. var portStr = port === null ? '' : ":".concat(port);
  4598. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  4599. authInternal.config.emulator = { url: "".concat(protocol, "//").concat(host).concat(portStr, "/") };
  4600. authInternal.settings.appVerificationDisabledForTesting = true;
  4601. authInternal.emulatorConfig = Object.freeze({
  4602. host: host,
  4603. port: port,
  4604. protocol: protocol.replace(':', ''),
  4605. options: Object.freeze({ disableWarnings: disableWarnings })
  4606. });
  4607. if (!disableWarnings) {
  4608. emitEmulatorWarning();
  4609. }
  4610. }
  4611. function extractProtocol(url) {
  4612. var protocolEnd = url.indexOf(':');
  4613. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  4614. }
  4615. function extractHostAndPort(url) {
  4616. var protocol = extractProtocol(url);
  4617. var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  4618. if (!authority) {
  4619. return { host: '', port: null };
  4620. }
  4621. var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  4622. var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  4623. if (bracketedIPv6) {
  4624. var host = bracketedIPv6[1];
  4625. return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  4626. }
  4627. else {
  4628. var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
  4629. return { host: host, port: parsePort(port) };
  4630. }
  4631. }
  4632. function parsePort(portStr) {
  4633. if (!portStr) {
  4634. return null;
  4635. }
  4636. var port = Number(portStr);
  4637. if (isNaN(port)) {
  4638. return null;
  4639. }
  4640. return port;
  4641. }
  4642. function emitEmulatorWarning() {
  4643. function attachBanner() {
  4644. var el = document.createElement('p');
  4645. var sty = el.style;
  4646. el.innerText =
  4647. 'Running in emulator mode. Do not use with production credentials.';
  4648. sty.position = 'fixed';
  4649. sty.width = '100%';
  4650. sty.backgroundColor = '#ffffff';
  4651. sty.border = '.1em solid #000000';
  4652. sty.color = '#b50000';
  4653. sty.bottom = '0px';
  4654. sty.left = '0px';
  4655. sty.margin = '0px';
  4656. sty.zIndex = '10000';
  4657. sty.textAlign = 'center';
  4658. el.classList.add('firebase-emulator-warning');
  4659. document.body.appendChild(el);
  4660. }
  4661. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  4662. console.info('WARNING: You are using the Auth Emulator,' +
  4663. ' which is intended for local testing only. Do not use with' +
  4664. ' production credentials.');
  4665. }
  4666. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  4667. if (document.readyState === 'loading') {
  4668. window.addEventListener('DOMContentLoaded', attachBanner);
  4669. }
  4670. else {
  4671. attachBanner();
  4672. }
  4673. }
  4674. }
  4675. /**
  4676. * @license
  4677. * Copyright 2020 Google LLC
  4678. *
  4679. * Licensed under the Apache License, Version 2.0 (the "License");
  4680. * you may not use this file except in compliance with the License.
  4681. * You may obtain a copy of the License at
  4682. *
  4683. * http://www.apache.org/licenses/LICENSE-2.0
  4684. *
  4685. * Unless required by applicable law or agreed to in writing, software
  4686. * distributed under the License is distributed on an "AS IS" BASIS,
  4687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4688. * See the License for the specific language governing permissions and
  4689. * limitations under the License.
  4690. */
  4691. /**
  4692. * Interface that represents the credentials returned by an {@link AuthProvider}.
  4693. *
  4694. * @remarks
  4695. * Implementations specify the details about each auth provider's credential requirements.
  4696. *
  4697. * @public
  4698. */
  4699. var AuthCredential = /** @class */ (function () {
  4700. /** @internal */
  4701. function AuthCredential(
  4702. /**
  4703. * The authentication provider ID for the credential.
  4704. *
  4705. * @remarks
  4706. * For example, 'facebook.com', or 'google.com'.
  4707. */
  4708. providerId,
  4709. /**
  4710. * The authentication sign in method for the credential.
  4711. *
  4712. * @remarks
  4713. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  4714. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  4715. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  4716. */
  4717. signInMethod) {
  4718. this.providerId = providerId;
  4719. this.signInMethod = signInMethod;
  4720. }
  4721. /**
  4722. * Returns a JSON-serializable representation of this object.
  4723. *
  4724. * @returns a JSON-serializable representation of this object.
  4725. */
  4726. AuthCredential.prototype.toJSON = function () {
  4727. return debugFail('not implemented');
  4728. };
  4729. /** @internal */
  4730. AuthCredential.prototype._getIdTokenResponse = function (_auth) {
  4731. return debugFail('not implemented');
  4732. };
  4733. /** @internal */
  4734. AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
  4735. return debugFail('not implemented');
  4736. };
  4737. /** @internal */
  4738. AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
  4739. return debugFail('not implemented');
  4740. };
  4741. return AuthCredential;
  4742. }());
  4743. /**
  4744. * @license
  4745. * Copyright 2020 Google LLC
  4746. *
  4747. * Licensed under the Apache License, Version 2.0 (the "License");
  4748. * you may not use this file except in compliance with the License.
  4749. * You may obtain a copy of the License at
  4750. *
  4751. * http://www.apache.org/licenses/LICENSE-2.0
  4752. *
  4753. * Unless required by applicable law or agreed to in writing, software
  4754. * distributed under the License is distributed on an "AS IS" BASIS,
  4755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4756. * See the License for the specific language governing permissions and
  4757. * limitations under the License.
  4758. */
  4759. function resetPassword(auth, request) {
  4760. return __awaiter(this, void 0, void 0, function () {
  4761. return __generator(this, function (_a) {
  4762. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
  4763. });
  4764. });
  4765. }
  4766. function updateEmailPassword(auth, request) {
  4767. return __awaiter(this, void 0, void 0, function () {
  4768. return __generator(this, function (_a) {
  4769. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  4770. });
  4771. });
  4772. }
  4773. function applyActionCode$1(auth, request) {
  4774. return __awaiter(this, void 0, void 0, function () {
  4775. return __generator(this, function (_a) {
  4776. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
  4777. });
  4778. });
  4779. }
  4780. /**
  4781. * @license
  4782. * Copyright 2020 Google LLC
  4783. *
  4784. * Licensed under the Apache License, Version 2.0 (the "License");
  4785. * you may not use this file except in compliance with the License.
  4786. * You may obtain a copy of the License at
  4787. *
  4788. * http://www.apache.org/licenses/LICENSE-2.0
  4789. *
  4790. * Unless required by applicable law or agreed to in writing, software
  4791. * distributed under the License is distributed on an "AS IS" BASIS,
  4792. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4793. * See the License for the specific language governing permissions and
  4794. * limitations under the License.
  4795. */
  4796. function signInWithPassword(auth, request) {
  4797. return __awaiter(this, void 0, void 0, function () {
  4798. return __generator(this, function (_a) {
  4799. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
  4800. });
  4801. });
  4802. }
  4803. function sendOobCode(auth, request) {
  4804. return __awaiter(this, void 0, void 0, function () {
  4805. return __generator(this, function (_a) {
  4806. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
  4807. });
  4808. });
  4809. }
  4810. function sendEmailVerification$1(auth, request) {
  4811. return __awaiter(this, void 0, void 0, function () {
  4812. return __generator(this, function (_a) {
  4813. return [2 /*return*/, sendOobCode(auth, request)];
  4814. });
  4815. });
  4816. }
  4817. function sendPasswordResetEmail$1(auth, request) {
  4818. return __awaiter(this, void 0, void 0, function () {
  4819. return __generator(this, function (_a) {
  4820. return [2 /*return*/, sendOobCode(auth, request)];
  4821. });
  4822. });
  4823. }
  4824. function sendSignInLinkToEmail$1(auth, request) {
  4825. return __awaiter(this, void 0, void 0, function () {
  4826. return __generator(this, function (_a) {
  4827. return [2 /*return*/, sendOobCode(auth, request)];
  4828. });
  4829. });
  4830. }
  4831. function verifyAndChangeEmail(auth, request) {
  4832. return __awaiter(this, void 0, void 0, function () {
  4833. return __generator(this, function (_a) {
  4834. return [2 /*return*/, sendOobCode(auth, request)];
  4835. });
  4836. });
  4837. }
  4838. /**
  4839. * @license
  4840. * Copyright 2020 Google LLC
  4841. *
  4842. * Licensed under the Apache License, Version 2.0 (the "License");
  4843. * you may not use this file except in compliance with the License.
  4844. * You may obtain a copy of the License at
  4845. *
  4846. * http://www.apache.org/licenses/LICENSE-2.0
  4847. *
  4848. * Unless required by applicable law or agreed to in writing, software
  4849. * distributed under the License is distributed on an "AS IS" BASIS,
  4850. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4851. * See the License for the specific language governing permissions and
  4852. * limitations under the License.
  4853. */
  4854. function signInWithEmailLink$1(auth, request) {
  4855. return __awaiter(this, void 0, void 0, function () {
  4856. return __generator(this, function (_a) {
  4857. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  4858. });
  4859. });
  4860. }
  4861. function signInWithEmailLinkForLinking(auth, request) {
  4862. return __awaiter(this, void 0, void 0, function () {
  4863. return __generator(this, function (_a) {
  4864. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  4865. });
  4866. });
  4867. }
  4868. /**
  4869. * @license
  4870. * Copyright 2020 Google LLC
  4871. *
  4872. * Licensed under the Apache License, Version 2.0 (the "License");
  4873. * you may not use this file except in compliance with the License.
  4874. * You may obtain a copy of the License at
  4875. *
  4876. * http://www.apache.org/licenses/LICENSE-2.0
  4877. *
  4878. * Unless required by applicable law or agreed to in writing, software
  4879. * distributed under the License is distributed on an "AS IS" BASIS,
  4880. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4881. * See the License for the specific language governing permissions and
  4882. * limitations under the License.
  4883. */
  4884. /**
  4885. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  4886. * {@link ProviderId}.PASSWORD
  4887. *
  4888. * @remarks
  4889. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  4890. * {@link SignInMethod}.EMAIL_LINK.
  4891. *
  4892. * @public
  4893. */
  4894. var EmailAuthCredential = /** @class */ (function (_super) {
  4895. __extends(EmailAuthCredential, _super);
  4896. /** @internal */
  4897. function EmailAuthCredential(
  4898. /** @internal */
  4899. _email,
  4900. /** @internal */
  4901. _password, signInMethod,
  4902. /** @internal */
  4903. _tenantId) {
  4904. if (_tenantId === void 0) { _tenantId = null; }
  4905. var _this = _super.call(this, "password" /* ProviderId.PASSWORD */, signInMethod) || this;
  4906. _this._email = _email;
  4907. _this._password = _password;
  4908. _this._tenantId = _tenantId;
  4909. return _this;
  4910. }
  4911. /** @internal */
  4912. EmailAuthCredential._fromEmailAndPassword = function (email, password) {
  4913. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  4914. };
  4915. /** @internal */
  4916. EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
  4917. if (tenantId === void 0) { tenantId = null; }
  4918. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  4919. };
  4920. /** {@inheritdoc AuthCredential.toJSON} */
  4921. EmailAuthCredential.prototype.toJSON = function () {
  4922. return {
  4923. email: this._email,
  4924. password: this._password,
  4925. signInMethod: this.signInMethod,
  4926. tenantId: this._tenantId
  4927. };
  4928. };
  4929. /**
  4930. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  4931. *
  4932. * @param json - Either `object` or the stringified representation of the object. When string is
  4933. * provided, `JSON.parse` would be called first.
  4934. *
  4935. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4936. */
  4937. EmailAuthCredential.fromJSON = function (json) {
  4938. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4939. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  4940. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  4941. return this._fromEmailAndPassword(obj.email, obj.password);
  4942. }
  4943. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  4944. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  4945. }
  4946. }
  4947. return null;
  4948. };
  4949. /** @internal */
  4950. EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
  4951. var _a;
  4952. return __awaiter(this, void 0, void 0, function () {
  4953. var _b, request_1, requestWithRecaptcha;
  4954. var _this = this;
  4955. return __generator(this, function (_c) {
  4956. switch (_c.label) {
  4957. case 0:
  4958. _b = this.signInMethod;
  4959. switch (_b) {
  4960. case "password" /* SignInMethod.EMAIL_PASSWORD */: return [3 /*break*/, 1];
  4961. case "emailLink" /* SignInMethod.EMAIL_LINK */: return [3 /*break*/, 4];
  4962. }
  4963. return [3 /*break*/, 5];
  4964. case 1:
  4965. request_1 = {
  4966. returnSecureToken: true,
  4967. email: this._email,
  4968. password: this._password,
  4969. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  4970. };
  4971. if (!((_a = auth._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  4972. return [4 /*yield*/, injectRecaptchaFields(auth, request_1, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */)];
  4973. case 2:
  4974. requestWithRecaptcha = _c.sent();
  4975. return [2 /*return*/, signInWithPassword(auth, requestWithRecaptcha)];
  4976. case 3: return [2 /*return*/, signInWithPassword(auth, request_1).catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  4977. var requestWithRecaptcha;
  4978. return __generator(this, function (_a) {
  4979. switch (_a.label) {
  4980. case 0:
  4981. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 2];
  4982. console.log('Sign-in with email address and password is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');
  4983. return [4 /*yield*/, injectRecaptchaFields(auth, request_1, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */)];
  4984. case 1:
  4985. requestWithRecaptcha = _a.sent();
  4986. return [2 /*return*/, signInWithPassword(auth, requestWithRecaptcha)];
  4987. case 2: return [2 /*return*/, Promise.reject(error)];
  4988. }
  4989. });
  4990. }); })];
  4991. case 4: return [2 /*return*/, signInWithEmailLink$1(auth, {
  4992. email: this._email,
  4993. oobCode: this._password
  4994. })];
  4995. case 5:
  4996. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4997. _c.label = 6;
  4998. case 6: return [2 /*return*/];
  4999. }
  5000. });
  5001. });
  5002. };
  5003. /** @internal */
  5004. EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  5005. return __awaiter(this, void 0, void 0, function () {
  5006. return __generator(this, function (_a) {
  5007. switch (this.signInMethod) {
  5008. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  5009. return [2 /*return*/, updateEmailPassword(auth, {
  5010. idToken: idToken,
  5011. returnSecureToken: true,
  5012. email: this._email,
  5013. password: this._password
  5014. })];
  5015. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  5016. return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
  5017. idToken: idToken,
  5018. email: this._email,
  5019. oobCode: this._password
  5020. })];
  5021. default:
  5022. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5023. }
  5024. return [2 /*return*/];
  5025. });
  5026. });
  5027. };
  5028. /** @internal */
  5029. EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  5030. return this._getIdTokenResponse(auth);
  5031. };
  5032. return EmailAuthCredential;
  5033. }(AuthCredential));
  5034. /**
  5035. * @license
  5036. * Copyright 2020 Google LLC
  5037. *
  5038. * Licensed under the Apache License, Version 2.0 (the "License");
  5039. * you may not use this file except in compliance with the License.
  5040. * You may obtain a copy of the License at
  5041. *
  5042. * http://www.apache.org/licenses/LICENSE-2.0
  5043. *
  5044. * Unless required by applicable law or agreed to in writing, software
  5045. * distributed under the License is distributed on an "AS IS" BASIS,
  5046. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5047. * See the License for the specific language governing permissions and
  5048. * limitations under the License.
  5049. */
  5050. function signInWithIdp(auth, request) {
  5051. return __awaiter(this, void 0, void 0, function () {
  5052. return __generator(this, function (_a) {
  5053. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
  5054. });
  5055. });
  5056. }
  5057. /**
  5058. * @license
  5059. * Copyright 2020 Google LLC
  5060. *
  5061. * Licensed under the Apache License, Version 2.0 (the "License");
  5062. * you may not use this file except in compliance with the License.
  5063. * You may obtain a copy of the License at
  5064. *
  5065. * http://www.apache.org/licenses/LICENSE-2.0
  5066. *
  5067. * Unless required by applicable law or agreed to in writing, software
  5068. * distributed under the License is distributed on an "AS IS" BASIS,
  5069. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5070. * See the License for the specific language governing permissions and
  5071. * limitations under the License.
  5072. */
  5073. var IDP_REQUEST_URI$1 = 'http://localhost';
  5074. /**
  5075. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  5076. *
  5077. * @remarks
  5078. * Implementations specify the details about each auth provider's credential requirements.
  5079. *
  5080. * @public
  5081. */
  5082. var OAuthCredential = /** @class */ (function (_super) {
  5083. __extends(OAuthCredential, _super);
  5084. function OAuthCredential() {
  5085. var _this = _super !== null && _super.apply(this, arguments) || this;
  5086. _this.pendingToken = null;
  5087. return _this;
  5088. }
  5089. /** @internal */
  5090. OAuthCredential._fromParams = function (params) {
  5091. var cred = new OAuthCredential(params.providerId, params.signInMethod);
  5092. if (params.idToken || params.accessToken) {
  5093. // OAuth 2 and either ID token or access token.
  5094. if (params.idToken) {
  5095. cred.idToken = params.idToken;
  5096. }
  5097. if (params.accessToken) {
  5098. cred.accessToken = params.accessToken;
  5099. }
  5100. // Add nonce if available and no pendingToken is present.
  5101. if (params.nonce && !params.pendingToken) {
  5102. cred.nonce = params.nonce;
  5103. }
  5104. if (params.pendingToken) {
  5105. cred.pendingToken = params.pendingToken;
  5106. }
  5107. }
  5108. else if (params.oauthToken && params.oauthTokenSecret) {
  5109. // OAuth 1 and OAuth token with token secret
  5110. cred.accessToken = params.oauthToken;
  5111. cred.secret = params.oauthTokenSecret;
  5112. }
  5113. else {
  5114. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5115. }
  5116. return cred;
  5117. };
  5118. /** {@inheritdoc AuthCredential.toJSON} */
  5119. OAuthCredential.prototype.toJSON = function () {
  5120. return {
  5121. idToken: this.idToken,
  5122. accessToken: this.accessToken,
  5123. secret: this.secret,
  5124. nonce: this.nonce,
  5125. pendingToken: this.pendingToken,
  5126. providerId: this.providerId,
  5127. signInMethod: this.signInMethod
  5128. };
  5129. };
  5130. /**
  5131. * Static method to deserialize a JSON representation of an object into an
  5132. * {@link AuthCredential}.
  5133. *
  5134. * @param json - Input can be either Object or the stringified representation of the object.
  5135. * When string is provided, JSON.parse would be called first.
  5136. *
  5137. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  5138. */
  5139. OAuthCredential.fromJSON = function (json) {
  5140. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  5141. var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = __rest(obj, ["providerId", "signInMethod"]);
  5142. if (!providerId || !signInMethod) {
  5143. return null;
  5144. }
  5145. var cred = new OAuthCredential(providerId, signInMethod);
  5146. cred.idToken = rest.idToken || undefined;
  5147. cred.accessToken = rest.accessToken || undefined;
  5148. cred.secret = rest.secret;
  5149. cred.nonce = rest.nonce;
  5150. cred.pendingToken = rest.pendingToken || null;
  5151. return cred;
  5152. };
  5153. /** @internal */
  5154. OAuthCredential.prototype._getIdTokenResponse = function (auth) {
  5155. var request = this.buildRequest();
  5156. return signInWithIdp(auth, request);
  5157. };
  5158. /** @internal */
  5159. OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  5160. var request = this.buildRequest();
  5161. request.idToken = idToken;
  5162. return signInWithIdp(auth, request);
  5163. };
  5164. /** @internal */
  5165. OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  5166. var request = this.buildRequest();
  5167. request.autoCreate = false;
  5168. return signInWithIdp(auth, request);
  5169. };
  5170. OAuthCredential.prototype.buildRequest = function () {
  5171. var request = {
  5172. requestUri: IDP_REQUEST_URI$1,
  5173. returnSecureToken: true
  5174. };
  5175. if (this.pendingToken) {
  5176. request.pendingToken = this.pendingToken;
  5177. }
  5178. else {
  5179. var postBody = {};
  5180. if (this.idToken) {
  5181. postBody['id_token'] = this.idToken;
  5182. }
  5183. if (this.accessToken) {
  5184. postBody['access_token'] = this.accessToken;
  5185. }
  5186. if (this.secret) {
  5187. postBody['oauth_token_secret'] = this.secret;
  5188. }
  5189. postBody['providerId'] = this.providerId;
  5190. if (this.nonce && !this.pendingToken) {
  5191. postBody['nonce'] = this.nonce;
  5192. }
  5193. request.postBody = querystring(postBody);
  5194. }
  5195. return request;
  5196. };
  5197. return OAuthCredential;
  5198. }(AuthCredential));
  5199. /**
  5200. * @license
  5201. * Copyright 2020 Google LLC
  5202. *
  5203. * Licensed under the Apache License, Version 2.0 (the "License");
  5204. * you may not use this file except in compliance with the License.
  5205. * You may obtain a copy of the License at
  5206. *
  5207. * http://www.apache.org/licenses/LICENSE-2.0
  5208. *
  5209. * Unless required by applicable law or agreed to in writing, software
  5210. * distributed under the License is distributed on an "AS IS" BASIS,
  5211. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5212. * See the License for the specific language governing permissions and
  5213. * limitations under the License.
  5214. */
  5215. var _a;
  5216. function signInWithPhoneNumber(auth, request) {
  5217. return __awaiter(this, void 0, void 0, function () {
  5218. return __generator(this, function (_a) {
  5219. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  5220. });
  5221. });
  5222. }
  5223. function linkWithPhoneNumber(auth, request) {
  5224. return __awaiter(this, void 0, void 0, function () {
  5225. var response;
  5226. return __generator(this, function (_a) {
  5227. switch (_a.label) {
  5228. case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  5229. case 1:
  5230. response = _a.sent();
  5231. if (response.temporaryProof) {
  5232. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  5233. }
  5234. return [2 /*return*/, response];
  5235. }
  5236. });
  5237. });
  5238. }
  5239. var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
  5240. _a["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  5241. _a);
  5242. function verifyPhoneNumberForExisting(auth, request) {
  5243. return __awaiter(this, void 0, void 0, function () {
  5244. var apiRequest;
  5245. return __generator(this, function (_a) {
  5246. apiRequest = __assign(__assign({}, request), { operation: 'REAUTH' });
  5247. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_)];
  5248. });
  5249. });
  5250. }
  5251. /**
  5252. * @license
  5253. * Copyright 2020 Google LLC
  5254. *
  5255. * Licensed under the Apache License, Version 2.0 (the "License");
  5256. * you may not use this file except in compliance with the License.
  5257. * You may obtain a copy of the License at
  5258. *
  5259. * http://www.apache.org/licenses/LICENSE-2.0
  5260. *
  5261. * Unless required by applicable law or agreed to in writing, software
  5262. * distributed under the License is distributed on an "AS IS" BASIS,
  5263. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5264. * See the License for the specific language governing permissions and
  5265. * limitations under the License.
  5266. */
  5267. /**
  5268. * Represents the credentials returned by {@link PhoneAuthProvider}.
  5269. *
  5270. * @public
  5271. */
  5272. var PhoneAuthCredential = /** @class */ (function (_super) {
  5273. __extends(PhoneAuthCredential, _super);
  5274. function PhoneAuthCredential(params) {
  5275. var _this = _super.call(this, "phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */) || this;
  5276. _this.params = params;
  5277. return _this;
  5278. }
  5279. /** @internal */
  5280. PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
  5281. return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
  5282. };
  5283. /** @internal */
  5284. PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
  5285. return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
  5286. };
  5287. /** @internal */
  5288. PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
  5289. return signInWithPhoneNumber(auth, this._makeVerificationRequest());
  5290. };
  5291. /** @internal */
  5292. PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  5293. return linkWithPhoneNumber(auth, __assign({ idToken: idToken }, this._makeVerificationRequest()));
  5294. };
  5295. /** @internal */
  5296. PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  5297. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  5298. };
  5299. /** @internal */
  5300. PhoneAuthCredential.prototype._makeVerificationRequest = function () {
  5301. var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
  5302. if (temporaryProof && phoneNumber) {
  5303. return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
  5304. }
  5305. return {
  5306. sessionInfo: verificationId,
  5307. code: verificationCode
  5308. };
  5309. };
  5310. /** {@inheritdoc AuthCredential.toJSON} */
  5311. PhoneAuthCredential.prototype.toJSON = function () {
  5312. var obj = {
  5313. providerId: this.providerId
  5314. };
  5315. if (this.params.phoneNumber) {
  5316. obj.phoneNumber = this.params.phoneNumber;
  5317. }
  5318. if (this.params.temporaryProof) {
  5319. obj.temporaryProof = this.params.temporaryProof;
  5320. }
  5321. if (this.params.verificationCode) {
  5322. obj.verificationCode = this.params.verificationCode;
  5323. }
  5324. if (this.params.verificationId) {
  5325. obj.verificationId = this.params.verificationId;
  5326. }
  5327. return obj;
  5328. };
  5329. /** Generates a phone credential based on a plain object or a JSON string. */
  5330. PhoneAuthCredential.fromJSON = function (json) {
  5331. if (typeof json === 'string') {
  5332. json = JSON.parse(json);
  5333. }
  5334. var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
  5335. if (!verificationCode &&
  5336. !verificationId &&
  5337. !phoneNumber &&
  5338. !temporaryProof) {
  5339. return null;
  5340. }
  5341. return new PhoneAuthCredential({
  5342. verificationId: verificationId,
  5343. verificationCode: verificationCode,
  5344. phoneNumber: phoneNumber,
  5345. temporaryProof: temporaryProof
  5346. });
  5347. };
  5348. return PhoneAuthCredential;
  5349. }(AuthCredential));
  5350. /**
  5351. * @license
  5352. * Copyright 2020 Google LLC
  5353. *
  5354. * Licensed under the Apache License, Version 2.0 (the "License");
  5355. * you may not use this file except in compliance with the License.
  5356. * You may obtain a copy of the License at
  5357. *
  5358. * http://www.apache.org/licenses/LICENSE-2.0
  5359. *
  5360. * Unless required by applicable law or agreed to in writing, software
  5361. * distributed under the License is distributed on an "AS IS" BASIS,
  5362. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5363. * See the License for the specific language governing permissions and
  5364. * limitations under the License.
  5365. */
  5366. /**
  5367. * Maps the mode string in action code URL to Action Code Info operation.
  5368. *
  5369. * @param mode
  5370. */
  5371. function parseMode(mode) {
  5372. switch (mode) {
  5373. case 'recoverEmail':
  5374. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  5375. case 'resetPassword':
  5376. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  5377. case 'signIn':
  5378. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  5379. case 'verifyEmail':
  5380. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  5381. case 'verifyAndChangeEmail':
  5382. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  5383. case 'revertSecondFactorAddition':
  5384. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  5385. default:
  5386. return null;
  5387. }
  5388. }
  5389. /**
  5390. * Helper to parse FDL links
  5391. *
  5392. * @param url
  5393. */
  5394. function parseDeepLink(url) {
  5395. var link = querystringDecode(extractQuerystring(url))['link'];
  5396. // Double link case (automatic redirect).
  5397. var doubleDeepLink = link
  5398. ? querystringDecode(extractQuerystring(link))['deep_link_id']
  5399. : null;
  5400. // iOS custom scheme links.
  5401. var iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
  5402. var iOSDoubleDeepLink = iOSDeepLink
  5403. ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
  5404. : null;
  5405. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  5406. }
  5407. /**
  5408. * A utility class to parse email action URLs such as password reset, email verification,
  5409. * email link sign in, etc.
  5410. *
  5411. * @public
  5412. */
  5413. var ActionCodeURL = /** @class */ (function () {
  5414. /**
  5415. * @param actionLink - The link from which to extract the URL.
  5416. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  5417. *
  5418. * @internal
  5419. */
  5420. function ActionCodeURL(actionLink) {
  5421. var _a, _b, _c, _d, _e, _f;
  5422. var searchParams = querystringDecode(extractQuerystring(actionLink));
  5423. var apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  5424. var code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  5425. var operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  5426. // Validate API key, code and mode.
  5427. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5428. this.apiKey = apiKey;
  5429. this.operation = operation;
  5430. this.code = code;
  5431. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  5432. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  5433. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  5434. }
  5435. /**
  5436. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  5437. * otherwise returns null.
  5438. *
  5439. * @param link - The email action link string.
  5440. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  5441. *
  5442. * @public
  5443. */
  5444. ActionCodeURL.parseLink = function (link) {
  5445. var actionLink = parseDeepLink(link);
  5446. try {
  5447. return new ActionCodeURL(actionLink);
  5448. }
  5449. catch (_a) {
  5450. return null;
  5451. }
  5452. };
  5453. return ActionCodeURL;
  5454. }());
  5455. /**
  5456. * Parses the email action link string and returns an {@link ActionCodeURL} if
  5457. * the link is valid, otherwise returns null.
  5458. *
  5459. * @public
  5460. */
  5461. function parseActionCodeURL(link) {
  5462. return ActionCodeURL.parseLink(link);
  5463. }
  5464. /**
  5465. * @license
  5466. * Copyright 2020 Google LLC
  5467. *
  5468. * Licensed under the Apache License, Version 2.0 (the "License");
  5469. * you may not use this file except in compliance with the License.
  5470. * You may obtain a copy of the License at
  5471. *
  5472. * http://www.apache.org/licenses/LICENSE-2.0
  5473. *
  5474. * Unless required by applicable law or agreed to in writing, software
  5475. * distributed under the License is distributed on an "AS IS" BASIS,
  5476. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5477. * See the License for the specific language governing permissions and
  5478. * limitations under the License.
  5479. */
  5480. /**
  5481. * Provider for generating {@link EmailAuthCredential}.
  5482. *
  5483. * @public
  5484. */
  5485. var EmailAuthProvider = /** @class */ (function () {
  5486. function EmailAuthProvider() {
  5487. /**
  5488. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  5489. */
  5490. this.providerId = EmailAuthProvider.PROVIDER_ID;
  5491. }
  5492. /**
  5493. * Initialize an {@link AuthCredential} using an email and password.
  5494. *
  5495. * @example
  5496. * ```javascript
  5497. * const authCredential = EmailAuthProvider.credential(email, password);
  5498. * const userCredential = await signInWithCredential(auth, authCredential);
  5499. * ```
  5500. *
  5501. * @example
  5502. * ```javascript
  5503. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  5504. * ```
  5505. *
  5506. * @param email - Email address.
  5507. * @param password - User account password.
  5508. * @returns The auth provider credential.
  5509. */
  5510. EmailAuthProvider.credential = function (email, password) {
  5511. return EmailAuthCredential._fromEmailAndPassword(email, password);
  5512. };
  5513. /**
  5514. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  5515. * email link operation.
  5516. *
  5517. * @example
  5518. * ```javascript
  5519. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  5520. * const userCredential = await signInWithCredential(auth, authCredential);
  5521. * ```
  5522. *
  5523. * @example
  5524. * ```javascript
  5525. * await sendSignInLinkToEmail(auth, email);
  5526. * // Obtain emailLink from user.
  5527. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  5528. * ```
  5529. *
  5530. * @param auth - The {@link Auth} instance used to verify the link.
  5531. * @param email - Email address.
  5532. * @param emailLink - Sign-in email link.
  5533. * @returns - The auth provider credential.
  5534. */
  5535. EmailAuthProvider.credentialWithLink = function (email, emailLink) {
  5536. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  5537. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5538. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  5539. };
  5540. /**
  5541. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  5542. */
  5543. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  5544. /**
  5545. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  5546. */
  5547. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  5548. /**
  5549. * Always set to {@link SignInMethod}.EMAIL_LINK.
  5550. */
  5551. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  5552. return EmailAuthProvider;
  5553. }());
  5554. /**
  5555. * @license
  5556. * Copyright 2020 Google LLC
  5557. *
  5558. * Licensed under the Apache License, Version 2.0 (the "License");
  5559. * you may not use this file except in compliance with the License.
  5560. * You may obtain a copy of the License at
  5561. *
  5562. * http://www.apache.org/licenses/LICENSE-2.0
  5563. *
  5564. * Unless required by applicable law or agreed to in writing, software
  5565. * distributed under the License is distributed on an "AS IS" BASIS,
  5566. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5567. * See the License for the specific language governing permissions and
  5568. * limitations under the License.
  5569. */
  5570. /**
  5571. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  5572. *
  5573. * This class is not meant to be instantiated directly.
  5574. *
  5575. * @public
  5576. */
  5577. var FederatedAuthProvider = /** @class */ (function () {
  5578. /**
  5579. * Constructor for generic OAuth providers.
  5580. *
  5581. * @param providerId - Provider for which credentials should be generated.
  5582. */
  5583. function FederatedAuthProvider(providerId) {
  5584. this.providerId = providerId;
  5585. /** @internal */
  5586. this.defaultLanguageCode = null;
  5587. /** @internal */
  5588. this.customParameters = {};
  5589. }
  5590. /**
  5591. * Set the language gode.
  5592. *
  5593. * @param languageCode - language code
  5594. */
  5595. FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
  5596. this.defaultLanguageCode = languageCode;
  5597. };
  5598. /**
  5599. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  5600. * operations.
  5601. *
  5602. * @remarks
  5603. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  5604. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  5605. *
  5606. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  5607. */
  5608. FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
  5609. this.customParameters = customOAuthParameters;
  5610. return this;
  5611. };
  5612. /**
  5613. * Retrieve the current list of {@link CustomParameters}.
  5614. */
  5615. FederatedAuthProvider.prototype.getCustomParameters = function () {
  5616. return this.customParameters;
  5617. };
  5618. return FederatedAuthProvider;
  5619. }());
  5620. /**
  5621. * @license
  5622. * Copyright 2019 Google LLC
  5623. *
  5624. * Licensed under the Apache License, Version 2.0 (the "License");
  5625. * you may not use this file except in compliance with the License.
  5626. * You may obtain a copy of the License at
  5627. *
  5628. * http://www.apache.org/licenses/LICENSE-2.0
  5629. *
  5630. * Unless required by applicable law or agreed to in writing, software
  5631. * distributed under the License is distributed on an "AS IS" BASIS,
  5632. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5633. * See the License for the specific language governing permissions and
  5634. * limitations under the License.
  5635. */
  5636. /**
  5637. * Common code to all OAuth providers. This is separate from the
  5638. * {@link OAuthProvider} so that child providers (like
  5639. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  5640. * Instead, they rely on a static `credential` method.
  5641. */
  5642. var BaseOAuthProvider = /** @class */ (function (_super) {
  5643. __extends(BaseOAuthProvider, _super);
  5644. function BaseOAuthProvider() {
  5645. var _this = _super !== null && _super.apply(this, arguments) || this;
  5646. /** @internal */
  5647. _this.scopes = [];
  5648. return _this;
  5649. }
  5650. /**
  5651. * Add an OAuth scope to the credential.
  5652. *
  5653. * @param scope - Provider OAuth scope to add.
  5654. */
  5655. BaseOAuthProvider.prototype.addScope = function (scope) {
  5656. // If not already added, add scope to list.
  5657. if (!this.scopes.includes(scope)) {
  5658. this.scopes.push(scope);
  5659. }
  5660. return this;
  5661. };
  5662. /**
  5663. * Retrieve the current list of OAuth scopes.
  5664. */
  5665. BaseOAuthProvider.prototype.getScopes = function () {
  5666. return __spreadArray([], this.scopes, true);
  5667. };
  5668. return BaseOAuthProvider;
  5669. }(FederatedAuthProvider));
  5670. /**
  5671. * Provider for generating generic {@link OAuthCredential}.
  5672. *
  5673. * @example
  5674. * ```javascript
  5675. * // Sign in using a redirect.
  5676. * const provider = new OAuthProvider('google.com');
  5677. * // Start a sign in process for an unauthenticated user.
  5678. * provider.addScope('profile');
  5679. * provider.addScope('email');
  5680. * await signInWithRedirect(auth, provider);
  5681. * // This will trigger a full page redirect away from your app
  5682. *
  5683. * // After returning from the redirect when your app initializes you can obtain the result
  5684. * const result = await getRedirectResult(auth);
  5685. * if (result) {
  5686. * // This is the signed-in user
  5687. * const user = result.user;
  5688. * // This gives you a OAuth Access Token for the provider.
  5689. * const credential = provider.credentialFromResult(auth, result);
  5690. * const token = credential.accessToken;
  5691. * }
  5692. * ```
  5693. *
  5694. * @example
  5695. * ```javascript
  5696. * // Sign in using a popup.
  5697. * const provider = new OAuthProvider('google.com');
  5698. * provider.addScope('profile');
  5699. * provider.addScope('email');
  5700. * const result = await signInWithPopup(auth, provider);
  5701. *
  5702. * // The signed-in user info.
  5703. * const user = result.user;
  5704. * // This gives you a OAuth Access Token for the provider.
  5705. * const credential = provider.credentialFromResult(auth, result);
  5706. * const token = credential.accessToken;
  5707. * ```
  5708. * @public
  5709. */
  5710. var OAuthProvider = /** @class */ (function (_super) {
  5711. __extends(OAuthProvider, _super);
  5712. function OAuthProvider() {
  5713. return _super !== null && _super.apply(this, arguments) || this;
  5714. }
  5715. /**
  5716. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  5717. * @param json - A plain object or a JSON string
  5718. */
  5719. OAuthProvider.credentialFromJSON = function (json) {
  5720. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  5721. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5722. return OAuthCredential._fromParams(obj);
  5723. };
  5724. /**
  5725. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  5726. *
  5727. * @remarks
  5728. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  5729. * the raw nonce must match the nonce field in the ID token.
  5730. *
  5731. * @example
  5732. * ```javascript
  5733. * // `googleUser` from the onsuccess Google Sign In callback.
  5734. * // Initialize a generate OAuth provider with a `google.com` providerId.
  5735. * const provider = new OAuthProvider('google.com');
  5736. * const credential = provider.credential({
  5737. * idToken: googleUser.getAuthResponse().id_token,
  5738. * });
  5739. * const result = await signInWithCredential(credential);
  5740. * ```
  5741. *
  5742. * @param params - Either the options object containing the ID token, access token and raw nonce
  5743. * or the ID token string.
  5744. */
  5745. OAuthProvider.prototype.credential = function (params) {
  5746. return this._credential(__assign(__assign({}, params), { nonce: params.rawNonce }));
  5747. };
  5748. /** An internal credential method that accepts more permissive options */
  5749. OAuthProvider.prototype._credential = function (params) {
  5750. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5751. // For OAuthCredential, sign in method is same as providerId.
  5752. return OAuthCredential._fromParams(__assign(__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  5753. };
  5754. /**
  5755. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5756. *
  5757. * @param userCredential - The user credential.
  5758. */
  5759. OAuthProvider.credentialFromResult = function (userCredential) {
  5760. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  5761. };
  5762. /**
  5763. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5764. * thrown during a sign-in, link, or reauthenticate operation.
  5765. *
  5766. * @param userCredential - The user credential.
  5767. */
  5768. OAuthProvider.credentialFromError = function (error) {
  5769. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  5770. };
  5771. OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
  5772. var tokenResponse = _a._tokenResponse;
  5773. if (!tokenResponse) {
  5774. return null;
  5775. }
  5776. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
  5777. if (!oauthAccessToken &&
  5778. !oauthTokenSecret &&
  5779. !oauthIdToken &&
  5780. !pendingToken) {
  5781. return null;
  5782. }
  5783. if (!providerId) {
  5784. return null;
  5785. }
  5786. try {
  5787. return new OAuthProvider(providerId)._credential({
  5788. idToken: oauthIdToken,
  5789. accessToken: oauthAccessToken,
  5790. nonce: nonce,
  5791. pendingToken: pendingToken
  5792. });
  5793. }
  5794. catch (e) {
  5795. return null;
  5796. }
  5797. };
  5798. return OAuthProvider;
  5799. }(BaseOAuthProvider));
  5800. /**
  5801. * @license
  5802. * Copyright 2020 Google LLC
  5803. *
  5804. * Licensed under the Apache License, Version 2.0 (the "License");
  5805. * you may not use this file except in compliance with the License.
  5806. * You may obtain a copy of the License at
  5807. *
  5808. * http://www.apache.org/licenses/LICENSE-2.0
  5809. *
  5810. * Unless required by applicable law or agreed to in writing, software
  5811. * distributed under the License is distributed on an "AS IS" BASIS,
  5812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5813. * See the License for the specific language governing permissions and
  5814. * limitations under the License.
  5815. */
  5816. /**
  5817. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  5818. *
  5819. * @example
  5820. * ```javascript
  5821. * // Sign in using a redirect.
  5822. * const provider = new FacebookAuthProvider();
  5823. * // Start a sign in process for an unauthenticated user.
  5824. * provider.addScope('user_birthday');
  5825. * await signInWithRedirect(auth, provider);
  5826. * // This will trigger a full page redirect away from your app
  5827. *
  5828. * // After returning from the redirect when your app initializes you can obtain the result
  5829. * const result = await getRedirectResult(auth);
  5830. * if (result) {
  5831. * // This is the signed-in user
  5832. * const user = result.user;
  5833. * // This gives you a Facebook Access Token.
  5834. * const credential = FacebookAuthProvider.credentialFromResult(result);
  5835. * const token = credential.accessToken;
  5836. * }
  5837. * ```
  5838. *
  5839. * @example
  5840. * ```javascript
  5841. * // Sign in using a popup.
  5842. * const provider = new FacebookAuthProvider();
  5843. * provider.addScope('user_birthday');
  5844. * const result = await signInWithPopup(auth, provider);
  5845. *
  5846. * // The signed-in user info.
  5847. * const user = result.user;
  5848. * // This gives you a Facebook Access Token.
  5849. * const credential = FacebookAuthProvider.credentialFromResult(result);
  5850. * const token = credential.accessToken;
  5851. * ```
  5852. *
  5853. * @public
  5854. */
  5855. var FacebookAuthProvider = /** @class */ (function (_super) {
  5856. __extends(FacebookAuthProvider, _super);
  5857. function FacebookAuthProvider() {
  5858. return _super.call(this, "facebook.com" /* ProviderId.FACEBOOK */) || this;
  5859. }
  5860. /**
  5861. * Creates a credential for Facebook.
  5862. *
  5863. * @example
  5864. * ```javascript
  5865. * // `event` from the Facebook auth.authResponseChange callback.
  5866. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  5867. * const result = await signInWithCredential(credential);
  5868. * ```
  5869. *
  5870. * @param accessToken - Facebook access token.
  5871. */
  5872. FacebookAuthProvider.credential = function (accessToken) {
  5873. return OAuthCredential._fromParams({
  5874. providerId: FacebookAuthProvider.PROVIDER_ID,
  5875. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  5876. accessToken: accessToken
  5877. });
  5878. };
  5879. /**
  5880. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5881. *
  5882. * @param userCredential - The user credential.
  5883. */
  5884. FacebookAuthProvider.credentialFromResult = function (userCredential) {
  5885. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  5886. };
  5887. /**
  5888. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5889. * thrown during a sign-in, link, or reauthenticate operation.
  5890. *
  5891. * @param userCredential - The user credential.
  5892. */
  5893. FacebookAuthProvider.credentialFromError = function (error) {
  5894. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5895. };
  5896. FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
  5897. var tokenResponse = _a._tokenResponse;
  5898. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  5899. return null;
  5900. }
  5901. if (!tokenResponse.oauthAccessToken) {
  5902. return null;
  5903. }
  5904. try {
  5905. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  5906. }
  5907. catch (_b) {
  5908. return null;
  5909. }
  5910. };
  5911. /** Always set to {@link SignInMethod}.FACEBOOK. */
  5912. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  5913. /** Always set to {@link ProviderId}.FACEBOOK. */
  5914. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  5915. return FacebookAuthProvider;
  5916. }(BaseOAuthProvider));
  5917. /**
  5918. * @license
  5919. * Copyright 2020 Google LLC
  5920. *
  5921. * Licensed under the Apache License, Version 2.0 (the "License");
  5922. * you may not use this file except in compliance with the License.
  5923. * You may obtain a copy of the License at
  5924. *
  5925. * http://www.apache.org/licenses/LICENSE-2.0
  5926. *
  5927. * Unless required by applicable law or agreed to in writing, software
  5928. * distributed under the License is distributed on an "AS IS" BASIS,
  5929. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5930. * See the License for the specific language governing permissions and
  5931. * limitations under the License.
  5932. */
  5933. /**
  5934. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  5935. *
  5936. * @example
  5937. * ```javascript
  5938. * // Sign in using a redirect.
  5939. * const provider = new GoogleAuthProvider();
  5940. * // Start a sign in process for an unauthenticated user.
  5941. * provider.addScope('profile');
  5942. * provider.addScope('email');
  5943. * await signInWithRedirect(auth, provider);
  5944. * // This will trigger a full page redirect away from your app
  5945. *
  5946. * // After returning from the redirect when your app initializes you can obtain the result
  5947. * const result = await getRedirectResult(auth);
  5948. * if (result) {
  5949. * // This is the signed-in user
  5950. * const user = result.user;
  5951. * // This gives you a Google Access Token.
  5952. * const credential = GoogleAuthProvider.credentialFromResult(result);
  5953. * const token = credential.accessToken;
  5954. * }
  5955. * ```
  5956. *
  5957. * @example
  5958. * ```javascript
  5959. * // Sign in using a popup.
  5960. * const provider = new GoogleAuthProvider();
  5961. * provider.addScope('profile');
  5962. * provider.addScope('email');
  5963. * const result = await signInWithPopup(auth, provider);
  5964. *
  5965. * // The signed-in user info.
  5966. * const user = result.user;
  5967. * // This gives you a Google Access Token.
  5968. * const credential = GoogleAuthProvider.credentialFromResult(result);
  5969. * const token = credential.accessToken;
  5970. * ```
  5971. *
  5972. * @public
  5973. */
  5974. var GoogleAuthProvider = /** @class */ (function (_super) {
  5975. __extends(GoogleAuthProvider, _super);
  5976. function GoogleAuthProvider() {
  5977. var _this = _super.call(this, "google.com" /* ProviderId.GOOGLE */) || this;
  5978. _this.addScope('profile');
  5979. return _this;
  5980. }
  5981. /**
  5982. * Creates a credential for Google. At least one of ID token and access token is required.
  5983. *
  5984. * @example
  5985. * ```javascript
  5986. * // \`googleUser\` from the onsuccess Google Sign In callback.
  5987. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  5988. * const result = await signInWithCredential(credential);
  5989. * ```
  5990. *
  5991. * @param idToken - Google ID token.
  5992. * @param accessToken - Google access token.
  5993. */
  5994. GoogleAuthProvider.credential = function (idToken, accessToken) {
  5995. return OAuthCredential._fromParams({
  5996. providerId: GoogleAuthProvider.PROVIDER_ID,
  5997. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  5998. idToken: idToken,
  5999. accessToken: accessToken
  6000. });
  6001. };
  6002. /**
  6003. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  6004. *
  6005. * @param userCredential - The user credential.
  6006. */
  6007. GoogleAuthProvider.credentialFromResult = function (userCredential) {
  6008. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  6009. };
  6010. /**
  6011. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  6012. * thrown during a sign-in, link, or reauthenticate operation.
  6013. *
  6014. * @param userCredential - The user credential.
  6015. */
  6016. GoogleAuthProvider.credentialFromError = function (error) {
  6017. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  6018. };
  6019. GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
  6020. var tokenResponse = _a._tokenResponse;
  6021. if (!tokenResponse) {
  6022. return null;
  6023. }
  6024. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
  6025. if (!oauthIdToken && !oauthAccessToken) {
  6026. // This could be an oauth 1 credential or a phone credential
  6027. return null;
  6028. }
  6029. try {
  6030. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  6031. }
  6032. catch (_c) {
  6033. return null;
  6034. }
  6035. };
  6036. /** Always set to {@link SignInMethod}.GOOGLE. */
  6037. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  6038. /** Always set to {@link ProviderId}.GOOGLE. */
  6039. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  6040. return GoogleAuthProvider;
  6041. }(BaseOAuthProvider));
  6042. /**
  6043. * @license
  6044. * Copyright 2020 Google LLC
  6045. *
  6046. * Licensed under the Apache License, Version 2.0 (the "License");
  6047. * you may not use this file except in compliance with the License.
  6048. * You may obtain a copy of the License at
  6049. *
  6050. * http://www.apache.org/licenses/LICENSE-2.0
  6051. *
  6052. * Unless required by applicable law or agreed to in writing, software
  6053. * distributed under the License is distributed on an "AS IS" BASIS,
  6054. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6055. * See the License for the specific language governing permissions and
  6056. * limitations under the License.
  6057. */
  6058. /**
  6059. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  6060. *
  6061. * @remarks
  6062. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  6063. * the {@link signInWithPopup} handler:
  6064. *
  6065. * @example
  6066. * ```javascript
  6067. * // Sign in using a redirect.
  6068. * const provider = new GithubAuthProvider();
  6069. * // Start a sign in process for an unauthenticated user.
  6070. * provider.addScope('repo');
  6071. * await signInWithRedirect(auth, provider);
  6072. * // This will trigger a full page redirect away from your app
  6073. *
  6074. * // After returning from the redirect when your app initializes you can obtain the result
  6075. * const result = await getRedirectResult(auth);
  6076. * if (result) {
  6077. * // This is the signed-in user
  6078. * const user = result.user;
  6079. * // This gives you a Github Access Token.
  6080. * const credential = GithubAuthProvider.credentialFromResult(result);
  6081. * const token = credential.accessToken;
  6082. * }
  6083. * ```
  6084. *
  6085. * @example
  6086. * ```javascript
  6087. * // Sign in using a popup.
  6088. * const provider = new GithubAuthProvider();
  6089. * provider.addScope('repo');
  6090. * const result = await signInWithPopup(auth, provider);
  6091. *
  6092. * // The signed-in user info.
  6093. * const user = result.user;
  6094. * // This gives you a Github Access Token.
  6095. * const credential = GithubAuthProvider.credentialFromResult(result);
  6096. * const token = credential.accessToken;
  6097. * ```
  6098. * @public
  6099. */
  6100. var GithubAuthProvider = /** @class */ (function (_super) {
  6101. __extends(GithubAuthProvider, _super);
  6102. function GithubAuthProvider() {
  6103. return _super.call(this, "github.com" /* ProviderId.GITHUB */) || this;
  6104. }
  6105. /**
  6106. * Creates a credential for Github.
  6107. *
  6108. * @param accessToken - Github access token.
  6109. */
  6110. GithubAuthProvider.credential = function (accessToken) {
  6111. return OAuthCredential._fromParams({
  6112. providerId: GithubAuthProvider.PROVIDER_ID,
  6113. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  6114. accessToken: accessToken
  6115. });
  6116. };
  6117. /**
  6118. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  6119. *
  6120. * @param userCredential - The user credential.
  6121. */
  6122. GithubAuthProvider.credentialFromResult = function (userCredential) {
  6123. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  6124. };
  6125. /**
  6126. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  6127. * thrown during a sign-in, link, or reauthenticate operation.
  6128. *
  6129. * @param userCredential - The user credential.
  6130. */
  6131. GithubAuthProvider.credentialFromError = function (error) {
  6132. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  6133. };
  6134. GithubAuthProvider.credentialFromTaggedObject = function (_a) {
  6135. var tokenResponse = _a._tokenResponse;
  6136. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  6137. return null;
  6138. }
  6139. if (!tokenResponse.oauthAccessToken) {
  6140. return null;
  6141. }
  6142. try {
  6143. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  6144. }
  6145. catch (_b) {
  6146. return null;
  6147. }
  6148. };
  6149. /** Always set to {@link SignInMethod}.GITHUB. */
  6150. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  6151. /** Always set to {@link ProviderId}.GITHUB. */
  6152. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  6153. return GithubAuthProvider;
  6154. }(BaseOAuthProvider));
  6155. /**
  6156. * @license
  6157. * Copyright 2020 Google LLC
  6158. *
  6159. * Licensed under the Apache License, Version 2.0 (the "License");
  6160. * you may not use this file except in compliance with the License.
  6161. * You may obtain a copy of the License at
  6162. *
  6163. * http://www.apache.org/licenses/LICENSE-2.0
  6164. *
  6165. * Unless required by applicable law or agreed to in writing, software
  6166. * distributed under the License is distributed on an "AS IS" BASIS,
  6167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6168. * See the License for the specific language governing permissions and
  6169. * limitations under the License.
  6170. */
  6171. var IDP_REQUEST_URI = 'http://localhost';
  6172. /**
  6173. * @public
  6174. */
  6175. var SAMLAuthCredential = /** @class */ (function (_super) {
  6176. __extends(SAMLAuthCredential, _super);
  6177. /** @internal */
  6178. function SAMLAuthCredential(providerId, pendingToken) {
  6179. var _this = _super.call(this, providerId, providerId) || this;
  6180. _this.pendingToken = pendingToken;
  6181. return _this;
  6182. }
  6183. /** @internal */
  6184. SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
  6185. var request = this.buildRequest();
  6186. return signInWithIdp(auth, request);
  6187. };
  6188. /** @internal */
  6189. SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  6190. var request = this.buildRequest();
  6191. request.idToken = idToken;
  6192. return signInWithIdp(auth, request);
  6193. };
  6194. /** @internal */
  6195. SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  6196. var request = this.buildRequest();
  6197. request.autoCreate = false;
  6198. return signInWithIdp(auth, request);
  6199. };
  6200. /** {@inheritdoc AuthCredential.toJSON} */
  6201. SAMLAuthCredential.prototype.toJSON = function () {
  6202. return {
  6203. signInMethod: this.signInMethod,
  6204. providerId: this.providerId,
  6205. pendingToken: this.pendingToken
  6206. };
  6207. };
  6208. /**
  6209. * Static method to deserialize a JSON representation of an object into an
  6210. * {@link AuthCredential}.
  6211. *
  6212. * @param json - Input can be either Object or the stringified representation of the object.
  6213. * When string is provided, JSON.parse would be called first.
  6214. *
  6215. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  6216. */
  6217. SAMLAuthCredential.fromJSON = function (json) {
  6218. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  6219. var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
  6220. if (!providerId ||
  6221. !signInMethod ||
  6222. !pendingToken ||
  6223. providerId !== signInMethod) {
  6224. return null;
  6225. }
  6226. return new SAMLAuthCredential(providerId, pendingToken);
  6227. };
  6228. /**
  6229. * Helper static method to avoid exposing the constructor to end users.
  6230. *
  6231. * @internal
  6232. */
  6233. SAMLAuthCredential._create = function (providerId, pendingToken) {
  6234. return new SAMLAuthCredential(providerId, pendingToken);
  6235. };
  6236. SAMLAuthCredential.prototype.buildRequest = function () {
  6237. return {
  6238. requestUri: IDP_REQUEST_URI,
  6239. returnSecureToken: true,
  6240. pendingToken: this.pendingToken
  6241. };
  6242. };
  6243. return SAMLAuthCredential;
  6244. }(AuthCredential));
  6245. /**
  6246. * @license
  6247. * Copyright 2020 Google LLC
  6248. *
  6249. * Licensed under the Apache License, Version 2.0 (the "License");
  6250. * you may not use this file except in compliance with the License.
  6251. * You may obtain a copy of the License at
  6252. *
  6253. * http://www.apache.org/licenses/LICENSE-2.0
  6254. *
  6255. * Unless required by applicable law or agreed to in writing, software
  6256. * distributed under the License is distributed on an "AS IS" BASIS,
  6257. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6258. * See the License for the specific language governing permissions and
  6259. * limitations under the License.
  6260. */
  6261. var SAML_PROVIDER_PREFIX = 'saml.';
  6262. /**
  6263. * An {@link AuthProvider} for SAML.
  6264. *
  6265. * @public
  6266. */
  6267. var SAMLAuthProvider = /** @class */ (function (_super) {
  6268. __extends(SAMLAuthProvider, _super);
  6269. /**
  6270. * Constructor. The providerId must start with "saml."
  6271. * @param providerId - SAML provider ID.
  6272. */
  6273. function SAMLAuthProvider(providerId) {
  6274. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6275. return _super.call(this, providerId) || this;
  6276. }
  6277. /**
  6278. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  6279. * successful SAML flow completes.
  6280. *
  6281. * @remarks
  6282. *
  6283. * For example, to get an {@link AuthCredential}, you could write the
  6284. * following code:
  6285. *
  6286. * ```js
  6287. * const userCredential = await signInWithPopup(auth, samlProvider);
  6288. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  6289. * ```
  6290. *
  6291. * @param userCredential - The user credential.
  6292. */
  6293. SAMLAuthProvider.credentialFromResult = function (userCredential) {
  6294. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  6295. };
  6296. /**
  6297. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  6298. * thrown during a sign-in, link, or reauthenticate operation.
  6299. *
  6300. * @param userCredential - The user credential.
  6301. */
  6302. SAMLAuthProvider.credentialFromError = function (error) {
  6303. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  6304. };
  6305. /**
  6306. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  6307. * @param json - A plain object or a JSON string
  6308. */
  6309. SAMLAuthProvider.credentialFromJSON = function (json) {
  6310. var credential = SAMLAuthCredential.fromJSON(json);
  6311. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6312. return credential;
  6313. };
  6314. SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
  6315. var tokenResponse = _a._tokenResponse;
  6316. if (!tokenResponse) {
  6317. return null;
  6318. }
  6319. var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
  6320. if (!pendingToken || !providerId) {
  6321. return null;
  6322. }
  6323. try {
  6324. return SAMLAuthCredential._create(providerId, pendingToken);
  6325. }
  6326. catch (e) {
  6327. return null;
  6328. }
  6329. };
  6330. return SAMLAuthProvider;
  6331. }(FederatedAuthProvider));
  6332. /**
  6333. * @license
  6334. * Copyright 2020 Google LLC
  6335. *
  6336. * Licensed under the Apache License, Version 2.0 (the "License");
  6337. * you may not use this file except in compliance with the License.
  6338. * You may obtain a copy of the License at
  6339. *
  6340. * http://www.apache.org/licenses/LICENSE-2.0
  6341. *
  6342. * Unless required by applicable law or agreed to in writing, software
  6343. * distributed under the License is distributed on an "AS IS" BASIS,
  6344. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6345. * See the License for the specific language governing permissions and
  6346. * limitations under the License.
  6347. */
  6348. /**
  6349. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  6350. *
  6351. * @example
  6352. * ```javascript
  6353. * // Sign in using a redirect.
  6354. * const provider = new TwitterAuthProvider();
  6355. * // Start a sign in process for an unauthenticated user.
  6356. * await signInWithRedirect(auth, provider);
  6357. * // This will trigger a full page redirect away from your app
  6358. *
  6359. * // After returning from the redirect when your app initializes you can obtain the result
  6360. * const result = await getRedirectResult(auth);
  6361. * if (result) {
  6362. * // This is the signed-in user
  6363. * const user = result.user;
  6364. * // This gives you a Twitter Access Token and Secret.
  6365. * const credential = TwitterAuthProvider.credentialFromResult(result);
  6366. * const token = credential.accessToken;
  6367. * const secret = credential.secret;
  6368. * }
  6369. * ```
  6370. *
  6371. * @example
  6372. * ```javascript
  6373. * // Sign in using a popup.
  6374. * const provider = new TwitterAuthProvider();
  6375. * const result = await signInWithPopup(auth, provider);
  6376. *
  6377. * // The signed-in user info.
  6378. * const user = result.user;
  6379. * // This gives you a Twitter Access Token and Secret.
  6380. * const credential = TwitterAuthProvider.credentialFromResult(result);
  6381. * const token = credential.accessToken;
  6382. * const secret = credential.secret;
  6383. * ```
  6384. *
  6385. * @public
  6386. */
  6387. var TwitterAuthProvider = /** @class */ (function (_super) {
  6388. __extends(TwitterAuthProvider, _super);
  6389. function TwitterAuthProvider() {
  6390. return _super.call(this, "twitter.com" /* ProviderId.TWITTER */) || this;
  6391. }
  6392. /**
  6393. * Creates a credential for Twitter.
  6394. *
  6395. * @param token - Twitter access token.
  6396. * @param secret - Twitter secret.
  6397. */
  6398. TwitterAuthProvider.credential = function (token, secret) {
  6399. return OAuthCredential._fromParams({
  6400. providerId: TwitterAuthProvider.PROVIDER_ID,
  6401. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  6402. oauthToken: token,
  6403. oauthTokenSecret: secret
  6404. });
  6405. };
  6406. /**
  6407. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  6408. *
  6409. * @param userCredential - The user credential.
  6410. */
  6411. TwitterAuthProvider.credentialFromResult = function (userCredential) {
  6412. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  6413. };
  6414. /**
  6415. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  6416. * thrown during a sign-in, link, or reauthenticate operation.
  6417. *
  6418. * @param userCredential - The user credential.
  6419. */
  6420. TwitterAuthProvider.credentialFromError = function (error) {
  6421. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  6422. };
  6423. TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
  6424. var tokenResponse = _a._tokenResponse;
  6425. if (!tokenResponse) {
  6426. return null;
  6427. }
  6428. var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
  6429. if (!oauthAccessToken || !oauthTokenSecret) {
  6430. return null;
  6431. }
  6432. try {
  6433. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  6434. }
  6435. catch (_c) {
  6436. return null;
  6437. }
  6438. };
  6439. /** Always set to {@link SignInMethod}.TWITTER. */
  6440. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  6441. /** Always set to {@link ProviderId}.TWITTER. */
  6442. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  6443. return TwitterAuthProvider;
  6444. }(BaseOAuthProvider));
  6445. /**
  6446. * @license
  6447. * Copyright 2020 Google LLC
  6448. *
  6449. * Licensed under the Apache License, Version 2.0 (the "License");
  6450. * you may not use this file except in compliance with the License.
  6451. * You may obtain a copy of the License at
  6452. *
  6453. * http://www.apache.org/licenses/LICENSE-2.0
  6454. *
  6455. * Unless required by applicable law or agreed to in writing, software
  6456. * distributed under the License is distributed on an "AS IS" BASIS,
  6457. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6458. * See the License for the specific language governing permissions and
  6459. * limitations under the License.
  6460. */
  6461. function signUp(auth, request) {
  6462. return __awaiter(this, void 0, void 0, function () {
  6463. return __generator(this, function (_a) {
  6464. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request))];
  6465. });
  6466. });
  6467. }
  6468. /**
  6469. * @license
  6470. * Copyright 2020 Google LLC
  6471. *
  6472. * Licensed under the Apache License, Version 2.0 (the "License");
  6473. * you may not use this file except in compliance with the License.
  6474. * You may obtain a copy of the License at
  6475. *
  6476. * http://www.apache.org/licenses/LICENSE-2.0
  6477. *
  6478. * Unless required by applicable law or agreed to in writing, software
  6479. * distributed under the License is distributed on an "AS IS" BASIS,
  6480. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6481. * See the License for the specific language governing permissions and
  6482. * limitations under the License.
  6483. */
  6484. var UserCredentialImpl = /** @class */ (function () {
  6485. function UserCredentialImpl(params) {
  6486. this.user = params.user;
  6487. this.providerId = params.providerId;
  6488. this._tokenResponse = params._tokenResponse;
  6489. this.operationType = params.operationType;
  6490. }
  6491. UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
  6492. if (isAnonymous === void 0) { isAnonymous = false; }
  6493. return __awaiter(this, void 0, void 0, function () {
  6494. var user, providerId, userCred;
  6495. return __generator(this, function (_a) {
  6496. switch (_a.label) {
  6497. case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
  6498. case 1:
  6499. user = _a.sent();
  6500. providerId = providerIdForResponse(idTokenResponse);
  6501. userCred = new UserCredentialImpl({
  6502. user: user,
  6503. providerId: providerId,
  6504. _tokenResponse: idTokenResponse,
  6505. operationType: operationType
  6506. });
  6507. return [2 /*return*/, userCred];
  6508. }
  6509. });
  6510. });
  6511. };
  6512. UserCredentialImpl._forOperation = function (user, operationType, response) {
  6513. return __awaiter(this, void 0, void 0, function () {
  6514. var providerId;
  6515. return __generator(this, function (_a) {
  6516. switch (_a.label) {
  6517. case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  6518. case 1:
  6519. _a.sent();
  6520. providerId = providerIdForResponse(response);
  6521. return [2 /*return*/, new UserCredentialImpl({
  6522. user: user,
  6523. providerId: providerId,
  6524. _tokenResponse: response,
  6525. operationType: operationType
  6526. })];
  6527. }
  6528. });
  6529. });
  6530. };
  6531. return UserCredentialImpl;
  6532. }());
  6533. function providerIdForResponse(response) {
  6534. if (response.providerId) {
  6535. return response.providerId;
  6536. }
  6537. if ('phoneNumber' in response) {
  6538. return "phone" /* ProviderId.PHONE */;
  6539. }
  6540. return null;
  6541. }
  6542. /**
  6543. * @license
  6544. * Copyright 2020 Google LLC
  6545. *
  6546. * Licensed under the Apache License, Version 2.0 (the "License");
  6547. * you may not use this file except in compliance with the License.
  6548. * You may obtain a copy of the License at
  6549. *
  6550. * http://www.apache.org/licenses/LICENSE-2.0
  6551. *
  6552. * Unless required by applicable law or agreed to in writing, software
  6553. * distributed under the License is distributed on an "AS IS" BASIS,
  6554. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6555. * See the License for the specific language governing permissions and
  6556. * limitations under the License.
  6557. */
  6558. /**
  6559. * Asynchronously signs in as an anonymous user.
  6560. *
  6561. * @remarks
  6562. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  6563. * new anonymous user identity will be created and returned.
  6564. *
  6565. * @param auth - The {@link Auth} instance.
  6566. *
  6567. * @public
  6568. */
  6569. function signInAnonymously(auth) {
  6570. var _a;
  6571. return __awaiter(this, void 0, void 0, function () {
  6572. var authInternal, response, userCredential;
  6573. return __generator(this, function (_b) {
  6574. switch (_b.label) {
  6575. case 0:
  6576. authInternal = _castAuth(auth);
  6577. return [4 /*yield*/, authInternal._initializationPromise];
  6578. case 1:
  6579. _b.sent();
  6580. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  6581. // If an anonymous user is already signed in, no need to sign them in again.
  6582. return [2 /*return*/, new UserCredentialImpl({
  6583. user: authInternal.currentUser,
  6584. providerId: null,
  6585. operationType: "signIn" /* OperationType.SIGN_IN */
  6586. })];
  6587. }
  6588. return [4 /*yield*/, signUp(authInternal, {
  6589. returnSecureToken: true
  6590. })];
  6591. case 2:
  6592. response = _b.sent();
  6593. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true)];
  6594. case 3:
  6595. userCredential = _b.sent();
  6596. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  6597. case 4:
  6598. _b.sent();
  6599. return [2 /*return*/, userCredential];
  6600. }
  6601. });
  6602. });
  6603. }
  6604. /**
  6605. * @license
  6606. * Copyright 2020 Google LLC
  6607. *
  6608. * Licensed under the Apache License, Version 2.0 (the "License");
  6609. * you may not use this file except in compliance with the License.
  6610. * You may obtain a copy of the License at
  6611. *
  6612. * http://www.apache.org/licenses/LICENSE-2.0
  6613. *
  6614. * Unless required by applicable law or agreed to in writing, software
  6615. * distributed under the License is distributed on an "AS IS" BASIS,
  6616. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6617. * See the License for the specific language governing permissions and
  6618. * limitations under the License.
  6619. */
  6620. var MultiFactorError = /** @class */ (function (_super) {
  6621. __extends(MultiFactorError, _super);
  6622. function MultiFactorError(auth, error, operationType, user) {
  6623. var _this = this;
  6624. var _a;
  6625. _this = _super.call(this, error.code, error.message) || this;
  6626. _this.operationType = operationType;
  6627. _this.user = user;
  6628. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6629. Object.setPrototypeOf(_this, MultiFactorError.prototype);
  6630. _this.customData = {
  6631. appName: auth.name,
  6632. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  6633. _serverResponse: error.customData._serverResponse,
  6634. operationType: operationType
  6635. };
  6636. return _this;
  6637. }
  6638. MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
  6639. return new MultiFactorError(auth, error, operationType, user);
  6640. };
  6641. return MultiFactorError;
  6642. }(FirebaseError));
  6643. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  6644. var idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  6645. ? credential._getReauthenticationResolver(auth)
  6646. : credential._getIdTokenResponse(auth);
  6647. return idTokenProvider.catch(function (error) {
  6648. if (error.code === "auth/".concat("multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */)) {
  6649. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  6650. }
  6651. throw error;
  6652. });
  6653. }
  6654. /**
  6655. * @license
  6656. * Copyright 2020 Google LLC
  6657. *
  6658. * Licensed under the Apache License, Version 2.0 (the "License");
  6659. * you may not use this file except in compliance with the License.
  6660. * You may obtain a copy of the License at
  6661. *
  6662. * http://www.apache.org/licenses/LICENSE-2.0
  6663. *
  6664. * Unless required by applicable law or agreed to in writing, software
  6665. * distributed under the License is distributed on an "AS IS" BASIS,
  6666. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6667. * See the License for the specific language governing permissions and
  6668. * limitations under the License.
  6669. */
  6670. /**
  6671. * Takes a set of UserInfo provider data and converts it to a set of names
  6672. */
  6673. function providerDataAsNames(providerData) {
  6674. return new Set(providerData
  6675. .map(function (_a) {
  6676. var providerId = _a.providerId;
  6677. return providerId;
  6678. })
  6679. .filter(function (pid) { return !!pid; }));
  6680. }
  6681. /**
  6682. * @license
  6683. * Copyright 2019 Google LLC
  6684. *
  6685. * Licensed under the Apache License, Version 2.0 (the "License");
  6686. * you may not use this file except in compliance with the License.
  6687. * You may obtain a copy of the License at
  6688. *
  6689. * http://www.apache.org/licenses/LICENSE-2.0
  6690. *
  6691. * Unless required by applicable law or agreed to in writing, software
  6692. * distributed under the License is distributed on an "AS IS" BASIS,
  6693. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6694. * See the License for the specific language governing permissions and
  6695. * limitations under the License.
  6696. */
  6697. /**
  6698. * Unlinks a provider from a user account.
  6699. *
  6700. * @param user - The user.
  6701. * @param providerId - The provider to unlink.
  6702. *
  6703. * @public
  6704. */
  6705. function unlink(user, providerId) {
  6706. return __awaiter(this, void 0, void 0, function () {
  6707. var userInternal, providerUserInfo, _a, _b, providersLeft;
  6708. var _c;
  6709. return __generator(this, function (_d) {
  6710. switch (_d.label) {
  6711. case 0:
  6712. userInternal = getModularInstance(user);
  6713. return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
  6714. case 1:
  6715. _d.sent();
  6716. _a = deleteLinkedAccounts;
  6717. _b = [userInternal.auth];
  6718. _c = {};
  6719. return [4 /*yield*/, userInternal.getIdToken()];
  6720. case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
  6721. _c.deleteProvider = [providerId],
  6722. _c)]))];
  6723. case 3:
  6724. providerUserInfo = (_d.sent()).providerUserInfo;
  6725. providersLeft = providerDataAsNames(providerUserInfo || []);
  6726. userInternal.providerData = userInternal.providerData.filter(function (pd) {
  6727. return providersLeft.has(pd.providerId);
  6728. });
  6729. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  6730. userInternal.phoneNumber = null;
  6731. }
  6732. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  6733. case 4:
  6734. _d.sent();
  6735. return [2 /*return*/, userInternal];
  6736. }
  6737. });
  6738. });
  6739. }
  6740. function _link(user, credential, bypassAuthState) {
  6741. if (bypassAuthState === void 0) { bypassAuthState = false; }
  6742. return __awaiter(this, void 0, void 0, function () {
  6743. var response, _a, _b, _c, _d, _e;
  6744. return __generator(this, function (_f) {
  6745. switch (_f.label) {
  6746. case 0:
  6747. _a = _logoutIfInvalidated;
  6748. _b = [user];
  6749. _d = (_c = credential)._linkToIdToken;
  6750. _e = [user.auth];
  6751. return [4 /*yield*/, user.getIdToken()];
  6752. case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])),
  6753. bypassAuthState]))];
  6754. case 2:
  6755. response = _f.sent();
  6756. return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response)];
  6757. }
  6758. });
  6759. });
  6760. }
  6761. function _assertLinkedStatus(expected, user, provider) {
  6762. return __awaiter(this, void 0, void 0, function () {
  6763. var providerIds, code;
  6764. return __generator(this, function (_a) {
  6765. switch (_a.label) {
  6766. case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
  6767. case 1:
  6768. _a.sent();
  6769. providerIds = providerDataAsNames(user.providerData);
  6770. code = expected === false
  6771. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  6772. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  6773. _assert(providerIds.has(provider) === expected, user.auth, code);
  6774. return [2 /*return*/];
  6775. }
  6776. });
  6777. });
  6778. }
  6779. /**
  6780. * @license
  6781. * Copyright 2019 Google LLC
  6782. *
  6783. * Licensed under the Apache License, Version 2.0 (the "License");
  6784. * you may not use this file except in compliance with the License.
  6785. * You may obtain a copy of the License at
  6786. *
  6787. * http://www.apache.org/licenses/LICENSE-2.0
  6788. *
  6789. * Unless required by applicable law or agreed to in writing, software
  6790. * distributed under the License is distributed on an "AS IS" BASIS,
  6791. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6792. * See the License for the specific language governing permissions and
  6793. * limitations under the License.
  6794. */
  6795. function _reauthenticate(user, credential, bypassAuthState) {
  6796. if (bypassAuthState === void 0) { bypassAuthState = false; }
  6797. return __awaiter(this, void 0, void 0, function () {
  6798. var auth, operationType, response, parsed, localId, e_1;
  6799. return __generator(this, function (_a) {
  6800. switch (_a.label) {
  6801. case 0:
  6802. auth = user.auth;
  6803. operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  6804. _a.label = 1;
  6805. case 1:
  6806. _a.trys.push([1, 3, , 4]);
  6807. return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
  6808. case 2:
  6809. response = _a.sent();
  6810. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6811. parsed = _parseToken(response.idToken);
  6812. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6813. localId = parsed.sub;
  6814. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  6815. return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
  6816. case 3:
  6817. e_1 = _a.sent();
  6818. // Convert user deleted error into user mismatch
  6819. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) === "auth/".concat("user-not-found" /* AuthErrorCode.USER_DELETED */)) {
  6820. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  6821. }
  6822. throw e_1;
  6823. case 4: return [2 /*return*/];
  6824. }
  6825. });
  6826. });
  6827. }
  6828. /**
  6829. * @license
  6830. * Copyright 2020 Google LLC
  6831. *
  6832. * Licensed under the Apache License, Version 2.0 (the "License");
  6833. * you may not use this file except in compliance with the License.
  6834. * You may obtain a copy of the License at
  6835. *
  6836. * http://www.apache.org/licenses/LICENSE-2.0
  6837. *
  6838. * Unless required by applicable law or agreed to in writing, software
  6839. * distributed under the License is distributed on an "AS IS" BASIS,
  6840. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6841. * See the License for the specific language governing permissions and
  6842. * limitations under the License.
  6843. */
  6844. function _signInWithCredential(auth, credential, bypassAuthState) {
  6845. if (bypassAuthState === void 0) { bypassAuthState = false; }
  6846. return __awaiter(this, void 0, void 0, function () {
  6847. var operationType, response, userCredential;
  6848. return __generator(this, function (_a) {
  6849. switch (_a.label) {
  6850. case 0:
  6851. operationType = "signIn" /* OperationType.SIGN_IN */;
  6852. return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
  6853. case 1:
  6854. response = _a.sent();
  6855. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
  6856. case 2:
  6857. userCredential = _a.sent();
  6858. if (!!bypassAuthState) return [3 /*break*/, 4];
  6859. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  6860. case 3:
  6861. _a.sent();
  6862. _a.label = 4;
  6863. case 4: return [2 /*return*/, userCredential];
  6864. }
  6865. });
  6866. });
  6867. }
  6868. /**
  6869. * Asynchronously signs in with the given credentials.
  6870. *
  6871. * @remarks
  6872. * An {@link AuthProvider} can be used to generate the credential.
  6873. *
  6874. * @param auth - The {@link Auth} instance.
  6875. * @param credential - The auth credential.
  6876. *
  6877. * @public
  6878. */
  6879. function signInWithCredential(auth, credential) {
  6880. return __awaiter(this, void 0, void 0, function () {
  6881. return __generator(this, function (_a) {
  6882. return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
  6883. });
  6884. });
  6885. }
  6886. /**
  6887. * Links the user account with the given credentials.
  6888. *
  6889. * @remarks
  6890. * An {@link AuthProvider} can be used to generate the credential.
  6891. *
  6892. * @param user - The user.
  6893. * @param credential - The auth credential.
  6894. *
  6895. * @public
  6896. */
  6897. function linkWithCredential(user, credential) {
  6898. return __awaiter(this, void 0, void 0, function () {
  6899. var userInternal;
  6900. return __generator(this, function (_a) {
  6901. switch (_a.label) {
  6902. case 0:
  6903. userInternal = getModularInstance(user);
  6904. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
  6905. case 1:
  6906. _a.sent();
  6907. return [2 /*return*/, _link(userInternal, credential)];
  6908. }
  6909. });
  6910. });
  6911. }
  6912. /**
  6913. * Re-authenticates a user using a fresh credential.
  6914. *
  6915. * @remarks
  6916. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  6917. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error
  6918. * or a `TOKEN_EXPIRED` error.
  6919. *
  6920. * @param user - The user.
  6921. * @param credential - The auth credential.
  6922. *
  6923. * @public
  6924. */
  6925. function reauthenticateWithCredential(user, credential) {
  6926. return __awaiter(this, void 0, void 0, function () {
  6927. return __generator(this, function (_a) {
  6928. return [2 /*return*/, _reauthenticate(getModularInstance(user), credential)];
  6929. });
  6930. });
  6931. }
  6932. /**
  6933. * @license
  6934. * Copyright 2020 Google LLC
  6935. *
  6936. * Licensed under the Apache License, Version 2.0 (the "License");
  6937. * you may not use this file except in compliance with the License.
  6938. * You may obtain a copy of the License at
  6939. *
  6940. * http://www.apache.org/licenses/LICENSE-2.0
  6941. *
  6942. * Unless required by applicable law or agreed to in writing, software
  6943. * distributed under the License is distributed on an "AS IS" BASIS,
  6944. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6945. * See the License for the specific language governing permissions and
  6946. * limitations under the License.
  6947. */
  6948. function signInWithCustomToken$1(auth, request) {
  6949. return __awaiter(this, void 0, void 0, function () {
  6950. return __generator(this, function (_a) {
  6951. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
  6952. });
  6953. });
  6954. }
  6955. /**
  6956. * @license
  6957. * Copyright 2020 Google LLC
  6958. *
  6959. * Licensed under the Apache License, Version 2.0 (the "License");
  6960. * you may not use this file except in compliance with the License.
  6961. * You may obtain a copy of the License at
  6962. *
  6963. * http://www.apache.org/licenses/LICENSE-2.0
  6964. *
  6965. * Unless required by applicable law or agreed to in writing, software
  6966. * distributed under the License is distributed on an "AS IS" BASIS,
  6967. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6968. * See the License for the specific language governing permissions and
  6969. * limitations under the License.
  6970. */
  6971. /**
  6972. * Asynchronously signs in using a custom token.
  6973. *
  6974. * @remarks
  6975. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  6976. * be generated by an auth backend using the
  6977. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  6978. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  6979. *
  6980. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  6981. *
  6982. * @param auth - The {@link Auth} instance.
  6983. * @param customToken - The custom token to sign in with.
  6984. *
  6985. * @public
  6986. */
  6987. function signInWithCustomToken(auth, customToken) {
  6988. return __awaiter(this, void 0, void 0, function () {
  6989. var authInternal, response, cred;
  6990. return __generator(this, function (_a) {
  6991. switch (_a.label) {
  6992. case 0:
  6993. authInternal = _castAuth(auth);
  6994. return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
  6995. token: customToken,
  6996. returnSecureToken: true
  6997. })];
  6998. case 1:
  6999. response = _a.sent();
  7000. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  7001. case 2:
  7002. cred = _a.sent();
  7003. return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
  7004. case 3:
  7005. _a.sent();
  7006. return [2 /*return*/, cred];
  7007. }
  7008. });
  7009. });
  7010. }
  7011. /**
  7012. * @license
  7013. * Copyright 2020 Google LLC
  7014. *
  7015. * Licensed under the Apache License, Version 2.0 (the "License");
  7016. * you may not use this file except in compliance with the License.
  7017. * You may obtain a copy of the License at
  7018. *
  7019. * http://www.apache.org/licenses/LICENSE-2.0
  7020. *
  7021. * Unless required by applicable law or agreed to in writing, software
  7022. * distributed under the License is distributed on an "AS IS" BASIS,
  7023. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7024. * See the License for the specific language governing permissions and
  7025. * limitations under the License.
  7026. */
  7027. var MultiFactorInfoImpl = /** @class */ (function () {
  7028. function MultiFactorInfoImpl(factorId, response) {
  7029. this.factorId = factorId;
  7030. this.uid = response.mfaEnrollmentId;
  7031. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  7032. this.displayName = response.displayName;
  7033. }
  7034. MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
  7035. if ('phoneInfo' in enrollment) {
  7036. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  7037. }
  7038. else if ('totpInfo' in enrollment) {
  7039. return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  7040. }
  7041. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7042. };
  7043. return MultiFactorInfoImpl;
  7044. }());
  7045. var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
  7046. __extends(PhoneMultiFactorInfoImpl, _super);
  7047. function PhoneMultiFactorInfoImpl(response) {
  7048. var _this = _super.call(this, "phone" /* FactorId.PHONE */, response) || this;
  7049. _this.phoneNumber = response.phoneInfo;
  7050. return _this;
  7051. }
  7052. PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  7053. return new PhoneMultiFactorInfoImpl(enrollment);
  7054. };
  7055. return PhoneMultiFactorInfoImpl;
  7056. }(MultiFactorInfoImpl));
  7057. var TotpMultiFactorInfoImpl = /** @class */ (function (_super) {
  7058. __extends(TotpMultiFactorInfoImpl, _super);
  7059. function TotpMultiFactorInfoImpl(response) {
  7060. return _super.call(this, "totp" /* FactorId.TOTP */, response) || this;
  7061. }
  7062. TotpMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  7063. return new TotpMultiFactorInfoImpl(enrollment);
  7064. };
  7065. return TotpMultiFactorInfoImpl;
  7066. }(MultiFactorInfoImpl));
  7067. /**
  7068. * @license
  7069. * Copyright 2020 Google LLC
  7070. *
  7071. * Licensed under the Apache License, Version 2.0 (the "License");
  7072. * you may not use this file except in compliance with the License.
  7073. * You may obtain a copy of the License at
  7074. *
  7075. * http://www.apache.org/licenses/LICENSE-2.0
  7076. *
  7077. * Unless required by applicable law or agreed to in writing, software
  7078. * distributed under the License is distributed on an "AS IS" BASIS,
  7079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7080. * See the License for the specific language governing permissions and
  7081. * limitations under the License.
  7082. */
  7083. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  7084. var _a;
  7085. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  7086. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  7087. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  7088. request.continueUrl = actionCodeSettings.url;
  7089. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  7090. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  7091. if (actionCodeSettings.iOS) {
  7092. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  7093. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  7094. }
  7095. if (actionCodeSettings.android) {
  7096. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  7097. request.androidInstallApp = actionCodeSettings.android.installApp;
  7098. request.androidMinimumVersionCode =
  7099. actionCodeSettings.android.minimumVersion;
  7100. request.androidPackageName = actionCodeSettings.android.packageName;
  7101. }
  7102. }
  7103. /**
  7104. * @license
  7105. * Copyright 2020 Google LLC
  7106. *
  7107. * Licensed under the Apache License, Version 2.0 (the "License");
  7108. * you may not use this file except in compliance with the License.
  7109. * You may obtain a copy of the License at
  7110. *
  7111. * http://www.apache.org/licenses/LICENSE-2.0
  7112. *
  7113. * Unless required by applicable law or agreed to in writing, software
  7114. * distributed under the License is distributed on an "AS IS" BASIS,
  7115. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7116. * See the License for the specific language governing permissions and
  7117. * limitations under the License.
  7118. */
  7119. /**
  7120. * Sends a password reset email to the given email address.
  7121. *
  7122. * @remarks
  7123. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  7124. * the email sent to the user, along with the new password specified by the user.
  7125. *
  7126. * @example
  7127. * ```javascript
  7128. * const actionCodeSettings = {
  7129. * url: 'https://www.example.com/?email=user@example.com',
  7130. * iOS: {
  7131. * bundleId: 'com.example.ios'
  7132. * },
  7133. * android: {
  7134. * packageName: 'com.example.android',
  7135. * installApp: true,
  7136. * minimumVersion: '12'
  7137. * },
  7138. * handleCodeInApp: true
  7139. * };
  7140. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  7141. * // Obtain code from user.
  7142. * await confirmPasswordReset('user@example.com', code);
  7143. * ```
  7144. *
  7145. * @param auth - The {@link Auth} instance.
  7146. * @param email - The user's email address.
  7147. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  7148. *
  7149. * @public
  7150. */
  7151. function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  7152. var _a;
  7153. return __awaiter(this, void 0, void 0, function () {
  7154. var authInternal, request, requestWithRecaptcha;
  7155. var _this = this;
  7156. return __generator(this, function (_b) {
  7157. switch (_b.label) {
  7158. case 0:
  7159. authInternal = _castAuth(auth);
  7160. request = {
  7161. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  7162. email: email,
  7163. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  7164. };
  7165. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  7166. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  7167. case 1:
  7168. requestWithRecaptcha = _b.sent();
  7169. if (actionCodeSettings) {
  7170. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  7171. }
  7172. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, requestWithRecaptcha)];
  7173. case 2:
  7174. _b.sent();
  7175. return [3 /*break*/, 5];
  7176. case 3:
  7177. if (actionCodeSettings) {
  7178. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  7179. }
  7180. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, request)
  7181. .catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  7182. var requestWithRecaptcha;
  7183. return __generator(this, function (_a) {
  7184. switch (_a.label) {
  7185. case 0:
  7186. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 3];
  7187. console.log('Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.');
  7188. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  7189. case 1:
  7190. requestWithRecaptcha = _a.sent();
  7191. if (actionCodeSettings) {
  7192. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  7193. }
  7194. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, requestWithRecaptcha)];
  7195. case 2:
  7196. _a.sent();
  7197. return [3 /*break*/, 4];
  7198. case 3: return [2 /*return*/, Promise.reject(error)];
  7199. case 4: return [2 /*return*/];
  7200. }
  7201. });
  7202. }); })];
  7203. case 4:
  7204. _b.sent();
  7205. _b.label = 5;
  7206. case 5: return [2 /*return*/];
  7207. }
  7208. });
  7209. });
  7210. }
  7211. /**
  7212. * Completes the password reset process, given a confirmation code and new password.
  7213. *
  7214. * @param auth - The {@link Auth} instance.
  7215. * @param oobCode - A confirmation code sent to the user.
  7216. * @param newPassword - The new password.
  7217. *
  7218. * @public
  7219. */
  7220. function confirmPasswordReset(auth, oobCode, newPassword) {
  7221. return __awaiter(this, void 0, void 0, function () {
  7222. return __generator(this, function (_a) {
  7223. switch (_a.label) {
  7224. case 0: return [4 /*yield*/, resetPassword(getModularInstance(auth), {
  7225. oobCode: oobCode,
  7226. newPassword: newPassword
  7227. })];
  7228. case 1:
  7229. _a.sent();
  7230. return [2 /*return*/];
  7231. }
  7232. });
  7233. });
  7234. }
  7235. /**
  7236. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  7237. *
  7238. * @param auth - The {@link Auth} instance.
  7239. * @param oobCode - A verification code sent to the user.
  7240. *
  7241. * @public
  7242. */
  7243. function applyActionCode(auth, oobCode) {
  7244. return __awaiter(this, void 0, void 0, function () {
  7245. return __generator(this, function (_a) {
  7246. switch (_a.label) {
  7247. case 0: return [4 /*yield*/, applyActionCode$1(getModularInstance(auth), { oobCode: oobCode })];
  7248. case 1:
  7249. _a.sent();
  7250. return [2 /*return*/];
  7251. }
  7252. });
  7253. });
  7254. }
  7255. /**
  7256. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  7257. *
  7258. * @returns metadata about the code.
  7259. *
  7260. * @param auth - The {@link Auth} instance.
  7261. * @param oobCode - A verification code sent to the user.
  7262. *
  7263. * @public
  7264. */
  7265. function checkActionCode(auth, oobCode) {
  7266. return __awaiter(this, void 0, void 0, function () {
  7267. var authModular, response, operation, multiFactorInfo;
  7268. return __generator(this, function (_a) {
  7269. switch (_a.label) {
  7270. case 0:
  7271. authModular = getModularInstance(auth);
  7272. return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
  7273. case 1:
  7274. response = _a.sent();
  7275. operation = response.requestType;
  7276. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7277. switch (operation) {
  7278. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  7279. break;
  7280. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  7281. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7282. break;
  7283. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  7284. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7285. // fall through
  7286. default:
  7287. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7288. }
  7289. multiFactorInfo = null;
  7290. if (response.mfaInfo) {
  7291. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  7292. }
  7293. return [2 /*return*/, {
  7294. data: {
  7295. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  7296. ? response.newEmail
  7297. : response.email) || null,
  7298. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  7299. ? response.email
  7300. : response.newEmail) || null,
  7301. multiFactorInfo: multiFactorInfo
  7302. },
  7303. operation: operation
  7304. }];
  7305. }
  7306. });
  7307. });
  7308. }
  7309. /**
  7310. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  7311. *
  7312. * @returns the user's email address if valid.
  7313. *
  7314. * @param auth - The {@link Auth} instance.
  7315. * @param code - A verification code sent to the user.
  7316. *
  7317. * @public
  7318. */
  7319. function verifyPasswordResetCode(auth, code) {
  7320. return __awaiter(this, void 0, void 0, function () {
  7321. var data;
  7322. return __generator(this, function (_a) {
  7323. switch (_a.label) {
  7324. case 0: return [4 /*yield*/, checkActionCode(getModularInstance(auth), code)];
  7325. case 1:
  7326. data = (_a.sent()).data;
  7327. // Email should always be present since a code was sent to it
  7328. return [2 /*return*/, data.email];
  7329. }
  7330. });
  7331. });
  7332. }
  7333. /**
  7334. * Creates a new user account associated with the specified email address and password.
  7335. *
  7336. * @remarks
  7337. * On successful creation of the user account, this user will also be signed in to your application.
  7338. *
  7339. * User account creation can fail if the account already exists or the password is invalid.
  7340. *
  7341. * Note: The email address acts as a unique identifier for the user and enables an email-based
  7342. * password reset. This function will create a new user account and set the initial user password.
  7343. *
  7344. * @param auth - The {@link Auth} instance.
  7345. * @param email - The user's email address.
  7346. * @param password - The user's chosen password.
  7347. *
  7348. * @public
  7349. */
  7350. function createUserWithEmailAndPassword(auth, email, password) {
  7351. var _a;
  7352. return __awaiter(this, void 0, void 0, function () {
  7353. var authInternal, request, signUpResponse, requestWithRecaptcha, response, userCredential;
  7354. var _this = this;
  7355. return __generator(this, function (_b) {
  7356. switch (_b.label) {
  7357. case 0:
  7358. authInternal = _castAuth(auth);
  7359. request = {
  7360. returnSecureToken: true,
  7361. email: email,
  7362. password: password,
  7363. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  7364. };
  7365. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 2];
  7366. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */)];
  7367. case 1:
  7368. requestWithRecaptcha = _b.sent();
  7369. signUpResponse = signUp(authInternal, requestWithRecaptcha);
  7370. return [3 /*break*/, 3];
  7371. case 2:
  7372. signUpResponse = signUp(authInternal, request).catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  7373. var requestWithRecaptcha;
  7374. return __generator(this, function (_a) {
  7375. switch (_a.label) {
  7376. case 0:
  7377. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 2];
  7378. console.log('Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.');
  7379. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */)];
  7380. case 1:
  7381. requestWithRecaptcha = _a.sent();
  7382. return [2 /*return*/, signUp(authInternal, requestWithRecaptcha)];
  7383. case 2: return [2 /*return*/, Promise.reject(error)];
  7384. }
  7385. });
  7386. }); });
  7387. _b.label = 3;
  7388. case 3: return [4 /*yield*/, signUpResponse.catch(function (error) {
  7389. return Promise.reject(error);
  7390. })];
  7391. case 4:
  7392. response = _b.sent();
  7393. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  7394. case 5:
  7395. userCredential = _b.sent();
  7396. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  7397. case 6:
  7398. _b.sent();
  7399. return [2 /*return*/, userCredential];
  7400. }
  7401. });
  7402. });
  7403. }
  7404. /**
  7405. * Asynchronously signs in using an email and password.
  7406. *
  7407. * @remarks
  7408. * Fails with an error if the email address and password do not match.
  7409. *
  7410. * Note: The user's password is NOT the password used to access the user's email account. The
  7411. * email address serves as a unique identifier for the user, and the password is used to access
  7412. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  7413. *
  7414. * @param auth - The {@link Auth} instance.
  7415. * @param email - The users email address.
  7416. * @param password - The users password.
  7417. *
  7418. * @public
  7419. */
  7420. function signInWithEmailAndPassword(auth, email, password) {
  7421. return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
  7422. }
  7423. /**
  7424. * @license
  7425. * Copyright 2020 Google LLC
  7426. *
  7427. * Licensed under the Apache License, Version 2.0 (the "License");
  7428. * you may not use this file except in compliance with the License.
  7429. * You may obtain a copy of the License at
  7430. *
  7431. * http://www.apache.org/licenses/LICENSE-2.0
  7432. *
  7433. * Unless required by applicable law or agreed to in writing, software
  7434. * distributed under the License is distributed on an "AS IS" BASIS,
  7435. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7436. * See the License for the specific language governing permissions and
  7437. * limitations under the License.
  7438. */
  7439. /**
  7440. * Sends a sign-in email link to the user with the specified email.
  7441. *
  7442. * @remarks
  7443. * The sign-in operation has to always be completed in the app unlike other out of band email
  7444. * actions (password reset and email verifications). This is because, at the end of the flow,
  7445. * the user is expected to be signed in and their Auth state persisted within the app.
  7446. *
  7447. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  7448. * address and the email link supplied in the email sent to the user.
  7449. *
  7450. * @example
  7451. * ```javascript
  7452. * const actionCodeSettings = {
  7453. * url: 'https://www.example.com/?email=user@example.com',
  7454. * iOS: {
  7455. * bundleId: 'com.example.ios'
  7456. * },
  7457. * android: {
  7458. * packageName: 'com.example.android',
  7459. * installApp: true,
  7460. * minimumVersion: '12'
  7461. * },
  7462. * handleCodeInApp: true
  7463. * };
  7464. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  7465. * // Obtain emailLink from the user.
  7466. * if(isSignInWithEmailLink(auth, emailLink)) {
  7467. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  7468. * }
  7469. * ```
  7470. *
  7471. * @param authInternal - The {@link Auth} instance.
  7472. * @param email - The user's email address.
  7473. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  7474. *
  7475. * @public
  7476. */
  7477. function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  7478. var _a;
  7479. return __awaiter(this, void 0, void 0, function () {
  7480. function setActionCodeSettings(request, actionCodeSettings) {
  7481. _assert(actionCodeSettings.handleCodeInApp, authInternal, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7482. if (actionCodeSettings) {
  7483. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  7484. }
  7485. }
  7486. var authInternal, request, requestWithRecaptcha;
  7487. var _this = this;
  7488. return __generator(this, function (_b) {
  7489. switch (_b.label) {
  7490. case 0:
  7491. authInternal = _castAuth(auth);
  7492. request = {
  7493. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  7494. email: email,
  7495. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  7496. };
  7497. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  7498. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  7499. case 1:
  7500. requestWithRecaptcha = _b.sent();
  7501. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  7502. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha)];
  7503. case 2:
  7504. _b.sent();
  7505. return [3 /*break*/, 5];
  7506. case 3:
  7507. setActionCodeSettings(request, actionCodeSettings);
  7508. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, request)
  7509. .catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  7510. var requestWithRecaptcha;
  7511. return __generator(this, function (_a) {
  7512. switch (_a.label) {
  7513. case 0:
  7514. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 3];
  7515. console.log('Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');
  7516. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  7517. case 1:
  7518. requestWithRecaptcha = _a.sent();
  7519. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  7520. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha)];
  7521. case 2:
  7522. _a.sent();
  7523. return [3 /*break*/, 4];
  7524. case 3: return [2 /*return*/, Promise.reject(error)];
  7525. case 4: return [2 /*return*/];
  7526. }
  7527. });
  7528. }); })];
  7529. case 4:
  7530. _b.sent();
  7531. _b.label = 5;
  7532. case 5: return [2 /*return*/];
  7533. }
  7534. });
  7535. });
  7536. }
  7537. /**
  7538. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  7539. *
  7540. * @param auth - The {@link Auth} instance.
  7541. * @param emailLink - The link sent to the user's email address.
  7542. *
  7543. * @public
  7544. */
  7545. function isSignInWithEmailLink(auth, emailLink) {
  7546. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  7547. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  7548. }
  7549. /**
  7550. * Asynchronously signs in using an email and sign-in email link.
  7551. *
  7552. * @remarks
  7553. * If no link is passed, the link is inferred from the current URL.
  7554. *
  7555. * Fails with an error if the email address is invalid or OTP in email link expires.
  7556. *
  7557. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  7558. *
  7559. * @example
  7560. * ```javascript
  7561. * const actionCodeSettings = {
  7562. * url: 'https://www.example.com/?email=user@example.com',
  7563. * iOS: {
  7564. * bundleId: 'com.example.ios'
  7565. * },
  7566. * android: {
  7567. * packageName: 'com.example.android',
  7568. * installApp: true,
  7569. * minimumVersion: '12'
  7570. * },
  7571. * handleCodeInApp: true
  7572. * };
  7573. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  7574. * // Obtain emailLink from the user.
  7575. * if(isSignInWithEmailLink(auth, emailLink)) {
  7576. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  7577. * }
  7578. * ```
  7579. *
  7580. * @param auth - The {@link Auth} instance.
  7581. * @param email - The user's email address.
  7582. * @param emailLink - The link sent to the user's email address.
  7583. *
  7584. * @public
  7585. */
  7586. function signInWithEmailLink(auth, email, emailLink) {
  7587. return __awaiter(this, void 0, void 0, function () {
  7588. var authModular, credential;
  7589. return __generator(this, function (_a) {
  7590. authModular = getModularInstance(auth);
  7591. credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  7592. // Check if the tenant ID in the email link matches the tenant ID on Auth
  7593. // instance.
  7594. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  7595. return [2 /*return*/, signInWithCredential(authModular, credential)];
  7596. });
  7597. });
  7598. }
  7599. /**
  7600. * @license
  7601. * Copyright 2020 Google LLC
  7602. *
  7603. * Licensed under the Apache License, Version 2.0 (the "License");
  7604. * you may not use this file except in compliance with the License.
  7605. * You may obtain a copy of the License at
  7606. *
  7607. * http://www.apache.org/licenses/LICENSE-2.0
  7608. *
  7609. * Unless required by applicable law or agreed to in writing, software
  7610. * distributed under the License is distributed on an "AS IS" BASIS,
  7611. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7612. * See the License for the specific language governing permissions and
  7613. * limitations under the License.
  7614. */
  7615. function createAuthUri(auth, request) {
  7616. return __awaiter(this, void 0, void 0, function () {
  7617. return __generator(this, function (_a) {
  7618. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
  7619. });
  7620. });
  7621. }
  7622. /**
  7623. * @license
  7624. * Copyright 2020 Google LLC
  7625. *
  7626. * Licensed under the Apache License, Version 2.0 (the "License");
  7627. * you may not use this file except in compliance with the License.
  7628. * You may obtain a copy of the License at
  7629. *
  7630. * http://www.apache.org/licenses/LICENSE-2.0
  7631. *
  7632. * Unless required by applicable law or agreed to in writing, software
  7633. * distributed under the License is distributed on an "AS IS" BASIS,
  7634. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7635. * See the License for the specific language governing permissions and
  7636. * limitations under the License.
  7637. */
  7638. /**
  7639. * Gets the list of possible sign in methods for the given email address.
  7640. *
  7641. * @remarks
  7642. * This is useful to differentiate methods of sign-in for the same provider, eg.
  7643. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  7644. * {@link SignInMethod}.EMAIL_PASSWORD and
  7645. * {@link SignInMethod}.EMAIL_LINK.
  7646. *
  7647. * @param auth - The {@link Auth} instance.
  7648. * @param email - The user's email address.
  7649. *
  7650. * @public
  7651. */
  7652. function fetchSignInMethodsForEmail(auth, email) {
  7653. return __awaiter(this, void 0, void 0, function () {
  7654. var continueUri, request, signinMethods;
  7655. return __generator(this, function (_a) {
  7656. switch (_a.label) {
  7657. case 0:
  7658. continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  7659. request = {
  7660. identifier: email,
  7661. continueUri: continueUri
  7662. };
  7663. return [4 /*yield*/, createAuthUri(getModularInstance(auth), request)];
  7664. case 1:
  7665. signinMethods = (_a.sent()).signinMethods;
  7666. return [2 /*return*/, signinMethods || []];
  7667. }
  7668. });
  7669. });
  7670. }
  7671. /**
  7672. * Sends a verification email to a user.
  7673. *
  7674. * @remarks
  7675. * The verification process is completed by calling {@link applyActionCode}.
  7676. *
  7677. * @example
  7678. * ```javascript
  7679. * const actionCodeSettings = {
  7680. * url: 'https://www.example.com/?email=user@example.com',
  7681. * iOS: {
  7682. * bundleId: 'com.example.ios'
  7683. * },
  7684. * android: {
  7685. * packageName: 'com.example.android',
  7686. * installApp: true,
  7687. * minimumVersion: '12'
  7688. * },
  7689. * handleCodeInApp: true
  7690. * };
  7691. * await sendEmailVerification(user, actionCodeSettings);
  7692. * // Obtain code from the user.
  7693. * await applyActionCode(auth, code);
  7694. * ```
  7695. *
  7696. * @param user - The user.
  7697. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  7698. *
  7699. * @public
  7700. */
  7701. function sendEmailVerification(user, actionCodeSettings) {
  7702. return __awaiter(this, void 0, void 0, function () {
  7703. var userInternal, idToken, request, email;
  7704. return __generator(this, function (_a) {
  7705. switch (_a.label) {
  7706. case 0:
  7707. userInternal = getModularInstance(user);
  7708. return [4 /*yield*/, user.getIdToken()];
  7709. case 1:
  7710. idToken = _a.sent();
  7711. request = {
  7712. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  7713. idToken: idToken
  7714. };
  7715. if (actionCodeSettings) {
  7716. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  7717. }
  7718. return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
  7719. case 2:
  7720. email = (_a.sent()).email;
  7721. if (!(email !== user.email)) return [3 /*break*/, 4];
  7722. return [4 /*yield*/, user.reload()];
  7723. case 3:
  7724. _a.sent();
  7725. _a.label = 4;
  7726. case 4: return [2 /*return*/];
  7727. }
  7728. });
  7729. });
  7730. }
  7731. /**
  7732. * Sends a verification email to a new email address.
  7733. *
  7734. * @remarks
  7735. * The user's email will be updated to the new one after being verified.
  7736. *
  7737. * If you have a custom email action handler, you can complete the verification process by calling
  7738. * {@link applyActionCode}.
  7739. *
  7740. * @example
  7741. * ```javascript
  7742. * const actionCodeSettings = {
  7743. * url: 'https://www.example.com/?email=user@example.com',
  7744. * iOS: {
  7745. * bundleId: 'com.example.ios'
  7746. * },
  7747. * android: {
  7748. * packageName: 'com.example.android',
  7749. * installApp: true,
  7750. * minimumVersion: '12'
  7751. * },
  7752. * handleCodeInApp: true
  7753. * };
  7754. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  7755. * // Obtain code from the user.
  7756. * await applyActionCode(auth, code);
  7757. * ```
  7758. *
  7759. * @param user - The user.
  7760. * @param newEmail - The new email address to be verified before update.
  7761. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  7762. *
  7763. * @public
  7764. */
  7765. function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  7766. return __awaiter(this, void 0, void 0, function () {
  7767. var userInternal, idToken, request, email;
  7768. return __generator(this, function (_a) {
  7769. switch (_a.label) {
  7770. case 0:
  7771. userInternal = getModularInstance(user);
  7772. return [4 /*yield*/, user.getIdToken()];
  7773. case 1:
  7774. idToken = _a.sent();
  7775. request = {
  7776. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  7777. idToken: idToken,
  7778. newEmail: newEmail
  7779. };
  7780. if (actionCodeSettings) {
  7781. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  7782. }
  7783. return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
  7784. case 2:
  7785. email = (_a.sent()).email;
  7786. if (!(email !== user.email)) return [3 /*break*/, 4];
  7787. // If the local copy of the email on user is outdated, reload the
  7788. // user.
  7789. return [4 /*yield*/, user.reload()];
  7790. case 3:
  7791. // If the local copy of the email on user is outdated, reload the
  7792. // user.
  7793. _a.sent();
  7794. _a.label = 4;
  7795. case 4: return [2 /*return*/];
  7796. }
  7797. });
  7798. });
  7799. }
  7800. /**
  7801. * @license
  7802. * Copyright 2020 Google LLC
  7803. *
  7804. * Licensed under the Apache License, Version 2.0 (the "License");
  7805. * you may not use this file except in compliance with the License.
  7806. * You may obtain a copy of the License at
  7807. *
  7808. * http://www.apache.org/licenses/LICENSE-2.0
  7809. *
  7810. * Unless required by applicable law or agreed to in writing, software
  7811. * distributed under the License is distributed on an "AS IS" BASIS,
  7812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7813. * See the License for the specific language governing permissions and
  7814. * limitations under the License.
  7815. */
  7816. function updateProfile$1(auth, request) {
  7817. return __awaiter(this, void 0, void 0, function () {
  7818. return __generator(this, function (_a) {
  7819. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  7820. });
  7821. });
  7822. }
  7823. /**
  7824. * @license
  7825. * Copyright 2020 Google LLC
  7826. *
  7827. * Licensed under the Apache License, Version 2.0 (the "License");
  7828. * you may not use this file except in compliance with the License.
  7829. * You may obtain a copy of the License at
  7830. *
  7831. * http://www.apache.org/licenses/LICENSE-2.0
  7832. *
  7833. * Unless required by applicable law or agreed to in writing, software
  7834. * distributed under the License is distributed on an "AS IS" BASIS,
  7835. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7836. * See the License for the specific language governing permissions and
  7837. * limitations under the License.
  7838. */
  7839. /**
  7840. * Updates a user's profile data.
  7841. *
  7842. * @param user - The user.
  7843. * @param profile - The profile's `displayName` and `photoURL` to update.
  7844. *
  7845. * @public
  7846. */
  7847. function updateProfile(user, _a) {
  7848. var displayName = _a.displayName, photoUrl = _a.photoURL;
  7849. return __awaiter(this, void 0, void 0, function () {
  7850. var userInternal, idToken, profileRequest, response, passwordProvider;
  7851. return __generator(this, function (_b) {
  7852. switch (_b.label) {
  7853. case 0:
  7854. if (displayName === undefined && photoUrl === undefined) {
  7855. return [2 /*return*/];
  7856. }
  7857. userInternal = getModularInstance(user);
  7858. return [4 /*yield*/, userInternal.getIdToken()];
  7859. case 1:
  7860. idToken = _b.sent();
  7861. profileRequest = {
  7862. idToken: idToken,
  7863. displayName: displayName,
  7864. photoUrl: photoUrl,
  7865. returnSecureToken: true
  7866. };
  7867. return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
  7868. case 2:
  7869. response = _b.sent();
  7870. userInternal.displayName = response.displayName || null;
  7871. userInternal.photoURL = response.photoUrl || null;
  7872. passwordProvider = userInternal.providerData.find(function (_a) {
  7873. var providerId = _a.providerId;
  7874. return providerId === "password" /* ProviderId.PASSWORD */;
  7875. });
  7876. if (passwordProvider) {
  7877. passwordProvider.displayName = userInternal.displayName;
  7878. passwordProvider.photoURL = userInternal.photoURL;
  7879. }
  7880. return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
  7881. case 3:
  7882. _b.sent();
  7883. return [2 /*return*/];
  7884. }
  7885. });
  7886. });
  7887. }
  7888. /**
  7889. * Updates the user's email address.
  7890. *
  7891. * @remarks
  7892. * An email will be sent to the original email address (if it was set) that allows to revoke the
  7893. * email address change, in order to protect them from account hijacking.
  7894. *
  7895. * Important: this is a security sensitive operation that requires the user to have recently signed
  7896. * in. If this requirement isn't met, ask the user to authenticate again and then call
  7897. * {@link reauthenticateWithCredential}.
  7898. *
  7899. * @param user - The user.
  7900. * @param newEmail - The new email address.
  7901. *
  7902. * @public
  7903. */
  7904. function updateEmail(user, newEmail) {
  7905. return updateEmailOrPassword(getModularInstance(user), newEmail, null);
  7906. }
  7907. /**
  7908. * Updates the user's password.
  7909. *
  7910. * @remarks
  7911. * Important: this is a security sensitive operation that requires the user to have recently signed
  7912. * in. If this requirement isn't met, ask the user to authenticate again and then call
  7913. * {@link reauthenticateWithCredential}.
  7914. *
  7915. * @param user - The user.
  7916. * @param newPassword - The new password.
  7917. *
  7918. * @public
  7919. */
  7920. function updatePassword(user, newPassword) {
  7921. return updateEmailOrPassword(getModularInstance(user), null, newPassword);
  7922. }
  7923. function updateEmailOrPassword(user, email, password) {
  7924. return __awaiter(this, void 0, void 0, function () {
  7925. var auth, idToken, request, response;
  7926. return __generator(this, function (_a) {
  7927. switch (_a.label) {
  7928. case 0:
  7929. auth = user.auth;
  7930. return [4 /*yield*/, user.getIdToken()];
  7931. case 1:
  7932. idToken = _a.sent();
  7933. request = {
  7934. idToken: idToken,
  7935. returnSecureToken: true
  7936. };
  7937. if (email) {
  7938. request.email = email;
  7939. }
  7940. if (password) {
  7941. request.password = password;
  7942. }
  7943. return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
  7944. case 2:
  7945. response = _a.sent();
  7946. return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  7947. case 3:
  7948. _a.sent();
  7949. return [2 /*return*/];
  7950. }
  7951. });
  7952. });
  7953. }
  7954. /**
  7955. * @license
  7956. * Copyright 2019 Google LLC
  7957. *
  7958. * Licensed under the Apache License, Version 2.0 (the "License");
  7959. * you may not use this file except in compliance with the License.
  7960. * You may obtain a copy of the License at
  7961. *
  7962. * http://www.apache.org/licenses/LICENSE-2.0
  7963. *
  7964. * Unless required by applicable law or agreed to in writing, software
  7965. * distributed under the License is distributed on an "AS IS" BASIS,
  7966. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7967. * See the License for the specific language governing permissions and
  7968. * limitations under the License.
  7969. */
  7970. /**
  7971. * Parse the `AdditionalUserInfo` from the ID token response.
  7972. *
  7973. */
  7974. function _fromIdTokenResponse(idTokenResponse) {
  7975. var _a, _b;
  7976. if (!idTokenResponse) {
  7977. return null;
  7978. }
  7979. var providerId = idTokenResponse.providerId;
  7980. var profile = idTokenResponse.rawUserInfo
  7981. ? JSON.parse(idTokenResponse.rawUserInfo)
  7982. : {};
  7983. var isNewUser = idTokenResponse.isNewUser ||
  7984. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  7985. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  7986. var signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
  7987. if (signInProvider) {
  7988. var filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  7989. signInProvider !== "custom" /* ProviderId.CUSTOM */
  7990. ? signInProvider
  7991. : null;
  7992. // Uses generic class in accordance with the legacy SDK.
  7993. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  7994. }
  7995. }
  7996. if (!providerId) {
  7997. return null;
  7998. }
  7999. switch (providerId) {
  8000. case "facebook.com" /* ProviderId.FACEBOOK */:
  8001. return new FacebookAdditionalUserInfo(isNewUser, profile);
  8002. case "github.com" /* ProviderId.GITHUB */:
  8003. return new GithubAdditionalUserInfo(isNewUser, profile);
  8004. case "google.com" /* ProviderId.GOOGLE */:
  8005. return new GoogleAdditionalUserInfo(isNewUser, profile);
  8006. case "twitter.com" /* ProviderId.TWITTER */:
  8007. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  8008. case "custom" /* ProviderId.CUSTOM */:
  8009. case "anonymous" /* ProviderId.ANONYMOUS */:
  8010. return new GenericAdditionalUserInfo(isNewUser, null);
  8011. default:
  8012. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  8013. }
  8014. }
  8015. var GenericAdditionalUserInfo = /** @class */ (function () {
  8016. function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
  8017. if (profile === void 0) { profile = {}; }
  8018. this.isNewUser = isNewUser;
  8019. this.providerId = providerId;
  8020. this.profile = profile;
  8021. }
  8022. return GenericAdditionalUserInfo;
  8023. }());
  8024. var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
  8025. __extends(FederatedAdditionalUserInfoWithUsername, _super);
  8026. function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
  8027. var _this = _super.call(this, isNewUser, providerId, profile) || this;
  8028. _this.username = username;
  8029. return _this;
  8030. }
  8031. return FederatedAdditionalUserInfoWithUsername;
  8032. }(GenericAdditionalUserInfo));
  8033. var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
  8034. __extends(FacebookAdditionalUserInfo, _super);
  8035. function FacebookAdditionalUserInfo(isNewUser, profile) {
  8036. return _super.call(this, isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile) || this;
  8037. }
  8038. return FacebookAdditionalUserInfo;
  8039. }(GenericAdditionalUserInfo));
  8040. var GithubAdditionalUserInfo = /** @class */ (function (_super) {
  8041. __extends(GithubAdditionalUserInfo, _super);
  8042. function GithubAdditionalUserInfo(isNewUser, profile) {
  8043. return _super.call(this, isNewUser, "github.com" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null) || this;
  8044. }
  8045. return GithubAdditionalUserInfo;
  8046. }(FederatedAdditionalUserInfoWithUsername));
  8047. var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
  8048. __extends(GoogleAdditionalUserInfo, _super);
  8049. function GoogleAdditionalUserInfo(isNewUser, profile) {
  8050. return _super.call(this, isNewUser, "google.com" /* ProviderId.GOOGLE */, profile) || this;
  8051. }
  8052. return GoogleAdditionalUserInfo;
  8053. }(GenericAdditionalUserInfo));
  8054. var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
  8055. __extends(TwitterAdditionalUserInfo, _super);
  8056. function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
  8057. return _super.call(this, isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName) || this;
  8058. }
  8059. return TwitterAdditionalUserInfo;
  8060. }(FederatedAdditionalUserInfoWithUsername));
  8061. /**
  8062. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  8063. *
  8064. * @param userCredential - The user credential.
  8065. *
  8066. * @public
  8067. */
  8068. function getAdditionalUserInfo(userCredential) {
  8069. var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
  8070. if (user.isAnonymous && !_tokenResponse) {
  8071. // Handle the special case where signInAnonymously() gets called twice.
  8072. // No network call is made so there's nothing to actually fill this in
  8073. return {
  8074. providerId: null,
  8075. isNewUser: false,
  8076. profile: null
  8077. };
  8078. }
  8079. return _fromIdTokenResponse(_tokenResponse);
  8080. }
  8081. /**
  8082. * @license
  8083. * Copyright 2020 Google LLC
  8084. *
  8085. * Licensed under the Apache License, Version 2.0 (the "License");
  8086. * you may not use this file except in compliance with the License.
  8087. * You may obtain a copy of the License at
  8088. *
  8089. * http://www.apache.org/licenses/LICENSE-2.0
  8090. *
  8091. * Unless required by applicable law or agreed to in writing, software
  8092. * distributed under the License is distributed on an "AS IS" BASIS,
  8093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8094. * See the License for the specific language governing permissions and
  8095. * limitations under the License.
  8096. */
  8097. // Non-optional auth methods.
  8098. /**
  8099. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  8100. * `Auth` session and applies this type of persistence for future sign-in requests, including
  8101. * sign-in with redirect requests.
  8102. *
  8103. * @remarks
  8104. * This makes it easy for a user signing in to specify whether their session should be
  8105. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  8106. * that are shared by other users or have sensitive data.
  8107. *
  8108. * @example
  8109. * ```javascript
  8110. * setPersistence(auth, browserSessionPersistence);
  8111. * ```
  8112. *
  8113. * @param auth - The {@link Auth} instance.
  8114. * @param persistence - The {@link Persistence} to use.
  8115. * @returns A `Promise` that resolves once the persistence change has completed
  8116. *
  8117. * @public
  8118. */
  8119. function setPersistence(auth, persistence) {
  8120. return getModularInstance(auth).setPersistence(persistence);
  8121. }
  8122. /**
  8123. * Loads the reCAPTCHA configuration into the `Auth` instance.
  8124. *
  8125. * @remarks
  8126. * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA
  8127. * verification flow should be triggered for each auth provider, into the
  8128. * current Auth session.
  8129. *
  8130. * If initializeRecaptchaConfig() is not invoked, the auth flow will always start
  8131. * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA
  8132. * verification, the SDK will transparently load the reCAPTCHA config and restart the
  8133. * auth flows.
  8134. *
  8135. * Thus, by calling this optional method, you will reduce the latency of future auth flows.
  8136. * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.
  8137. *
  8138. * @example
  8139. * ```javascript
  8140. * initializeRecaptchaConfig(auth);
  8141. * ```
  8142. *
  8143. * @param auth - The {@link Auth} instance.
  8144. *
  8145. * @public
  8146. */
  8147. function initializeRecaptchaConfig(auth) {
  8148. var authInternal = _castAuth(auth);
  8149. return authInternal.initializeRecaptchaConfig();
  8150. }
  8151. /**
  8152. * Adds an observer for changes to the signed-in user's ID token.
  8153. *
  8154. * @remarks
  8155. * This includes sign-in, sign-out, and token refresh events.
  8156. * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.
  8157. *
  8158. * @param auth - The {@link Auth} instance.
  8159. * @param nextOrObserver - callback triggered on change.
  8160. * @param error - Deprecated. This callback is never triggered. Errors
  8161. * on signing in/out can be caught in promises returned from
  8162. * sign-in/sign-out functions.
  8163. * @param completed - Deprecated. This callback is never triggered.
  8164. *
  8165. * @public
  8166. */
  8167. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  8168. return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  8169. }
  8170. /**
  8171. * Adds a blocking callback that runs before an auth state change
  8172. * sets a new user.
  8173. *
  8174. * @param auth - The {@link Auth} instance.
  8175. * @param callback - callback triggered before new user value is set.
  8176. * If this throws, it blocks the user from being set.
  8177. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  8178. * callback throws, allowing you to undo any side effects.
  8179. */
  8180. function beforeAuthStateChanged(auth, callback, onAbort) {
  8181. return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  8182. }
  8183. /**
  8184. * Adds an observer for changes to the user's sign-in state.
  8185. *
  8186. * @remarks
  8187. * To keep the old behavior, see {@link onIdTokenChanged}.
  8188. *
  8189. * @param auth - The {@link Auth} instance.
  8190. * @param nextOrObserver - callback triggered on change.
  8191. * @param error - Deprecated. This callback is never triggered. Errors
  8192. * on signing in/out can be caught in promises returned from
  8193. * sign-in/sign-out functions.
  8194. * @param completed - Deprecated. This callback is never triggered.
  8195. *
  8196. * @public
  8197. */
  8198. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  8199. return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  8200. }
  8201. /**
  8202. * Sets the current language to the default device/browser preference.
  8203. *
  8204. * @param auth - The {@link Auth} instance.
  8205. *
  8206. * @public
  8207. */
  8208. function useDeviceLanguage(auth) {
  8209. getModularInstance(auth).useDeviceLanguage();
  8210. }
  8211. /**
  8212. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  8213. * {@link Auth} instance.
  8214. *
  8215. * @remarks
  8216. * A new instance copy of the user provided will be made and set as currentUser.
  8217. *
  8218. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  8219. * like other sign in methods.
  8220. *
  8221. * The operation fails with an error if the user to be updated belongs to a different Firebase
  8222. * project.
  8223. *
  8224. * @param auth - The {@link Auth} instance.
  8225. * @param user - The new {@link User}.
  8226. *
  8227. * @public
  8228. */
  8229. function updateCurrentUser(auth, user) {
  8230. return getModularInstance(auth).updateCurrentUser(user);
  8231. }
  8232. /**
  8233. * Signs out the current user.
  8234. *
  8235. * @param auth - The {@link Auth} instance.
  8236. *
  8237. * @public
  8238. */
  8239. function signOut(auth) {
  8240. return getModularInstance(auth).signOut();
  8241. }
  8242. /**
  8243. * Deletes and signs out the user.
  8244. *
  8245. * @remarks
  8246. * Important: this is a security-sensitive operation that requires the user to have recently
  8247. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  8248. * {@link reauthenticateWithCredential}.
  8249. *
  8250. * @param user - The user.
  8251. *
  8252. * @public
  8253. */
  8254. function deleteUser(user) {
  8255. return __awaiter(this, void 0, void 0, function () {
  8256. return __generator(this, function (_a) {
  8257. return [2 /*return*/, getModularInstance(user).delete()];
  8258. });
  8259. });
  8260. }
  8261. var MultiFactorSessionImpl = /** @class */ (function () {
  8262. function MultiFactorSessionImpl(type, credential, auth) {
  8263. this.type = type;
  8264. this.credential = credential;
  8265. this.auth = auth;
  8266. }
  8267. MultiFactorSessionImpl._fromIdtoken = function (idToken, auth) {
  8268. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  8269. };
  8270. MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
  8271. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  8272. };
  8273. MultiFactorSessionImpl.prototype.toJSON = function () {
  8274. var _a;
  8275. var key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  8276. ? 'idToken'
  8277. : 'pendingCredential';
  8278. return {
  8279. multiFactorSession: (_a = {},
  8280. _a[key] = this.credential,
  8281. _a)
  8282. };
  8283. };
  8284. MultiFactorSessionImpl.fromJSON = function (obj) {
  8285. var _a, _b;
  8286. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  8287. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  8288. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  8289. }
  8290. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  8291. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  8292. }
  8293. }
  8294. return null;
  8295. };
  8296. return MultiFactorSessionImpl;
  8297. }());
  8298. /**
  8299. * @license
  8300. * Copyright 2020 Google LLC
  8301. *
  8302. * Licensed under the Apache License, Version 2.0 (the "License");
  8303. * you may not use this file except in compliance with the License.
  8304. * You may obtain a copy of the License at
  8305. *
  8306. * http://www.apache.org/licenses/LICENSE-2.0
  8307. *
  8308. * Unless required by applicable law or agreed to in writing, software
  8309. * distributed under the License is distributed on an "AS IS" BASIS,
  8310. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8311. * See the License for the specific language governing permissions and
  8312. * limitations under the License.
  8313. */
  8314. var MultiFactorResolverImpl = /** @class */ (function () {
  8315. function MultiFactorResolverImpl(session, hints, signInResolver) {
  8316. this.session = session;
  8317. this.hints = hints;
  8318. this.signInResolver = signInResolver;
  8319. }
  8320. /** @internal */
  8321. MultiFactorResolverImpl._fromError = function (authExtern, error) {
  8322. var _this = this;
  8323. var auth = _castAuth(authExtern);
  8324. var serverResponse = error.customData._serverResponse;
  8325. var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
  8326. return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  8327. });
  8328. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8329. var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  8330. return new MultiFactorResolverImpl(session, hints, function (assertion) { return __awaiter(_this, void 0, void 0, function () {
  8331. var mfaResponse, idTokenResponse, _a, userCredential;
  8332. return __generator(this, function (_b) {
  8333. switch (_b.label) {
  8334. case 0: return [4 /*yield*/, assertion._process(auth, session)];
  8335. case 1:
  8336. mfaResponse = _b.sent();
  8337. // Clear out the unneeded fields from the old login response
  8338. delete serverResponse.mfaInfo;
  8339. delete serverResponse.mfaPendingCredential;
  8340. idTokenResponse = __assign(__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  8341. _a = error.operationType;
  8342. switch (_a) {
  8343. case "signIn" /* OperationType.SIGN_IN */: return [3 /*break*/, 2];
  8344. case "reauthenticate" /* OperationType.REAUTHENTICATE */: return [3 /*break*/, 5];
  8345. }
  8346. return [3 /*break*/, 6];
  8347. case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
  8348. case 3:
  8349. userCredential = _b.sent();
  8350. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  8351. case 4:
  8352. _b.sent();
  8353. return [2 /*return*/, userCredential];
  8354. case 5:
  8355. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8356. return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
  8357. case 6:
  8358. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8359. _b.label = 7;
  8360. case 7: return [2 /*return*/];
  8361. }
  8362. });
  8363. }); });
  8364. };
  8365. MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
  8366. return __awaiter(this, void 0, void 0, function () {
  8367. var assertion;
  8368. return __generator(this, function (_a) {
  8369. assertion = assertionExtern;
  8370. return [2 /*return*/, this.signInResolver(assertion)];
  8371. });
  8372. });
  8373. };
  8374. return MultiFactorResolverImpl;
  8375. }());
  8376. /**
  8377. * Provides a {@link MultiFactorResolver} suitable for completion of a
  8378. * multi-factor flow.
  8379. *
  8380. * @param auth - The {@link Auth} instance.
  8381. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  8382. * reauthentication operation.
  8383. *
  8384. * @public
  8385. */
  8386. function getMultiFactorResolver(auth, error) {
  8387. var _a;
  8388. var authModular = getModularInstance(auth);
  8389. var errorInternal = error;
  8390. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8391. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8392. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  8393. }
  8394. /**
  8395. * @license
  8396. * Copyright 2020 Google LLC
  8397. *
  8398. * Licensed under the Apache License, Version 2.0 (the "License");
  8399. * you may not use this file except in compliance with the License.
  8400. * You may obtain a copy of the License at
  8401. *
  8402. * http://www.apache.org/licenses/LICENSE-2.0
  8403. *
  8404. * Unless required by applicable law or agreed to in writing, software
  8405. * distributed under the License is distributed on an "AS IS" BASIS,
  8406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8407. * See the License for the specific language governing permissions and
  8408. * limitations under the License.
  8409. */
  8410. function withdrawMfa(auth, request) {
  8411. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  8412. }
  8413. var MultiFactorUserImpl = /** @class */ (function () {
  8414. function MultiFactorUserImpl(user) {
  8415. var _this = this;
  8416. this.user = user;
  8417. this.enrolledFactors = [];
  8418. user._onReload(function (userInfo) {
  8419. if (userInfo.mfaInfo) {
  8420. _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
  8421. return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
  8422. });
  8423. }
  8424. });
  8425. }
  8426. MultiFactorUserImpl._fromUser = function (user) {
  8427. return new MultiFactorUserImpl(user);
  8428. };
  8429. MultiFactorUserImpl.prototype.getSession = function () {
  8430. return __awaiter(this, void 0, void 0, function () {
  8431. var _a, _b;
  8432. return __generator(this, function (_c) {
  8433. switch (_c.label) {
  8434. case 0:
  8435. _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
  8436. return [4 /*yield*/, this.user.getIdToken()];
  8437. case 1: return [2 /*return*/, _b.apply(_a, [_c.sent(), this.user.auth])];
  8438. }
  8439. });
  8440. });
  8441. };
  8442. MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
  8443. return __awaiter(this, void 0, void 0, function () {
  8444. var assertion, session, finalizeMfaResponse;
  8445. return __generator(this, function (_a) {
  8446. switch (_a.label) {
  8447. case 0:
  8448. assertion = assertionExtern;
  8449. return [4 /*yield*/, this.getSession()];
  8450. case 1:
  8451. session = (_a.sent());
  8452. return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
  8453. case 2:
  8454. finalizeMfaResponse = _a.sent();
  8455. // New tokens will be issued after enrollment of the new second factors.
  8456. // They need to be updated on the user.
  8457. return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
  8458. case 3:
  8459. // New tokens will be issued after enrollment of the new second factors.
  8460. // They need to be updated on the user.
  8461. _a.sent();
  8462. // The user needs to be reloaded to get the new multi-factor information
  8463. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  8464. // will be updated.
  8465. return [2 /*return*/, this.user.reload()];
  8466. }
  8467. });
  8468. });
  8469. };
  8470. MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
  8471. return __awaiter(this, void 0, void 0, function () {
  8472. var mfaEnrollmentId, idToken, idTokenResponse, e_1;
  8473. return __generator(this, function (_a) {
  8474. switch (_a.label) {
  8475. case 0:
  8476. mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  8477. return [4 /*yield*/, this.user.getIdToken()];
  8478. case 1:
  8479. idToken = _a.sent();
  8480. _a.label = 2;
  8481. case 2:
  8482. _a.trys.push([2, 6, , 7]);
  8483. return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  8484. idToken: idToken,
  8485. mfaEnrollmentId: mfaEnrollmentId
  8486. }))];
  8487. case 3:
  8488. idTokenResponse = _a.sent();
  8489. // Remove the second factor from the user's list.
  8490. this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
  8491. var uid = _a.uid;
  8492. return uid !== mfaEnrollmentId;
  8493. });
  8494. // Depending on whether the backend decided to revoke the user's session,
  8495. // the tokenResponse may be empty. If the tokens were not updated (and they
  8496. // are now invalid), reloading the user will discover this and invalidate
  8497. // the user's state accordingly.
  8498. return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
  8499. case 4:
  8500. // Depending on whether the backend decided to revoke the user's session,
  8501. // the tokenResponse may be empty. If the tokens were not updated (and they
  8502. // are now invalid), reloading the user will discover this and invalidate
  8503. // the user's state accordingly.
  8504. _a.sent();
  8505. return [4 /*yield*/, this.user.reload()];
  8506. case 5:
  8507. _a.sent();
  8508. return [3 /*break*/, 7];
  8509. case 6:
  8510. e_1 = _a.sent();
  8511. throw e_1;
  8512. case 7: return [2 /*return*/];
  8513. }
  8514. });
  8515. });
  8516. };
  8517. return MultiFactorUserImpl;
  8518. }());
  8519. var multiFactorUserCache = new WeakMap();
  8520. /**
  8521. * The {@link MultiFactorUser} corresponding to the user.
  8522. *
  8523. * @remarks
  8524. * This is used to access all multi-factor properties and operations related to the user.
  8525. *
  8526. * @param user - The user.
  8527. *
  8528. * @public
  8529. */
  8530. function multiFactor(user) {
  8531. var userModular = getModularInstance(user);
  8532. if (!multiFactorUserCache.has(userModular)) {
  8533. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  8534. }
  8535. return multiFactorUserCache.get(userModular);
  8536. }
  8537. /**
  8538. * @license
  8539. * Copyright 2017 Google LLC
  8540. *
  8541. * Licensed under the Apache License, Version 2.0 (the "License");
  8542. * you may not use this file except in compliance with the License.
  8543. * You may obtain a copy of the License at
  8544. *
  8545. * http://www.apache.org/licenses/LICENSE-2.0
  8546. *
  8547. * Unless required by applicable law or agreed to in writing, software
  8548. * distributed under the License is distributed on an "AS IS" BASIS,
  8549. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8550. * See the License for the specific language governing permissions and
  8551. * limitations under the License.
  8552. */
  8553. registerAuth("Worker" /* ClientPlatform.WORKER */);
  8554. function getAuth(app) {
  8555. if (app === void 0) { app = getApp(); }
  8556. // Unlike the other environments, we need to explicitly check if indexedDb is
  8557. // available. That means doing the whole rigamarole
  8558. var auth = _getProvider(app, "auth" /* _ComponentName.AUTH */).getImmediate();
  8559. // This promise is intended to float; auth initialization happens in the
  8560. // background, meanwhile the auth object may be used by the app.
  8561. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  8562. _getInstance(indexedDBLocalPersistence)
  8563. ._isAvailable()
  8564. .then(function (avail) {
  8565. var deps = avail ? { persistence: indexedDBLocalPersistence } : {};
  8566. _initializeAuthInstance(auth, deps);
  8567. });
  8568. return auth;
  8569. }
  8570. export { ActionCodeOperation, ActionCodeURL, AuthCredential, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as AuthErrorCodes, EmailAuthCredential, EmailAuthProvider, FacebookAuthProvider, FactorId, GithubAuthProvider, GoogleAuthProvider, OAuthCredential, OAuthProvider, OperationType, PhoneAuthCredential, ProviderId, SAMLAuthProvider, SignInMethod, TwitterAuthProvider, applyActionCode, beforeAuthStateChanged, checkActionCode, confirmPasswordReset, connectAuthEmulator, createUserWithEmailAndPassword, debugErrorMap, deleteUser, fetchSignInMethodsForEmail, getAdditionalUserInfo, getAuth, getIdToken, getIdTokenResult, getMultiFactorResolver, inMemoryPersistence, indexedDBLocalPersistence, initializeAuth, initializeRecaptchaConfig, isSignInWithEmailLink, linkWithCredential, multiFactor, onAuthStateChanged, onIdTokenChanged, parseActionCodeURL, prodErrorMap, reauthenticateWithCredential, reload, sendEmailVerification, sendPasswordResetEmail, sendSignInLinkToEmail, setPersistence, signInAnonymously, signInWithCredential, signInWithCustomToken, signInWithEmailAndPassword, signInWithEmailLink, signOut, unlink, updateCurrentUser, updateEmail, updatePassword, updateProfile, useDeviceLanguage, verifyBeforeUpdateEmail, verifyPasswordResetCode };
  8571. //# sourceMappingURL=index.webworker.esm5.js.map