No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.webworker.esm5.js 344KB

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