@entropic-bond/firebase 1.13.13 → 1.13.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39,7 +39,7 @@ This typically indicates that your device does not have a healthy Internet conne
39
39
  {
40
40
  ${t}
41
41
  }
42
- `)}}static propInfo(n,e){return _e.createInstance(n).getPropInfo(e)}static getSystemRegisteredReferencesWithCachedProps(){return _e.registeredClassesAndLegacyNames().reduce((n,e)=>{const t=_e.createInstance(e).getPersistentProperties().filter(r=>r.cachedPropsConfig?.cachedProps);return t.length>0&&(n[e]=t),n},{})}},_e._factoryMap={},_e);RE([jn],mh.prototype,"_id");let fe=mh;function jn(n,e){return bE()(n,e)}function bE(n){return function(e,t){Object.getOwnPropertyDescriptor(e,"_persistentProperties")||(e._persistentProperties?e._persistentProperties=[...e._persistentProperties]:e._persistentProperties=[]);const r=e._persistentProperties.find(s=>s.name===t);r?Object.assign(r,n):e._persistentProperties.push({name:t,...n})}}function PE(n,e){return t=>{fe.registerFactory(n,t,e),t.prototype.__className=n}}const gh=class up{constructor(e,t,r){if(r){if(!(t instanceof fe))throw new Error(up.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof fe?t.className:t;this._stream=e}findById(e,t){return new Promise((r,s)=>{this._stream.findById(e,this.collectionName).then(i=>{i?(t?t.fromObject(i):t=fe.createInstance(i),r(t)):r(void 0)}).catch(i=>s(i))})}save(e){const t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((r,s)=>{this._stream.save(t.__rootCollections).then(()=>r()).catch(i=>s(i))})}delete(e){return new Promise((t,r)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(s=>r(s))})}find(){return new SE(this)}query(e={},t){if(t){const r=t instanceof fe?t.className:t;e.operations||(e.operations=[]),e.operations.push({property:"__className",operator:"==",value:r})}return this.mapToInstance(()=>this._stream.find(this.preprocessQueryObject(e),this.collectionName))}count(e){return this._stream.count(e,this.collectionName)}next(e){return this.mapToInstance(()=>this._stream.next(e))}onDocumentChange(e,t){return this._stream.onDocumentChange(this.collectionName,e,r=>t(this.toPersistentChangeObject(r)))}onCollectionChange(e,t){return this._stream.onCollectionChange(e.getQueryObject(),this.collectionName,r=>t(r.map(s=>({after:s.after&&fe.createInstance(s.after),before:s.before&&fe.createInstance(s.before),type:s.type,params:s.params}))))}toPersistentChangeObject(e){return{...e,before:e.before&&fe.createInstance(e.before),after:e.after&&fe.createInstance(e.after)}}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(i=>fe.createInstance(i)))).catch(s=>r(s))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;const t=e.operations?.map(r=>{const s=r.value[0]??r.value;return hn.isArrayOperator(r.operator)&&s instanceof fe?{property:fe.searchableArrayNameFor(r.property),operator:r.operator,value:Array.isArray(r.value)?r.value.map(i=>i.id):s.id,aggregate:r.aggregate}:{property:r.property,operator:r.operator,value:r.value instanceof fe?{id:r.value.id}:r.value,aggregate:r.aggregate}})??[];return{...e,operations:t}}};gh.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let ri=gh;class SE{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(ri.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(ri.error.invalidQueryOrder);const i=e.split(".");let a={},c=i.length>1?a:r;return i.slice(1).forEach((l,d)=>{a[l]=d<i.length-2?{}:r,a=a[l]}),this.queryObject.operations?.push({property:i[0],operator:t,value:c,aggregate:s}),this}and(e,t,r){return this.where(e,t,r)}andDeepProp(e,t,r){return this.whereDeepProp(e,t,r)}or(e,t,r){return this.where(e,t,r,!0)}orDeepProp(e,t,r){return this.whereDeepProp(e,t,r,!0)}instanceOf(e){const t=e instanceof fe?e.className:e;return this.queryObject.operations?.push({property:"__className",operator:"==",value:t}),this}get(e){return e&&(this.queryObject.limit=e),this.model.query(this.queryObject)}limit(e){return this.queryObject.limit=e,this}orderBy(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}orderByDeepProp(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}count(){return this.model.count(this.queryObject)}getQueryObject(){return this.queryObject}}const _h=class nr{constructor(){}static useDataSource(e){this._dataSource=e}static get dataSource(){return nr._dataSource}static getModel(e){if(!nr._dataSource)throw new Error(this.error.shouldBeRegistered);return new ri(nr._dataSource,e)}static getModelForSubCollection(e,t){if(!nr._dataSource)throw new Error(this.error.shouldBeRegistered);return new ri(nr._dataSource,e,t)}static async populate(e){if(!e)return;const t=async r=>{const s=r;if(!s.__documentReference)return r;const i=await this.getModel(s.__documentReference.storedInCollection).findById(s.id,r);return i&&(i.__documentReference=void 0),i};return Array.isArray(e)?(await Promise.all(e.map(r=>t(r)))).filter(r=>r):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((t,r)=>t&&r.__documentReference===void 0,!0):e.__documentReference===void 0}};_h.error={shouldBeRegistered:"You should register a data source before using the data Store."};let CE=_h;class hn{installCachedPropsUpdaters(e={}){hn.onUpdate=e.onUpdate;const t=fe.getSystemRegisteredReferencesWithCachedProps(),r={};Object.entries(t).forEach(([i,a])=>{a.forEach(c=>{const l=fe.collectionPath(fe.createInstance(i),c);r[l]||(r[l]=[]),r[l].push({prop:c,collectionPropOwner:i})})});const s=[];return Object.entries(r).forEach(([i,a])=>{const c=this.subscribeToDocumentChangeListener(i,l=>hn.processDocumentChange(l,a));if(c)s.push(c);else if(e.noThrowOnNonImplementedListener)throw new Error("The method documentChangeListener has not been implemented in the concrete data source")}),s}subscribeToDocumentChangeListener(e,t){}static toPropertyPathOperations(e){return e?e.map(t=>{if(hn.isArrayOperator(t.operator)&&t.value[0]instanceof fe)return{property:fe.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(i=>i.id),aggregate:t.aggregate};const[r,s]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${r?"."+r:""}`,operator:t.operator,value:s,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e==="containsAny"||e==="contains"}static toPropertyPathValue(e){if(typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e)[0],[r,s]=this.toPropertyPathValue(e[t]);return[`${t}${r?"."+r:""}`,s]}else return[void 0,e]}static async processDocumentChange(e,t){if(e.before)return t.map(async r=>{const s=CE.getModel(r.collectionPropOwner);let i=s.find();r.prop.cachedPropsConfig?.cachedProps?.forEach(c=>{const l=e.before?.[c],d=e.after?.[c];l!==d&&(i=i.orDeepProp(`${r.prop.name}.${c}`,"==",l))});const a=await i.get();return Promise.all([a.map(async c=>{r.prop.cachedPropsConfig?.cachedProps?.forEach(async l=>{const d=e.before?.[l],f=e.after?.[l];d!==f&&(c[`_${r.prop.name}`][`_${l}`]=f,await s.save(c),this.onUpdate?.(c,r.prop))})})])})}}const yh=class rr{static registerCloudStorage(e,t){rr._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=rr._cloudStorageFactoryMap[e];if(!t)throw new Error(`You should register the ${e} cloud storage provider prior to use it`);return t()}get className(){return this.__className}static useCloudStorage(e){rr._defaultCloudStorage=e}static get defaultCloudStorage(){if(!rr._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return rr._defaultCloudStorage}};yh._cloudStorageFactoryMap={};let $n=yh;function Eh(n,e){return $n.registerCloudStorage(n,e),t=>{t.prototype.__className=n}}var kE=(n,e,t,r)=>{for(var s=e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(s)||s);return s};let la=class extends $n{constructor(n=""){super(),this._simulateDelay=0,this._pendingPromises=[],this.mockFileSystem={},this._pathToMockFiles=n}simulateDelay(n){return this._simulateDelay=n,this}resolveWithDelay(n){if(this._simulateDelay<=0)return Promise.resolve(n);const e=new Promise(t=>{setTimeout(()=>t(n),this._simulateDelay)});return this._pendingPromises.push(e),e.finally(()=>this._pendingPromises=this._pendingPromises.filter(t=>t===e)),e}save(n,e){const t=n;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[n]=JSON.stringify(e),this._onProgress&&this._onProgress(100,100);const r=e instanceof File?e.name:t;return this.resolveWithDelay(r)}uploadControl(){return{resume:()=>{},pause:()=>{},cancel:()=>{},onProgress:n=>this._onProgress=n}}getUrl(n){return Promise.resolve(this._pathToMockFiles+n)}delete(n){return delete this.mockFileSystem[n],this.resolveWithDelay()}};la=kE([Eh("MockCloudStorage",()=>new la)],la);var NE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,zn=(n,e,t,r)=>{for(var s=r>1?void 0:r?DE(e,t):e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&NE(e,t,s),s};let dn=class extends fe{constructor(){super(...arguments),this._onChange=new fh}async save({data:n,fileName:e,progress:t,cloudStorageProvider:r}={}){const s=n||this._pendingData;s&&(this._reference&&await this.delete(),this.provider=r||$n.defaultCloudStorage,this._originalFileName=e||(s instanceof File?s.name:void 0),this._reference=await this.provider.save(this.id,s,t),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:0,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw new Error("Cannot delete a not stored file");await this.provider.delete(this._reference),this._reference=void 0,this._url=void 0,this._onChange.notify({event:2,storedFile:this})}set provider(n){this._provider=n,this._cloudStorageProviderName=n.className}get provider(){if(!this._provider)try{this._provider=$n.createInstance(this._cloudStorageProviderName)}catch{this._provider=$n.defaultCloudStorage}return this._provider}get url(){return this._url}get mimeType(){return this._mimeType}setDataToStore(n){return this._pendingData=n,this._originalFileName=n instanceof File?n.name:void 0,this._mimeType=n instanceof Blob?n.type:void 0,this._onChange.notify({event:1,pendingData:n,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(n){return this._onChange.subscribe(n)}};zn([jn],dn.prototype,"_reference",2),zn([jn],dn.prototype,"_url",2),zn([jn],dn.prototype,"_cloudStorageProviderName",2),zn([jn],dn.prototype,"_originalFileName",2),zn([jn],dn.prototype,"_mimeType",2),dn=zn([PE("StoredFile")],dn);class Th{}const wh=class xe extends Th{constructor(){if(super(),this._onAuthStateChange=new fh,!xe._authService)throw new Error(xe.error.shouldBeRegistered);xe._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){xe._authService!=e&&(xe._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return xe._authService.signUp(e)}login(e){return xe._authService.login(e)}logout(){return xe._authService.logout()}resetEmailPassword(e){return xe._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return xe._authService.resendVerificationEmail(e,t,r)}refreshToken(){return xe._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return xe._authService.linkAdditionalProvider(e)}unlinkProvider(e){return xe._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};wh.error={shouldBeRegistered:"You should register an auth service before using Auth."},wh._instance=void 0;function si(n){return n?n.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}var OE="firebase",VE="12.7.0";je(OE,VE,"app");function Ih(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const LE=Ih,vh=new or("auth","Firebase",Ih());const ii=new $i("@firebase/auth");function ME(n,...e){ii.logLevel<=H.WARN&&ii.warn(`Auth (${tn}): ${n}`,...e)}function oi(n,...e){ii.logLevel<=H.ERROR&&ii.error(`Auth (${tn}): ${n}`,...e)}function He(n,...e){throw da(n,...e)}function Qe(n,...e){return da(n,...e)}function ha(n,e,t){const r={...LE(),[e]:t};return new or("auth","Firebase",r).create(e,{appName:n.name})}function ut(n){return ha(n,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Ah(n,e,t){const r=t;if(!(e instanceof r))throw r.name!==e.constructor.name&&He(n,"argument-error"),ha(n,"argument-error",`Type of ${e.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function da(n,...e){if(typeof n!="string"){const t=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=n.name),n._errorFactory.create(t,...r)}return vh.create(n,...e)}function M(n,e,...t){if(!n)throw da(e,...t)}function wt(n){const e="INTERNAL ASSERTION FAILED: "+n;throw oi(e),new Error(e)}function It(n,e){n||wt(e)}function fa(){return typeof self<"u"&&self.location?.href||""}function xE(){return Rh()==="http:"||Rh()==="https:"}function Rh(){return typeof self<"u"&&self.location?.protocol||null}function UE(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(xE()||vp()||"connection"in navigator)?navigator.onLine:!0}function FE(){if(typeof navigator>"u")return null;const n=navigator;return n.languages&&n.languages[0]||n.language||null}class Or{constructor(e,t){this.shortDelay=e,this.longDelay=t,It(t>e,"Short delay should be less than long delay!"),this.isMobile=Tp()||Ap()}get(){return UE()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function pa(n,e){It(n.emulator,"Emulator should always be set here");const{url:t}=n.emulator;return e?`${t}${e.startsWith("/")?e.slice(1):e}`:t}class bh{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;wt("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;wt("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;wt("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const BE={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"};const qE=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],jE=new Or(3e4,6e4);function vt(n,e){return n.tenantId&&!e.tenantId?{...e,tenantId:n.tenantId}:e}async function Xe(n,e,t,r,s={}){return Ph(n,s,async()=>{let i={},a={};r&&(e==="GET"?a=r:i={body:JSON.stringify(r)});const c=ar({key:n.config.apiKey,...a}).slice(1),l=await n._getAdditionalHeaders();l["Content-Type"]="application/json",n.languageCode&&(l["X-Firebase-Locale"]=n.languageCode);const d={method:e,headers:l,...i};return Ip()||(d.referrerPolicy="no-referrer"),n.emulatorConfig&&et(n.emulatorConfig.host)&&(d.credentials="include"),bh.fetch()(await Sh(n,n.config.apiHost,t,c),d)})}async function Ph(n,e,t){n._canInitEmulator=!1;const r={...BE,...e};try{const s=new zE(n),i=await Promise.race([t(),s.promise]);s.clearNetworkTimeout();const a=await i.json();if("needConfirmation"in a)throw ai(n,"account-exists-with-different-credential",a);if(i.ok&&!("errorMessage"in a))return a;{const c=i.ok?a.errorMessage:a.error.message,[l,d]=c.split(" : ");if(l==="FEDERATED_USER_ID_ALREADY_LINKED")throw ai(n,"credential-already-in-use",a);if(l==="EMAIL_EXISTS")throw ai(n,"email-already-in-use",a);if(l==="USER_DISABLED")throw ai(n,"user-disabled",a);const f=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(d)throw ha(n,f,d);He(n,f)}}catch(s){if(s instanceof We)throw s;He(n,"network-request-failed",{message:String(s)})}}async function Vr(n,e,t,r,s={}){const i=await Xe(n,e,t,r,s);return"mfaPendingCredential"in i&&He(n,"multi-factor-auth-required",{_serverResponse:i}),i}async function Sh(n,e,t,r){const s=`${e}${t}?${r}`,i=n,a=i.config.emulator?pa(n.config,s):`${n.config.apiScheme}://${s}`;return qE.includes(t)&&(await i._persistenceManagerAvailable,i._getPersistenceType()==="COOKIE")?i._getPersistence()._getFinalTarget(a).toString():a}function $E(n){switch(n){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class zE{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((t,r)=>{this.timer=setTimeout(()=>r(Qe(this.auth,"network-request-failed")),jE.get())})}}function ai(n,e,t){const r={appName:n.name};t.email&&(r.email=t.email),t.phoneNumber&&(r.phoneNumber=t.phoneNumber);const s=Qe(n,e,r);return s.customData._tokenResponse=t,s}function Ch(n){return n!==void 0&&n.enterprise!==void 0}class HE{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return $E(t.enforcementState);return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function WE(n,e){return Xe(n,"GET","/v2/recaptchaConfig",vt(n,e))}async function GE(n,e){return Xe(n,"POST","/v1/accounts:delete",e)}async function KE(n,e){return Xe(n,"POST","/v1/accounts:update",e)}async function ci(n,e){return Xe(n,"POST","/v1/accounts:lookup",e)}function Lr(n){if(n)try{const e=new Date(Number(n));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function QE(n,e=!1){const t=X(n),r=await t.getIdToken(e),s=ga(r);M(s&&s.exp&&s.auth_time&&s.iat,t.auth,"internal-error");const i=typeof s.firebase=="object"?s.firebase:void 0,a=i?.sign_in_provider;return{claims:s,token:r,authTime:Lr(ma(s.auth_time)),issuedAtTime:Lr(ma(s.iat)),expirationTime:Lr(ma(s.exp)),signInProvider:a||null,signInSecondFactor:i?.sign_in_second_factor||null}}function ma(n){return Number(n)*1e3}function ga(n){const[e,t,r]=n.split(".");if(e===void 0||t===void 0||r===void 0)return oi("JWT malformed, contained fewer than 3 sections"),null;try{const s=fc(t);return s?JSON.parse(s):(oi("Failed to decode base64 JWT payload"),null)}catch(s){return oi("Caught error parsing JWT payload as JSON",s?.toString()),null}}function kh(n){const e=ga(n);return M(e,"internal-error"),M(typeof e.exp<"u","internal-error"),M(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Hn(n,e,t=!1){if(t)return e;try{return await e}catch(r){throw r instanceof We&&XE(r)&&n.auth.currentUser===n&&await n.auth.signOut(),r}}function XE({code:n}){return n==="auth/user-disabled"||n==="auth/user-token-expired"}class YE{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){if(e){const t=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),t}else{this.errorBackoff=3e4;const r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class _a{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Lr(this.lastLoginAt),this.creationTime=Lr(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Mr(n){const e=n.auth,t=await n.getIdToken(),r=await Hn(n,ci(e,{idToken:t}));M(r?.users.length,e,"internal-error");const s=r.users[0];n._notifyReloadListener(s);const i=s.providerUserInfo?.length?Nh(s.providerUserInfo):[],a=ZE(n.providerData,i),c=n.isAnonymous,l=!(n.email&&s.passwordHash)&&!a?.length,d=c?l:!1,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new _a(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(n,f)}async function JE(n){const e=X(n);await Mr(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function ZE(n,e){return[...n.filter(r=>!e.some(s=>s.providerId===r.providerId)),...e]}function Nh(n){return n.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}async function eT(n,e){const t=await Ph(n,{},async()=>{const r=ar({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:s,apiKey:i}=n.config,a=await Sh(n,s,"/v1/token",`key=${i}`),c=await n._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";const l={method:"POST",headers:c,body:r};return n.emulatorConfig&&et(n.emulatorConfig.host)&&(l.credentials="include"),bh.fetch()(a,l)});return{accessToken:t.access_token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}async function tT(n,e){return Xe(n,"POST","/v2/accounts:revokeToken",vt(n,e))}class Wn{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){M(e.idToken,"internal-error"),M(typeof e.idToken<"u","internal-error"),M(typeof e.refreshToken<"u","internal-error");const t="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):kh(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){M(e.length!==0,"internal-error");const t=kh(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return!t&&this.accessToken&&!this.isExpired?this.accessToken:(M(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:s,expiresIn:i}=await eT(e,t);this.updateTokensAndExpiration(r,s,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,t){const{refreshToken:r,accessToken:s,expirationTime:i}=t,a=new Wn;return r&&(M(typeof r=="string","internal-error",{appName:e}),a.refreshToken=r),s&&(M(typeof s=="string","internal-error",{appName:e}),a.accessToken=s),i&&(M(typeof i=="number","internal-error",{appName:e}),a.expirationTime=i),a}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new Wn,this.toJSON())}_performRefresh(){return wt("not implemented")}}function $t(n,e){M(typeof n=="string"||typeof n>"u","internal-error",{appName:e})}class Ye{constructor({uid:e,auth:t,stsTokenManager:r,...s}){this.providerId="firebase",this.proactiveRefresh=new YE(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new _a(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await Hn(this,this.stsTokenManager.getToken(this.auth,e));return M(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return QE(this,e)}reload(){return JE(this)}_assign(e){this!==e&&(M(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(t=>({...t})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new Ye({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){M(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await Mr(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Ae(this.auth.app))return Promise.reject(ut(this.auth));const e=await this.getIdToken();return await Hn(this,GE(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const r=t.displayName??void 0,s=t.email??void 0,i=t.phoneNumber??void 0,a=t.photoURL??void 0,c=t.tenantId??void 0,l=t._redirectEventId??void 0,d=t.createdAt??void 0,f=t.lastLoginAt??void 0,{uid:m,emailVerified:y,isAnonymous:R,providerData:k,stsTokenManager:N}=t;M(m&&N,e,"internal-error");const C=Wn.fromJSON(this.name,N);M(typeof m=="string",e,"internal-error"),$t(r,e.name),$t(s,e.name),M(typeof y=="boolean",e,"internal-error"),M(typeof R=="boolean",e,"internal-error"),$t(i,e.name),$t(a,e.name),$t(c,e.name),$t(l,e.name),$t(d,e.name),$t(f,e.name);const U=new Ye({uid:m,auth:e,email:s,emailVerified:y,displayName:r,isAnonymous:R,photoURL:a,phoneNumber:i,tenantId:c,stsTokenManager:C,createdAt:d,lastLoginAt:f});return k&&Array.isArray(k)&&(U.providerData=k.map($=>({...$}))),l&&(U._redirectEventId=l),U}static async _fromIdTokenResponse(e,t,r=!1){const s=new Wn;s.updateFromServerResponse(t);const i=new Ye({uid:t.localId,auth:e,stsTokenManager:s,isAnonymous:r});return await Mr(i),i}static async _fromGetAccountInfoResponse(e,t,r){const s=t.users[0];M(s.localId!==void 0,"internal-error");const i=s.providerUserInfo!==void 0?Nh(s.providerUserInfo):[],a=!(s.email&&s.passwordHash)&&!i?.length,c=new Wn;c.updateFromIdToken(r);const l=new Ye({uid:s.localId,auth:e,stsTokenManager:c,isAnonymous:a}),d={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:i,metadata:new _a(s.createdAt,s.lastLoginAt),isAnonymous:!(s.email&&s.passwordHash)&&!i?.length};return Object.assign(l,d),l}}const Dh=new Map;function At(n){It(n instanceof Function,"Expected a class definition");let e=Dh.get(n);return e?(It(e instanceof n,"Instance stored in cache mismatched with class"),e):(e=new n,Dh.set(n,e),e)}class Oh{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return t===void 0?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Oh.type="NONE";const Vh=Oh;function ui(n,e,t){return`firebase:${n}:${e}:${t}`}class Gn{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:s,name:i}=this.auth;this.fullUserKey=ui(this.userKey,s.apiKey,i),this.fullPersistenceKey=ui("persistence",s.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){const t=await ci(this.auth,{idToken:e}).catch(()=>{});return t?Ye._fromGetAccountInfoResponse(this.auth,t,e):null}return Ye._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new Gn(At(Vh),e,r);const s=(await Promise.all(t.map(async d=>{if(await d._isAvailable())return d}))).filter(d=>d);let i=s[0]||At(Vh);const a=ui(r,e.config.apiKey,e.name);let c=null;for(const d of t)try{const f=await d._get(a);if(f){let m;if(typeof f=="string"){const y=await ci(e,{idToken:f}).catch(()=>{});if(!y)break;m=await Ye._fromGetAccountInfoResponse(e,y,f)}else m=Ye._fromJSON(e,f);d!==i&&(c=m),i=d;break}}catch{}const l=s.filter(d=>d._shouldAllowMigration);return!i._shouldAllowMigration||!l.length?new Gn(i,e,r):(i=l[0],c&&await i._set(a,c.toJSON()),await Promise.all(t.map(async d=>{if(d!==i)try{await d._remove(a)}catch{}})),new Gn(i,e,r))}}function Lh(n){const e=n.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(Fh(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Mh(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(qh(e))return"Blackberry";if(jh(e))return"Webos";if(xh(e))return"Safari";if((e.includes("chrome/")||Uh(e))&&!e.includes("edge/"))return"Chrome";if(Bh(e))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=n.match(t);if(r?.length===2)return r[1]}return"Other"}function Mh(n=ve()){return/firefox\//i.test(n)}function xh(n=ve()){const e=n.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function Uh(n=ve()){return/crios\//i.test(n)}function Fh(n=ve()){return/iemobile/i.test(n)}function Bh(n=ve()){return/android/i.test(n)}function qh(n=ve()){return/blackberry/i.test(n)}function jh(n=ve()){return/webos/i.test(n)}function ya(n=ve()){return/iphone|ipad|ipod/i.test(n)||/macintosh/i.test(n)&&/mobile/i.test(n)}function nT(n=ve()){return ya(n)&&!!window.navigator?.standalone}function rT(){return Rp()&&document.documentMode===10}function $h(n=ve()){return ya(n)||Bh(n)||jh(n)||qh(n)||/windows phone/i.test(n)||Fh(n)}function zh(n,e=[]){let t;switch(n){case"Browser":t=Lh(ve());break;case"Worker":t=`${Lh(ve())}-${n}`;break;default:t=n}const r=e.length?e.join(","):"FirebaseCore-web";return`${t}/JsCore/${tn}/${r}`}class sT{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const r=i=>new Promise((a,c)=>{try{const l=e(i);a(l)}catch(l){c(l)}});r.onAbort=t,this.queue.push(r);const s=this.queue.length-1;return()=>{this.queue[s]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(r){t.reverse();for(const s of t)try{s()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}}async function iT(n,e={}){return Xe(n,"GET","/v2/passwordPolicy",vt(n,e))}const oT=6;class aT{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??oT,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),t.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),t.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),t.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),t.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,s=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),s&&(t.meetsMaxPasswordLength=e.length<=s)}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);let r;for(let s=0;s<e.length;s++)r=e.charAt(s),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,s,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=s)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class cT{constructor(e,t,r,s){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=s,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Hh(this),this.idTokenSubscription=new Hh(this),this.beforeStateQueue=new sT(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=vh,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=s.sdkClientVersion,this._persistenceManagerAvailable=new Promise(i=>this._resolvePersistenceManagerAvailable=i)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=At(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Gn.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{const t=await ci(this,{idToken:e}),r=await Ye._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(t){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",t),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(Ae(this.app)){const i=this.app.settings.authIdToken;return i?new Promise(a=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(i).then(a,a))}):this.directlySetCurrentUser(null)}const t=await this.assertedPersistence.getCurrentUser();let r=t,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const i=this.redirectUser?._redirectEventId,a=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!i||i===a)&&c?.user&&(r=c.user,s=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(r)}catch(i){r=t,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(i))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return M(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Mr(e)}catch(t){if(t?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=FE()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Ae(this.app))return Promise.reject(ut(this));const t=e?X(e):null;return t&&M(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&M(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return Ae(this.app)?Promise.reject(ut(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Ae(this.app)?Promise.reject(ut(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(At(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await iT(this),t=new aT(e);this.tenantId===null?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new or("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged(()=>{r(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){const t=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:t};this.tenantId!=null&&(r.tenantId=this.tenantId),await tT(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&At(e)||this._popupRedirectResolver;M(t,this,"argument-error"),this.redirectPersistenceManager=await Gn.create(this,[At(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,s){if(this._deleted)return()=>{};const i=typeof t=="function"?t:t.next.bind(t);let a=!1;const c=this._isInitialized?Promise.resolve():this._initializationPromise;if(M(c,this,"internal-error"),c.then(()=>{a||i(this.currentUser)}),typeof t=="function"){const l=e.addObserver(t,r,s);return()=>{a=!0,l()}}else{const l=e.addObserver(t);return()=>{a=!0,l()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return M(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=zh(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);const t=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();t&&(e["X-Firebase-Client"]=t);const r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(Ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&ME(`Error while retrieving App Check token: ${e.error}`),e?.token}}function lt(n){return X(n)}class Hh{constructor(e){this.auth=e,this.observer=null,this.addObserver=Op(t=>this.observer=t)}get next(){return M(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let li={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function uT(n){li=n}function Wh(n){return li.loadJS(n)}function lT(){return li.recaptchaEnterpriseScript}function hT(){return li.gapiScript}function dT(n){return`__${n}${Math.floor(Math.random()*1e6)}`}class fT{constructor(){this.enterprise=new pT}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class pT{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}const mT="recaptcha-enterprise",Gh="NO_RECAPTCHA";class gT{constructor(e){this.type=mT,this.auth=lt(e)}async verify(e="verify",t=!1){async function r(i){if(!t){if(i.tenantId==null&&i._agentRecaptchaConfig!=null)return i._agentRecaptchaConfig.siteKey;if(i.tenantId!=null&&i._tenantRecaptchaConfigs[i.tenantId]!==void 0)return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(a,c)=>{WE(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(l=>{if(l.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{const d=new HE(l);return i.tenantId==null?i._agentRecaptchaConfig=d:i._tenantRecaptchaConfigs[i.tenantId]=d,a(d.siteKey)}}).catch(l=>{c(l)})})}function s(i,a,c){const l=window.grecaptcha;Ch(l)?l.enterprise.ready(()=>{l.enterprise.execute(i,{action:e}).then(d=>{a(d)}).catch(()=>{a(Gh)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new fT().execute("siteKey",{action:"verify"}):new Promise((i,a)=>{r(this.auth).then(c=>{if(!t&&Ch(window.grecaptcha))s(c,i,a);else{if(typeof window>"u"){a(new Error("RecaptchaVerifier is only supported in browser"));return}let l=lT();l.length!==0&&(l+=c),Wh(l).then(()=>{s(c,i,a)}).catch(d=>{a(d)})}}).catch(c=>{a(c)})})}}async function Kh(n,e,t,r=!1,s=!1){const i=new gT(n);let a;if(s)a=Gh;else try{a=await i.verify(t)}catch{a=await i.verify(t,!0)}const c={...e};if(t==="mfaSmsEnrollment"||t==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){const l=c.phoneEnrollmentInfo.phoneNumber,d=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:l,recaptchaToken:d,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){const l=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:l,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return r?Object.assign(c,{captchaResp:a}):Object.assign(c,{captchaResponse:a}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function hi(n,e,t,r,s){if(n._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await Kh(n,e,t,t==="getOobCode");return r(n,i)}else return r(n,e).catch(async i=>{if(i.code==="auth/missing-recaptcha-token"){console.log(`${t} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const a=await Kh(n,e,t,t==="getOobCode");return r(n,a)}else return Promise.reject(i)})}function _T(n,e){const t=lr(n,"auth");if(t.isInitialized()){const s=t.getImmediate(),i=t.getOptions();if(Zt(i,e??{}))return s;He(s,"already-initialized")}return t.initialize({options:e})}function yT(n,e){const t=e?.persistence||[],r=(Array.isArray(t)?t:[t]).map(At);e?.errorMap&&n._updateErrorMap(e.errorMap),n._initializeWithPersistence(r,e?.popupRedirectResolver)}function Qh(n,e,t){const r=lt(n);M(/^https?:\/\//.test(e),r,"invalid-emulator-scheme");const s=!1,i=Xh(e),{host:a,port:c}=ET(e),l=c===null?"":`:${c}`,d={url:`${i}//${a}${l}/`},f=Object.freeze({host:a,port:c,protocol:i.replace(":",""),options:Object.freeze({disableWarnings:s})});if(!r._canInitEmulator){M(r.config.emulator&&r.emulatorConfig,r,"emulator-config-failed"),M(Zt(d,r.config.emulator)&&Zt(f,r.emulatorConfig),r,"emulator-config-failed");return}r.config.emulator=d,r.emulatorConfig=f,r.settings.appVerificationDisabledForTesting=!0,et(a)?(as(`${i}//${a}${l}`),cs("Auth",!0)):TT()}function Xh(n){const e=n.indexOf(":");return e<0?"":n.substr(0,e+1)}function ET(n){const e=Xh(n),t=/(\/\/)?([^?#/]+)/.exec(n.substr(e.length));if(!t)return{host:"",port:null};const r=t[2].split("@").pop()||"",s=/^(\[[^\]]+\])(:|$)/.exec(r);if(s){const i=s[1];return{host:i,port:Yh(r.substr(i.length+1))}}else{const[i,a]=r.split(":");return{host:i,port:Yh(a)}}}function Yh(n){if(!n)return null;const e=Number(n);return isNaN(e)?null:e}function TT(){function n(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",n):n())}class Ea{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return wt("not implemented")}_getIdTokenResponse(e){return wt("not implemented")}_linkToIdToken(e,t){return wt("not implemented")}_getReauthenticationResolver(e){return wt("not implemented")}}async function wT(n,e){return Xe(n,"POST","/v1/accounts:signUp",e)}async function IT(n,e){return Vr(n,"POST","/v1/accounts:signInWithPassword",vt(n,e))}async function Jh(n,e){return Xe(n,"POST","/v1/accounts:sendOobCode",vt(n,e))}async function vT(n,e){return Jh(n,e)}async function AT(n,e){return Jh(n,e)}async function RT(n,e){return Vr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}async function bT(n,e){return Vr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}class xr extends Ea{constructor(e,t,r,s=null){super("password",r),this._email=e,this._password=t,this._tenantId=s}static _fromEmailAndPassword(e,t){return new xr(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new xr(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t=typeof e=="string"?JSON.parse(e):e;if(t?.email&&t?.password){if(t.signInMethod==="password")return this._fromEmailAndPassword(t.email,t.password);if(t.signInMethod==="emailLink")return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":const t={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return hi(e,t,"signInWithPassword",IT);case"emailLink":return RT(e,{email:this._email,oobCode:this._password});default:He(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":const r={idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return hi(e,r,"signUpPassword",wT);case"emailLink":return bT(e,{idToken:t,email:this._email,oobCode:this._password});default:He(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Kn(n,e){return Vr(n,"POST","/v1/accounts:signInWithIdp",vt(n,e))}const PT="http://localhost";class fn extends Ea{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new fn(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):He("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:s,...i}=t;if(!r||!s)return null;const a=new fn(r,s);return a.idToken=i.idToken||void 0,a.accessToken=i.accessToken||void 0,a.secret=i.secret,a.nonce=i.nonce,a.pendingToken=i.pendingToken||null,a}_getIdTokenResponse(e){const t=this.buildRequest();return Kn(e,t)}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,Kn(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Kn(e,t)}buildRequest(){const e={requestUri:PT,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=ar(t)}return e}}function ST(n){switch(n){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}function CT(n){const e=cr(ur(n)).link,t=e?cr(ur(e)).deep_link_id:null,r=cr(ur(n)).deep_link_id;return(r?cr(ur(r)).link:null)||r||t||e||n}class Ta{constructor(e){const t=cr(ur(e)),r=t.apiKey??null,s=t.oobCode??null,i=ST(t.mode??null);M(r&&s&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=s,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){const t=CT(e);try{return new Ta(t)}catch{return null}}}class Qn{constructor(){this.providerId=Qn.PROVIDER_ID}static credential(e,t){return xr._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=Ta.parseLink(t);return M(r,"argument-error"),xr._fromEmailAndCode(e,r.code,r.tenantId)}}Qn.PROVIDER_ID="password",Qn.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Qn.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class di{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class Ur extends di{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class ht extends Ur{constructor(){super("facebook.com")}static credential(e){return fn._fromParams({providerId:ht.PROVIDER_ID,signInMethod:ht.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ht.credentialFromTaggedObject(e)}static credentialFromError(e){return ht.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return ht.credential(e.oauthAccessToken)}catch{return null}}}ht.FACEBOOK_SIGN_IN_METHOD="facebook.com",ht.PROVIDER_ID="facebook.com";class dt extends Ur{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return fn._fromParams({providerId:dt.PROVIDER_ID,signInMethod:dt.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return dt.credentialFromTaggedObject(e)}static credentialFromError(e){return dt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return dt.credential(t,r)}catch{return null}}}dt.GOOGLE_SIGN_IN_METHOD="google.com",dt.PROVIDER_ID="google.com";class zt extends Ur{constructor(){super("github.com")}static credential(e){return fn._fromParams({providerId:zt.PROVIDER_ID,signInMethod:zt.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return zt.credentialFromTaggedObject(e)}static credentialFromError(e){return zt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return zt.credential(e.oauthAccessToken)}catch{return null}}}zt.GITHUB_SIGN_IN_METHOD="github.com",zt.PROVIDER_ID="github.com";class Je extends Ur{constructor(){super("twitter.com")}static credential(e,t){return fn._fromParams({providerId:Je.PROVIDER_ID,signInMethod:Je.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Je.credentialFromTaggedObject(e)}static credentialFromError(e){return Je.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return Je.credential(t,r)}catch{return null}}}Je.TWITTER_SIGN_IN_METHOD="twitter.com",Je.PROVIDER_ID="twitter.com";async function Zh(n,e){return Vr(n,"POST","/v1/accounts:signUp",vt(n,e))}class Rt{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,s=!1){const i=await Ye._fromIdTokenResponse(e,r,s),a=ed(r);return new Rt({user:i,providerId:a,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const s=ed(r);return new Rt({user:e,providerId:s,_tokenResponse:r,operationType:t})}}function ed(n){return n.providerId?n.providerId:"phoneNumber"in n?"phone":null}async function kT(n){if(Ae(n.app))return Promise.reject(ut(n));const e=lt(n);if(await e._initializationPromise,e.currentUser?.isAnonymous)return new Rt({user:e.currentUser,providerId:null,operationType:"signIn"});const t=await Zh(e,{returnSecureToken:!0}),r=await Rt._fromIdTokenResponse(e,"signIn",t,!0);return await e._updateCurrentUser(r.user),r}class fi extends We{constructor(e,t,r,s){super(t.code,t.message),this.operationType=r,this.user=s,Object.setPrototypeOf(this,fi.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,s){return new fi(e,t,r,s)}}function td(n,e,t,r){return(e==="reauthenticate"?t._getReauthenticationResolver(n):t._getIdTokenResponse(n)).catch(i=>{throw i.code==="auth/multi-factor-auth-required"?fi._fromErrorAndOperation(n,i,e,r):i})}function nd(n){return new Set(n.map(({providerId:e})=>e).filter(e=>!!e))}async function NT(n,e){const t=X(n);await OT(!0,t,e);const{providerUserInfo:r}=await KE(t.auth,{idToken:await t.getIdToken(),deleteProvider:[e]}),s=nd(r||[]);return t.providerData=t.providerData.filter(i=>s.has(i.providerId)),s.has("phone")||(t.phoneNumber=null),await t.auth._persistUserIfCurrent(t),t}async function DT(n,e,t=!1){const r=await Hn(n,e._linkToIdToken(n.auth,await n.getIdToken()),t);return Rt._forOperation(n,"link",r)}async function OT(n,e,t){await Mr(e);const r=nd(e.providerData);M(r.has(t)===n,e.auth,"no-such-provider")}async function VT(n,e,t=!1){const{auth:r}=n;if(Ae(r.app))return Promise.reject(ut(r));const s="reauthenticate";try{const i=await Hn(n,td(r,s,e,n),t);M(i.idToken,r,"internal-error");const a=ga(i.idToken);M(a,r,"internal-error");const{sub:c}=a;return M(n.uid===c,r,"user-mismatch"),Rt._forOperation(n,s,i)}catch(i){throw i?.code==="auth/user-not-found"&&He(r,"user-mismatch"),i}}async function rd(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r="signIn",s=await td(n,r,e),i=await Rt._fromIdTokenResponse(n,r,s);return t||await n._updateCurrentUser(i.user),i}async function LT(n,e){return rd(lt(n),e)}function MT(n,e,t){M(t.url?.length>0,n,"invalid-continue-uri"),M(typeof t.dynamicLinkDomain>"u"||t.dynamicLinkDomain.length>0,n,"invalid-dynamic-link-domain"),M(typeof t.linkDomain>"u"||t.linkDomain.length>0,n,"invalid-hosting-link-domain"),e.continueUrl=t.url,e.dynamicLinkDomain=t.dynamicLinkDomain,e.linkDomain=t.linkDomain,e.canHandleCodeInApp=t.handleCodeInApp,t.iOS&&(M(t.iOS.bundleId.length>0,n,"missing-ios-bundle-id"),e.iOSBundleId=t.iOS.bundleId),t.android&&(M(t.android.packageName.length>0,n,"missing-android-pkg-name"),e.androidInstallApp=t.android.installApp,e.androidMinimumVersionCode=t.android.minimumVersion,e.androidPackageName=t.android.packageName)}async function sd(n){const e=lt(n);e._getPasswordPolicyInternal()&&await e._updatePasswordPolicy()}async function xT(n,e,t){const r=lt(n);await hi(r,{requestType:"PASSWORD_RESET",email:e,clientType:"CLIENT_TYPE_WEB"},"getOobCode",AT)}async function UT(n,e,t){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),a=await hi(r,{returnSecureToken:!0,email:e,password:t,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Zh).catch(l=>{throw l.code==="auth/password-does-not-meet-requirements"&&sd(n),l}),c=await Rt._fromIdTokenResponse(r,"signIn",a);return await r._updateCurrentUser(c.user),c}function id(n,e,t){return Ae(n.app)?Promise.reject(ut(n)):LT(X(n),Qn.credential(e,t)).catch(async r=>{throw r.code==="auth/password-does-not-meet-requirements"&&sd(n),r})}async function od(n,e){const t=X(n),s={requestType:"VERIFY_EMAIL",idToken:await n.getIdToken()};e&&MT(t.auth,s,e);const{email:i}=await vT(t.auth,s);i!==n.email&&await n.reload()}async function FT(n,e){return Xe(n,"POST","/v1/accounts:update",e)}async function BT(n,{displayName:e,photoURL:t}){if(e===void 0&&t===void 0)return;const r=X(n),i={idToken:await r.getIdToken(),displayName:e,photoUrl:t,returnSecureToken:!0},a=await Hn(r,FT(r.auth,i));r.displayName=a.displayName||null,r.photoURL=a.photoUrl||null;const c=r.providerData.find(({providerId:l})=>l==="password");c&&(c.displayName=r.displayName,c.photoURL=r.photoURL),await r._updateTokensIfNecessary(a)}function qT(n,e,t,r){return X(n).onIdTokenChanged(e,t,r)}function jT(n,e,t){return X(n).beforeAuthStateChanged(e,t)}const pi="__sak";class ad{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(pi,"1"),this.storage.removeItem(pi),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}const $T=1e3,zT=10;class cd extends ad{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=$h(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const r=this.storage.getItem(t),s=this.localCache[t];r!==s&&e(t,s,r)}}onStorageEvent(e,t=!1){if(!e.key){this.forAllChangedKeys((a,c,l)=>{this.notifyListeners(a,l)});return}const r=e.key;t?this.detachListener():this.stopPolling();const s=()=>{const a=this.storage.getItem(r);!t&&this.localCache[r]===a||this.notifyListeners(r,a)},i=this.storage.getItem(r);rT()&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(s,zT):s()}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)})},$T)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){Object.keys(this.listeners).length===0&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}cd.type="LOCAL";const HT=cd;class ud extends ad{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}ud.type="SESSION";const ld=ud;function WT(n){return Promise.all(n.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}}))}class mi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find(s=>s.isListeningto(e));if(t)return t;const r=new mi(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:s,data:i}=t.data,a=this.handlersMap[s];if(!a?.size)return;t.ports[0].postMessage({status:"ack",eventId:r,eventType:s});const c=Array.from(a).map(async d=>d(t.origin,i)),l=await WT(c);t.ports[0].postMessage({status:"done",eventId:r,eventType:s,response:l})}_subscribe(e,t){Object.keys(this.handlersMap).length===0&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),(!t||this.handlersMap[e].size===0)&&delete this.handlersMap[e],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}mi.receivers=[];function wa(n="",e=10){let t="";for(let r=0;r<e;r++)t+=Math.floor(Math.random()*10);return n+t}class GT{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){const s=typeof MessageChannel<"u"?new MessageChannel:null;if(!s)throw new Error("connection_unavailable");let i,a;return new Promise((c,l)=>{const d=wa("",20);s.port1.start();const f=setTimeout(()=>{l(new Error("unsupported_event"))},r);a={messageChannel:s,onMessage(m){const y=m;if(y.data.eventId===d)switch(y.data.status){case"ack":clearTimeout(f),i=setTimeout(()=>{l(new Error("timeout"))},3e3);break;case"done":clearTimeout(i),c(y.data.response);break;default:clearTimeout(f),clearTimeout(i),l(new Error("invalid_response"));break}}},this.handlers.add(a),s.port1.addEventListener("message",a.onMessage),this.target.postMessage({eventType:e,eventId:d,data:t},[s.port2])}).finally(()=>{a&&this.removeMessageHandler(a)})}}function ft(){return window}function KT(n){ft().location.href=n}function hd(){return typeof ft().WorkerGlobalScope<"u"&&typeof ft().importScripts=="function"}async function QT(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function XT(){return navigator?.serviceWorker?.controller||null}function YT(){return hd()?self:null}const dd="firebaseLocalStorageDb",JT=1,gi="firebaseLocalStorage",fd="fbase_key";class Fr{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function _i(n,e){return n.transaction([gi],e?"readwrite":"readonly").objectStore(gi)}function ZT(){const n=indexedDB.deleteDatabase(dd);return new Fr(n).toPromise()}function Ia(){const n=indexedDB.open(dd,JT);return new Promise((e,t)=>{n.addEventListener("error",()=>{t(n.error)}),n.addEventListener("upgradeneeded",()=>{const r=n.result;try{r.createObjectStore(gi,{keyPath:fd})}catch(s){t(s)}}),n.addEventListener("success",async()=>{const r=n.result;r.objectStoreNames.contains(gi)?e(r):(r.close(),await ZT(),e(await Ia()))})})}async function pd(n,e,t){const r=_i(n,!0).put({[fd]:e,value:t});return new Fr(r).toPromise()}async function ew(n,e){const t=_i(n,!1).get(e),r=await new Fr(t).toPromise();return r===void 0?null:r.value}function md(n,e){const t=_i(n,!0).delete(e);return new Fr(t).toPromise()}const tw=800,nw=3;class gd{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db?this.db:(this.db=await Ia(),this.db)}async _withRetries(e){let t=0;for(;;)try{const r=await this._openDb();return await e(r)}catch(r){if(t++>nw)throw r;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return hd()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=mi._getInstance(YT()),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){if(this.activeServiceWorker=await QT(),!this.activeServiceWorker)return;this.sender=new GT(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(!(!this.sender||!this.activeServiceWorker||XT()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Ia();return await pd(e,pi,"1"),await md(e,pi),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(r=>pd(r,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){const t=await this._withRetries(r=>ew(r,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>md(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(s=>{const i=_i(s,!1).getAll();return new Fr(i).toPromise()});if(!e)return[];if(this.pendingWrites!==0)return[];const t=[],r=new Set;if(e.length!==0)for(const{fbase_key:s,value:i}of e)r.add(s),JSON.stringify(this.localCache[s])!==JSON.stringify(i)&&(this.notifyListeners(s,i),t.push(s));for(const s of Object.keys(this.localCache))this.localCache[s]&&!r.has(s)&&(this.notifyListeners(s,null),t.push(s));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),tw)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){Object.keys(this.listeners).length===0&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&this.stopPolling()}}gd.type="LOCAL";const rw=gd;new Or(3e4,6e4);function va(n,e){return e?At(e):(M(n._popupRedirectResolver,n,"argument-error"),n._popupRedirectResolver)}class Aa extends Ea{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Kn(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Kn(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Kn(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function sw(n){return rd(n.auth,new Aa(n),n.bypassAuthState)}function iw(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),VT(t,new Aa(n),n.bypassAuthState)}async function ow(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),DT(t,new Aa(n),n.bypassAuthState)}class _d{constructor(e,t,r,s,i=!1){this.auth=e,this.resolver=r,this.user=s,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(r){this.reject(r)}})}async onAuthEvent(e){const{urlResponse:t,sessionId:r,postBody:s,tenantId:i,error:a,type:c}=e;if(a){this.reject(a);return}const l={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:s||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(c)(l))}catch(d){this.reject(d)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return sw;case"linkViaPopup":case"linkViaRedirect":return ow;case"reauthViaPopup":case"reauthViaRedirect":return iw;default:He(this.auth,"internal-error")}}resolve(e){It(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){It(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const aw=new Or(2e3,1e4);async function Ra(n,e,t){if(Ae(n.app))return Promise.reject(Qe(n,"operation-not-supported-in-this-environment"));const r=lt(n);Ah(n,e,di);const s=va(r,t);return new Ht(r,"signInViaPopup",e,s).executeNotNull()}async function yd(n,e,t){const r=X(n);Ah(r.auth,e,di);const s=va(r.auth,t);return new Ht(r.auth,"linkViaPopup",e,s,r).executeNotNull()}class Ht extends _d{constructor(e,t,r,s,i){super(e,t,s,i),this.provider=r,this.authWindow=null,this.pollId=null,Ht.currentPopupAction&&Ht.currentPopupAction.cancel(),Ht.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return M(e,this.auth,"internal-error"),e}async onExecution(){It(this.filter.length===1,"Popup operations only handle one event");const e=wa();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(t=>{this.reject(t)}),this.resolver._isIframeWebStorageSupported(this.auth,t=>{t||this.reject(Qe(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(Qe(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Ht.currentPopupAction=null}pollUserCancellation(){const e=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Qe(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,aw.get())};e()}}Ht.currentPopupAction=null;const cw="pendingRedirect",yi=new Map;class uw extends _d{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let e=yi.get(this.auth._key());if(!e){try{const r=await lw(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(r)}catch(t){e=()=>Promise.reject(t)}yi.set(this.auth._key(),e)}return this.bypassAuthState||yi.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if(e.type==="signInViaRedirect")return super.onAuthEvent(e);if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function lw(n,e){const t=fw(e),r=dw(n);if(!await r._isAvailable())return!1;const s=await r._get(t)==="true";return await r._remove(t),s}function hw(n,e){yi.set(n._key(),e)}function dw(n){return At(n._redirectPersistence)}function fw(n){return ui(cw,n.config.apiKey,n.name)}async function pw(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),s=va(r,e),a=await new uw(r,s,t).execute();return a&&!t&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,e)),a}const mw=10*60*1e3;class gw{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!_w(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!Td(e)){const r=e.error.code?.split("auth/")[1]||"internal-error";t.onError(Qe(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const r=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=mw&&this.cachedEventUids.clear(),this.cachedEventUids.has(Ed(e))}saveEventToCache(e){this.cachedEventUids.add(Ed(e)),this.lastProcessedEventTime=Date.now()}}function Ed(n){return[n.type,n.eventId,n.sessionId,n.tenantId].filter(e=>e).join("-")}function Td({type:n,error:e}){return n==="unknown"&&e?.code==="auth/no-auth-event"}function _w(n){switch(n.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return Td(n);default:return!1}}async function yw(n,e={}){return Xe(n,"GET","/v1/projects",e)}const Ew=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Tw=/^https?/;async function ww(n){if(n.config.emulator)return;const{authorizedDomains:e}=await yw(n);for(const t of e)try{if(Iw(t))return}catch{}He(n,"unauthorized-domain")}function Iw(n){const e=fa(),{protocol:t,hostname:r}=new URL(e);if(n.startsWith("chrome-extension://")){const a=new URL(n);return a.hostname===""&&r===""?t==="chrome-extension:"&&n.replace("chrome-extension://","")===e.replace("chrome-extension://",""):t==="chrome-extension:"&&a.hostname===r}if(!Tw.test(t))return!1;if(Ew.test(n))return r===n;const s=n.replace(/\./g,"\\.");return new RegExp("^(.+\\."+s+"|"+s+")$","i").test(r)}const vw=new Or(3e4,6e4);function wd(){const n=ft().___jsl;if(n?.H){for(const e of Object.keys(n.H))if(n.H[e].r=n.H[e].r||[],n.H[e].L=n.H[e].L||[],n.H[e].r=[...n.H[e].L],n.CP)for(let t=0;t<n.CP.length;t++)n.CP[t]=null}}function Aw(n){return new Promise((e,t)=>{function r(){wd(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{wd(),t(Qe(n,"network-request-failed"))},timeout:vw.get()})}if(ft().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else if(ft().gapi?.load)r();else{const s=dT("iframefcb");return ft()[s]=()=>{gapi.load?r():t(Qe(n,"network-request-failed"))},Wh(`${hT()}?onload=${s}`).catch(i=>t(i))}}).catch(e=>{throw Ei=null,e})}let Ei=null;function Rw(n){return Ei=Ei||Aw(n),Ei}const bw=new Or(5e3,15e3),Pw="__/auth/iframe",Sw="emulator/auth/iframe",Cw={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},kw=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function Nw(n){const e=n.config;M(e.authDomain,n,"auth-domain-config-required");const t=e.emulator?pa(e,Sw):`https://${n.config.authDomain}/${Pw}`,r={apiKey:e.apiKey,appName:n.name,v:tn},s=kw.get(n.config.apiHost);s&&(r.eid=s);const i=n._getFrameworks();return i.length&&(r.fw=i.join(",")),`${t}?${ar(r).slice(1)}`}async function Dw(n){const e=await Rw(n),t=ft().gapi;return M(t,n,"internal-error"),e.open({where:document.body,url:Nw(n),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Cw,dontclear:!0},r=>new Promise(async(s,i)=>{await r.restyle({setHideOnLeave:!1});const a=Qe(n,"network-request-failed"),c=ft().setTimeout(()=>{i(a)},bw.get());function l(){ft().clearTimeout(c),s(r)}r.ping(l).then(l,()=>{i(a)})}))}const Ow={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},Vw=500,Lw=600,Mw="_blank",xw="http://localhost";class Id{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function Uw(n,e,t,r=Vw,s=Lw){const i=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const l={...Ow,width:r.toString(),height:s.toString(),top:i,left:a},d=ve().toLowerCase();t&&(c=Uh(d)?Mw:t),Mh(d)&&(e=e||xw,l.scrollbars="yes");const f=Object.entries(l).reduce((y,[R,k])=>`${y}${R}=${k},`,"");if(nT(d)&&c!=="_self")return Fw(e||"",c),new Id(null);const m=window.open(e||"",c,f);M(m,n,"popup-blocked");try{m.focus()}catch{}return new Id(m)}function Fw(n,e){const t=document.createElement("a");t.href=n,t.target=e;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),t.dispatchEvent(r)}const Bw="__/auth/handler",qw="emulator/auth/handler",jw=encodeURIComponent("fac");async function vd(n,e,t,r,s,i){M(n.config.authDomain,n,"auth-domain-config-required"),M(n.config.apiKey,n,"invalid-api-key");const a={apiKey:n.config.apiKey,appName:n.name,authType:t,redirectUrl:r,v:tn,eventId:s};if(e instanceof di){e.setDefaultLanguage(n.languageCode),a.providerId=e.providerId||"",Dp(e.getCustomParameters())||(a.customParameters=JSON.stringify(e.getCustomParameters()));for(const[f,m]of Object.entries({}))a[f]=m}if(e instanceof Ur){const f=e.getScopes().filter(m=>m!=="");f.length>0&&(a.scopes=f.join(","))}n.tenantId&&(a.tid=n.tenantId);const c=a;for(const f of Object.keys(c))c[f]===void 0&&delete c[f];const l=await n._getAppCheckToken(),d=l?`#${jw}=${encodeURIComponent(l)}`:"";return`${$w(n)}?${ar(c).slice(1)}${d}`}function $w({config:n}){return n.emulator?pa(n,qw):`https://${n.authDomain}/${Bw}`}const ba="webStorageSupport";class zw{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=ld,this._completeRedirectFn=pw,this._overrideRedirectResult=hw}async _openPopup(e,t,r,s){It(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");const i=await vd(e,t,r,fa(),s);return Uw(e,i,wa())}async _openRedirect(e,t,r,s){await this._originValidation(e);const i=await vd(e,t,r,fa(),s);return KT(i),new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:s,promise:i}=this.eventManagers[t];return s?Promise.resolve(s):(It(i,"If manager is not set, promise should be"),i)}const r=this.initAndGetManager(e);return this.eventManagers[t]={promise:r},r.catch(()=>{delete this.eventManagers[t]}),r}async initAndGetManager(e){const t=await Dw(e),r=new gw(e);return t.register("authEvent",s=>(M(s?.authEvent,e,"invalid-auth-event"),{status:r.onEvent(s.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(ba,{type:ba},s=>{const i=s?.[0]?.[ba];i!==void 0&&t(!!i),He(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=ww(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return $h()||xh()||ya()}}const Hw=zw;var Ad="@firebase/auth",Rd="1.12.0";class Ww{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){M(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function Gw(n){switch(n){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function Kw(n){St(new _t("auth",(e,{options:t})=>{const r=e.getProvider("app").getImmediate(),s=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:a,authDomain:c}=r.options;M(a&&!a.includes(":"),"invalid-api-key",{appName:r.name});const l={apiKey:a,authDomain:c,clientPlatform:n,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:zh(n)},d=new cT(r,s,i,l);return yT(d,t),d},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),St(new _t("auth-internal",e=>{const t=lt(e.getProvider("auth").getImmediate());return(r=>new Ww(r))(t)},"PRIVATE").setInstantiationMode("EXPLICIT")),je(Ad,Rd,Gw(n)),je(Ad,Rd,"esm2020")}const Qw=5*60,Xw=gc("authIdTokenMaxAge")||Qw;let bd=null;const Yw=n=>async e=>{const t=e&&await e.getIdTokenResult(),r=t&&(new Date().getTime()-Date.parse(t.issuedAtTime))/1e3;if(r&&r>Xw)return;const s=t?.token;bd!==s&&(bd=s,await fetch(n,{method:s?"POST":"DELETE",headers:s?{Authorization:`Bearer ${s}`}:{}}))};function Jw(n=ls()){const e=lr(n,"auth");if(e.isInitialized())return e.getImmediate();const t=_T(n,{popupRedirectResolver:Hw,persistence:[rw,HT,ld]}),r=gc("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const i=new URL(r,location.origin);if(location.origin===i.origin){const a=Yw(i.toString());jT(t,a,()=>a(t.currentUser)),qT(t,c=>a(c))}}const s=pc("auth");return s&&Qh(t,`http://${s}`),t}function Zw(){return document.getElementsByTagName("head")?.[0]??document}uT({loadJS(n){return new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",n),r.onload=e,r.onerror=s=>{const i=Qe("internal-error");i.customData=s,t(i)},r.type="text/javascript",r.charset="UTF-8",Zw().appendChild(r)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="}),Kw("Browser");const Pd="firebasestorage.googleapis.com",Sd="storageBucket",eI=2*60*1e3,tI=10*60*1e3,nI=1e3;class ie extends We{constructor(e,t,r=0){super(Pa(e),`Firebase Storage: ${t} (${Pa(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,ie.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return Pa(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
42
+ `)}}static propInfo(n,e){return _e.createInstance(n).getPropInfo(e)}static getSystemRegisteredReferencesWithCachedProps(){return _e.registeredClassesAndLegacyNames().reduce((n,e)=>{const t=_e.createInstance(e).getPersistentProperties().filter(r=>r.cachedPropsConfig?.cachedProps);return t.length>0&&(n[e]=t),n},{})}},_e._factoryMap={},_e);RE([jn],mh.prototype,"_id");let fe=mh;function jn(n,e){return bE()(n,e)}function bE(n){return function(e,t){Object.getOwnPropertyDescriptor(e,"_persistentProperties")||(e._persistentProperties?e._persistentProperties=[...e._persistentProperties]:e._persistentProperties=[]);const r=e._persistentProperties.find(s=>s.name===t);r?Object.assign(r,n):e._persistentProperties.push({name:t,...n})}}function PE(n,e){return t=>{fe.registerFactory(n,t,e),t.prototype.__className=n}}const gh=class up{constructor(e,t,r){if(r){if(!(t instanceof fe))throw new Error(up.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof fe?t.className:t;this._stream=e}findById(e,t){return new Promise((r,s)=>{this._stream.findById(e,this.collectionName).then(i=>{i?(t?t.fromObject(i):t=fe.createInstance(i),r(t)):r(void 0)}).catch(i=>s(i))})}save(e){const t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((r,s)=>{this._stream.save(t.__rootCollections).then(()=>r()).catch(i=>s(i))})}delete(e){return new Promise((t,r)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(s=>r(s))})}find(){return new SE(this)}query(e={},t){if(t){const r=t instanceof fe?t.className:t;e.operations||(e.operations=[]),e.operations.push({property:"__className",operator:"==",value:r})}return this.mapToInstance(()=>this._stream.find(this.preprocessQueryObject(e),this.collectionName))}count(e){return this._stream.count(e,this.collectionName)}next(e){return this.mapToInstance(()=>this._stream.next(e))}onDocumentChange(e,t){return this._stream.onDocumentChange(this.collectionName,e,r=>t(this.toPersistentChangeObject(r)))}onCollectionChange(e,t){return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()),this.collectionName,r=>t(r.map(s=>({after:s.after&&fe.createInstance(s.after),before:s.before&&fe.createInstance(s.before),type:s.type,params:s.params}))))}toPersistentChangeObject(e){return{...e,before:e.before&&fe.createInstance(e.before),after:e.after&&fe.createInstance(e.after)}}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(i=>fe.createInstance(i)))).catch(s=>r(s))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;const t=e.operations?.map(r=>{const s=r.value[0]??r.value;return hn.isArrayOperator(r.operator)&&s instanceof fe?{property:fe.searchableArrayNameFor(r.property),operator:r.operator,value:Array.isArray(r.value)?r.value.map(i=>i.id):s.id,aggregate:r.aggregate}:{property:r.property,operator:r.operator,value:r.value instanceof fe?{id:r.value.id}:r.value,aggregate:r.aggregate}})??[];return{...e,operations:t}}};gh.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let ri=gh;class SE{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(ri.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(ri.error.invalidQueryOrder);const i=e.split(".");let a={},c=i.length>1?a:r;return i.slice(1).forEach((l,d)=>{a[l]=d<i.length-2?{}:r,a=a[l]}),this.queryObject.operations?.push({property:i[0],operator:t,value:c,aggregate:s}),this}and(e,t,r){return this.where(e,t,r)}andDeepProp(e,t,r){return this.whereDeepProp(e,t,r)}or(e,t,r){return this.where(e,t,r,!0)}orDeepProp(e,t,r){return this.whereDeepProp(e,t,r,!0)}instanceOf(e){const t=e instanceof fe?e.className:e;return this.queryObject.operations?.push({property:"__className",operator:"==",value:t}),this}get(e){return e&&(this.queryObject.limit=e),this.model.query(this.queryObject)}limit(e){return this.queryObject.limit=e,this}orderBy(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}orderByDeepProp(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}count(){return this.model.count(this.queryObject)}getQueryObject(){return this.queryObject}}const _h=class nr{constructor(){}static useDataSource(e){this._dataSource=e}static get dataSource(){return nr._dataSource}static getModel(e){if(!nr._dataSource)throw new Error(this.error.shouldBeRegistered);return new ri(nr._dataSource,e)}static getModelForSubCollection(e,t){if(!nr._dataSource)throw new Error(this.error.shouldBeRegistered);return new ri(nr._dataSource,e,t)}static async populate(e){if(!e)return;const t=async r=>{const s=r;if(!s.__documentReference)return r;const i=await this.getModel(s.__documentReference.storedInCollection).findById(s.id,r);return i&&(i.__documentReference=void 0),i};return Array.isArray(e)?(await Promise.all(e.map(r=>t(r)))).filter(r=>r):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((t,r)=>t&&r.__documentReference===void 0,!0):e.__documentReference===void 0}};_h.error={shouldBeRegistered:"You should register a data source before using the data Store."};let CE=_h;class hn{installCachedPropsUpdaters(e={}){hn.onUpdate=e.onUpdate;const t=fe.getSystemRegisteredReferencesWithCachedProps(),r={};Object.entries(t).forEach(([i,a])=>{a.forEach(c=>{const l=fe.collectionPath(fe.createInstance(i),c);r[l]||(r[l]=[]),r[l].push({prop:c,collectionPropOwner:i})})});const s=[];return Object.entries(r).forEach(([i,a])=>{const c=this.subscribeToDocumentChangeListener(i,l=>hn.processDocumentChange(l,a));if(c)s.push(c);else if(e.noThrowOnNonImplementedListener)throw new Error("The method documentChangeListener has not been implemented in the concrete data source")}),s}subscribeToDocumentChangeListener(e,t){}static toPropertyPathOperations(e){return e?e.map(t=>{if(hn.isArrayOperator(t.operator)&&t.value[0]instanceof fe)return{property:fe.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(i=>i.id),aggregate:t.aggregate};const[r,s]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${r?"."+r:""}`,operator:t.operator,value:s,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e==="containsAny"||e==="contains"}static toPropertyPathValue(e){if(typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e)[0],[r,s]=this.toPropertyPathValue(e[t]);return[`${t}${r?"."+r:""}`,s]}else return[void 0,e]}static async processDocumentChange(e,t){if(e.before)return t.map(async r=>{const s=CE.getModel(r.collectionPropOwner);let i=s.find();r.prop.cachedPropsConfig?.cachedProps?.forEach(c=>{const l=e.before?.[c],d=e.after?.[c];l!==d&&(i=i.orDeepProp(`${r.prop.name}.${c}`,"==",l))});const a=await i.get();return Promise.all([a.map(async c=>{r.prop.cachedPropsConfig?.cachedProps?.forEach(async l=>{const d=e.before?.[l],f=e.after?.[l];d!==f&&(c[`_${r.prop.name}`][`_${l}`]=f,await s.save(c),this.onUpdate?.(c,r.prop))})})])})}}const yh=class rr{static registerCloudStorage(e,t){rr._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=rr._cloudStorageFactoryMap[e];if(!t)throw new Error(`You should register the ${e} cloud storage provider prior to use it`);return t()}get className(){return this.__className}static useCloudStorage(e){rr._defaultCloudStorage=e}static get defaultCloudStorage(){if(!rr._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return rr._defaultCloudStorage}};yh._cloudStorageFactoryMap={};let $n=yh;function Eh(n,e){return $n.registerCloudStorage(n,e),t=>{t.prototype.__className=n}}var kE=(n,e,t,r)=>{for(var s=e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(s)||s);return s};let la=class extends $n{constructor(n=""){super(),this._simulateDelay=0,this._pendingPromises=[],this.mockFileSystem={},this._pathToMockFiles=n}simulateDelay(n){return this._simulateDelay=n,this}resolveWithDelay(n){if(this._simulateDelay<=0)return Promise.resolve(n);const e=new Promise(t=>{setTimeout(()=>t(n),this._simulateDelay)});return this._pendingPromises.push(e),e.finally(()=>this._pendingPromises=this._pendingPromises.filter(t=>t===e)),e}save(n,e){const t=n;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[n]=JSON.stringify(e),this._onProgress&&this._onProgress(100,100);const r=e instanceof File?e.name:t;return this.resolveWithDelay(r)}uploadControl(){return{resume:()=>{},pause:()=>{},cancel:()=>{},onProgress:n=>this._onProgress=n}}getUrl(n){return Promise.resolve(this._pathToMockFiles+n)}delete(n){return delete this.mockFileSystem[n],this.resolveWithDelay()}};la=kE([Eh("MockCloudStorage",()=>new la)],la);var NE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,zn=(n,e,t,r)=>{for(var s=r>1?void 0:r?DE(e,t):e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&NE(e,t,s),s};let dn=class extends fe{constructor(){super(...arguments),this._onChange=new fh}async save({data:n,fileName:e,progress:t,cloudStorageProvider:r}={}){const s=n||this._pendingData;s&&(this._reference&&await this.delete(),this.provider=r||$n.defaultCloudStorage,this._originalFileName=e||(s instanceof File?s.name:void 0),this._reference=await this.provider.save(this.id,s,t),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:0,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw new Error("Cannot delete a not stored file");await this.provider.delete(this._reference),this._reference=void 0,this._url=void 0,this._onChange.notify({event:2,storedFile:this})}set provider(n){this._provider=n,this._cloudStorageProviderName=n.className}get provider(){if(!this._provider)try{this._provider=$n.createInstance(this._cloudStorageProviderName)}catch{this._provider=$n.defaultCloudStorage}return this._provider}get url(){return this._url}get mimeType(){return this._mimeType}setDataToStore(n){return this._pendingData=n,this._originalFileName=n instanceof File?n.name:void 0,this._mimeType=n instanceof Blob?n.type:void 0,this._onChange.notify({event:1,pendingData:n,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(n){return this._onChange.subscribe(n)}};zn([jn],dn.prototype,"_reference",2),zn([jn],dn.prototype,"_url",2),zn([jn],dn.prototype,"_cloudStorageProviderName",2),zn([jn],dn.prototype,"_originalFileName",2),zn([jn],dn.prototype,"_mimeType",2),dn=zn([PE("StoredFile")],dn);class Th{}const wh=class xe extends Th{constructor(){if(super(),this._onAuthStateChange=new fh,!xe._authService)throw new Error(xe.error.shouldBeRegistered);xe._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){xe._authService!=e&&(xe._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return xe._authService.signUp(e)}login(e){return xe._authService.login(e)}logout(){return xe._authService.logout()}resetEmailPassword(e){return xe._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return xe._authService.resendVerificationEmail(e,t,r)}refreshToken(){return xe._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return xe._authService.linkAdditionalProvider(e)}unlinkProvider(e){return xe._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};wh.error={shouldBeRegistered:"You should register an auth service before using Auth."},wh._instance=void 0;function si(n){return n?n.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}var OE="firebase",VE="12.7.0";je(OE,VE,"app");function Ih(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const LE=Ih,vh=new or("auth","Firebase",Ih());const ii=new $i("@firebase/auth");function ME(n,...e){ii.logLevel<=H.WARN&&ii.warn(`Auth (${tn}): ${n}`,...e)}function oi(n,...e){ii.logLevel<=H.ERROR&&ii.error(`Auth (${tn}): ${n}`,...e)}function He(n,...e){throw da(n,...e)}function Qe(n,...e){return da(n,...e)}function ha(n,e,t){const r={...LE(),[e]:t};return new or("auth","Firebase",r).create(e,{appName:n.name})}function ut(n){return ha(n,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Ah(n,e,t){const r=t;if(!(e instanceof r))throw r.name!==e.constructor.name&&He(n,"argument-error"),ha(n,"argument-error",`Type of ${e.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function da(n,...e){if(typeof n!="string"){const t=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=n.name),n._errorFactory.create(t,...r)}return vh.create(n,...e)}function M(n,e,...t){if(!n)throw da(e,...t)}function wt(n){const e="INTERNAL ASSERTION FAILED: "+n;throw oi(e),new Error(e)}function It(n,e){n||wt(e)}function fa(){return typeof self<"u"&&self.location?.href||""}function xE(){return Rh()==="http:"||Rh()==="https:"}function Rh(){return typeof self<"u"&&self.location?.protocol||null}function UE(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(xE()||vp()||"connection"in navigator)?navigator.onLine:!0}function FE(){if(typeof navigator>"u")return null;const n=navigator;return n.languages&&n.languages[0]||n.language||null}class Or{constructor(e,t){this.shortDelay=e,this.longDelay=t,It(t>e,"Short delay should be less than long delay!"),this.isMobile=Tp()||Ap()}get(){return UE()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function pa(n,e){It(n.emulator,"Emulator should always be set here");const{url:t}=n.emulator;return e?`${t}${e.startsWith("/")?e.slice(1):e}`:t}class bh{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;wt("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;wt("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;wt("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const BE={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"};const qE=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],jE=new Or(3e4,6e4);function vt(n,e){return n.tenantId&&!e.tenantId?{...e,tenantId:n.tenantId}:e}async function Xe(n,e,t,r,s={}){return Ph(n,s,async()=>{let i={},a={};r&&(e==="GET"?a=r:i={body:JSON.stringify(r)});const c=ar({key:n.config.apiKey,...a}).slice(1),l=await n._getAdditionalHeaders();l["Content-Type"]="application/json",n.languageCode&&(l["X-Firebase-Locale"]=n.languageCode);const d={method:e,headers:l,...i};return Ip()||(d.referrerPolicy="no-referrer"),n.emulatorConfig&&et(n.emulatorConfig.host)&&(d.credentials="include"),bh.fetch()(await Sh(n,n.config.apiHost,t,c),d)})}async function Ph(n,e,t){n._canInitEmulator=!1;const r={...BE,...e};try{const s=new zE(n),i=await Promise.race([t(),s.promise]);s.clearNetworkTimeout();const a=await i.json();if("needConfirmation"in a)throw ai(n,"account-exists-with-different-credential",a);if(i.ok&&!("errorMessage"in a))return a;{const c=i.ok?a.errorMessage:a.error.message,[l,d]=c.split(" : ");if(l==="FEDERATED_USER_ID_ALREADY_LINKED")throw ai(n,"credential-already-in-use",a);if(l==="EMAIL_EXISTS")throw ai(n,"email-already-in-use",a);if(l==="USER_DISABLED")throw ai(n,"user-disabled",a);const f=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(d)throw ha(n,f,d);He(n,f)}}catch(s){if(s instanceof We)throw s;He(n,"network-request-failed",{message:String(s)})}}async function Vr(n,e,t,r,s={}){const i=await Xe(n,e,t,r,s);return"mfaPendingCredential"in i&&He(n,"multi-factor-auth-required",{_serverResponse:i}),i}async function Sh(n,e,t,r){const s=`${e}${t}?${r}`,i=n,a=i.config.emulator?pa(n.config,s):`${n.config.apiScheme}://${s}`;return qE.includes(t)&&(await i._persistenceManagerAvailable,i._getPersistenceType()==="COOKIE")?i._getPersistence()._getFinalTarget(a).toString():a}function $E(n){switch(n){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class zE{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((t,r)=>{this.timer=setTimeout(()=>r(Qe(this.auth,"network-request-failed")),jE.get())})}}function ai(n,e,t){const r={appName:n.name};t.email&&(r.email=t.email),t.phoneNumber&&(r.phoneNumber=t.phoneNumber);const s=Qe(n,e,r);return s.customData._tokenResponse=t,s}function Ch(n){return n!==void 0&&n.enterprise!==void 0}class HE{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return $E(t.enforcementState);return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function WE(n,e){return Xe(n,"GET","/v2/recaptchaConfig",vt(n,e))}async function GE(n,e){return Xe(n,"POST","/v1/accounts:delete",e)}async function KE(n,e){return Xe(n,"POST","/v1/accounts:update",e)}async function ci(n,e){return Xe(n,"POST","/v1/accounts:lookup",e)}function Lr(n){if(n)try{const e=new Date(Number(n));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function QE(n,e=!1){const t=X(n),r=await t.getIdToken(e),s=ga(r);M(s&&s.exp&&s.auth_time&&s.iat,t.auth,"internal-error");const i=typeof s.firebase=="object"?s.firebase:void 0,a=i?.sign_in_provider;return{claims:s,token:r,authTime:Lr(ma(s.auth_time)),issuedAtTime:Lr(ma(s.iat)),expirationTime:Lr(ma(s.exp)),signInProvider:a||null,signInSecondFactor:i?.sign_in_second_factor||null}}function ma(n){return Number(n)*1e3}function ga(n){const[e,t,r]=n.split(".");if(e===void 0||t===void 0||r===void 0)return oi("JWT malformed, contained fewer than 3 sections"),null;try{const s=fc(t);return s?JSON.parse(s):(oi("Failed to decode base64 JWT payload"),null)}catch(s){return oi("Caught error parsing JWT payload as JSON",s?.toString()),null}}function kh(n){const e=ga(n);return M(e,"internal-error"),M(typeof e.exp<"u","internal-error"),M(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Hn(n,e,t=!1){if(t)return e;try{return await e}catch(r){throw r instanceof We&&XE(r)&&n.auth.currentUser===n&&await n.auth.signOut(),r}}function XE({code:n}){return n==="auth/user-disabled"||n==="auth/user-token-expired"}class YE{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){if(e){const t=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),t}else{this.errorBackoff=3e4;const r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class _a{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Lr(this.lastLoginAt),this.creationTime=Lr(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Mr(n){const e=n.auth,t=await n.getIdToken(),r=await Hn(n,ci(e,{idToken:t}));M(r?.users.length,e,"internal-error");const s=r.users[0];n._notifyReloadListener(s);const i=s.providerUserInfo?.length?Nh(s.providerUserInfo):[],a=ZE(n.providerData,i),c=n.isAnonymous,l=!(n.email&&s.passwordHash)&&!a?.length,d=c?l:!1,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new _a(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(n,f)}async function JE(n){const e=X(n);await Mr(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function ZE(n,e){return[...n.filter(r=>!e.some(s=>s.providerId===r.providerId)),...e]}function Nh(n){return n.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}async function eT(n,e){const t=await Ph(n,{},async()=>{const r=ar({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:s,apiKey:i}=n.config,a=await Sh(n,s,"/v1/token",`key=${i}`),c=await n._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";const l={method:"POST",headers:c,body:r};return n.emulatorConfig&&et(n.emulatorConfig.host)&&(l.credentials="include"),bh.fetch()(a,l)});return{accessToken:t.access_token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}async function tT(n,e){return Xe(n,"POST","/v2/accounts:revokeToken",vt(n,e))}class Wn{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){M(e.idToken,"internal-error"),M(typeof e.idToken<"u","internal-error"),M(typeof e.refreshToken<"u","internal-error");const t="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):kh(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){M(e.length!==0,"internal-error");const t=kh(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return!t&&this.accessToken&&!this.isExpired?this.accessToken:(M(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:s,expiresIn:i}=await eT(e,t);this.updateTokensAndExpiration(r,s,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,t){const{refreshToken:r,accessToken:s,expirationTime:i}=t,a=new Wn;return r&&(M(typeof r=="string","internal-error",{appName:e}),a.refreshToken=r),s&&(M(typeof s=="string","internal-error",{appName:e}),a.accessToken=s),i&&(M(typeof i=="number","internal-error",{appName:e}),a.expirationTime=i),a}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new Wn,this.toJSON())}_performRefresh(){return wt("not implemented")}}function $t(n,e){M(typeof n=="string"||typeof n>"u","internal-error",{appName:e})}class Ye{constructor({uid:e,auth:t,stsTokenManager:r,...s}){this.providerId="firebase",this.proactiveRefresh=new YE(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new _a(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await Hn(this,this.stsTokenManager.getToken(this.auth,e));return M(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return QE(this,e)}reload(){return JE(this)}_assign(e){this!==e&&(M(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(t=>({...t})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new Ye({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){M(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await Mr(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Ae(this.auth.app))return Promise.reject(ut(this.auth));const e=await this.getIdToken();return await Hn(this,GE(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const r=t.displayName??void 0,s=t.email??void 0,i=t.phoneNumber??void 0,a=t.photoURL??void 0,c=t.tenantId??void 0,l=t._redirectEventId??void 0,d=t.createdAt??void 0,f=t.lastLoginAt??void 0,{uid:m,emailVerified:y,isAnonymous:R,providerData:k,stsTokenManager:N}=t;M(m&&N,e,"internal-error");const C=Wn.fromJSON(this.name,N);M(typeof m=="string",e,"internal-error"),$t(r,e.name),$t(s,e.name),M(typeof y=="boolean",e,"internal-error"),M(typeof R=="boolean",e,"internal-error"),$t(i,e.name),$t(a,e.name),$t(c,e.name),$t(l,e.name),$t(d,e.name),$t(f,e.name);const U=new Ye({uid:m,auth:e,email:s,emailVerified:y,displayName:r,isAnonymous:R,photoURL:a,phoneNumber:i,tenantId:c,stsTokenManager:C,createdAt:d,lastLoginAt:f});return k&&Array.isArray(k)&&(U.providerData=k.map($=>({...$}))),l&&(U._redirectEventId=l),U}static async _fromIdTokenResponse(e,t,r=!1){const s=new Wn;s.updateFromServerResponse(t);const i=new Ye({uid:t.localId,auth:e,stsTokenManager:s,isAnonymous:r});return await Mr(i),i}static async _fromGetAccountInfoResponse(e,t,r){const s=t.users[0];M(s.localId!==void 0,"internal-error");const i=s.providerUserInfo!==void 0?Nh(s.providerUserInfo):[],a=!(s.email&&s.passwordHash)&&!i?.length,c=new Wn;c.updateFromIdToken(r);const l=new Ye({uid:s.localId,auth:e,stsTokenManager:c,isAnonymous:a}),d={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:i,metadata:new _a(s.createdAt,s.lastLoginAt),isAnonymous:!(s.email&&s.passwordHash)&&!i?.length};return Object.assign(l,d),l}}const Dh=new Map;function At(n){It(n instanceof Function,"Expected a class definition");let e=Dh.get(n);return e?(It(e instanceof n,"Instance stored in cache mismatched with class"),e):(e=new n,Dh.set(n,e),e)}class Oh{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return t===void 0?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Oh.type="NONE";const Vh=Oh;function ui(n,e,t){return`firebase:${n}:${e}:${t}`}class Gn{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:s,name:i}=this.auth;this.fullUserKey=ui(this.userKey,s.apiKey,i),this.fullPersistenceKey=ui("persistence",s.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){const t=await ci(this.auth,{idToken:e}).catch(()=>{});return t?Ye._fromGetAccountInfoResponse(this.auth,t,e):null}return Ye._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new Gn(At(Vh),e,r);const s=(await Promise.all(t.map(async d=>{if(await d._isAvailable())return d}))).filter(d=>d);let i=s[0]||At(Vh);const a=ui(r,e.config.apiKey,e.name);let c=null;for(const d of t)try{const f=await d._get(a);if(f){let m;if(typeof f=="string"){const y=await ci(e,{idToken:f}).catch(()=>{});if(!y)break;m=await Ye._fromGetAccountInfoResponse(e,y,f)}else m=Ye._fromJSON(e,f);d!==i&&(c=m),i=d;break}}catch{}const l=s.filter(d=>d._shouldAllowMigration);return!i._shouldAllowMigration||!l.length?new Gn(i,e,r):(i=l[0],c&&await i._set(a,c.toJSON()),await Promise.all(t.map(async d=>{if(d!==i)try{await d._remove(a)}catch{}})),new Gn(i,e,r))}}function Lh(n){const e=n.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(Fh(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Mh(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(qh(e))return"Blackberry";if(jh(e))return"Webos";if(xh(e))return"Safari";if((e.includes("chrome/")||Uh(e))&&!e.includes("edge/"))return"Chrome";if(Bh(e))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=n.match(t);if(r?.length===2)return r[1]}return"Other"}function Mh(n=ve()){return/firefox\//i.test(n)}function xh(n=ve()){const e=n.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function Uh(n=ve()){return/crios\//i.test(n)}function Fh(n=ve()){return/iemobile/i.test(n)}function Bh(n=ve()){return/android/i.test(n)}function qh(n=ve()){return/blackberry/i.test(n)}function jh(n=ve()){return/webos/i.test(n)}function ya(n=ve()){return/iphone|ipad|ipod/i.test(n)||/macintosh/i.test(n)&&/mobile/i.test(n)}function nT(n=ve()){return ya(n)&&!!window.navigator?.standalone}function rT(){return Rp()&&document.documentMode===10}function $h(n=ve()){return ya(n)||Bh(n)||jh(n)||qh(n)||/windows phone/i.test(n)||Fh(n)}function zh(n,e=[]){let t;switch(n){case"Browser":t=Lh(ve());break;case"Worker":t=`${Lh(ve())}-${n}`;break;default:t=n}const r=e.length?e.join(","):"FirebaseCore-web";return`${t}/JsCore/${tn}/${r}`}class sT{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const r=i=>new Promise((a,c)=>{try{const l=e(i);a(l)}catch(l){c(l)}});r.onAbort=t,this.queue.push(r);const s=this.queue.length-1;return()=>{this.queue[s]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(r){t.reverse();for(const s of t)try{s()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}}async function iT(n,e={}){return Xe(n,"GET","/v2/passwordPolicy",vt(n,e))}const oT=6;class aT{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??oT,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),t.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),t.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),t.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),t.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,s=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),s&&(t.meetsMaxPasswordLength=e.length<=s)}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);let r;for(let s=0;s<e.length;s++)r=e.charAt(s),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,s,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=s)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class cT{constructor(e,t,r,s){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=s,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Hh(this),this.idTokenSubscription=new Hh(this),this.beforeStateQueue=new sT(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=vh,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=s.sdkClientVersion,this._persistenceManagerAvailable=new Promise(i=>this._resolvePersistenceManagerAvailable=i)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=At(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Gn.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{const t=await ci(this,{idToken:e}),r=await Ye._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(t){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",t),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(Ae(this.app)){const i=this.app.settings.authIdToken;return i?new Promise(a=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(i).then(a,a))}):this.directlySetCurrentUser(null)}const t=await this.assertedPersistence.getCurrentUser();let r=t,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const i=this.redirectUser?._redirectEventId,a=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!i||i===a)&&c?.user&&(r=c.user,s=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(r)}catch(i){r=t,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(i))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return M(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Mr(e)}catch(t){if(t?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=FE()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Ae(this.app))return Promise.reject(ut(this));const t=e?X(e):null;return t&&M(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&M(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return Ae(this.app)?Promise.reject(ut(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Ae(this.app)?Promise.reject(ut(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(At(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await iT(this),t=new aT(e);this.tenantId===null?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new or("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged(()=>{r(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){const t=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:t};this.tenantId!=null&&(r.tenantId=this.tenantId),await tT(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&At(e)||this._popupRedirectResolver;M(t,this,"argument-error"),this.redirectPersistenceManager=await Gn.create(this,[At(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,s){if(this._deleted)return()=>{};const i=typeof t=="function"?t:t.next.bind(t);let a=!1;const c=this._isInitialized?Promise.resolve():this._initializationPromise;if(M(c,this,"internal-error"),c.then(()=>{a||i(this.currentUser)}),typeof t=="function"){const l=e.addObserver(t,r,s);return()=>{a=!0,l()}}else{const l=e.addObserver(t);return()=>{a=!0,l()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return M(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=zh(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);const t=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();t&&(e["X-Firebase-Client"]=t);const r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(Ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&ME(`Error while retrieving App Check token: ${e.error}`),e?.token}}function lt(n){return X(n)}class Hh{constructor(e){this.auth=e,this.observer=null,this.addObserver=Op(t=>this.observer=t)}get next(){return M(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let li={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function uT(n){li=n}function Wh(n){return li.loadJS(n)}function lT(){return li.recaptchaEnterpriseScript}function hT(){return li.gapiScript}function dT(n){return`__${n}${Math.floor(Math.random()*1e6)}`}class fT{constructor(){this.enterprise=new pT}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class pT{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}const mT="recaptcha-enterprise",Gh="NO_RECAPTCHA";class gT{constructor(e){this.type=mT,this.auth=lt(e)}async verify(e="verify",t=!1){async function r(i){if(!t){if(i.tenantId==null&&i._agentRecaptchaConfig!=null)return i._agentRecaptchaConfig.siteKey;if(i.tenantId!=null&&i._tenantRecaptchaConfigs[i.tenantId]!==void 0)return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(a,c)=>{WE(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(l=>{if(l.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{const d=new HE(l);return i.tenantId==null?i._agentRecaptchaConfig=d:i._tenantRecaptchaConfigs[i.tenantId]=d,a(d.siteKey)}}).catch(l=>{c(l)})})}function s(i,a,c){const l=window.grecaptcha;Ch(l)?l.enterprise.ready(()=>{l.enterprise.execute(i,{action:e}).then(d=>{a(d)}).catch(()=>{a(Gh)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new fT().execute("siteKey",{action:"verify"}):new Promise((i,a)=>{r(this.auth).then(c=>{if(!t&&Ch(window.grecaptcha))s(c,i,a);else{if(typeof window>"u"){a(new Error("RecaptchaVerifier is only supported in browser"));return}let l=lT();l.length!==0&&(l+=c),Wh(l).then(()=>{s(c,i,a)}).catch(d=>{a(d)})}}).catch(c=>{a(c)})})}}async function Kh(n,e,t,r=!1,s=!1){const i=new gT(n);let a;if(s)a=Gh;else try{a=await i.verify(t)}catch{a=await i.verify(t,!0)}const c={...e};if(t==="mfaSmsEnrollment"||t==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){const l=c.phoneEnrollmentInfo.phoneNumber,d=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:l,recaptchaToken:d,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){const l=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:l,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return r?Object.assign(c,{captchaResp:a}):Object.assign(c,{captchaResponse:a}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function hi(n,e,t,r,s){if(n._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await Kh(n,e,t,t==="getOobCode");return r(n,i)}else return r(n,e).catch(async i=>{if(i.code==="auth/missing-recaptcha-token"){console.log(`${t} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const a=await Kh(n,e,t,t==="getOobCode");return r(n,a)}else return Promise.reject(i)})}function _T(n,e){const t=lr(n,"auth");if(t.isInitialized()){const s=t.getImmediate(),i=t.getOptions();if(Zt(i,e??{}))return s;He(s,"already-initialized")}return t.initialize({options:e})}function yT(n,e){const t=e?.persistence||[],r=(Array.isArray(t)?t:[t]).map(At);e?.errorMap&&n._updateErrorMap(e.errorMap),n._initializeWithPersistence(r,e?.popupRedirectResolver)}function Qh(n,e,t){const r=lt(n);M(/^https?:\/\//.test(e),r,"invalid-emulator-scheme");const s=!1,i=Xh(e),{host:a,port:c}=ET(e),l=c===null?"":`:${c}`,d={url:`${i}//${a}${l}/`},f=Object.freeze({host:a,port:c,protocol:i.replace(":",""),options:Object.freeze({disableWarnings:s})});if(!r._canInitEmulator){M(r.config.emulator&&r.emulatorConfig,r,"emulator-config-failed"),M(Zt(d,r.config.emulator)&&Zt(f,r.emulatorConfig),r,"emulator-config-failed");return}r.config.emulator=d,r.emulatorConfig=f,r.settings.appVerificationDisabledForTesting=!0,et(a)?(as(`${i}//${a}${l}`),cs("Auth",!0)):TT()}function Xh(n){const e=n.indexOf(":");return e<0?"":n.substr(0,e+1)}function ET(n){const e=Xh(n),t=/(\/\/)?([^?#/]+)/.exec(n.substr(e.length));if(!t)return{host:"",port:null};const r=t[2].split("@").pop()||"",s=/^(\[[^\]]+\])(:|$)/.exec(r);if(s){const i=s[1];return{host:i,port:Yh(r.substr(i.length+1))}}else{const[i,a]=r.split(":");return{host:i,port:Yh(a)}}}function Yh(n){if(!n)return null;const e=Number(n);return isNaN(e)?null:e}function TT(){function n(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",n):n())}class Ea{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return wt("not implemented")}_getIdTokenResponse(e){return wt("not implemented")}_linkToIdToken(e,t){return wt("not implemented")}_getReauthenticationResolver(e){return wt("not implemented")}}async function wT(n,e){return Xe(n,"POST","/v1/accounts:signUp",e)}async function IT(n,e){return Vr(n,"POST","/v1/accounts:signInWithPassword",vt(n,e))}async function Jh(n,e){return Xe(n,"POST","/v1/accounts:sendOobCode",vt(n,e))}async function vT(n,e){return Jh(n,e)}async function AT(n,e){return Jh(n,e)}async function RT(n,e){return Vr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}async function bT(n,e){return Vr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}class xr extends Ea{constructor(e,t,r,s=null){super("password",r),this._email=e,this._password=t,this._tenantId=s}static _fromEmailAndPassword(e,t){return new xr(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new xr(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t=typeof e=="string"?JSON.parse(e):e;if(t?.email&&t?.password){if(t.signInMethod==="password")return this._fromEmailAndPassword(t.email,t.password);if(t.signInMethod==="emailLink")return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":const t={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return hi(e,t,"signInWithPassword",IT);case"emailLink":return RT(e,{email:this._email,oobCode:this._password});default:He(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":const r={idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return hi(e,r,"signUpPassword",wT);case"emailLink":return bT(e,{idToken:t,email:this._email,oobCode:this._password});default:He(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Kn(n,e){return Vr(n,"POST","/v1/accounts:signInWithIdp",vt(n,e))}const PT="http://localhost";class fn extends Ea{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new fn(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):He("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:s,...i}=t;if(!r||!s)return null;const a=new fn(r,s);return a.idToken=i.idToken||void 0,a.accessToken=i.accessToken||void 0,a.secret=i.secret,a.nonce=i.nonce,a.pendingToken=i.pendingToken||null,a}_getIdTokenResponse(e){const t=this.buildRequest();return Kn(e,t)}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,Kn(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Kn(e,t)}buildRequest(){const e={requestUri:PT,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=ar(t)}return e}}function ST(n){switch(n){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}function CT(n){const e=cr(ur(n)).link,t=e?cr(ur(e)).deep_link_id:null,r=cr(ur(n)).deep_link_id;return(r?cr(ur(r)).link:null)||r||t||e||n}class Ta{constructor(e){const t=cr(ur(e)),r=t.apiKey??null,s=t.oobCode??null,i=ST(t.mode??null);M(r&&s&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=s,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){const t=CT(e);try{return new Ta(t)}catch{return null}}}class Qn{constructor(){this.providerId=Qn.PROVIDER_ID}static credential(e,t){return xr._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=Ta.parseLink(t);return M(r,"argument-error"),xr._fromEmailAndCode(e,r.code,r.tenantId)}}Qn.PROVIDER_ID="password",Qn.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Qn.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class di{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class Ur extends di{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class ht extends Ur{constructor(){super("facebook.com")}static credential(e){return fn._fromParams({providerId:ht.PROVIDER_ID,signInMethod:ht.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ht.credentialFromTaggedObject(e)}static credentialFromError(e){return ht.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return ht.credential(e.oauthAccessToken)}catch{return null}}}ht.FACEBOOK_SIGN_IN_METHOD="facebook.com",ht.PROVIDER_ID="facebook.com";class dt extends Ur{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return fn._fromParams({providerId:dt.PROVIDER_ID,signInMethod:dt.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return dt.credentialFromTaggedObject(e)}static credentialFromError(e){return dt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return dt.credential(t,r)}catch{return null}}}dt.GOOGLE_SIGN_IN_METHOD="google.com",dt.PROVIDER_ID="google.com";class zt extends Ur{constructor(){super("github.com")}static credential(e){return fn._fromParams({providerId:zt.PROVIDER_ID,signInMethod:zt.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return zt.credentialFromTaggedObject(e)}static credentialFromError(e){return zt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return zt.credential(e.oauthAccessToken)}catch{return null}}}zt.GITHUB_SIGN_IN_METHOD="github.com",zt.PROVIDER_ID="github.com";class Je extends Ur{constructor(){super("twitter.com")}static credential(e,t){return fn._fromParams({providerId:Je.PROVIDER_ID,signInMethod:Je.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Je.credentialFromTaggedObject(e)}static credentialFromError(e){return Je.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return Je.credential(t,r)}catch{return null}}}Je.TWITTER_SIGN_IN_METHOD="twitter.com",Je.PROVIDER_ID="twitter.com";async function Zh(n,e){return Vr(n,"POST","/v1/accounts:signUp",vt(n,e))}class Rt{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,s=!1){const i=await Ye._fromIdTokenResponse(e,r,s),a=ed(r);return new Rt({user:i,providerId:a,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const s=ed(r);return new Rt({user:e,providerId:s,_tokenResponse:r,operationType:t})}}function ed(n){return n.providerId?n.providerId:"phoneNumber"in n?"phone":null}async function kT(n){if(Ae(n.app))return Promise.reject(ut(n));const e=lt(n);if(await e._initializationPromise,e.currentUser?.isAnonymous)return new Rt({user:e.currentUser,providerId:null,operationType:"signIn"});const t=await Zh(e,{returnSecureToken:!0}),r=await Rt._fromIdTokenResponse(e,"signIn",t,!0);return await e._updateCurrentUser(r.user),r}class fi extends We{constructor(e,t,r,s){super(t.code,t.message),this.operationType=r,this.user=s,Object.setPrototypeOf(this,fi.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,s){return new fi(e,t,r,s)}}function td(n,e,t,r){return(e==="reauthenticate"?t._getReauthenticationResolver(n):t._getIdTokenResponse(n)).catch(i=>{throw i.code==="auth/multi-factor-auth-required"?fi._fromErrorAndOperation(n,i,e,r):i})}function nd(n){return new Set(n.map(({providerId:e})=>e).filter(e=>!!e))}async function NT(n,e){const t=X(n);await OT(!0,t,e);const{providerUserInfo:r}=await KE(t.auth,{idToken:await t.getIdToken(),deleteProvider:[e]}),s=nd(r||[]);return t.providerData=t.providerData.filter(i=>s.has(i.providerId)),s.has("phone")||(t.phoneNumber=null),await t.auth._persistUserIfCurrent(t),t}async function DT(n,e,t=!1){const r=await Hn(n,e._linkToIdToken(n.auth,await n.getIdToken()),t);return Rt._forOperation(n,"link",r)}async function OT(n,e,t){await Mr(e);const r=nd(e.providerData);M(r.has(t)===n,e.auth,"no-such-provider")}async function VT(n,e,t=!1){const{auth:r}=n;if(Ae(r.app))return Promise.reject(ut(r));const s="reauthenticate";try{const i=await Hn(n,td(r,s,e,n),t);M(i.idToken,r,"internal-error");const a=ga(i.idToken);M(a,r,"internal-error");const{sub:c}=a;return M(n.uid===c,r,"user-mismatch"),Rt._forOperation(n,s,i)}catch(i){throw i?.code==="auth/user-not-found"&&He(r,"user-mismatch"),i}}async function rd(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r="signIn",s=await td(n,r,e),i=await Rt._fromIdTokenResponse(n,r,s);return t||await n._updateCurrentUser(i.user),i}async function LT(n,e){return rd(lt(n),e)}function MT(n,e,t){M(t.url?.length>0,n,"invalid-continue-uri"),M(typeof t.dynamicLinkDomain>"u"||t.dynamicLinkDomain.length>0,n,"invalid-dynamic-link-domain"),M(typeof t.linkDomain>"u"||t.linkDomain.length>0,n,"invalid-hosting-link-domain"),e.continueUrl=t.url,e.dynamicLinkDomain=t.dynamicLinkDomain,e.linkDomain=t.linkDomain,e.canHandleCodeInApp=t.handleCodeInApp,t.iOS&&(M(t.iOS.bundleId.length>0,n,"missing-ios-bundle-id"),e.iOSBundleId=t.iOS.bundleId),t.android&&(M(t.android.packageName.length>0,n,"missing-android-pkg-name"),e.androidInstallApp=t.android.installApp,e.androidMinimumVersionCode=t.android.minimumVersion,e.androidPackageName=t.android.packageName)}async function sd(n){const e=lt(n);e._getPasswordPolicyInternal()&&await e._updatePasswordPolicy()}async function xT(n,e,t){const r=lt(n);await hi(r,{requestType:"PASSWORD_RESET",email:e,clientType:"CLIENT_TYPE_WEB"},"getOobCode",AT)}async function UT(n,e,t){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),a=await hi(r,{returnSecureToken:!0,email:e,password:t,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Zh).catch(l=>{throw l.code==="auth/password-does-not-meet-requirements"&&sd(n),l}),c=await Rt._fromIdTokenResponse(r,"signIn",a);return await r._updateCurrentUser(c.user),c}function id(n,e,t){return Ae(n.app)?Promise.reject(ut(n)):LT(X(n),Qn.credential(e,t)).catch(async r=>{throw r.code==="auth/password-does-not-meet-requirements"&&sd(n),r})}async function od(n,e){const t=X(n),s={requestType:"VERIFY_EMAIL",idToken:await n.getIdToken()};e&&MT(t.auth,s,e);const{email:i}=await vT(t.auth,s);i!==n.email&&await n.reload()}async function FT(n,e){return Xe(n,"POST","/v1/accounts:update",e)}async function BT(n,{displayName:e,photoURL:t}){if(e===void 0&&t===void 0)return;const r=X(n),i={idToken:await r.getIdToken(),displayName:e,photoUrl:t,returnSecureToken:!0},a=await Hn(r,FT(r.auth,i));r.displayName=a.displayName||null,r.photoURL=a.photoUrl||null;const c=r.providerData.find(({providerId:l})=>l==="password");c&&(c.displayName=r.displayName,c.photoURL=r.photoURL),await r._updateTokensIfNecessary(a)}function qT(n,e,t,r){return X(n).onIdTokenChanged(e,t,r)}function jT(n,e,t){return X(n).beforeAuthStateChanged(e,t)}const pi="__sak";class ad{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(pi,"1"),this.storage.removeItem(pi),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}const $T=1e3,zT=10;class cd extends ad{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=$h(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const r=this.storage.getItem(t),s=this.localCache[t];r!==s&&e(t,s,r)}}onStorageEvent(e,t=!1){if(!e.key){this.forAllChangedKeys((a,c,l)=>{this.notifyListeners(a,l)});return}const r=e.key;t?this.detachListener():this.stopPolling();const s=()=>{const a=this.storage.getItem(r);!t&&this.localCache[r]===a||this.notifyListeners(r,a)},i=this.storage.getItem(r);rT()&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(s,zT):s()}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)})},$T)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){Object.keys(this.listeners).length===0&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}cd.type="LOCAL";const HT=cd;class ud extends ad{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}ud.type="SESSION";const ld=ud;function WT(n){return Promise.all(n.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}}))}class mi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find(s=>s.isListeningto(e));if(t)return t;const r=new mi(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:s,data:i}=t.data,a=this.handlersMap[s];if(!a?.size)return;t.ports[0].postMessage({status:"ack",eventId:r,eventType:s});const c=Array.from(a).map(async d=>d(t.origin,i)),l=await WT(c);t.ports[0].postMessage({status:"done",eventId:r,eventType:s,response:l})}_subscribe(e,t){Object.keys(this.handlersMap).length===0&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),(!t||this.handlersMap[e].size===0)&&delete this.handlersMap[e],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}mi.receivers=[];function wa(n="",e=10){let t="";for(let r=0;r<e;r++)t+=Math.floor(Math.random()*10);return n+t}class GT{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){const s=typeof MessageChannel<"u"?new MessageChannel:null;if(!s)throw new Error("connection_unavailable");let i,a;return new Promise((c,l)=>{const d=wa("",20);s.port1.start();const f=setTimeout(()=>{l(new Error("unsupported_event"))},r);a={messageChannel:s,onMessage(m){const y=m;if(y.data.eventId===d)switch(y.data.status){case"ack":clearTimeout(f),i=setTimeout(()=>{l(new Error("timeout"))},3e3);break;case"done":clearTimeout(i),c(y.data.response);break;default:clearTimeout(f),clearTimeout(i),l(new Error("invalid_response"));break}}},this.handlers.add(a),s.port1.addEventListener("message",a.onMessage),this.target.postMessage({eventType:e,eventId:d,data:t},[s.port2])}).finally(()=>{a&&this.removeMessageHandler(a)})}}function ft(){return window}function KT(n){ft().location.href=n}function hd(){return typeof ft().WorkerGlobalScope<"u"&&typeof ft().importScripts=="function"}async function QT(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function XT(){return navigator?.serviceWorker?.controller||null}function YT(){return hd()?self:null}const dd="firebaseLocalStorageDb",JT=1,gi="firebaseLocalStorage",fd="fbase_key";class Fr{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function _i(n,e){return n.transaction([gi],e?"readwrite":"readonly").objectStore(gi)}function ZT(){const n=indexedDB.deleteDatabase(dd);return new Fr(n).toPromise()}function Ia(){const n=indexedDB.open(dd,JT);return new Promise((e,t)=>{n.addEventListener("error",()=>{t(n.error)}),n.addEventListener("upgradeneeded",()=>{const r=n.result;try{r.createObjectStore(gi,{keyPath:fd})}catch(s){t(s)}}),n.addEventListener("success",async()=>{const r=n.result;r.objectStoreNames.contains(gi)?e(r):(r.close(),await ZT(),e(await Ia()))})})}async function pd(n,e,t){const r=_i(n,!0).put({[fd]:e,value:t});return new Fr(r).toPromise()}async function ew(n,e){const t=_i(n,!1).get(e),r=await new Fr(t).toPromise();return r===void 0?null:r.value}function md(n,e){const t=_i(n,!0).delete(e);return new Fr(t).toPromise()}const tw=800,nw=3;class gd{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db?this.db:(this.db=await Ia(),this.db)}async _withRetries(e){let t=0;for(;;)try{const r=await this._openDb();return await e(r)}catch(r){if(t++>nw)throw r;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return hd()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=mi._getInstance(YT()),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){if(this.activeServiceWorker=await QT(),!this.activeServiceWorker)return;this.sender=new GT(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(!(!this.sender||!this.activeServiceWorker||XT()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Ia();return await pd(e,pi,"1"),await md(e,pi),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(r=>pd(r,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){const t=await this._withRetries(r=>ew(r,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>md(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(s=>{const i=_i(s,!1).getAll();return new Fr(i).toPromise()});if(!e)return[];if(this.pendingWrites!==0)return[];const t=[],r=new Set;if(e.length!==0)for(const{fbase_key:s,value:i}of e)r.add(s),JSON.stringify(this.localCache[s])!==JSON.stringify(i)&&(this.notifyListeners(s,i),t.push(s));for(const s of Object.keys(this.localCache))this.localCache[s]&&!r.has(s)&&(this.notifyListeners(s,null),t.push(s));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),tw)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){Object.keys(this.listeners).length===0&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&this.stopPolling()}}gd.type="LOCAL";const rw=gd;new Or(3e4,6e4);function va(n,e){return e?At(e):(M(n._popupRedirectResolver,n,"argument-error"),n._popupRedirectResolver)}class Aa extends Ea{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Kn(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Kn(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Kn(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function sw(n){return rd(n.auth,new Aa(n),n.bypassAuthState)}function iw(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),VT(t,new Aa(n),n.bypassAuthState)}async function ow(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),DT(t,new Aa(n),n.bypassAuthState)}class _d{constructor(e,t,r,s,i=!1){this.auth=e,this.resolver=r,this.user=s,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(r){this.reject(r)}})}async onAuthEvent(e){const{urlResponse:t,sessionId:r,postBody:s,tenantId:i,error:a,type:c}=e;if(a){this.reject(a);return}const l={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:s||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(c)(l))}catch(d){this.reject(d)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return sw;case"linkViaPopup":case"linkViaRedirect":return ow;case"reauthViaPopup":case"reauthViaRedirect":return iw;default:He(this.auth,"internal-error")}}resolve(e){It(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){It(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const aw=new Or(2e3,1e4);async function Ra(n,e,t){if(Ae(n.app))return Promise.reject(Qe(n,"operation-not-supported-in-this-environment"));const r=lt(n);Ah(n,e,di);const s=va(r,t);return new Ht(r,"signInViaPopup",e,s).executeNotNull()}async function yd(n,e,t){const r=X(n);Ah(r.auth,e,di);const s=va(r.auth,t);return new Ht(r.auth,"linkViaPopup",e,s,r).executeNotNull()}class Ht extends _d{constructor(e,t,r,s,i){super(e,t,s,i),this.provider=r,this.authWindow=null,this.pollId=null,Ht.currentPopupAction&&Ht.currentPopupAction.cancel(),Ht.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return M(e,this.auth,"internal-error"),e}async onExecution(){It(this.filter.length===1,"Popup operations only handle one event");const e=wa();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(t=>{this.reject(t)}),this.resolver._isIframeWebStorageSupported(this.auth,t=>{t||this.reject(Qe(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(Qe(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Ht.currentPopupAction=null}pollUserCancellation(){const e=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Qe(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,aw.get())};e()}}Ht.currentPopupAction=null;const cw="pendingRedirect",yi=new Map;class uw extends _d{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let e=yi.get(this.auth._key());if(!e){try{const r=await lw(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(r)}catch(t){e=()=>Promise.reject(t)}yi.set(this.auth._key(),e)}return this.bypassAuthState||yi.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if(e.type==="signInViaRedirect")return super.onAuthEvent(e);if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function lw(n,e){const t=fw(e),r=dw(n);if(!await r._isAvailable())return!1;const s=await r._get(t)==="true";return await r._remove(t),s}function hw(n,e){yi.set(n._key(),e)}function dw(n){return At(n._redirectPersistence)}function fw(n){return ui(cw,n.config.apiKey,n.name)}async function pw(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),s=va(r,e),a=await new uw(r,s,t).execute();return a&&!t&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,e)),a}const mw=10*60*1e3;class gw{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!_w(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!Td(e)){const r=e.error.code?.split("auth/")[1]||"internal-error";t.onError(Qe(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const r=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=mw&&this.cachedEventUids.clear(),this.cachedEventUids.has(Ed(e))}saveEventToCache(e){this.cachedEventUids.add(Ed(e)),this.lastProcessedEventTime=Date.now()}}function Ed(n){return[n.type,n.eventId,n.sessionId,n.tenantId].filter(e=>e).join("-")}function Td({type:n,error:e}){return n==="unknown"&&e?.code==="auth/no-auth-event"}function _w(n){switch(n.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return Td(n);default:return!1}}async function yw(n,e={}){return Xe(n,"GET","/v1/projects",e)}const Ew=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Tw=/^https?/;async function ww(n){if(n.config.emulator)return;const{authorizedDomains:e}=await yw(n);for(const t of e)try{if(Iw(t))return}catch{}He(n,"unauthorized-domain")}function Iw(n){const e=fa(),{protocol:t,hostname:r}=new URL(e);if(n.startsWith("chrome-extension://")){const a=new URL(n);return a.hostname===""&&r===""?t==="chrome-extension:"&&n.replace("chrome-extension://","")===e.replace("chrome-extension://",""):t==="chrome-extension:"&&a.hostname===r}if(!Tw.test(t))return!1;if(Ew.test(n))return r===n;const s=n.replace(/\./g,"\\.");return new RegExp("^(.+\\."+s+"|"+s+")$","i").test(r)}const vw=new Or(3e4,6e4);function wd(){const n=ft().___jsl;if(n?.H){for(const e of Object.keys(n.H))if(n.H[e].r=n.H[e].r||[],n.H[e].L=n.H[e].L||[],n.H[e].r=[...n.H[e].L],n.CP)for(let t=0;t<n.CP.length;t++)n.CP[t]=null}}function Aw(n){return new Promise((e,t)=>{function r(){wd(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{wd(),t(Qe(n,"network-request-failed"))},timeout:vw.get()})}if(ft().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else if(ft().gapi?.load)r();else{const s=dT("iframefcb");return ft()[s]=()=>{gapi.load?r():t(Qe(n,"network-request-failed"))},Wh(`${hT()}?onload=${s}`).catch(i=>t(i))}}).catch(e=>{throw Ei=null,e})}let Ei=null;function Rw(n){return Ei=Ei||Aw(n),Ei}const bw=new Or(5e3,15e3),Pw="__/auth/iframe",Sw="emulator/auth/iframe",Cw={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},kw=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function Nw(n){const e=n.config;M(e.authDomain,n,"auth-domain-config-required");const t=e.emulator?pa(e,Sw):`https://${n.config.authDomain}/${Pw}`,r={apiKey:e.apiKey,appName:n.name,v:tn},s=kw.get(n.config.apiHost);s&&(r.eid=s);const i=n._getFrameworks();return i.length&&(r.fw=i.join(",")),`${t}?${ar(r).slice(1)}`}async function Dw(n){const e=await Rw(n),t=ft().gapi;return M(t,n,"internal-error"),e.open({where:document.body,url:Nw(n),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Cw,dontclear:!0},r=>new Promise(async(s,i)=>{await r.restyle({setHideOnLeave:!1});const a=Qe(n,"network-request-failed"),c=ft().setTimeout(()=>{i(a)},bw.get());function l(){ft().clearTimeout(c),s(r)}r.ping(l).then(l,()=>{i(a)})}))}const Ow={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},Vw=500,Lw=600,Mw="_blank",xw="http://localhost";class Id{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function Uw(n,e,t,r=Vw,s=Lw){const i=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const l={...Ow,width:r.toString(),height:s.toString(),top:i,left:a},d=ve().toLowerCase();t&&(c=Uh(d)?Mw:t),Mh(d)&&(e=e||xw,l.scrollbars="yes");const f=Object.entries(l).reduce((y,[R,k])=>`${y}${R}=${k},`,"");if(nT(d)&&c!=="_self")return Fw(e||"",c),new Id(null);const m=window.open(e||"",c,f);M(m,n,"popup-blocked");try{m.focus()}catch{}return new Id(m)}function Fw(n,e){const t=document.createElement("a");t.href=n,t.target=e;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),t.dispatchEvent(r)}const Bw="__/auth/handler",qw="emulator/auth/handler",jw=encodeURIComponent("fac");async function vd(n,e,t,r,s,i){M(n.config.authDomain,n,"auth-domain-config-required"),M(n.config.apiKey,n,"invalid-api-key");const a={apiKey:n.config.apiKey,appName:n.name,authType:t,redirectUrl:r,v:tn,eventId:s};if(e instanceof di){e.setDefaultLanguage(n.languageCode),a.providerId=e.providerId||"",Dp(e.getCustomParameters())||(a.customParameters=JSON.stringify(e.getCustomParameters()));for(const[f,m]of Object.entries({}))a[f]=m}if(e instanceof Ur){const f=e.getScopes().filter(m=>m!=="");f.length>0&&(a.scopes=f.join(","))}n.tenantId&&(a.tid=n.tenantId);const c=a;for(const f of Object.keys(c))c[f]===void 0&&delete c[f];const l=await n._getAppCheckToken(),d=l?`#${jw}=${encodeURIComponent(l)}`:"";return`${$w(n)}?${ar(c).slice(1)}${d}`}function $w({config:n}){return n.emulator?pa(n,qw):`https://${n.authDomain}/${Bw}`}const ba="webStorageSupport";class zw{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=ld,this._completeRedirectFn=pw,this._overrideRedirectResult=hw}async _openPopup(e,t,r,s){It(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");const i=await vd(e,t,r,fa(),s);return Uw(e,i,wa())}async _openRedirect(e,t,r,s){await this._originValidation(e);const i=await vd(e,t,r,fa(),s);return KT(i),new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:s,promise:i}=this.eventManagers[t];return s?Promise.resolve(s):(It(i,"If manager is not set, promise should be"),i)}const r=this.initAndGetManager(e);return this.eventManagers[t]={promise:r},r.catch(()=>{delete this.eventManagers[t]}),r}async initAndGetManager(e){const t=await Dw(e),r=new gw(e);return t.register("authEvent",s=>(M(s?.authEvent,e,"invalid-auth-event"),{status:r.onEvent(s.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(ba,{type:ba},s=>{const i=s?.[0]?.[ba];i!==void 0&&t(!!i),He(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=ww(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return $h()||xh()||ya()}}const Hw=zw;var Ad="@firebase/auth",Rd="1.12.0";class Ww{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){M(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function Gw(n){switch(n){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function Kw(n){St(new _t("auth",(e,{options:t})=>{const r=e.getProvider("app").getImmediate(),s=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:a,authDomain:c}=r.options;M(a&&!a.includes(":"),"invalid-api-key",{appName:r.name});const l={apiKey:a,authDomain:c,clientPlatform:n,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:zh(n)},d=new cT(r,s,i,l);return yT(d,t),d},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),St(new _t("auth-internal",e=>{const t=lt(e.getProvider("auth").getImmediate());return(r=>new Ww(r))(t)},"PRIVATE").setInstantiationMode("EXPLICIT")),je(Ad,Rd,Gw(n)),je(Ad,Rd,"esm2020")}const Qw=5*60,Xw=gc("authIdTokenMaxAge")||Qw;let bd=null;const Yw=n=>async e=>{const t=e&&await e.getIdTokenResult(),r=t&&(new Date().getTime()-Date.parse(t.issuedAtTime))/1e3;if(r&&r>Xw)return;const s=t?.token;bd!==s&&(bd=s,await fetch(n,{method:s?"POST":"DELETE",headers:s?{Authorization:`Bearer ${s}`}:{}}))};function Jw(n=ls()){const e=lr(n,"auth");if(e.isInitialized())return e.getImmediate();const t=_T(n,{popupRedirectResolver:Hw,persistence:[rw,HT,ld]}),r=gc("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const i=new URL(r,location.origin);if(location.origin===i.origin){const a=Yw(i.toString());jT(t,a,()=>a(t.currentUser)),qT(t,c=>a(c))}}const s=pc("auth");return s&&Qh(t,`http://${s}`),t}function Zw(){return document.getElementsByTagName("head")?.[0]??document}uT({loadJS(n){return new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",n),r.onload=e,r.onerror=s=>{const i=Qe("internal-error");i.customData=s,t(i)},r.type="text/javascript",r.charset="UTF-8",Zw().appendChild(r)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="}),Kw("Browser");const Pd="firebasestorage.googleapis.com",Sd="storageBucket",eI=2*60*1e3,tI=10*60*1e3,nI=1e3;class ie extends We{constructor(e,t,r=0){super(Pa(e),`Firebase Storage: ${t} (${Pa(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,ie.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return Pa(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
43
43
  ${this.customData.serverResponse}`:this.message=this._baseMessage}}var te;(function(n){n.UNKNOWN="unknown",n.OBJECT_NOT_FOUND="object-not-found",n.BUCKET_NOT_FOUND="bucket-not-found",n.PROJECT_NOT_FOUND="project-not-found",n.QUOTA_EXCEEDED="quota-exceeded",n.UNAUTHENTICATED="unauthenticated",n.UNAUTHORIZED="unauthorized",n.UNAUTHORIZED_APP="unauthorized-app",n.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",n.INVALID_CHECKSUM="invalid-checksum",n.CANCELED="canceled",n.INVALID_EVENT_NAME="invalid-event-name",n.INVALID_URL="invalid-url",n.INVALID_DEFAULT_BUCKET="invalid-default-bucket",n.NO_DEFAULT_BUCKET="no-default-bucket",n.CANNOT_SLICE_BLOB="cannot-slice-blob",n.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",n.NO_DOWNLOAD_URL="no-download-url",n.INVALID_ARGUMENT="invalid-argument",n.INVALID_ARGUMENT_COUNT="invalid-argument-count",n.APP_DELETED="app-deleted",n.INVALID_ROOT_OPERATION="invalid-root-operation",n.INVALID_FORMAT="invalid-format",n.INTERNAL_ERROR="internal-error",n.UNSUPPORTED_ENVIRONMENT="unsupported-environment"})(te||(te={}));function Pa(n){return"storage/"+n}function Sa(){const n="An unknown error occurred, please check the error payload for server response.";return new ie(te.UNKNOWN,n)}function rI(n){return new ie(te.OBJECT_NOT_FOUND,"Object '"+n+"' does not exist.")}function sI(n){return new ie(te.QUOTA_EXCEEDED,"Quota for bucket '"+n+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function iI(){const n="User is not authenticated, please authenticate using Firebase Authentication and try again.";return new ie(te.UNAUTHENTICATED,n)}function oI(){return new ie(te.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}function aI(n){return new ie(te.UNAUTHORIZED,"User does not have permission to access '"+n+"'.")}function Cd(){return new ie(te.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function kd(){return new ie(te.CANCELED,"User canceled the upload/download.")}function cI(n){return new ie(te.INVALID_URL,"Invalid URL '"+n+"'.")}function uI(n){return new ie(te.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+n+"'.")}function lI(){return new ie(te.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+Sd+"' property when initializing the app?")}function Nd(){return new ie(te.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function hI(){return new ie(te.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function dI(){return new ie(te.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function fI(n){return new ie(te.UNSUPPORTED_ENVIRONMENT,`${n} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}function Ca(n){return new ie(te.INVALID_ARGUMENT,n)}function Dd(){return new ie(te.APP_DELETED,"The Firebase app was deleted.")}function pI(n){return new ie(te.INVALID_ROOT_OPERATION,"The operation '"+n+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function Br(n,e){return new ie(te.INVALID_FORMAT,"String does not match format '"+n+"': "+e)}function qr(n){throw new ie(te.INTERNAL_ERROR,"Internal error: "+n)}class Be{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return this.path.length===0}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let r;try{r=Be.makeFromUrl(e,t)}catch{return new Be(e,"")}if(r.path==="")return r;throw uI(e)}static makeFromUrl(e,t){let r=null;const s="([A-Za-z0-9.\\-_]+)";function i(Q){Q.path.charAt(Q.path.length-1)==="/"&&(Q.path_=Q.path_.slice(0,-1))}const a="(/(.*))?$",c=new RegExp("^gs://"+s+a,"i"),l={bucket:1,path:3};function d(Q){Q.path_=decodeURIComponent(Q.path)}const f="v[A-Za-z0-9_]+",m=t.replace(/[.]/g,"\\."),y="(/([^?#]*).*)?$",R=new RegExp(`^https?://${m}/${f}/b/${s}/o${y}`,"i"),k={bucket:1,path:3},N=t===Pd?"(?:storage.googleapis.com|storage.cloud.google.com)":t,C="([^?#]*)",U=new RegExp(`^https?://${N}/${s}/${C}`,"i"),F=[{regex:c,indices:l,postModify:i},{regex:R,indices:k,postModify:d},{regex:U,indices:{bucket:1,path:2},postModify:d}];for(let Q=0;Q<F.length;Q++){const ce=F[Q],ne=ce.regex.exec(e);if(ne){const w=ne[ce.indices.bucket];let g=ne[ce.indices.path];g||(g=""),r=new Be(w,g),ce.postModify(r);break}}if(r==null)throw cI(e);return r}}class mI{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function gI(n,e,t){let r=1,s=null,i=null,a=!1,c=0;function l(){return c===2}let d=!1;function f(...C){d||(d=!0,e.apply(null,C))}function m(C){s=setTimeout(()=>{s=null,n(R,l())},C)}function y(){i&&clearTimeout(i)}function R(C,...U){if(d){y();return}if(C){y(),f.call(null,C,...U);return}if(l()||a){y(),f.call(null,C,...U);return}r<64&&(r*=2);let F;c===1?(c=2,F=0):F=(r+Math.random())*1e3,m(F)}let k=!1;function N(C){k||(k=!0,y(),!d&&(s!==null?(C||(c=2),clearTimeout(s),m(0)):C||(c=1)))}return m(0),i=setTimeout(()=>{a=!0,N(!0)},t),N}function _I(n){n(!1)}function yI(n){return n!==void 0}function EI(n){return typeof n=="function"}function TI(n){return typeof n=="object"&&!Array.isArray(n)}function Ti(n){return typeof n=="string"||n instanceof String}function Od(n){return ka()&&n instanceof Blob}function ka(){return typeof Blob<"u"}function Vd(n,e,t,r){if(r<e)throw Ca(`Invalid value for '${n}'. Expected ${e} or greater.`);if(r>t)throw Ca(`Invalid value for '${n}'. Expected ${t} or less.`)}function Xn(n,e,t){let r=e;return t==null&&(r=`https://${e}`),`${t}://${r}/v0${n}`}function Ld(n){const e=encodeURIComponent;let t="?";for(const r in n)if(n.hasOwnProperty(r)){const s=e(r)+"="+e(n[r]);t=t+s+"&"}return t=t.slice(0,-1),t}var pn;(function(n){n[n.NO_ERROR=0]="NO_ERROR",n[n.NETWORK_ERROR=1]="NETWORK_ERROR",n[n.ABORT=2]="ABORT"})(pn||(pn={}));function Md(n,e){const t=n>=500&&n<600,s=[408,429].indexOf(n)!==-1,i=e.indexOf(n)!==-1;return t||s||i}class wI{constructor(e,t,r,s,i,a,c,l,d,f,m,y=!0,R=!1){this.url_=e,this.method_=t,this.headers_=r,this.body_=s,this.successCodes_=i,this.additionalRetryCodes_=a,this.callback_=c,this.errorCallback_=l,this.timeout_=d,this.progressCallback_=f,this.connectionFactory_=m,this.retry=y,this.isUsingEmulator=R,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((k,N)=>{this.resolve_=k,this.reject_=N,this.start_()})}start_(){const e=(r,s)=>{if(s){r(!1,new wi(!1,null,!0));return}const i=this.connectionFactory_();this.pendingConnection_=i;const a=c=>{const l=c.loaded,d=c.lengthComputable?c.total:-1;this.progressCallback_!==null&&this.progressCallback_(l,d)};this.progressCallback_!==null&&i.addUploadProgressListener(a),i.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{this.progressCallback_!==null&&i.removeUploadProgressListener(a),this.pendingConnection_=null;const c=i.getErrorCode()===pn.NO_ERROR,l=i.getStatus();if(!c||Md(l,this.additionalRetryCodes_)&&this.retry){const f=i.getErrorCode()===pn.ABORT;r(!1,new wi(!1,null,f));return}const d=this.successCodes_.indexOf(l)!==-1;r(!0,new wi(d,i))})},t=(r,s)=>{const i=this.resolve_,a=this.reject_,c=s.connection;if(s.wasSuccessCode)try{const l=this.callback_(c,c.getResponse());yI(l)?i(l):i()}catch(l){a(l)}else if(c!==null){const l=Sa();l.serverResponse=c.getErrorText(),this.errorCallback_?a(this.errorCallback_(c,l)):a(l)}else if(s.canceled){const l=this.appDelete_?Dd():kd();a(l)}else{const l=Cd();a(l)}};this.canceled_?t(!1,new wi(!1,null,!0)):this.backoffId_=gI(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,this.backoffId_!==null&&_I(this.backoffId_),this.pendingConnection_!==null&&this.pendingConnection_.abort()}}class wi{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function II(n,e){e!==null&&e.length>0&&(n.Authorization="Firebase "+e)}function vI(n,e){n["X-Firebase-Storage-Version"]="webjs/"+(e??"AppManager")}function AI(n,e){e&&(n["X-Firebase-GMPID"]=e)}function RI(n,e){e!==null&&(n["X-Firebase-AppCheck"]=e)}function bI(n,e,t,r,s,i,a=!0,c=!1){const l=Ld(n.urlParams),d=n.url+l,f=Object.assign({},n.headers);return AI(f,e),II(f,t),vI(f,i),RI(f,r),new wI(d,n.method,f,n.body,n.successCodes,n.additionalRetryCodes,n.handler,n.errorHandler,n.timeout,n.progressCallback,s,a,c)}function PI(){return typeof BlobBuilder<"u"?BlobBuilder:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:void 0}function SI(...n){const e=PI();if(e!==void 0){const t=new e;for(let r=0;r<n.length;r++)t.append(n[r]);return t.getBlob()}else{if(ka())return new Blob(n);throw new ie(te.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}}function CI(n,e,t){return n.webkitSlice?n.webkitSlice(e,t):n.mozSlice?n.mozSlice(e,t):n.slice?n.slice(e,t):null}function kI(n){if(typeof atob>"u")throw fI("base-64");return atob(n)}const pt={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class Na{constructor(e,t){this.data=e,this.contentType=t||null}}function NI(n,e){switch(n){case pt.RAW:return new Na(xd(e));case pt.BASE64:case pt.BASE64URL:return new Na(Ud(n,e));case pt.DATA_URL:return new Na(OI(e),VI(e))}throw Sa()}function xd(n){const e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r<=127)e.push(r);else if(r<=2047)e.push(192|r>>6,128|r&63);else if((r&64512)===55296)if(!(t<n.length-1&&(n.charCodeAt(t+1)&64512)===56320))e.push(239,191,189);else{const i=r,a=n.charCodeAt(++t);r=65536|(i&1023)<<10|a&1023,e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}else(r&64512)===56320?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|r&63)}return new Uint8Array(e)}function DI(n){let e;try{e=decodeURIComponent(n)}catch{throw Br(pt.DATA_URL,"Malformed data URL.")}return xd(e)}function Ud(n,e){switch(n){case pt.BASE64:{const s=e.indexOf("-")!==-1,i=e.indexOf("_")!==-1;if(s||i)throw Br(n,"Invalid character '"+(s?"-":"_")+"' found: is it base64url encoded?");break}case pt.BASE64URL:{const s=e.indexOf("+")!==-1,i=e.indexOf("/")!==-1;if(s||i)throw Br(n,"Invalid character '"+(s?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/");break}}let t;try{t=kI(e)}catch(s){throw s.message.includes("polyfill")?s:Br(n,"Invalid character found")}const r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}class Fd{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(t===null)throw Br(pt.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const r=t[1]||null;r!=null&&(this.base64=LI(r,";base64"),this.contentType=this.base64?r.substring(0,r.length-7):r),this.rest=e.substring(e.indexOf(",")+1)}}function OI(n){const e=new Fd(n);return e.base64?Ud(pt.BASE64,e.rest):DI(e.rest)}function VI(n){return new Fd(n).contentType}function LI(n,e){return n.length>=e.length?n.substring(n.length-e.length)===e:!1}class Wt{constructor(e,t){let r=0,s="";Od(e)?(this.data_=e,r=e.size,s=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=s}size(){return this.size_}type(){return this.type_}slice(e,t){if(Od(this.data_)){const r=this.data_,s=CI(r,e,t);return s===null?null:new Wt(s)}else{const r=new Uint8Array(this.data_.buffer,e,t-e);return new Wt(r,!0)}}static getBlob(...e){if(ka()){const t=e.map(r=>r instanceof Wt?r.data_:r);return new Wt(SI.apply(null,t))}else{const t=e.map(a=>Ti(a)?NI(pt.RAW,a).data:a.data_);let r=0;t.forEach(a=>{r+=a.byteLength});const s=new Uint8Array(r);let i=0;return t.forEach(a=>{for(let c=0;c<a.length;c++)s[i++]=a[c]}),new Wt(s,!0)}}uploadData(){return this.data_}}function Bd(n){let e;try{e=JSON.parse(n)}catch{return null}return TI(e)?e:null}function MI(n){if(n.length===0)return null;const e=n.lastIndexOf("/");return e===-1?"":n.slice(0,e)}function xI(n,e){const t=e.split("/").filter(r=>r.length>0).join("/");return n.length===0?t:n+"/"+t}function qd(n){const e=n.lastIndexOf("/",n.length-2);return e===-1?n:n.slice(e+1)}function UI(n,e){return e}class Ce{constructor(e,t,r,s){this.server=e,this.local=t||e,this.writable=!!r,this.xform=s||UI}}let Ii=null;function FI(n){return!Ti(n)||n.length<2?n:qd(n)}function jd(){if(Ii)return Ii;const n=[];n.push(new Ce("bucket")),n.push(new Ce("generation")),n.push(new Ce("metageneration")),n.push(new Ce("name","fullPath",!0));function e(i,a){return FI(a)}const t=new Ce("name");t.xform=e,n.push(t);function r(i,a){return a!==void 0?Number(a):a}const s=new Ce("size");return s.xform=r,n.push(s),n.push(new Ce("timeCreated")),n.push(new Ce("updated")),n.push(new Ce("md5Hash",null,!0)),n.push(new Ce("cacheControl",null,!0)),n.push(new Ce("contentDisposition",null,!0)),n.push(new Ce("contentEncoding",null,!0)),n.push(new Ce("contentLanguage",null,!0)),n.push(new Ce("contentType",null,!0)),n.push(new Ce("metadata","customMetadata",!0)),Ii=n,Ii}function BI(n,e){function t(){const r=n.bucket,s=n.fullPath,i=new Be(r,s);return e._makeStorageReference(i)}Object.defineProperty(n,"ref",{get:t})}function qI(n,e,t){const r={};r.type="file";const s=t.length;for(let i=0;i<s;i++){const a=t[i];r[a.local]=a.xform(r,e[a.server])}return BI(r,n),r}function $d(n,e,t){const r=Bd(e);return r===null?null:qI(n,r,t)}function jI(n,e,t,r){const s=Bd(e);if(s===null||!Ti(s.downloadTokens))return null;const i=s.downloadTokens;if(i.length===0)return null;const a=encodeURIComponent;return i.split(",").map(d=>{const f=n.bucket,m=n.fullPath,y="/b/"+a(f)+"/o/"+a(m),R=Xn(y,t,r),k=Ld({alt:"media",token:d});return R+k})[0]}function zd(n,e){const t={},r=e.length;for(let s=0;s<r;s++){const i=e[s];i.writable&&(t[i.server]=n[i.local])}return JSON.stringify(t)}class mn{constructor(e,t,r,s){this.url=e,this.method=t,this.handler=r,this.timeout=s,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function bt(n){if(!n)throw Sa()}function Da(n,e){function t(r,s){const i=$d(n,s,e);return bt(i!==null),i}return t}function $I(n,e){function t(r,s){const i=$d(n,s,e);return bt(i!==null),jI(i,s,n.host,n._protocol)}return t}function jr(n){function e(t,r){let s;return t.getStatus()===401?t.getErrorText().includes("Firebase App Check token is invalid")?s=oI():s=iI():t.getStatus()===402?s=sI(n.bucket):t.getStatus()===403?s=aI(n.path):s=r,s.status=t.getStatus(),s.serverResponse=r.serverResponse,s}return e}function Oa(n){const e=jr(n);function t(r,s){let i=e(r,s);return r.getStatus()===404&&(i=rI(n.path)),i.serverResponse=s.serverResponse,i}return t}function zI(n,e,t){const r=e.fullServerUrl(),s=Xn(r,n.host,n._protocol),i="GET",a=n.maxOperationRetryTime,c=new mn(s,i,Da(n,t),a);return c.errorHandler=Oa(e),c}function HI(n,e,t){const r=e.fullServerUrl(),s=Xn(r,n.host,n._protocol),i="GET",a=n.maxOperationRetryTime,c=new mn(s,i,$I(n,t),a);return c.errorHandler=Oa(e),c}function WI(n,e){const t=e.fullServerUrl(),r=Xn(t,n.host,n._protocol),s="DELETE",i=n.maxOperationRetryTime;function a(l,d){}const c=new mn(r,s,a,i);return c.successCodes=[200,204],c.errorHandler=Oa(e),c}function GI(n,e){return n&&n.contentType||e&&e.type()||"application/octet-stream"}function Hd(n,e,t){const r=Object.assign({},t);return r.fullPath=n.path,r.size=e.size(),r.contentType||(r.contentType=GI(null,e)),r}function KI(n,e,t,r,s){const i=e.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};function c(){let F="";for(let Q=0;Q<2;Q++)F=F+Math.random().toString().slice(2);return F}const l=c();a["Content-Type"]="multipart/related; boundary="+l;const d=Hd(e,r,s),f=zd(d,t),m="--"+l+`\r
44
44
  Content-Type: application/json; charset=utf-8\r
45
45
  \r