whipdesk 0.0.8 → 0.0.9

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.
@@ -0,0 +1 @@
1
+ import{B as e,D as t,F as n,G as r,H as i,I as a,J as o,K as s,N as c,R as l,U as u,W as d,X as f,_ as ee,b as p,c as m,g as te,j as h,n as g,nt as _,o as ne,p as re,rt as v,s as y,tt as ie,u as ae,v as oe,x as se,y as ce,z as b}from"./index.esm-B3ZTr43m.js";function le(){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."}}var ue=le,de=new p(`auth`,`Firebase`,le()),x=new ee(`@firebase/auth`);function fe(e,...t){x.logLevel<=te.WARN&&x.warn(`Auth (${g}): ${e}`,...t)}function S(e,...t){x.logLevel<=te.ERROR&&x.error(`Auth (${g}): ${e}`,...t)}function C(e,...t){throw me(e,...t)}function w(e,...t){return me(e,...t)}function pe(e,t,n){return new p(`auth`,`Firebase`,{...ue(),[t]:n}).create(t,{appName:e.name})}function T(e){return pe(e,`operation-not-supported-in-this-environment`,`Operations that alter the current user are not supported in conjunction with FirebaseServerApp`)}function me(e,...t){if(typeof e!=`string`){let n=t[0],r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}return de.create(e,...t)}function E(e,t,...n){if(!e)throw me(t,...n)}function D(e){let t=`INTERNAL ASSERTION FAILED: `+e;throw S(t),Error(t)}function O(e,t){e||D(t)}function he(){return typeof self<`u`&&self.location?.href||``}function ge(){return _e()===`http:`||_e()===`https:`}function _e(){return typeof self<`u`&&self.location?.protocol||null}function ve(){return typeof navigator<`u`&&navigator&&`onLine`in navigator&&typeof navigator.onLine==`boolean`&&(ge()||i()||`connection`in navigator)?navigator.onLine:!0}function ye(){if(typeof navigator>`u`)return null;let e=navigator;return e.languages&&e.languages[0]||e.language||null}var k=class{constructor(e,t){this.shortDelay=e,this.longDelay=t,O(t>e,`Short delay should be less than long delay!`),this.isMobile=o()||f()}get(){return ve()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function be(e,t){O(e.emulator,`Emulator should always be set here`);let{url:n}=e.emulator;return t?`${n}${t.startsWith(`/`)?t.slice(1):t}`:n}var xe=class{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}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;D(`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;D(`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;D(`Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill`)}},Se={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`},Ce=[`/v1/accounts:signInWithCustomToken`,`/v1/accounts:signInWithEmailLink`,`/v1/accounts:signInWithIdp`,`/v1/accounts:signInWithPassword`,`/v1/accounts:signInWithPhoneNumber`,`/v1/token`],we=new k(3e4,6e4);function A(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function j(e,t,n,r,i={}){return Te(e,i,async()=>{let i={},a={};r&&(t===`GET`?a=r:i={body:JSON.stringify(r)});let o=_({...a,key:e.config.apiKey}).slice(1),s=await e._getAdditionalHeaders();s[`Content-Type`]=`application/json`,e.languageCode&&(s[`X-Firebase-Locale`]=e.languageCode);let c={method:t,headers:s,...i};return d()||(c.referrerPolicy=`strict-origin-when-cross-origin`),e.emulatorConfig&&u(e.emulatorConfig.host)&&(c.credentials=`include`),xe.fetch()(await Ee(e,e.config.apiHost,n,o),c)})}async function Te(e,t,n){e._canInitEmulator=!1;let r={...Se,...t};try{let t=new Oe(e),i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();let a=await i.json();if(`needConfirmation`in a)throw N(e,`account-exists-with-different-credential`,a);if(i.ok&&!(`errorMessage`in a))return a;{let[t,n]=(i.ok?a.errorMessage:a.error.message).split(` : `);if(t===`FEDERATED_USER_ID_ALREADY_LINKED`)throw N(e,`credential-already-in-use`,a);if(t===`EMAIL_EXISTS`)throw N(e,`email-already-in-use`,a);if(t===`USER_DISABLED`)throw N(e,`user-disabled`,a);let o=r[t]||t.toLowerCase().replace(/[_\s]+/g,`-`);if(n)throw pe(e,o,n);C(e,o)}}catch(t){if(t instanceof se)throw t;C(e,`network-request-failed`,{message:String(t)})}}async function M(e,t,n,r,i={}){let a=await j(e,t,n,r,i);return`mfaPendingCredential`in a&&C(e,`multi-factor-auth-required`,{_serverResponse:a}),a}async function Ee(e,t,n,r){let i=`${t}${n}?${r}`,a=e,o=a.config.emulator?be(e.config,i):`${e.config.apiScheme}://${i}`;return Ce.includes(n)&&(await a._persistenceManagerAvailable,a._getPersistenceType()===`COOKIE`)?a._getPersistence()._getFinalTarget(o).toString():o}function De(e){switch(e){case`ENFORCE`:return`ENFORCE`;case`AUDIT`:return`AUDIT`;case`OFF`:return`OFF`;default:return`ENFORCEMENT_STATE_UNSPECIFIED`}}var Oe=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(w(this.auth,`network-request-failed`)),we.get())})}};function N(e,t,n){let r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);let i=w(e,t,r);return i.customData._tokenResponse=n,i}function ke(e){return e!==void 0&&e.enterprise!==void 0}var Ae=class{constructor(e){if(this.siteKey=``,this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw 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(let t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return De(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 je(e,t){return j(e,`GET`,`/v2/recaptchaConfig`,A(e,t))}async function Me(e,t){return j(e,`POST`,`/v1/accounts:delete`,t)}async function P(e,t){return j(e,`POST`,`/v1/accounts:lookup`,t)}function F(e){if(e)try{let t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch{}}async function Ne(e,t=!1){let n=b(e),r=await n.getIdToken(t),i=Fe(r);E(i&&i.exp&&i.auth_time&&i.iat,n.auth,`internal-error`);let a=typeof i.firebase==`object`?i.firebase:void 0,o=a?.sign_in_provider;return{claims:i,token:r,authTime:F(Pe(i.auth_time)),issuedAtTime:F(Pe(i.iat)),expirationTime:F(Pe(i.exp)),signInProvider:o||null,signInSecondFactor:a?.sign_in_second_factor||null}}function Pe(e){return Number(e)*1e3}function Fe(e){let[n,r,i]=e.split(`.`);if(n===void 0||r===void 0||i===void 0)return S(`JWT malformed, contained fewer than 3 sections`),null;try{let e=t(r);return e?JSON.parse(e):(S(`Failed to decode base64 JWT payload`),null)}catch(e){return S(`Caught error parsing JWT payload as JSON`,e?.toString()),null}}function Ie(e){let t=Fe(e);return E(t,`internal-error`),E(t.exp!==void 0,`internal-error`),E(t.iat!==void 0,`internal-error`),Number(t.exp)-Number(t.iat)}async function I(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof se&&Le(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}function Le({code:e}){return e===`auth/user-disabled`||e===`auth/user-token-expired`}var Re=class{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){let e=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),e}else{this.errorBackoff=3e4;let e=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;let 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()}},ze=class{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=F(this.lastLoginAt),this.creationTime=F(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function L(e){let t=e.auth,n=await I(e,P(t,{idToken:await e.getIdToken()}));E(n?.users.length,t,`internal-error`);let r=n.users[0];e._notifyReloadListener(r);let i=r.providerUserInfo?.length?He(r.providerUserInfo):[],a=Ve(e.providerData,i),o=e.isAnonymous,s=!(e.email&&r.passwordHash)&&!a?.length,c=o?s:!1,l={uid:r.localId,displayName:r.displayName||null,photoURL:r.photoUrl||null,email:r.email||null,emailVerified:r.emailVerified||!1,phoneNumber:r.phoneNumber||null,tenantId:r.tenantId||null,providerData:a,metadata:new ze(r.createdAt,r.lastLoginAt),isAnonymous:c};Object.assign(e,l)}async function Be(e){let t=b(e);await L(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function Ve(e,t){return[...e.filter(e=>!t.some(t=>t.providerId===e.providerId)),...t]}function He(e){return e.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 Ue(e,t){let n=await Te(e,{},async()=>{let n=_({grant_type:`refresh_token`,refresh_token:t}).slice(1),{tokenApiHost:r,apiKey:i}=e.config,a=await Ee(e,r,`/v1/token`,`key=${i}`),o=await e._getAdditionalHeaders();o[`Content-Type`]=`application/x-www-form-urlencoded`;let s={method:`POST`,headers:o,body:n};return e.emulatorConfig&&u(e.emulatorConfig.host)&&(s.credentials=`include`),xe.fetch()(a,s)});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function We(e,t){return j(e,`POST`,`/v2/accounts:revokeToken`,A(e,t))}var Ge=class e{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){E(e.idToken,`internal-error`),E(e.idToken!==void 0,`internal-error`),E(e.refreshToken!==void 0,`internal-error`);let t=`expiresIn`in e&&e.expiresIn!==void 0?Number(e.expiresIn):Ie(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){E(e.length!==0,`internal-error`);let t=Ie(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return!t&&this.accessToken&&!this.isExpired?this.accessToken:(E(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){let{accessToken:n,refreshToken:r,expiresIn:i}=await Ue(e,t);this.updateTokensAndExpiration(n,r,Number(i))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+n*1e3}static fromJSON(t,n){let{refreshToken:r,accessToken:i,expirationTime:a}=n,o=new e;return r&&(E(typeof r==`string`,`internal-error`,{appName:t}),o.refreshToken=r),i&&(E(typeof i==`string`,`internal-error`,{appName:t}),o.accessToken=i),a&&(E(typeof a==`number`,`internal-error`,{appName:t}),o.expirationTime=a),o}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 e,this.toJSON())}_performRefresh(){return D(`not implemented`)}};function R(e,t){E(typeof e==`string`||e===void 0,`internal-error`,{appName:t})}var z=class e{constructor({uid:e,auth:t,stsTokenManager:n,...r}){this.providerId=`firebase`,this.proactiveRefresh=new Re(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=n,this.accessToken=n.accessToken,this.displayName=r.displayName||null,this.email=r.email||null,this.emailVerified=r.emailVerified||!1,this.phoneNumber=r.phoneNumber||null,this.photoURL=r.photoURL||null,this.isAnonymous=r.isAnonymous||!1,this.tenantId=r.tenantId||null,this.providerData=r.providerData?[...r.providerData]:[],this.metadata=new ze(r.createdAt||void 0,r.lastLoginAt||void 0)}async getIdToken(e){let t=await I(this,this.stsTokenManager.getToken(this.auth,e));return E(t,this.auth,`internal-error`),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return Ne(this,e)}reload(){return Be(this)}_assign(e){this!==e&&(E(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(e=>({...e})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(t){let n=new e({...this,auth:t,stsTokenManager:this.stsTokenManager._clone()});return n.metadata._copy(this.metadata),n}_onReload(e){E(!this.reloadListener,this.auth,`internal-error`),this.reloadListener=e,this.reloadUserInfo&&=(this._notifyReloadListener(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 n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await L(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(y(this.auth.app))return Promise.reject(T(this.auth));let e=await this.getIdToken();return await I(this,Me(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(t,n){let r=n.displayName??void 0,i=n.email??void 0,a=n.phoneNumber??void 0,o=n.photoURL??void 0,s=n.tenantId??void 0,c=n._redirectEventId??void 0,l=n.createdAt??void 0,u=n.lastLoginAt??void 0,{uid:d,emailVerified:f,isAnonymous:ee,providerData:p,stsTokenManager:m}=n;E(d&&m,t,`internal-error`);let te=Ge.fromJSON(this.name,m);E(typeof d==`string`,t,`internal-error`),R(r,t.name),R(i,t.name),E(typeof f==`boolean`,t,`internal-error`),E(typeof ee==`boolean`,t,`internal-error`),R(a,t.name),R(o,t.name),R(s,t.name),R(c,t.name),R(l,t.name),R(u,t.name);let h=new e({uid:d,auth:t,email:i,emailVerified:f,displayName:r,isAnonymous:ee,photoURL:o,phoneNumber:a,tenantId:s,stsTokenManager:te,createdAt:l,lastLoginAt:u});return p&&Array.isArray(p)&&(h.providerData=p.map(e=>({...e}))),c&&(h._redirectEventId=c),h}static async _fromIdTokenResponse(t,n,r=!1){let i=new Ge;i.updateFromServerResponse(n);let a=new e({uid:n.localId,auth:t,stsTokenManager:i,isAnonymous:r});return await L(a),a}static async _fromGetAccountInfoResponse(t,n,r){let i=n.users[0];E(i.localId!==void 0,`internal-error`);let a=i.providerUserInfo===void 0?[]:He(i.providerUserInfo),o=!(i.email&&i.passwordHash)&&!a?.length,s=new Ge;s.updateFromIdToken(r);let c=new e({uid:i.localId,auth:t,stsTokenManager:s,isAnonymous:o}),l={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:a,metadata:new ze(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!a?.length};return Object.assign(c,l),c}},Ke=new Map;function B(e){O(e instanceof Function,`Expected a class definition`);let t=Ke.get(e);return t?(O(t instanceof e,`Instance stored in cache mismatched with class`),t):(t=new e,Ke.set(e,t),t)}var qe=class{constructor(){this.type=`NONE`,this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){let t=this.storage[e];return t===void 0?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}};qe.type=`NONE`;var Je=qe;function V(e,t,n){return`firebase:${e}:${t}:${n}`}var Ye=class e{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;let{config:r,name:i}=this.auth;this.fullUserKey=V(this.userKey,r.apiKey,i),this.fullPersistenceKey=V(`persistence`,r.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(){let e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e==`string`){let t=await P(this.auth,{idToken:e}).catch(()=>void 0);return t?z._fromGetAccountInfoResponse(this.auth,t,e):null}return z._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;let 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(t,n,r=`authUser`){if(!n.length)return new e(B(Je),t,r);let i=(await Promise.all(n.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e),a=i[0]||B(Je),o=V(r,t.config.apiKey,t.name),s=null;for(let e of n)try{let n=await e._get(o);if(n){let r;if(typeof n==`string`){let e=await P(t,{idToken:n}).catch(()=>void 0);if(!e)break;r=await z._fromGetAccountInfoResponse(t,e,n)}else r=z._fromJSON(t,n);e!==a&&(s=r),a=e;break}}catch{}let c=i.filter(e=>e._shouldAllowMigration);return!a._shouldAllowMigration||!c.length?new e(a,t,r):(a=c[0],s&&await a._set(o,s.toJSON()),await Promise.all(n.map(async e=>{if(e!==a)try{await e._remove(o)}catch{}})),new e(a,t,r))}};function Xe(e){let t=e.toLowerCase();if(t.includes(`opera/`)||t.includes(`opr/`)||t.includes(`opios/`))return`Opera`;if(et(t))return`IEMobile`;if(t.includes(`msie`)||t.includes(`trident/`))return`IE`;if(t.includes(`edge/`))return`Edge`;if(Ze(t))return`Firefox`;if(t.includes(`silk/`))return`Silk`;if(nt(t))return`Blackberry`;if(rt(t))return`Webos`;if(Qe(t))return`Safari`;if((t.includes(`chrome/`)||$e(t))&&!t.includes(`edge/`))return`Chrome`;if(tt(t))return`Android`;{let t=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);if(t?.length===2)return t[1]}return`Other`}function Ze(t=e()){return/firefox\//i.test(t)}function Qe(t=e()){let n=t.toLowerCase();return n.includes(`safari/`)&&!n.includes(`chrome/`)&&!n.includes(`crios/`)&&!n.includes(`android`)}function $e(t=e()){return/crios\//i.test(t)}function et(t=e()){return/iemobile/i.test(t)}function tt(t=e()){return/android/i.test(t)}function nt(t=e()){return/blackberry/i.test(t)}function rt(t=e()){return/webos/i.test(t)}function it(t=e()){return/iphone|ipad|ipod/i.test(t)||/macintosh/i.test(t)&&/mobile/i.test(t)}function at(t=e()){return it(t)&&!!window.navigator?.standalone}function ot(){return s()&&document.documentMode===10}function st(t=e()){return it(t)||tt(t)||rt(t)||nt(t)||/windows phone/i.test(t)||et(t)}function ct(t,n=[]){let r;switch(t){case`Browser`:r=Xe(e());break;case`Worker`:r=`${Xe(e())}-${t}`;break;default:r=t}let i=n.length?n.join(`,`):`FirebaseCore-web`;return`${r}/JsCore/${g}/${i}`}var lt=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){let n=t=>new Promise((n,r)=>{try{n(e(t))}catch(e){r(e)}});n.onAbort=t,this.queue.push(n);let r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let t=[];try{for(let n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(let e of t)try{e()}catch{}throw this.auth._errorFactory.create(`login-blocked`,{originalMessage:e?.message})}}};async function ut(e,t={}){return j(e,`GET`,`/v2/passwordPolicy`,A(e,t))}var dt=6,ft=class{constructor(e){let t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??dt,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){let t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&=t.meetsMinPasswordLength??!0,t.isValid&&=t.meetsMaxPasswordLength??!0,t.isValid&&=t.containsLowercaseLetter??!0,t.isValid&&=t.containsUppercaseLetter??!0,t.isValid&&=t.containsNumericCharacter??!0,t.isValid&&=t.containsNonAlphanumericCharacter??!0,t}validatePasswordLengthOptions(e,t){let n=this.customStrengthOptions.minPasswordLength,r=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),r&&(t.meetsMaxPasswordLength=e.length<=r)}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);let n;for(let r=0;r<e.length;r++)n=e.charAt(r),this.updatePasswordCharacterOptionsStatuses(t,n>=`a`&&n<=`z`,n>=`A`&&n<=`Z`,n>=`0`&&n<=`9`,this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,r,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||=t),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||=n),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||=r),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||=i)}},pt=class{constructor(e,t,n,r){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=r,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new mt(this),this.idTokenSubscription=new mt(this),this.beforeStateQueue=new lt(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=de,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=r.sdkClientVersion,this._persistenceManagerAvailable=new Promise(e=>this._resolvePersistenceManagerAvailable=e)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=B(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Ye.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;let 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{let t=await P(this,{idToken:e}),n=await z._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn(`FirebaseServerApp could not login user with provided authIdToken: `,e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(y(this.app)){let e=this.app.settings.authIdToken;return e?new Promise(t=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(e).then(t,t))}):this.directlySetCurrentUser(null)}let t=await this.assertedPersistence.getCurrentUser(),n=t,r=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let t=this.redirectUser?._redirectEventId,i=n?._redirectEventId,a=await this.tryRedirectSignIn(e);(!t||t===i)&&a?.user&&(n=a.user,r=!0)}if(!n)return this.directlySetCurrentUser(null);if(!n._redirectEventId){if(r)try{await this.beforeStateQueue.runMiddleware(n)}catch(e){n=t,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return n?this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}return E(this._popupRedirectResolver,this,`argument-error`),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)}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 L(e)}catch(e){if(e?.code!==`auth/network-request-failed`)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=ye()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(y(this.app))return Promise.reject(T(this));let t=e?b(e):null;return t&&E(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&&E(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 y(this.app)?Promise.reject(T(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return y(this.app)?Promise.reject(T(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(B(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let t=this._getPasswordPolicyInternal();return t.schemaVersion===this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?t.validatePassword(e):Promise.reject(this._errorFactory.create(`unsupported-password-policy-schema-version`,{}))}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=new ft(await ut(this));this.tenantId===null?this._projectPasswordPolicy=e:this._tenantPasswordPolicies[this.tenantId]=e}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new p(`auth`,`Firebase`,e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{let n=this.onAuthStateChanged(()=>{n(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){let t={providerId:`apple.com`,tokenType:`ACCESS_TOKEN`,token:e,idToken:await this.currentUser.getIdToken()};this.tenantId!=null&&(t.tenantId=this.tenantId),await We(this,t)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){let n=await this.getOrInitRedirectPersistenceManager(t);return e===null?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let t=e&&B(e)||this._popupRedirectResolver;E(t,this,`argument-error`),this.redirectPersistenceManager=await Ye.create(this,[B(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);let e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};let i=typeof t==`function`?t:t.next.bind(t),a=!1,o=this._isInitialized?Promise.resolve():this._initializationPromise;if(E(o,this,`internal-error`),o.then(()=>{a||i(this.currentUser)}),typeof t==`function`){let i=e.addObserver(t,n,r);return()=>{a=!0,i()}}else{let n=e.addObserver(t);return()=>{a=!0,n()}}}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 E(this.persistenceManager,this,`internal-error`),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=ct(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){let e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e[`X-Firebase-gmpid`]=this.app.options.appId);let t=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();t&&(e[`X-Firebase-Client`]=t);let n=await this._getAppCheckToken();return n&&(e[`X-Firebase-AppCheck`]=n),e}async _getAppCheckToken(){if(y(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&fe(`Error while retrieving App Check token: ${e.error}`),e?.token}};function H(e){return b(e)}var mt=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=h(e=>this.observer=e)}get next(){return E(this.observer,this.auth,`internal-error`),this.observer.next.bind(this.observer)}},U={async loadJS(){throw Error(`Unable to load external scripts`)},recaptchaV2Script:``,recaptchaEnterpriseScript:``,gapiScript:``};function ht(e){U=e}function gt(e){return U.loadJS(e)}function _t(){return U.recaptchaEnterpriseScript}function vt(){return U.gapiScript}function yt(e){return`__${e}${Math.floor(Math.random()*1e6)}`}var bt=class{constructor(){this.enterprise=new xt}ready(e){e()}execute(e,t){return Promise.resolve(`token`)}render(e,t){return``}},xt=class{ready(e){e()}execute(e,t){return Promise.resolve(`token`)}render(e,t){return``}},St=`recaptcha-enterprise`,W=`NO_RECAPTCHA`,Ct=`onFirebaseAuthREInstanceReady`,wt=class e{constructor(e){this.type=St,this.auth=H(e)}async verify(t=`verify`,n=!1){async function r(e){if(!n){if(e.tenantId==null&&e._agentRecaptchaConfig!=null)return e._agentRecaptchaConfig.siteKey;if(e.tenantId!=null&&e._tenantRecaptchaConfigs[e.tenantId]!==void 0)return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise(async(t,n)=>{je(e,{clientType:`CLIENT_TYPE_WEB`,version:`RECAPTCHA_ENTERPRISE`}).then(r=>{if(r.recaptchaKey===void 0)n(Error(`recaptcha Enterprise site key undefined`));else{let n=new Ae(r);return e.tenantId==null?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}}).catch(e=>{n(e)})})}function i(e,n,r){let i=window.grecaptcha;ke(i)?i.enterprise.ready(()=>{i.enterprise.execute(e,{action:t}).then(e=>{n(e)}).catch(()=>{n(W)})}):r(Error(`No reCAPTCHA enterprise script loaded.`))}return this.auth.settings.appVerificationDisabledForTesting?new bt().execute(`siteKey`,{action:`verify`}):new Promise((t,a)=>{r(this.auth).then(async r=>{if(!n&&ke(window.grecaptcha)&&e.scriptInjectionDeferred)await e.scriptInjectionDeferred.promise,i(r,t,a);else{if(typeof window>`u`){a(Error(`RecaptchaVerifier is only supported in browser`));return}let n=_t();n.length!==0&&(n+=r+`&onload=${Ct}`),e.scriptInjectionDeferred=new ce,window[Ct]=()=>{e.scriptInjectionDeferred?.resolve()},gt(n).then(()=>e.scriptInjectionDeferred?.promise).then(()=>{i(r,t,a)}).catch(e=>{a(e)})}}).catch(e=>{a(e)})})}};wt.scriptInjectionDeferred=null;async function G(e,t,n,r=!1,i=!1){let a=new wt(e),o;if(i)o=W;else try{o=await a.verify(n)}catch{o=await a.verify(n,!0)}let s={...t};if(n===`mfaSmsEnrollment`||n===`mfaSmsSignIn`){if(`phoneEnrollmentInfo`in s){let e=s.phoneEnrollmentInfo.phoneNumber,t=s.phoneEnrollmentInfo.recaptchaToken;Object.assign(s,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:o,clientType:`CLIENT_TYPE_WEB`,recaptchaVersion:`RECAPTCHA_ENTERPRISE`}})}else if(`phoneSignInInfo`in s){let e=s.phoneSignInInfo.recaptchaToken;Object.assign(s,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:o,clientType:`CLIENT_TYPE_WEB`,recaptchaVersion:`RECAPTCHA_ENTERPRISE`}})}return s}return r?Object.assign(s,{captchaResp:o}):Object.assign(s,{captchaResponse:o}),Object.assign(s,{clientType:`CLIENT_TYPE_WEB`}),Object.assign(s,{recaptchaVersion:`RECAPTCHA_ENTERPRISE`}),s}async function K(e,t,n,r,i){return i===`EMAIL_PASSWORD_PROVIDER`?e._getRecaptchaConfig()?.isProviderEnabled(`EMAIL_PASSWORD_PROVIDER`)?r(e,await G(e,t,n,n===`getOobCode`)):r(e,t).catch(async i=>i.code===`auth/missing-recaptcha-token`?(console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`),r(e,await G(e,t,n,n===`getOobCode`))):Promise.reject(i)):i===`PHONE_PROVIDER`?e._getRecaptchaConfig()?.isProviderEnabled(`PHONE_PROVIDER`)?r(e,await G(e,t,n)).catch(async i=>e._getRecaptchaConfig()?.getProviderEnforcementState(`PHONE_PROVIDER`)===`AUDIT`&&(i.code===`auth/missing-recaptcha-token`||i.code===`auth/invalid-app-credential`)?(console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${n} flow.`),r(e,await G(e,t,n,!1,!0))):Promise.reject(i)):r(e,await G(e,t,n,!1,!0)):Promise.reject(i+` provider is not supported.`)}async function Tt(e){let t=H(e),n=new Ae(await je(t,{clientType:`CLIENT_TYPE_WEB`,version:`RECAPTCHA_ENTERPRISE`}));t.tenantId==null?t._agentRecaptchaConfig=n:t._tenantRecaptchaConfigs[t.tenantId]=n,n.isAnyProviderEnabled()&&new wt(t).verify()}function Et(e,t){let n=ne(e,`auth`);if(n.isInitialized()){let e=n.getImmediate();if(c(n.getOptions(),t??{}))return e;C(e,`already-initialized`)}return n.initialize({options:t})}function Dt(e,t){let n=t?.persistence||[],r=(Array.isArray(n)?n:[n]).map(B);t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,t?.popupRedirectResolver)}function Ot(e,t,n){let r=H(e);E(/^https?:\/\//.test(t),r,`invalid-emulator-scheme`);let i=!!n?.disableWarnings,a=kt(t),{host:o,port:s}=At(t),l=s===null?``:`:${s}`,d={url:`${a}//${o}${l}/`},f=Object.freeze({host:o,port:s,protocol:a.replace(`:`,``),options:Object.freeze({disableWarnings:i})});if(!r._canInitEmulator){E(r.config.emulator&&r.emulatorConfig,r,`emulator-config-failed`),E(c(d,r.config.emulator)&&c(f,r.emulatorConfig),r,`emulator-config-failed`);return}r.config.emulator=d,r.emulatorConfig=f,r.settings.appVerificationDisabledForTesting=!0,u(o)?ie(`${a}//${o}${l}`):i||Mt()}function kt(e){let t=e.indexOf(`:`);return t<0?``:e.substr(0,t+1)}function At(e){let t=kt(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:``,port:null};let r=n[2].split(`@`).pop()||``,i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){let e=i[1];return{host:e,port:jt(r.substr(e.length+1))}}else{let[e,t]=r.split(`:`);return{host:e,port:jt(t)}}}function jt(e){if(!e)return null;let t=Number(e);return isNaN(t)?null:t}function Mt(){function e(){let 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`,e):e())}var q=class{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return D(`not implemented`)}_getIdTokenResponse(e){return D(`not implemented`)}_linkToIdToken(e,t){return D(`not implemented`)}_getReauthenticationResolver(e){return D(`not implemented`)}};async function Nt(e,t){return j(e,`POST`,`/v1/accounts:signUp`,t)}async function Pt(e,t){return M(e,`POST`,`/v1/accounts:signInWithPassword`,A(e,t))}async function Ft(e,t){return M(e,`POST`,`/v1/accounts:signInWithEmailLink`,A(e,t))}async function It(e,t){return M(e,`POST`,`/v1/accounts:signInWithEmailLink`,A(e,t))}var Lt=class e extends q{constructor(e,t,n,r=null){super(`password`,n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(t,n){return new e(t,n,`password`)}static _fromEmailAndCode(t,n,r=null){return new e(t,n,`emailLink`,r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let 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`:return K(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:`CLIENT_TYPE_WEB`},`signInWithPassword`,Pt,`EMAIL_PASSWORD_PROVIDER`);case`emailLink`:return Ft(e,{email:this._email,oobCode:this._password});default:C(e,`internal-error`)}}async _linkToIdToken(e,t){switch(this.signInMethod){case`password`:return K(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:`CLIENT_TYPE_WEB`},`signUpPassword`,Nt,`EMAIL_PASSWORD_PROVIDER`);case`emailLink`:return It(e,{idToken:t,email:this._email,oobCode:this._password});default:C(e,`internal-error`)}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function J(e,t){return M(e,`POST`,`/v1/accounts:signInWithIdp`,A(e,t))}var Rt=`http://localhost`,Y=class e extends q{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(t){let n=new e(t.providerId,t.signInMethod);return t.idToken||t.accessToken?(t.idToken&&(n.idToken=t.idToken),t.accessToken&&(n.accessToken=t.accessToken),t.nonce&&!t.pendingToken&&(n.nonce=t.nonce),t.pendingToken&&(n.pendingToken=t.pendingToken)):t.oauthToken&&t.oauthTokenSecret?(n.accessToken=t.oauthToken,n.secret=t.oauthTokenSecret):C(`argument-error`),n}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(t){let{providerId:n,signInMethod:r,...i}=typeof t==`string`?JSON.parse(t):t;if(!n||!r)return null;let a=new e(n,r);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){return J(e,this.buildRequest())}_linkToIdToken(e,t){let n=this.buildRequest();return n.idToken=t,J(e,n)}_getReauthenticationResolver(e){let t=this.buildRequest();return t.autoCreate=!1,J(e,t)}buildRequest(){let e={requestUri:Rt,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let 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=_(t)}return e}};async function zt(e,t){return j(e,`POST`,`/v1/accounts:sendVerificationCode`,A(e,t))}async function Bt(e,t){return M(e,`POST`,`/v1/accounts:signInWithPhoneNumber`,A(e,t))}async function Vt(e,t){let n=await M(e,`POST`,`/v1/accounts:signInWithPhoneNumber`,A(e,t));if(n.temporaryProof)throw N(e,`account-exists-with-different-credential`,n);return n}var Ht={USER_NOT_FOUND:`user-not-found`};async function Ut(e,t){return M(e,`POST`,`/v1/accounts:signInWithPhoneNumber`,A(e,{...t,operation:`REAUTH`}),Ht)}var Wt=class e extends q{constructor(e){super(`phone`,`phone`),this.params=e}static _fromVerification(t,n){return new e({verificationId:t,verificationCode:n})}static _fromTokenResponse(t,n){return new e({phoneNumber:t,temporaryProof:n})}_getIdTokenResponse(e){return Bt(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return Vt(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return Ut(e,this._makeVerificationRequest())}_makeVerificationRequest(){let{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){let e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(t){typeof t==`string`&&(t=JSON.parse(t));let{verificationId:n,verificationCode:r,phoneNumber:i,temporaryProof:a}=t;return!r&&!n&&!i&&!a?null:new e({verificationId:n,verificationCode:r,phoneNumber:i,temporaryProof:a})}};function Gt(e){switch(e){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 Kt(e){let t=v(n(e)).link,r=t?v(n(t)).deep_link_id:null,i=v(n(e)).deep_link_id;return(i?v(n(i)).link:null)||i||r||t||e}var qt=class e{constructor(e){let t=v(n(e)),r=t.apiKey??null,i=t.oobCode??null,a=Gt(t.mode??null);E(r&&i&&a,`argument-error`),this.apiKey=r,this.operation=a,this.code=i,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(t){let n=Kt(t);try{return new e(n)}catch{return null}}},Jt=class e{constructor(){this.providerId=e.PROVIDER_ID}static credential(e,t){return Lt._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){let n=qt.parseLink(t);return E(n,`argument-error`),Lt._fromEmailAndCode(e,n.code,n.tenantId)}};Jt.PROVIDER_ID=`password`,Jt.EMAIL_PASSWORD_SIGN_IN_METHOD=`password`,Jt.EMAIL_LINK_SIGN_IN_METHOD=`emailLink`;var Yt=class{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}},X=class extends Yt{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}},Xt=class e extends X{constructor(){super(`facebook.com`)}static credential(t){return Y._fromParams({providerId:e.PROVIDER_ID,signInMethod:e.FACEBOOK_SIGN_IN_METHOD,accessToken:t})}static credentialFromResult(t){return e.credentialFromTaggedObject(t)}static credentialFromError(t){return e.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t||!(`oauthAccessToken`in t)||!t.oauthAccessToken)return null;try{return e.credential(t.oauthAccessToken)}catch{return null}}};Xt.FACEBOOK_SIGN_IN_METHOD=`facebook.com`,Xt.PROVIDER_ID=`facebook.com`;var Zt=class e extends X{constructor(){super(`google.com`),this.addScope(`profile`)}static credential(t,n){return Y._fromParams({providerId:e.PROVIDER_ID,signInMethod:e.GOOGLE_SIGN_IN_METHOD,idToken:t,accessToken:n})}static credentialFromResult(t){return e.credentialFromTaggedObject(t)}static credentialFromError(t){return e.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;let{oauthIdToken:n,oauthAccessToken:r}=t;if(!n&&!r)return null;try{return e.credential(n,r)}catch{return null}}};Zt.GOOGLE_SIGN_IN_METHOD=`google.com`,Zt.PROVIDER_ID=`google.com`;var Qt=class e extends X{constructor(){super(`github.com`)}static credential(t){return Y._fromParams({providerId:e.PROVIDER_ID,signInMethod:e.GITHUB_SIGN_IN_METHOD,accessToken:t})}static credentialFromResult(t){return e.credentialFromTaggedObject(t)}static credentialFromError(t){return e.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t||!(`oauthAccessToken`in t)||!t.oauthAccessToken)return null;try{return e.credential(t.oauthAccessToken)}catch{return null}}};Qt.GITHUB_SIGN_IN_METHOD=`github.com`,Qt.PROVIDER_ID=`github.com`;var $t=class e extends X{constructor(){super(`twitter.com`)}static credential(t,n){return Y._fromParams({providerId:e.PROVIDER_ID,signInMethod:e.TWITTER_SIGN_IN_METHOD,oauthToken:t,oauthTokenSecret:n})}static credentialFromResult(t){return e.credentialFromTaggedObject(t)}static credentialFromError(t){return e.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;let{oauthAccessToken:n,oauthTokenSecret:r}=t;if(!n||!r)return null;try{return e.credential(n,r)}catch{return null}}};$t.TWITTER_SIGN_IN_METHOD=`twitter.com`,$t.PROVIDER_ID=`twitter.com`;var en=class e{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(t,n,r,i=!1){let a=await z._fromIdTokenResponse(t,r,i),o=tn(r);return new e({user:a,providerId:o,_tokenResponse:r,operationType:n})}static async _forOperation(t,n,r){await t._updateTokensIfNecessary(r,!0);let i=tn(r);return new e({user:t,providerId:i,_tokenResponse:r,operationType:n})}};function tn(e){return e.providerId?e.providerId:`phoneNumber`in e?`phone`:null}var nn=class e extends se{constructor(t,n,r,i){super(n.code,n.message),this.operationType=r,this.user=i,Object.setPrototypeOf(this,e.prototype),this.customData={appName:t.name,tenantId:t.tenantId??void 0,_serverResponse:n.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(t,n,r,i){return new e(t,n,r,i)}};function rn(e,t,n,r){return(t===`reauthenticate`?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch(n=>{throw n.code===`auth/multi-factor-auth-required`?nn._fromErrorAndOperation(e,n,t,r):n})}async function an(e,t,n=!1){let r=await I(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return en._forOperation(e,`link`,r)}async function on(e,t,n=!1){let{auth:r}=e;if(y(r.app))return Promise.reject(T(r));let i=`reauthenticate`;try{let a=await I(e,rn(r,i,t,e),n);E(a.idToken,r,`internal-error`);let o=Fe(a.idToken);E(o,r,`internal-error`);let{sub:s}=o;return E(e.uid===s,r,`user-mismatch`),en._forOperation(e,i,a)}catch(e){throw e?.code===`auth/user-not-found`&&C(r,`user-mismatch`),e}}async function sn(e,t,n=!1){if(y(e.app))return Promise.reject(T(e));let r=`signIn`,i=await rn(e,r,t),a=await en._fromIdTokenResponse(e,r,i);return n||await e._updateCurrentUser(a.user),a}function cn(e,t,n,r){return b(e).onIdTokenChanged(t,n,r)}function ln(e,t,n){return b(e).beforeAuthStateChanged(t,n)}function un(e,t){return j(e,`POST`,`/v2/accounts/mfaEnrollment:start`,A(e,t))}function dn(e,t){return j(e,`POST`,`/v2/accounts/mfaEnrollment:finalize`,A(e,t))}function fn(e,t){return j(e,`POST`,`/v2/accounts/mfaEnrollment:start`,A(e,t))}function pn(e,t){return j(e,`POST`,`/v2/accounts/mfaEnrollment:finalize`,A(e,t))}var Z=`__sak`,mn=class{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Z,`1`),this.storage.removeItem(Z),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){let 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()}},hn=1e3,gn=10,_n=class extends mn{constructor(){super(()=>window.localStorage,`LOCAL`),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=st(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(let t of Object.keys(this.listeners)){let n=this.storage.getItem(t),r=this.localCache[t];n!==r&&e(t,r,n)}}onStorageEvent(e,t=!1){if(!e.key){this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)});return}let n=e.key;t?this.detachListener():this.stopPolling();let r=()=>{let e=this.storage.getItem(n);!t&&this.localCache[n]===e||this.notifyListeners(n,e)},i=this.storage.getItem(n);ot()&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(r,gn):r()}notifyListeners(e,t){this.localCache[e]=t;let n=this.listeners[e];if(n)for(let e of Array.from(n))e(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,n)=>{this.onStorageEvent(new StorageEvent(`storage`,{key:e,oldValue:t,newValue:n}),!0)})},hn)}stopPolling(){this.pollTimer&&=(clearInterval(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){let t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}};_n.type=`LOCAL`;var vn=_n,yn=1e3;function bn(e){let t=e.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),n=RegExp(`${t}=([^;]+)`);return document.cookie.match(n)?.[1]??null}function xn(e){return`${window.location.protocol===`http:`?`__dev_`:`__HOST-`}FIREBASE_${e.split(`:`)[3]}`}var Sn=class{constructor(){this.type=`COOKIE`,this.listenerUnsubscribes=new Map}_getFinalTarget(e){let t=new URL(`${window.location.origin}/__cookies__`);return t.searchParams.set(`finalTarget`,e),t}async _isAvailable(){return typeof isSecureContext==`boolean`&&!isSecureContext||typeof navigator>`u`||typeof document>`u`?!1:navigator.cookieEnabled??!0}async _set(e,t){}async _get(e){if(!this._isAvailable())return null;let t=xn(e);return window.cookieStore?(await window.cookieStore.get(t))?.value:bn(t)}async _remove(e){if(!this._isAvailable()||!await this._get(e))return;let t=xn(e);document.cookie=`${t}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`,await fetch(`/__cookies__`,{method:`DELETE`}).catch(()=>void 0)}_addListener(e,t){if(!this._isAvailable())return;let n=xn(e);if(window.cookieStore){let e=(e=>{let r=e.changed.find(e=>e.name===n);r&&t(r.value),e.deleted.find(e=>e.name===n)&&t(null)});return this.listenerUnsubscribes.set(t,()=>window.cookieStore.removeEventListener(`change`,e)),window.cookieStore.addEventListener(`change`,e)}let r=bn(n),i=setInterval(()=>{let e=bn(n);e!==r&&(t(e),r=e)},yn);this.listenerUnsubscribes.set(t,()=>clearInterval(i))}_removeListener(e,t){let n=this.listenerUnsubscribes.get(t);n&&(n(),this.listenerUnsubscribes.delete(t))}};Sn.type=`COOKIE`;var Cn=class extends mn{constructor(){super(()=>window.sessionStorage,`SESSION`)}_addListener(e,t){}_removeListener(e,t){}};Cn.type=`SESSION`;var wn=Cn;function Tn(e){return Promise.all(e.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}}))}var En=class e{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){let n=this.receivers.find(e=>e.isListeningto(t));if(n)return n;let r=new e(t);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let t=e,{eventId:n,eventType:r,data:i}=t.data,a=this.handlersMap[r];if(!a?.size)return;t.ports[0].postMessage({status:`ack`,eventId:n,eventType:r});let o=await Tn(Array.from(a).map(async e=>e(t.origin,i)));t.ports[0].postMessage({status:`done`,eventId:n,eventType:r,response:o})}_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)}};En.receivers=[];function Dn(e=``,t=10){let n=``;for(let e=0;e<t;e++)n+=Math.floor(Math.random()*10);return e+n}var On=class{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,n=50){let r=typeof MessageChannel<`u`?new MessageChannel:null;if(!r)throw Error(`connection_unavailable`);let i,a;return new Promise((o,s)=>{let c=Dn(``,20);r.port1.start();let l=setTimeout(()=>{s(Error(`unsupported_event`))},n);a={messageChannel:r,onMessage(e){let t=e;if(t.data.eventId===c)switch(t.data.status){case`ack`:clearTimeout(l),i=setTimeout(()=>{s(Error(`timeout`))},3e3);break;case`done`:clearTimeout(i),o(t.data.response);break;default:clearTimeout(l),clearTimeout(i),s(Error(`invalid_response`));break}}},this.handlers.add(a),r.port1.addEventListener(`message`,a.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[r.port2])}).finally(()=>{a&&this.removeMessageHandler(a)})}};function Q(){return window}function kn(e){Q().location.href=e}function An(){return Q().WorkerGlobalScope!==void 0&&typeof Q().importScripts==`function`}async function jn(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function Mn(){return navigator?.serviceWorker?.controller||null}function Nn(){return An()?self:null}var Pn=`firebaseLocalStorageDb`,Fn=1,In=`firebaseLocalStorage`,Ln=`fbase_key`,$=class{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 Rn(e,t){return e.transaction([In],t?`readwrite`:`readonly`).objectStore(In)}function zn(){return new $(indexedDB.deleteDatabase(Pn)).toPromise()}function Bn(){let e=indexedDB.open(Pn,Fn);return new Promise((t,n)=>{e.addEventListener(`error`,()=>{n(e.error)}),e.addEventListener(`upgradeneeded`,()=>{let t=e.result;try{t.createObjectStore(In,{keyPath:Ln})}catch(e){n(e)}}),e.addEventListener(`success`,async()=>{let n=e.result;n.objectStoreNames.contains(In)?t(n):(n.close(),await zn(),t(await Bn()))})})}async function Vn(e,t,n){return new $(Rn(e,!0).put({[Ln]:t,value:n})).toPromise()}async function Hn(e,t){let n=await new $(Rn(e,!1).get(t)).toPromise();return n===void 0?null:n.value}function Un(e,t){return new $(Rn(e,!0).delete(t)).toPromise()}var Wn=800,Gn=3,Kn=class{constructor(){this.type=`LOCAL`,this.dbPromise=null,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.dbPromise?this.dbPromise:(this.dbPromise=Bn(),this.dbPromise.catch(()=>{this.dbPromise=null}),this.dbPromise)}async _withRetries(e){let t=0;for(;;)try{return await e(await this._openDb())}catch(e){if(t++>Gn)throw e;this.dbPromise&&=((await this.dbPromise).close(),null)}}async initializeServiceWorkerMessaging(){return An()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=En._getInstance(Nn()),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 jn(),!this.activeServiceWorker)return;this.sender=new On(this.activeServiceWorker);let 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||Mn()!==this.activeServiceWorker))try{await this.sender._send(`keyChanged`,{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{return indexedDB?(await this._withRetries(async e=>{await Vn(e,Z,`1`),await Un(e,Z)}),!0):!1}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(n=>Vn(n,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){let t=await this._withRetries(t=>Hn(t,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>Un(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){let e=await this._withRetries(e=>new $(Rn(e,!1).getAll()).toPromise());if(!e||this.pendingWrites!==0)return[];let t=[],n=new Set;if(e.length!==0)for(let{fbase_key:r,value:i}of e)n.add(r),JSON.stringify(this.localCache[r])!==JSON.stringify(i)&&(this.notifyListeners(r,i),t.push(r));for(let e of Object.keys(this.localCache))this.localCache[e]&&!n.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;let n=this.listeners[e];if(n)for(let e of Array.from(n))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),Wn)}stopPolling(){this.pollTimer&&=(clearInterval(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()}};Kn.type=`LOCAL`;var qn=Kn;function Jn(e,t){return j(e,`POST`,`/v2/accounts/mfaSignIn:start`,A(e,t))}function Yn(e,t){return j(e,`POST`,`/v2/accounts/mfaSignIn:finalize`,A(e,t))}function Xn(e,t){return j(e,`POST`,`/v2/accounts/mfaSignIn:finalize`,A(e,t))}yt(`rcb`),new k(3e4,6e4);var Zn=`recaptcha`;async function Qn(e,t,n){if(!e._getRecaptchaConfig())try{await Tt(e)}catch{console.log(`Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.`)}try{let r;if(r=typeof t==`string`?{phoneNumber:t}:t,`session`in r){let t=r.session;if(`phoneNumber`in r)return E(t.type===`enroll`,e,`internal-error`),(await K(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:r.phoneNumber,clientType:`CLIENT_TYPE_WEB`}},`mfaSmsEnrollment`,async(e,t)=>t.phoneEnrollmentInfo.captchaResponse===W?(E(n?.type===Zn,e,`argument-error`),un(e,await $n(e,t,n))):un(e,t),`PHONE_PROVIDER`).catch(e=>Promise.reject(e))).phoneSessionInfo.sessionInfo;{E(t.type===`signin`,e,`internal-error`);let i=r.multiFactorHint?.uid||r.multiFactorUid;return E(i,e,`missing-multi-factor-info`),(await K(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:i,phoneSignInInfo:{clientType:`CLIENT_TYPE_WEB`}},`mfaSmsSignIn`,async(e,t)=>t.phoneSignInInfo.captchaResponse===W?(E(n?.type===Zn,e,`argument-error`),Jn(e,await $n(e,t,n))):Jn(e,t),`PHONE_PROVIDER`).catch(e=>Promise.reject(e))).phoneResponseInfo.sessionInfo}}else return(await K(e,{phoneNumber:r.phoneNumber,clientType:`CLIENT_TYPE_WEB`},`sendVerificationCode`,async(e,t)=>t.captchaResponse===W?(E(n?.type===Zn,e,`argument-error`),zt(e,await $n(e,t,n))):zt(e,t),`PHONE_PROVIDER`).catch(e=>Promise.reject(e))).sessionInfo}finally{n?._reset()}}async function $n(e,t,n){E(n.type===Zn,e,`argument-error`);let r=await n.verify();E(typeof r==`string`,e,`argument-error`);let i={...t};if(`phoneEnrollmentInfo`in i){let e=i.phoneEnrollmentInfo.phoneNumber,t=i.phoneEnrollmentInfo.captchaResponse,n=i.phoneEnrollmentInfo.clientType,a=i.phoneEnrollmentInfo.recaptchaVersion;return Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:r,captchaResponse:t,clientType:n,recaptchaVersion:a}}),i}else if(`phoneSignInInfo`in i){let e=i.phoneSignInInfo.captchaResponse,t=i.phoneSignInInfo.clientType,n=i.phoneSignInInfo.recaptchaVersion;return Object.assign(i,{phoneSignInInfo:{recaptchaToken:r,captchaResponse:e,clientType:t,recaptchaVersion:n}}),i}else return Object.assign(i,{recaptchaToken:r}),i}var er=class e{constructor(t){this.providerId=e.PROVIDER_ID,this.auth=H(t)}verifyPhoneNumber(e,t){return Qn(this.auth,e,b(t))}static credential(e,t){return Wt._fromVerification(e,t)}static credentialFromResult(t){let n=t;return e.credentialFromTaggedObject(n)}static credentialFromError(t){return e.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{phoneNumber:t,temporaryProof:n}=e;return t&&n?Wt._fromTokenResponse(t,n):null}};er.PROVIDER_ID=`phone`,er.PHONE_SIGN_IN_METHOD=`phone`;function tr(e,t){return t?B(t):(E(e._popupRedirectResolver,e,`argument-error`),e._popupRedirectResolver)}var nr=class extends q{constructor(e){super(`custom`,`custom`),this.params=e}_getIdTokenResponse(e){return J(e,this._buildIdpRequest())}_linkToIdToken(e,t){return J(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return J(e,this._buildIdpRequest())}_buildIdpRequest(e){let 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 rr(e){return sn(e.auth,new nr(e),e.bypassAuthState)}function ir(e){let{auth:t,user:n}=e;return E(n,t,`internal-error`),on(n,new nr(e),e.bypassAuthState)}async function ar(e){let{auth:t,user:n}=e;return E(n,t,`internal-error`),an(n,new nr(e),e.bypassAuthState)}var or=class{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,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(e){this.reject(e)}})}async onAuthEvent(e){let{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:a,type:o}=e;if(a){this.reject(a);return}let s={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(s))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case`signInViaPopup`:case`signInViaRedirect`:return rr;case`linkViaPopup`:case`linkViaRedirect`:return ar;case`reauthViaPopup`:case`reauthViaRedirect`:return ir;default:C(this.auth,`internal-error`)}}resolve(e){O(this.pendingPromise,`Pending promise was never set`),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){O(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()}},sr=new k(2e3,1e4),cr=class e extends or{constructor(t,n,r,i,a){super(t,n,i,a),this.provider=r,this.authWindow=null,this.pollId=null,e.currentPopupAction&&e.currentPopupAction.cancel(),e.currentPopupAction=this}async executeNotNull(){let e=await this.execute();return E(e,this.auth,`internal-error`),e}async onExecution(){O(this.filter.length===1,`Popup operations only handle one event`);let e=Dn();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(w(this.auth,`web-storage-unsupported`))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(w(this.auth,`cancelled-popup-request`))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,e.currentPopupAction=null}pollUserCancellation(){let e=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(w(this.auth,`popup-closed-by-user`))},8e3);return}this.pollId=window.setTimeout(e,sr.get())};e()}};cr.currentPopupAction=null;var lr=`pendingRedirect`,ur=new Map,dr=class extends or{constructor(e,t,n=!1){super(e,[`signInViaRedirect`,`linkViaRedirect`,`reauthViaRedirect`,`unknown`],t,void 0,n),this.eventId=null}async execute(){let e=ur.get(this.auth._key());if(!e){try{let t=await fr(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}ur.set(this.auth._key(),e)}return this.bypassAuthState||ur.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){let t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}};async function fr(e,t){let n=hr(t),r=mr(e);if(!await r._isAvailable())return!1;let i=await r._get(n)===`true`;return await r._remove(n),i}function pr(e,t){ur.set(e._key(),t)}function mr(e){return B(e._redirectPersistence)}function hr(e){return V(lr,e.config.apiKey,e.name)}async function gr(e,t,n=!1){if(y(e.app))return Promise.reject(T(e));let r=H(e),i=await new dr(r,tr(r,t),n).execute();return i&&!n&&(delete i.user._redirectEventId,await r._persistUserIfCurrent(i.user),await r._setRedirectUser(null,t)),i}var _r=600*1e3,vr=class{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(n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!xr(e)?t:(this.hasHandledPotentialRedirect=!0,t||=(this.queuedRedirectEvent=e,!0),t)}sendToConsumer(e,t){if(e.error&&!br(e)){let n=e.error.code?.split(`auth/`)[1]||`internal-error`;t.onError(w(this.auth,n))}else t.onAuthEvent(e)}isEventForConsumer(e,t){let n=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=_r&&this.cachedEventUids.clear(),this.cachedEventUids.has(yr(e))}saveEventToCache(e){this.cachedEventUids.add(yr(e)),this.lastProcessedEventTime=Date.now()}};function yr(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join(`-`)}function br({type:e,error:t}){return e===`unknown`&&t?.code===`auth/no-auth-event`}function xr(e){switch(e.type){case`signInViaRedirect`:case`linkViaRedirect`:case`reauthViaRedirect`:return!0;case`unknown`:return br(e);default:return!1}}async function Sr(e,t={}){return j(e,`GET`,`/v1/projects`,t)}var Cr=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,wr=/^https?/;async function Tr(e){if(e.config.emulator)return;let{authorizedDomains:t}=await Sr(e);for(let e of t)try{if(Er(e))return}catch{}C(e,`unauthorized-domain`)}function Er(e){let t=he(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith(`chrome-extension://`)){let i=new URL(e);return i.hostname===``&&r===``?n===`chrome-extension:`&&e.replace(`chrome-extension://`,``)===t.replace(`chrome-extension://`,``):n===`chrome-extension:`&&i.hostname===r}if(!wr.test(n))return!1;if(Cr.test(e))return r===e;let i=e.replace(/\./g,`\\.`);return RegExp(`^(.+\\.`+i+`|`+i+`)$`,`i`).test(r)}var Dr=new k(3e4,6e4);function Or(){let e=Q().___jsl;if(e?.H){for(let t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t<e.CP.length;t++)e.CP[t]=null}}function kr(e){return new Promise((t,n)=>{function r(){Or(),gapi.load(`gapi.iframes`,{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{Or(),n(w(e,`network-request-failed`))},timeout:Dr.get()})}if(Q().gapi?.iframes?.Iframe)t(gapi.iframes.getContext());else if(Q().gapi?.load)r();else{let t=yt(`iframefcb`);return Q()[t]=()=>{gapi.load?r():n(w(e,`network-request-failed`))},gt(`${vt()}?onload=${t}`).catch(e=>n(e))}}).catch(e=>{throw Ar=null,e})}var Ar=null;function jr(e){return Ar||=kr(e),Ar}var Mr=new k(5e3,15e3),Nr=`__/auth/iframe`,Pr=`emulator/auth/iframe`,Fr={style:{position:`absolute`,top:`-100px`,width:`1px`,height:`1px`},"aria-hidden":`true`,tabindex:`-1`},Ir=new Map([[`identitytoolkit.googleapis.com`,`p`],[`staging-identitytoolkit.sandbox.googleapis.com`,`s`],[`test-identitytoolkit.sandbox.googleapis.com`,`t`]]);function Lr(e){let t=e.config;E(t.authDomain,e,`auth-domain-config-required`);let n=t.emulator?be(t,Pr):`https://${e.config.authDomain}/${Nr}`,r={apiKey:t.apiKey,appName:e.name,v:g},i=Ir.get(e.config.apiHost);i&&(r.eid=i);let a=e._getFrameworks();return a.length&&(r.fw=a.join(`,`)),`${n}?${_(r).slice(1)}`}async function Rr(e){let t=await jr(e),n=Q().gapi;return E(n,e,`internal-error`),t.open({where:document.body,url:Lr(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Fr,dontclear:!0},t=>new Promise(async(n,r)=>{await t.restyle({setHideOnLeave:!1});let i=w(e,`network-request-failed`),a=Q().setTimeout(()=>{r(i)},Mr.get());function o(){Q().clearTimeout(a),n(t)}t.ping(o).then(o,()=>{r(i)})}))}var zr={location:`yes`,resizable:`yes`,statusbar:`yes`,toolbar:`no`},Br=500,Vr=600,Hr=`_blank`,Ur=`http://localhost`,Wr=class{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}};function Gr(t,n,r,i=Br,a=Vr){let o=Math.max((window.screen.availHeight-a)/2,0).toString(),s=Math.max((window.screen.availWidth-i)/2,0).toString(),c=``,l={...zr,width:i.toString(),height:a.toString(),top:o,left:s},u=e().toLowerCase();r&&(c=$e(u)?Hr:r),Ze(u)&&(n||=Ur,l.scrollbars=`yes`);let d=Object.entries(l).reduce((e,[t,n])=>`${e}${t}=${n},`,``);if(at(u)&&c!==`_self`)return Kr(n||``,c),new Wr(null);let f=window.open(n||``,c,d);E(f,t,`popup-blocked`);try{f.focus()}catch{}return new Wr(f)}function Kr(e,t){let n=document.createElement(`a`);n.href=e,n.target=t;let r=document.createEvent(`MouseEvent`);r.initMouseEvent(`click`,!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}var qr=`__/auth/handler`,Jr=`emulator/auth/handler`,Yr=`fac`;async function Xr(e,t,n,i,a,o){E(e.config.authDomain,e,`auth-domain-config-required`),E(e.config.apiKey,e,`invalid-api-key`);let s={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:i,v:g,eventId:a};if(t instanceof Yt){t.setDefaultLanguage(e.languageCode),s.providerId=t.providerId||``,r(t.getCustomParameters())||(s.customParameters=JSON.stringify(t.getCustomParameters()));for(let[e,t]of Object.entries(o||{}))s[e]=t}if(t instanceof X){let e=t.getScopes().filter(e=>e!==``);e.length>0&&(s.scopes=e.join(`,`))}e.tenantId&&(s.tid=e.tenantId);let c=s;for(let e of Object.keys(c))c[e]===void 0&&delete c[e];let l=await e._getAppCheckToken(),u=l?`#${Yr}=${encodeURIComponent(l)}`:``;return`${Zr(e)}?${_(c).slice(1)}${u}`}function Zr({config:e}){return e.emulator?be(e,Jr):`https://${e.authDomain}/${qr}`}var Qr=`webStorageSupport`,$r=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=wn,this._completeRedirectFn=gr,this._overrideRedirectResult=pr}async _openPopup(e,t,n,r){return O(this.eventManagers[e._key()]?.manager,`_initialize() not called before _openPopup()`),Gr(e,await Xr(e,t,n,he(),r),Dn())}async _openRedirect(e,t,n,r){return await this._originValidation(e),kn(await Xr(e,t,n,he(),r)),new Promise(()=>{})}_initialize(e){let t=e._key();if(this.eventManagers[t]){let{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(O(n,`If manager is not set, promise should be`),n)}let n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(e){let t=await Rr(e),n=new vr(e);return t.register(`authEvent`,t=>(E(t?.authEvent,e,`invalid-auth-event`),{status:n.onEvent(t.authEvent)?`ACK`:`ERROR`}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(Qr,{type:Qr},n=>{let r=n?.[0]?.[Qr];r!==void 0&&t(!!r),C(e,`internal-error`)},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){let t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Tr(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return st()||Qe()||it()}},ei=class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case`enroll`:return this._finalizeEnroll(e,t.credential,n);case`signin`:return this._finalizeSignIn(e,t.credential);default:return D(`unexpected MultiFactorSessionType`)}}},ti=class e extends ei{constructor(e){super(`phone`),this.credential=e}static _fromCredential(t){return new e(t)}_finalizeEnroll(e,t,n){return dn(e,{idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return Yn(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}},ni=class{constructor(){}static assertion(e){return ti._fromCredential(e)}};ni.FACTOR_ID=`phone`;var ri=class{static assertionForEnrollment(e,t){return ii._fromSecret(e,t)}static assertionForSignIn(e,t){return ii._fromEnrollmentId(e,t)}static async generateSecret(e){let t=e;E(t.user?.auth!==void 0,`internal-error`);let n=await fn(t.user.auth,{idToken:t.credential,totpEnrollmentInfo:{}});return ai._fromStartTotpMfaEnrollmentResponse(n,t.user.auth)}};ri.FACTOR_ID=`totp`;var ii=class e extends ei{constructor(e,t,n){super(`totp`),this.otp=e,this.enrollmentId=t,this.secret=n}static _fromSecret(t,n){return new e(n,void 0,t)}static _fromEnrollmentId(t,n){return new e(n,t)}async _finalizeEnroll(e,t,n){return E(this.secret!==void 0,e,`argument-error`),pn(e,{idToken:t,displayName:n,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,t){E(this.enrollmentId!==void 0&&this.otp!==void 0,e,`argument-error`);let n={verificationCode:this.otp};return Xn(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:n})}},ai=class e{constructor(e,t,n,r,i,a,o){this.sessionInfo=a,this.auth=o,this.secretKey=e,this.hashingAlgorithm=t,this.codeLength=n,this.codeIntervalSeconds=r,this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(t,n){return new e(t.totpSessionInfo.sharedSecretKey,t.totpSessionInfo.hashingAlgorithm,t.totpSessionInfo.verificationCodeLength,t.totpSessionInfo.periodSec,new Date(t.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),t.totpSessionInfo.sessionInfo,n)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,t){let n=!1;return(oi(e)||oi(t))&&(n=!0),n&&(oi(e)&&(e=this.auth.currentUser?.email||`unknownuser`),oi(t)&&(t=this.auth.name)),`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function oi(e){return e===void 0||e?.length===0}var si=`@firebase/auth`,ci=`1.13.3`,li=class{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;let t=this.auth.onIdTokenChanged(t=>{e(t?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){E(this.auth._initializationPromise,`dependent-sdk-initialized-before-auth`)}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function ui(e){switch(e){case`Node`:return`node`;case`ReactNative`:return`rn`;case`Worker`:return`webworker`;case`Cordova`:return`cordova`;case`WebExtension`:return`web-extension`;default:return}}function di(e){m(new oe(`auth`,(t,{options:n})=>{let r=t.getProvider(`app`).getImmediate(),i=t.getProvider(`heartbeat`),a=t.getProvider(`app-check-internal`),{apiKey:o,authDomain:s}=r.options;E(o&&!o.includes(`:`),`invalid-api-key`,{appName:r.name});let c=new pt(r,i,a,{apiKey:o,authDomain:s,clientPlatform:e,apiHost:`identitytoolkit.googleapis.com`,tokenApiHost:`securetoken.googleapis.com`,apiScheme:`https`,sdkClientVersion:ct(e)});return Dt(c,n),c},`PUBLIC`).setInstantiationMode(`EXPLICIT`).setInstanceCreatedCallback((e,t,n)=>{e.getProvider(`auth-internal`).initialize()})),m(new oe(`auth-internal`,e=>(e=>new li(e))(H(e.getProvider(`auth`).getImmediate())),`PRIVATE`).setInstantiationMode(`EXPLICIT`)),re(si,ci,ui(e)),re(si,ci,`esm2020`)}var fi=l(`authIdTokenMaxAge`)||300,pi=null,mi=e=>async t=>{let n=t&&await t.getIdTokenResult(),r=n&&(new Date().getTime()-Date.parse(n.issuedAtTime))/1e3;if(r&&r>fi)return;let i=n?.token;pi!==i&&(pi=i,await fetch(e,{method:i?`POST`:`DELETE`,headers:i?{Authorization:`Bearer ${i}`}:{}}))};function hi(e=ae()){let t=ne(e,`auth`);if(t.isInitialized())return t.getImmediate();let n=Et(e,{popupRedirectResolver:$r,persistence:[qn,vn,wn]}),r=l(`authTokenSyncURL`);if(r&&typeof isSecureContext==`boolean`&&isSecureContext){let e=new URL(r,location.origin);if(location.origin===e.origin){let t=mi(e.toString());ln(n,t,()=>t(n.currentUser)),cn(n,e=>t(e))}}let i=a(`auth`);return i&&Ot(n,`http://${i}`),n}function gi(){return document.getElementsByTagName(`head`)?.[0]??document}ht({loadJS(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.setAttribute(`src`,e),r.onload=t,r.onerror=e=>{let t=w(`internal-error`);t.customData=e,n(t)},r.type=`text/javascript`,r.charset=`UTF-8`,gi().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=`}),di(`Browser`);export{hi as getAuth};
@@ -0,0 +1,4 @@
1
+ import{$ as e,A as t,E as n,G as r,J as i,L as a,M as o,N as s,O as c,P as l,Q as u,S as d,T as f,U as ee,V as te,X as ne,Y as p,_ as re,at as ie,c as ae,et as oe,g as se,it as ce,k as m,n as le,nt as ue,o as de,ot as fe,p as pe,s as me,st as h,tt as he,u as ge,v as _e,w as g,y as _,z as v}from"./index.esm-B3ZTr43m.js";var ve=`@firebase/database`,ye=`1.1.3`,be=``;function xe(e){be=e}var Se=class{constructor(e){this.domStorage_=e,this.prefix_=`firebase:`}set(e,t){t==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),h(t))}get(t){let n=this.domStorage_.getItem(this.prefixedName_(t));return n==null?null:e(n)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}},Ce=class{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){t==null?delete this.cache_[e]:this.cache_[e]=t}get(e){return m(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}},we=function(e){try{if(typeof window<`u`&&window[e]!==void 0){let t=window[e];return t.setItem(`firebase:sentinel`,`cache`),t.removeItem(`firebase:sentinel`),new Se(t)}}catch{}return new Ce},Te=we(`localStorage`),Ee=we(`sessionStorage`),De=new re(`@firebase/database`),Oe=(function(){let e=1;return function(){return e++}})(),ke=function(e){let t=fe(e),r=new d;r.update(t);let i=r.digest();return n.encodeByteArray(i)},Ae=function(...e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];Array.isArray(r)||r&&typeof r==`object`&&typeof r.length==`number`?t+=Ae.apply(null,r):typeof r==`object`?t+=h(r):t+=r,t+=` `}return t},y=null,je=!0,Me=function(e,t){g(!t||e===!0||e===!1,`Can't turn on custom loggers persistently.`),e===!0?(De.logLevel=se.VERBOSE,y=De.log.bind(De),t&&Ee.set(`logging_enabled`,!0)):typeof e==`function`?y=e:(y=null,Ee.remove(`logging_enabled`))},b=function(...e){if(je===!0&&(je=!1,y===null&&Ee.get(`logging_enabled`)===!0&&Me(!0)),y){let t=Ae.apply(null,e);y(t)}},Ne=function(e){return function(...t){b(e,...t)}},Pe=function(...e){let t=`FIREBASE INTERNAL ERROR: `+Ae(...e);De.error(t)},x=function(...e){let t=`FIREBASE FATAL ERROR: ${Ae(...e)}`;throw De.error(t),Error(t)},S=function(...e){let t=`FIREBASE WARNING: `+Ae(...e);De.warn(t)},Fe=function(){typeof window<`u`&&window.location&&window.location.protocol&&window.location.protocol.indexOf(`https:`)!==-1&&S(`Insecure Firebase access from a secure page. Please use https in calls to new Firebase().`)},Ie=function(e){return typeof e==`number`&&(e!==e||e===1/0||e===-1/0)},Le=function(e){if(p()||document.readyState===`complete`)e();else{let t=!1,n=function(){if(!document.body){setTimeout(n,10);return}t||(t=!0,e())};document.addEventListener?(document.addEventListener(`DOMContentLoaded`,n,!1),window.addEventListener(`load`,n,!1)):document.attachEvent&&(document.attachEvent(`onreadystatechange`,()=>{document.readyState===`complete`&&n()}),window.attachEvent(`onload`,n))}},Re=`[MIN_NAME]`,C=`[MAX_NAME]`,w=function(e,t){if(e===t)return 0;if(e===Re||t===C)return-1;if(t===Re||e===C)return 1;{let n=Xe(e),r=Xe(t);return n===null?r===null&&e<t?-1:1:r===null?-1:n-r===0?e.length-t.length:n-r}},ze=function(e,t){return e===t?0:e<t?-1:1},Be=function(e,t){if(t&&e in t)return t[e];throw Error(`Missing required key (`+e+`) in object: `+h(t))},Ve=function(e){if(typeof e!=`object`||!e)return h(e);let t=[];for(let n in e)t.push(n);t.sort();let n=`{`;for(let r=0;r<t.length;r++)r!==0&&(n+=`,`),n+=h(t[r]),n+=`:`,n+=Ve(e[t[r]]);return n+=`}`,n},He=function(e,t){let n=e.length;if(n<=t)return[e];let r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r};function T(e,t){for(let n in e)e.hasOwnProperty(n)&&t(n,e[n])}var Ue=function(e){g(!Ie(e),`Invalid JSON number`);let t=1023,n,r,i,a,o;e===0?(r=0,i=0,n=+(1/e==-1/0)):(n=e<0,e=Math.abs(e),e>=2**(1-t)?(a=Math.min(Math.floor(Math.log(e)/Math.LN2),t),r=a+t,i=Math.round(e*2**(52-a)-2**52)):(r=0,i=Math.round(e/2**(1-t-52))));let s=[];for(o=52;o;--o)s.push(i%2?1:0),i=Math.floor(i/2);for(o=11;o;--o)s.push(r%2?1:0),r=Math.floor(r/2);s.push(+!!n),s.reverse();let c=s.join(``),l=``;for(o=0;o<64;o+=8){let e=parseInt(c.substr(o,8),2).toString(16);e.length===1&&(e=`0`+e),l+=e}return l.toLowerCase()},We=function(){return!!(typeof window==`object`&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},Ge=function(){return typeof Windows==`object`&&typeof Windows.UI==`object`};function Ke(e,t){let n=`Unknown Error`;e===`too_big`?n=`The data requested exceeds the maximum size that can be accessed with a single request.`:e===`permission_denied`?n=`Client doesn't have permission to access the desired data.`:e===`unavailable`&&(n=`The service is unavailable`);let r=Error(e+` at `+t._path.toString()+`: `+n);return r.code=e.toUpperCase(),r}var qe=RegExp(`^-?(0*)\\d{1,10}$`),Je=-2147483648,Ye=2147483647,Xe=function(e){if(qe.test(e)){let t=Number(e);if(t>=Je&&t<=Ye)return t}return null},Ze=function(e){try{e()}catch(e){setTimeout(()=>{throw S(`Exception was thrown by user callback.`,e.stack||``),e},0)}},Qe=function(){return(typeof window==`object`&&window.navigator&&window.navigator.userAgent||``).search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},$e=function(e,t){let n=setTimeout(e,t);return typeof n==`number`&&typeof Deno<`u`&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n==`object`&&n.unref&&n.unref(),n},et=class{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,me(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(e=>this.appCheck=e)}getToken(e){if(this.serverAppAppCheckToken){if(e)throw Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise((t,n)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.appCheckProvider?.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){S(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}},tt=class{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(e=>e&&e.code===`auth/token-not-initialized`?(b(`Got auth/token-not-initialized error. Treating as null token.`),null):Promise.reject(e)):new Promise((t,n)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}notifyForInvalidToken(){let e=`Provided authentication credentials for the app named "`+this.appName_+`" are invalid. This usually indicates your app was not initialized correctly. `;`credential`in this.firebaseOptions_?e+=`Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.`:`serviceAccount`in this.firebaseOptions_?e+=`Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.`:e+=`Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.`,S(e)}},nt=class{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}};nt.OWNER=`owner`;var rt=`5`,it=`v`,at=`s`,ot=`r`,st=`f`,ct=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,lt=`ls`,ut=`p`,dt=`ac`,ft=`websocket`,pt=`long_polling`,mt=class{constructor(e,t,n,r,i=!1,a=``,o=!1,s=!1,c=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=a,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=s,this.emulatorOptions=c,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(`.`)+1),this.internalHost=Te.get(`host:`+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)===`s-`}isCustomHost(){return this._domain!==`firebaseio.com`&&this._domain!==`firebaseio-demo.com`}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&Te.set(`host:`+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+=`<`+this.persistenceKey+`>`),e}toURLString(){let e=this.secure?`https://`:`http://`,t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:``;return`${e}${this.host}/${t}`}};function ht(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams}function gt(e,t,n){g(typeof t==`string`,`typeof type must == string`),g(typeof n==`object`,`typeof params must == object`);let r;if(t===ft)r=(e.secure?`wss://`:`ws://`)+e.internalHost+`/.ws?`;else if(t===pt)r=(e.secure?`https://`:`http://`)+e.internalHost+`/.lp?`;else throw Error(`Unknown connection type: `+t);ht(e)&&(n.ns=e.namespace);let i=[];return T(n,(e,t)=>{i.push(e+`=`+t)}),r+i.join(`&`)}var _t=class{constructor(){this.counters_={}}incrementCounter(e,t=1){m(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return o(this.counters_)}},vt={},yt={};function bt(e){let t=e.toString();return vt[t]||(vt[t]=new _t),vt[t]}function xt(e,t){let n=e.toString();return yt[n]||(yt[n]=t()),yt[n]}var St=class{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&Ze(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&=(this.onClose(),null);break}this.currentResponseNum++}}},Ct=`start`,wt=`close`,Tt=`pLPCommand`,Et=`pRTLPCB`,Dt=`id`,Ot=`pw`,kt=`ser`,At=`cb`,jt=`dframe`,Mt=1870,Nt=30,Pt=Mt-Nt,Ft=25e3,It=3e4,Lt=class e{constructor(e,t,n,r,i,a,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=a,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Ne(e),this.stats_=bt(t),this.urlFn=e=>(this.appCheckToken&&(e[dt]=this.appCheckToken),gt(t,pt,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new St(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_(`Timed out trying to connect.`),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(It)),Le(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Rt((...e)=>{let[t,n,r,i,a]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&=(clearTimeout(this.connectTimeoutTimer_),null),this.everConnected_=!0,t===Ct)this.id=n,this.password=r;else if(t===wt)n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_();else throw Error(`Unrecognized command received: `+t)},(...e)=>{let[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);let e={};e[Ct]=`t`,e[kt]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(e[At]=this.scriptTagHolder.uniqueCallbackIdentifier),e[it]=rt,this.transportSessionId&&(e[at]=this.transportSessionId),this.lastSessionId&&(e[lt]=this.lastSessionId),this.applicationId&&(e[ut]=this.applicationId),this.appCheckToken&&(e[dt]=this.appCheckToken),typeof location<`u`&&location.hostname&&ct.test(location.hostname)&&(e[ot]=st);let t=this.urlFn(e);this.log_(`Connecting via long-poll to `+t),this.scriptTagHolder.addTag(t,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){e.forceAllow_=!0}static forceDisallow(){e.forceDisallow_=!0}static isAvailable(){return p()?!1:e.forceAllow_?!0:!e.forceDisallow_&&typeof document<`u`&&document.createElement!=null&&!We()&&!Ge()}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&=(this.scriptTagHolder.close(),null),this.myDisconnFrame&&=(document.body.removeChild(this.myDisconnFrame),null),this.connectTimeoutTimer_&&=(clearTimeout(this.connectTimeoutTimer_),null)}onClosed_(){this.isClosed_||(this.log_(`Longpoll is closing itself`),this.shutdown_(),this.onDisconnect_&&=(this.onDisconnect_(this.everConnected_),null))}close(){this.isClosed_||(this.log_(`Longpoll is being closed.`),this.shutdown_())}send(e){let t=h(e);this.bytesSent+=t.length,this.stats_.incrementCounter(`bytes_sent`,t.length);let n=He(c(t),Pt);for(let e=0;e<n.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if(p())return;this.myDisconnFrame=document.createElement(`iframe`);let n={};n[jt]=`t`,n[Dt]=e,n[Ot]=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display=`none`,document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){let t=h(e).length;this.bytesReceived+=t,this.stats_.incrementCounter(`bytes_received`,t)}},Rt=class e{constructor(t,n,r,i){if(this.onDisconnect=r,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0,p())this.commandCB=t,this.onMessageCB=n;else{this.uniqueCallbackIdentifier=Oe(),window[Tt+this.uniqueCallbackIdentifier]=t,window[Et+this.uniqueCallbackIdentifier]=n,this.myIFrame=e.createIFrame_();let r=``;this.myIFrame.src&&this.myIFrame.src.substr(0,11)===`javascript:`&&(r=`<script>document.domain="`+document.domain+`";<\/script>`);let i=`<html><body>`+r+`</body></html>`;try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){b(`frame writing exception`),e.stack&&b(e.stack),b(e)}}}static createIFrame_(){let e=document.createElement(`iframe`);if(e.style.display=`none`,document.body){document.body.appendChild(e);try{e.contentWindow.document||b(`No IE domain setting required`)}catch{e.src=`javascript:void((function(){document.open();document.domain='`+document.domain+`';document.close();})())`}}else throw`Document body has not initialized. Wait to initialize Firebase until after the document is ready.`;return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent=``,setTimeout(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},0));let e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;let e={};e[Dt]=this.myID,e[Ot]=this.myPW,e[kt]=this.currentSerial;let t=this.urlFn(e),n=``,r=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+Nt+n.length<=Mt;){let e=this.pendingSegs.shift();n=n+`&seg`+r+`=`+e.seg+`&ts`+r+`=`+e.ts+`&d`+r+`=`+e.d,r++}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}else return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(Ft));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,t){p()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;let n=this.myIFrame.doc.createElement(`script`);n.type=`text/javascript`,n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){let e=n.readyState;(!e||e===`loaded`||e===`complete`)&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{b(`Long-poll script failed to load: `+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch{}},1)}},zt=16384,Bt=45e3,Vt=null;typeof MozWebSocket<`u`?Vt=MozWebSocket:typeof WebSocket<`u`&&(Vt=WebSocket);var E=class t{constructor(e,n,r,i,a,o,s){this.connId=e,this.applicationId=r,this.appCheckToken=i,this.authToken=a,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Ne(this.connId),this.stats_=bt(n),this.connURL=t.connectionURL_(n,o,s,i,r),this.nodeAdmin=n.nodeAdmin}static connectionURL_(e,t,n,r,i){let a={};return a[it]=rt,!p()&&typeof location<`u`&&location.hostname&&ct.test(location.hostname)&&(a[ot]=st),t&&(a[at]=t),n&&(a[lt]=n),r&&(a[dt]=r),i&&(a[ut]=i),gt(e,ft,a)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_(`Websocket connecting to `+this.connURL),this.everConnected_=!1,Te.set(`previous_websocket_failure`,!0);try{let e;if(p()){let t=this.nodeAdmin?`AdminNode`:`Node`;e={headers:{"User-Agent":`Firebase/${rt}/${be}/${process.platform}/${t}`,"X-Firebase-GMPID":this.applicationId||``}},this.authToken&&(e.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(e.headers[`X-Firebase-AppCheck`]=this.appCheckToken);let n={},r=this.connURL.indexOf(`wss://`)===0?n.HTTPS_PROXY||n.https_proxy:n.HTTP_PROXY||n.http_proxy;r&&(e.proxy={origin:r})}this.mySock=new Vt(this.connURL,[],e)}catch(e){this.log_(`Error instantiating WebSocket.`);let t=e.message||e.data;t&&this.log_(t),this.onClosed_();return}this.mySock.onopen=()=>{this.log_(`Websocket connected.`),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_(`Websocket connection was disconnected.`),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_(`WebSocket error. Closing connection.`);let t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){t.forceDisallow_=!0}static isAvailable(){let e=!1;if(typeof navigator<`u`&&navigator.userAgent){let t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);t&&t.length>1&&parseFloat(t[1])<4.4&&(e=!0)}return!e&&Vt!==null&&!t.forceDisallow_}static previouslyFailed(){return Te.isInMemoryStorage||Te.get(`previous_websocket_failure`)===!0}markConnectionHealthy(){Te.remove(`previous_websocket_failure`)}appendFrame_(t){if(this.frames.push(t),this.frames.length===this.totalFrames){let t=this.frames.join(``);this.frames=null;let n=e(t);this.onMessage(n)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(g(this.frames===null,`We already have a frame buffer`),e.length<=6){let t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(this.mySock===null)return;let t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter(`bytes_received`,t.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(t);else{let e=this.extractFrameCount_(t);e!==null&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();let t=h(e);this.bytesSent+=t.length,this.stats_.incrementCounter(`bytes_sent`,t.length);let n=He(t,zt);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&=(clearInterval(this.keepaliveTimer),null),this.mySock&&=(this.mySock.close(),null)}onClosed_(){this.isClosed_||(this.log_(`WebSocket is closing itself`),this.shutdown_(),this.onDisconnect&&=(this.onDisconnect(this.everConnected_),null))}close(){this.isClosed_||(this.log_(`WebSocket is being closed`),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_(`0`),this.resetKeepAlive()},Math.floor(Bt))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_(`Exception thrown from WebSocket.send():`,e.message||e.data,`Closing connection.`),setTimeout(this.onClosed_.bind(this),0)}}};E.responsesRequiredToBeHealthy=2,E.healthyTimeout=3e4;var Ht=class e{static get ALL_TRANSPORTS(){return[Lt,E]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(t){let n=E&&E.isAvailable(),r=n&&!E.previouslyFailed();if(t.webSocketOnly&&(n||S(`wss:// URL used, but browser isn't known to support websockets. Trying anyway.`),r=!0),r)this.transports_=[E];else{let t=this.transports_=[];for(let n of e.ALL_TRANSPORTS)n&&n.isAvailable()&&t.push(n);e.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw Error(`No transports available`)}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}};Ht.globalTransportInitialized_=!1;var Ut=6e4,Wt=5e3,Gt=10*1024,Kt=100*1024,qt=`t`,Jt=`d`,Yt=`s`,Xt=`r`,Zt=`e`,Qt=`o`,$t=`a`,en=`n`,tn=`p`,nn=`h`,rn=class{constructor(e,t,n,r,i,a,o,s,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=a,this.onReady_=o,this.onDisconnect_=s,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Ne(`c:`+this.id+`:`),this.transportManager_=new Ht(t),this.log_(`Connection created`),this.start_()}start_(){let e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},0);let r=e.healthyTimeout||0;r>0&&(this.healthyTimeout_=$e(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>Kt?(this.log_(`Connection exceeded healthy timeout but has received `+this.conn_.bytesReceived+` bytes. Marking connection healthy.`),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>Gt?this.log_(`Connection exceeded healthy timeout but has sent `+this.conn_.bytesSent+` bytes. Leaving connection alive.`):(this.log_(`Closing unhealthy connection after timeout.`),this.close()))},Math.floor(r)))}nextTransportId_(){return`c:`+this.id+`:`+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_(`Secondary connection lost.`),this.onSecondaryConnectionLost_()):this.log_(`closing an old connection`)}}connReceiver_(e){return t=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_(`message on old connection`))}}sendRequest(e){let t={t:`d`,d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_(`cleaning up and promoting a connection: `+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if(qt in e){let t=e[qt];t===$t?this.upgradeIfSecondaryHealthy_():t===Xt?(this.log_(`Got a reset on secondary, closing it`),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):t===Qt&&(this.log_(`got pong on secondary.`),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let t=Be(`t`,e),n=Be(`d`,e);if(t===`c`)this.onSecondaryControl_(n);else if(t===`d`)this.pendingDataMessages.push(n);else throw Error(`Unknown protocol layer: `+t)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_(`Secondary connection is healthy.`),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_(`sending ping on secondary.`),this.secondaryConn_.send({t:`c`,d:{t:tn,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_(`sending client ack on secondary`),this.secondaryConn_.send({t:`c`,d:{t:$t,d:{}}}),this.log_(`Ending transmission on primary`),this.conn_.send({t:`c`,d:{t:en,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let t=Be(`t`,e),n=Be(`d`,e);t===`c`?this.onControl_(n):t===`d`&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_(`Primary connection is healthy.`),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){let t=Be(qt,e);if(Jt in e){let n=e[Jt];if(t===nn){let e={...n};this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if(t===en){this.log_(`recvd end transmission on primary`),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else t===Yt?this.onConnectionShutdown_(n):t===Xt?this.onReset_(n):t===Zt?Pe(`Server Error: `+n):t===Qt?(this.log_(`got pong on primary.`),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Pe(`Unknown control packet command: `+t)}}onHandshake_(e){let t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),rt!==n&&S(`Protocol version mismatch detected`),this.tryStartUpgrade_())}tryStartUpgrade_(){let e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),$e(()=>{this.secondaryConn_&&(this.log_(`Timed out trying to upgrade.`),this.secondaryConn_.close())},Math.floor(Ut))}onReset_(e){this.log_(`Reset packet received. New host: `+e),this.repoInfo_.host=e,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_(`Realtime connection established.`),this.conn_=e,this.state_=1,this.onReady_&&=(this.onReady_(t,this.sessionId),null),this.primaryResponsesRequired_===0?(this.log_(`Primary connection is healthy.`),this.isHealthy_=!0):$e(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(Wt))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_(`sending ping on primary.`),this.sendData_({t:`c`,d:{t:tn,d:{}}}))}onSecondaryConnectionLost_(){let e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_(`Realtime connection failed.`),this.repoInfo_.isCacheableHost()&&(Te.remove(`host:`+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_(`Realtime connection lost.`),this.close()}onConnectionShutdown_(e){this.log_(`Connection shutdown command received. Shutting down...`),this.onKill_&&=(this.onKill_(e),null),this.onDisconnect_=null,this.close()}sendData_(e){if(this.state_!==1)throw`Connection is not connected`;this.tx_.send(e)}close(){this.state_!==2&&(this.log_(`Closing realtime connection.`),this.state_=2,this.closeConnections_(),this.onDisconnect_&&=(this.onDisconnect_(),null))}closeConnections_(){this.log_(`Shutting down all connections`),this.conn_&&=(this.conn_.close(),null),this.secondaryConn_&&=(this.secondaryConn_.close(),null),this.healthyTimeout_&&=(clearTimeout(this.healthyTimeout_),null)}},an=class{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}},on=class{constructor(e){this.allowedEvents_=e,this.listeners_={},g(Array.isArray(e)&&e.length>0,`Requires a non-empty array`)}trigger(e,...t){if(Array.isArray(this.listeners_[e])){let n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});let r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);let r=this.listeners_[e]||[];for(let e=0;e<r.length;e++)if(r[e].callback===t&&(!n||n===r[e].context)){r.splice(e,1);return}}validateEventType_(e){g(this.allowedEvents_.find(t=>t===e),`Unknown event: `+e)}},sn=class e extends on{static getInstance(){return new e}constructor(){super([`online`]),this.online_=!0,typeof window<`u`&&window.addEventListener!==void 0&&!i()&&(window.addEventListener(`online`,()=>{this.online_||(this.online_=!0,this.trigger(`online`,!0))},!1),window.addEventListener(`offline`,()=>{this.online_&&(this.online_=!1,this.trigger(`online`,!1))},!1))}getInitialEvent(e){return g(e===`online`,`Unknown event type: `+e),[this.online_]}currentlyOnline(){return this.online_}},cn=32,ln=768,D=class{constructor(e,t){if(t===void 0){this.pieces_=e.split(`/`);let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e=``;for(let t=this.pieceNum_;t<this.pieces_.length;t++)this.pieces_[t]!==``&&(e+=`/`+this.pieces_[t]);return e||`/`}};function O(){return new D(``)}function k(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function A(e){return e.pieces_.length-e.pieceNum_}function j(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new D(e.pieces_,t)}function un(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function dn(e){let t=``;for(let n=e.pieceNum_;n<e.pieces_.length;n++)e.pieces_[n]!==``&&(t+=`/`+encodeURIComponent(String(e.pieces_[n])));return t||`/`}function fn(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function pn(e){if(e.pieceNum_>=e.pieces_.length)return null;let t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new D(t,0)}function M(e,t){let n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof D)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{let e=t.split(`/`);for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new D(n,0)}function N(e){return e.pieceNum_>=e.pieces_.length}function P(e,t){let n=k(e),r=k(t);if(n===null)return t;if(n===r)return P(j(e),j(t));throw Error(`INTERNAL ERROR: innerPath (`+t+`) is not within outerPath (`+e+`)`)}function mn(e,t){let n=fn(e,0),r=fn(t,0);for(let e=0;e<n.length&&e<r.length;e++){let t=w(n[e],r[e]);if(t!==0)return t}return n.length===r.length?0:n.length<r.length?-1:1}function hn(e,t){if(A(e)!==A(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function F(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(A(e)>A(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}var gn=class{constructor(e,t){this.errorPrefix_=t,this.parts_=fn(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=ie(this.parts_[e]);yn(this)}};function _n(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=ie(t),yn(e)}function vn(e){let t=e.parts_.pop();e.byteLength_-=ie(t),e.parts_.length>0&&--e.byteLength_}function yn(e){if(e.byteLength_>ln)throw Error(e.errorPrefix_+`has a key path longer than 768 bytes (`+e.byteLength_+`).`);if(e.parts_.length>cn)throw Error(e.errorPrefix_+`path specified exceeds the maximum depth that can be written (32) or object contains a cycle `+I(e))}function I(e){return e.parts_.length===0?``:`in property '`+e.parts_.join(`.`)+`'`}var bn=class e extends on{static getInstance(){return new e}constructor(){super([`visible`]);let e,t;typeof document<`u`&&document.addEventListener!==void 0&&(document.hidden===void 0?document.mozHidden===void 0?document.msHidden===void 0?document.webkitHidden!==void 0&&(t=`webkitvisibilitychange`,e=`webkitHidden`):(t=`msvisibilitychange`,e=`msHidden`):(t=`mozvisibilitychange`,e=`mozHidden`):(t=`visibilitychange`,e=`hidden`)),this.visible_=!0,t&&document.addEventListener(t,()=>{let t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger(`visible`,t))},!1)}getInitialEvent(e){return g(e===`visible`,`Unknown event type: `+e),[this.visible_]}},xn=1e3,Sn=300*1e3,Cn=30*1e3,wn=1.3,Tn=3e4,En=`server_kill`,Dn=3,On=class e extends an{constructor(t,n,r,i,a,o,s,c){if(super(),this.repoInfo_=t,this.applicationId_=n,this.onDataUpdate_=r,this.onConnectStatus_=i,this.onServerInfoUpdate_=a,this.authTokenProvider_=o,this.appCheckTokenProvider_=s,this.authOverride_=c,this.id=e.nextPersistentConnectionId_++,this.log_=Ne(`p:`+this.id+`:`),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=xn,this.maxReconnectDelay_=Sn,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,c&&!p())throw Error(`Auth override specified in options, but not supported on non Node.js platforms`);bn.getInstance().on(`visible`,this.onVisible_,this),t.host.indexOf(`fblocal`)===-1&&sn.getInstance().on(`online`,this.onOnline_,this)}sendRequest(e,t,n){let r=++this.requestNumber_,i={r,a:e,b:t};this.log_(h(i)),g(this.connected_,`sendRequest call when we're not connected not allowed.`),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();let t=new _,n={action:`g`,request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{let n=e.d;e.s===`ok`?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;let r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,t,n,r){this.initConnection_();let i=e._queryIdentifier,a=e._path.toString();this.log_(`Listen called for `+a+` `+i),this.listens.has(a)||this.listens.set(a,new Map),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),`listen() called for non-default but complete query`),g(!this.listens.get(a).has(i),`listen() called twice for same path/queryId.`);let o={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(a).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(e){let t=this.outstandingGets_[e];this.sendRequest(`g`,t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(t){let n=t.query,r=n._path.toString(),i=n._queryIdentifier;this.log_(`Listen on `+r+` for `+i);let a={p:r};t.tag&&(a.q=n._queryObject,a.t=t.tag),a.h=t.hashFn(),this.sendRequest(`q`,a,a=>{let o=a.d,s=a.s;e.warnOnListenWarnings_(o,n),(this.listens.get(r)&&this.listens.get(r).get(i))===t&&(this.log_(`listen response`,a),s!==`ok`&&this.removeListen_(r,i),t.onComplete&&t.onComplete(s,o))})}static warnOnListenWarnings_(e,t){if(e&&typeof e==`object`&&m(e,`w`)){let n=ce(e,`w`);Array.isArray(n)&&~n.indexOf(`no_index`)&&S(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${`".indexOn": "`+t._queryParams.getIndex().toString()+`"`} at ${t._path.toString()} to your security rules for better performance.`)}}refreshAuthToken(e){this.authToken_=e,this.log_(`Auth token refreshed`),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest(`unauth`,{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&e.length===40||te(e))&&(this.log_(`Admin auth credential detected. Reducing max reconnect time.`),this.maxReconnectDelay_=Cn)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_(`App check token refreshed`),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest(`unappeck`,{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let e=this.authToken_,t=u(e)?`auth`:`gauth`,n={cred:e};this.authOverride_===null?n.noauth=!0:typeof this.authOverride_==`object`&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{let n=t.s,r=t.d||`error`;this.authToken_===e&&(n===`ok`?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,r))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest(`appcheck`,{token:this.appCheckToken_},e=>{let t=e.s,n=e.d||`error`;t===`ok`?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){let n=e._path.toString(),r=e._queryIdentifier;this.log_(`Unlisten called for `+n+` `+r),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),`unlisten() called for non-default but complete query`),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_(`Unlisten on `+e+` for `+t);let i={p:e};r&&(i.q=n,i.t=r),this.sendRequest(`n`,i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_(`o`,e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:`o`,data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_(`om`,e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:`om`,data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_(`oc`,e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:`oc`,data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){let i={p:t,d:n};this.log_(`onDisconnect `+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},0)})}put(e,t,n,r){this.putInternal(`p`,e,t,n,r)}merge(e,t,n,r){this.putInternal(`m`,e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();let a={p:t,d:n};i!==void 0&&(a.h=i),this.outstandingPuts_.push({action:e,request:a,onComplete:r}),this.outstandingPutCount_++;let o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_(`Buffering put: `+t)}sendPut_(e){let t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,r=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,n=>{this.log_(t+` response`,n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),r&&r(n.s,n.d)})}reportStats(e){if(this.connected_){let t={c:e};this.log_(`reportStats`,t),this.sendRequest(`s`,t,e=>{if(e.s!==`ok`){let t=e.d;this.log_(`reportStats`,`Error sending stats: `+t)}})}}onDataMessage_(e){if(`r`in e){this.log_(`from server: `+h(e));let t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else if(`error`in e)throw`A server-side error has occurred: `+e.error;else`a`in e&&this.onDataPush_(e.a,e.b)}onDataPush_(e,t){this.log_(`handleServerMessage`,e,t),e===`d`?this.onDataUpdate_(t.p,t.d,!1,t.t):e===`m`?this.onDataUpdate_(t.p,t.d,!0,t.t):e===`c`?this.onListenRevoked_(t.p,t.q):e===`ac`?this.onAuthRevoked_(t.s,t.d):e===`apc`?this.onAppCheckRevoked_(t.s,t.d):e===`sd`?this.onSecurityDebugPacket_(t):Pe(`Unrecognized action received from server: `+h(e)+`
2
+ Are you using the latest client?`)}onReady_(e,t){this.log_(`connection ready`),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){g(!this.realtime_,`Scheduling a connect when we're already connected/ing?`),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_(`Window became visible. Reducing delay.`),this.reconnectDelay_=xn,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_(`Browser went online.`),this.reconnectDelay_=xn,this.realtime_||this.scheduleConnect_(0)):(this.log_(`Browser went offline. Killing connection.`),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_(`data client disconnected`),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&=(new Date().getTime()-this.lastConnectionEstablishedTime_>Tn&&(this.reconnectDelay_=xn),null):(this.log_(`Window isn't visible. Delaying reconnect.`),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());let e=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_),t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_(`Trying to reconnect in `+t+`ms`),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*wn)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_(`Making a connection attempt`),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;let t=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+`:`+e.nextConnectionId_++,a=this.lastSessionId,o=!1,s=null,c=function(){s?s.close():(o=!0,r())},l=function(e){g(s,`sendRequest call when we're not connected not allowed.`),s.sendRequest(e)};this.realtime_={close:c,sendRequest:l};let u=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{let[e,c]=await Promise.all([this.authTokenProvider_.getToken(u),this.appCheckTokenProvider_.getToken(u)]);o?b(`getToken() completed but was canceled`):(b(`getToken() completed. Creating connection.`),this.authToken_=e&&e.accessToken,this.appCheckToken_=c&&c.token,s=new rn(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,t,n,r,e=>{S(e+` (`+this.repoInfo_.toString()+`)`),this.interrupt(En)},a))}catch(e){this.log_(`Failed to get token: `+e),o||(this.repoInfo_.nodeAdmin&&S(e),c())}}}interrupt(e){b(`Interrupting connection for reason: `+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&=(clearTimeout(this.establishConnectionTimer_),null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){b(`Resuming connection for reason: `+e),delete this.interruptReasons_[e],r(this.interruptReasons_)&&(this.reconnectDelay_=xn,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){let t=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){let t=this.outstandingPuts_[e];t&&`h`in t.request&&t.queued&&(t.onComplete&&t.onComplete(`disconnect`),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>Ve(e)).join(`$`):`default`;let r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete(`permission_denied`)}removeListen_(e,t){let n=new D(e).toString(),r;if(this.listens.has(n)){let e=this.listens.get(n);r=e.get(t),e.delete(t),e.size===0&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){b(`Auth token revoked: `+e+`/`+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e===`invalid_token`||e===`permission_denied`)&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=Dn&&(this.reconnectDelay_=Cn,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){b(`App check token revoked: `+e+`/`+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e===`invalid_token`||e===`permission_denied`)&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=Dn&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):`msg`in e&&console.log(`FIREBASE: `+e.msg.replace(`
3
+ `,`
4
+ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(let e of this.listens.values())for(let t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){let e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){let e={},t=`js`;p()&&(t=this.repoInfo_.nodeAdmin?`admin_node`:`node`),e[`sdk.`+t+`.`+be.replace(/\./g,`-`)]=1,i()?e[`framework.cordova`]=1:ne()&&(e[`framework.reactnative`]=1),this.reportStats(e)}shouldReconnect_(){let e=sn.getInstance().currentlyOnline();return r(this.interruptReasons_)&&e}};On.nextPersistentConnectionId_=0,On.nextConnectionId_=0;var L=class e{constructor(e,t){this.name=e,this.node=t}static Wrap(t,n){return new e(t,n)}},kn=class{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){let n=new L(Re,e),r=new L(Re,t);return this.compare(n,r)!==0}minPost(){return L.MIN}},An,jn=class extends kn{static get __EMPTY_NODE(){return An}static set __EMPTY_NODE(e){An=e}compare(e,t){return w(e.name,t.name)}isDefinedOn(e){throw f(`KeyIndex.isDefinedOn not expected to be called.`)}indexedValueChanged(e,t){return!1}minPost(){return L.MIN}maxPost(){return new L(C,An)}makePost(e,t){return g(typeof e==`string`,`KeyIndex indexValue must always be a string.`),new L(e,An)}toString(){return`.key`}},Mn=new jn,Nn=class{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let a=1;for(;!e.isEmpty();)if(e=e,a=t?n(e.key,t):1,r&&(a*=-1),a<0)e=this.isReverse_?e.left:e.right;else if(a===0){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}getNext(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}},R=class e{constructor(t,n,r,i,a){this.key=t,this.value=n,this.color=r??e.RED,this.left=i??z.EMPTY_NODE,this.right=a??z.EMPTY_NODE}copy(t,n,r,i,a){return new e(t??this.key,n??this.value,r??this.color,i??this.left,a??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this,i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):i===0?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return z.EMPTY_NODE;let e=this;return!e.left.isRed_()&&!e.left.left.isRed_()&&(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)!n.left.isEmpty()&&!n.left.isRed_()&&!n.left.left.isRed_()&&(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),!n.right.isEmpty()&&!n.right.isRed_()&&!n.right.left.isRed_()&&(n=n.moveRedRight_()),t(e,n.key)===0){if(n.right.isEmpty())return z.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){let t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}rotateRight_(){let t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}colorFlip_(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){return 2**this.check_()<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw Error(`Red node has red child(`+this.key+`,`+this.value+`)`);if(this.right.isRed_())throw Error(`Right child of (`+this.key+`,`+this.value+`) is red`);let e=this.left.check_();if(e!==this.right.check_())throw Error(`Black depths differ`);return e+ +!this.isRed_()}};R.RED=!0,R.BLACK=!1;var Pn=class{copy(e,t,n,r,i){return this}insert(e,t,n){return new R(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}},z=class e{constructor(t,n=e.EMPTY_NODE){this.comparator_=t,this.root_=n}insert(t,n){return new e(this.comparator_,this.root_.insert(t,n,this.comparator_).copy(null,null,R.BLACK,null,null))}remove(t){return new e(this.comparator_,this.root_.remove(t,this.comparator_).copy(null,null,R.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),t===0)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();)if(t=this.comparator_(e,n.key),t===0)if(!n.left.isEmpty()){for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}else if(r)return r.key;else return null;else t<0?n=n.left:t>0&&(r=n,n=n.right);throw Error(`Attempted to find predecessor key for a nonexistent key. What gives?`)}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Nn(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Nn(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Nn(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Nn(this.root_,null,this.comparator_,!0,e)}};z.EMPTY_NODE=new Pn;function Fn(e,t){return w(e.name,t.name)}function In(e,t){return w(e,t)}var Ln;function Rn(e){Ln=e}var zn=function(e){return typeof e==`number`?`number:`+Ue(e):`string:`+e},Bn=function(e){if(e.isLeafNode()){let t=e.val();g(typeof t==`string`||typeof t==`number`||typeof t==`object`&&m(t,`.sv`),`Priority must be a string or number.`)}else g(e===Ln||e.isEmpty(),`priority of unexpected type.`);g(e===Ln||e.getPriority().isEmpty(),`Priority nodes can't have a priority of their own.`)},Vn,B=class e{static set __childrenNodeConstructor(e){Vn=e}static get __childrenNodeConstructor(){return Vn}constructor(t,n=e.__childrenNodeConstructor.EMPTY_NODE){this.value_=t,this.priorityNode_=n,this.lazyHash_=null,g(this.value_!==void 0&&this.value_!==null,`LeafNode shouldn't be created with null/undefined value.`),Bn(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(t){return new e(this.value_,t)}getImmediateChild(t){return t===`.priority`?this.priorityNode_:e.__childrenNodeConstructor.EMPTY_NODE}getChild(t){return N(t)?this:k(t)===`.priority`?this.priorityNode_:e.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(t,n){return t===`.priority`?this.updatePriority(n):n.isEmpty()&&t!==`.priority`?this:e.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(t,n).updatePriority(this.priorityNode_)}updateChild(t,n){let r=k(t);return r===null?n:n.isEmpty()&&r!==`.priority`?this:(g(r!==`.priority`||A(t)===1,`.priority must be the last token in a path`),this.updateImmediateChild(r,e.__childrenNodeConstructor.EMPTY_NODE.updateChild(j(t),n)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let e=``;this.priorityNode_.isEmpty()||(e+=`priority:`+zn(this.priorityNode_.val())+`:`);let t=typeof this.value_;e+=t+`:`,t===`number`?e+=Ue(this.value_):e+=this.value_,this.lazyHash_=ke(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(t){return t===e.__childrenNodeConstructor.EMPTY_NODE?1:t instanceof e.__childrenNodeConstructor?-1:(g(t.isLeafNode(),`Unknown node type`),this.compareToLeafNode_(t))}compareToLeafNode_(t){let n=typeof t.value_,r=typeof this.value_,i=e.VALUE_TYPE_ORDER.indexOf(n),a=e.VALUE_TYPE_ORDER.indexOf(r);return g(i>=0,`Unknown leaf type: `+n),g(a>=0,`Unknown leaf type: `+r),i===a?r===`object`?0:this.value_<t.value_?-1:this.value_===t.value_?0:1:a-i}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){let t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}else return!1}};B.VALUE_TYPE_ORDER=[`object`,`boolean`,`number`,`string`];var Hn,Un;function Wn(e){Hn=e}function Gn(e){Un=e}var V=new class extends kn{compare(e,t){let n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return i===0?w(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return L.MIN}maxPost(){return new L(C,new B(`[PRIORITY-POST]`,Un))}makePost(e,t){return new L(t,new B(`[PRIORITY-POST]`,Hn(e)))}toString(){return`.priority`}},Kn=Math.log(2),qn=class{constructor(e){let t=e=>parseInt(Math.log(e)/Kn,10),n=e=>parseInt(Array(e+1).join(`1`),2);this.count=t(e+1),this.current_=this.count-1;let r=n(this.count);this.bits_=e+1&r}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}},Jn=function(e,t,n,r){e.sort(t);let i=function(t,r){let a=r-t,o,s;if(a===0)return null;if(a===1)return o=e[t],s=n?n(o):o,new R(s,o.node,R.BLACK,null,null);{let c=parseInt(a/2,10)+t,l=i(t,c),u=i(c+1,r);return o=e[c],s=n?n(o):o,new R(s,o.node,R.BLACK,l,u)}},a=function(t){let r=null,a=null,o=e.length,s=function(t,r){let a=o-t,s=o;o-=t;let l=i(a+1,s),u=e[a],d=n?n(u):u;c(new R(d,u.node,r,null,l))},c=function(e){r?(r.left=e,r=e):(a=e,r=e)};for(let e=0;e<t.count;++e){let n=t.nextBitIsOne(),r=2**(t.count-(e+1));n?s(r,R.BLACK):(s(r,R.BLACK),s(r,R.RED))}return a}(new qn(e.length));return new z(r||t,a)},Yn,Xn={},Zn=class e{static get Default(){return g(Xn&&V,`ChildrenNode.ts has not been loaded`),Yn||=new e({".priority":Xn},{".priority":V}),Yn}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){let t=ce(this.indexes_,e);if(!t)throw Error(`No index defined for `+e);return t instanceof z?t:null}hasIndex(e){return m(this.indexSet_,e.toString())}addIndex(t,n){g(t!==Mn,`KeyIndex always exists and isn't meant to be added to the IndexMap.`);let r=[],i=!1,a=n.getIterator(L.Wrap),o=a.getNext();for(;o;)i||=t.isDefinedOn(o.node),r.push(o),o=a.getNext();let s;s=i?Jn(r,t.getCompare()):Xn;let c=t.toString(),l={...this.indexSet_};l[c]=t;let u={...this.indexes_};return u[c]=s,new e(u,l)}addToIndexes(t,n){let r=oe(this.indexes_,(e,r)=>{let i=ce(this.indexSet_,r);if(g(i,`Missing index implementation for `+r),e===Xn)if(i.isDefinedOn(t.node)){let e=[],r=n.getIterator(L.Wrap),a=r.getNext();for(;a;)a.name!==t.name&&e.push(a),a=r.getNext();return e.push(t),Jn(e,i.getCompare())}else return Xn;else{let r=n.get(t.name),i=e;return r&&(i=i.remove(new L(t.name,r))),i.insert(t,t.node)}});return new e(r,this.indexSet_)}removeFromIndexes(t,n){let r=oe(this.indexes_,e=>{if(e===Xn)return e;{let r=n.get(t.name);return r?e.remove(new L(t.name,r)):e}});return new e(r,this.indexSet_)}},Qn,H=class e{static get EMPTY_NODE(){return Qn||=new e(new z(In),null,Zn.Default)}constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Bn(this.priorityNode_),this.children_.isEmpty()&&g(!this.priorityNode_||this.priorityNode_.isEmpty(),`An empty node cannot have a priority`)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Qn}updatePriority(t){return this.children_.isEmpty()?this:new e(this.children_,t,this.indexMap_)}getImmediateChild(e){if(e===`.priority`)return this.getPriority();{let t=this.children_.get(e);return t===null?Qn:t}}getChild(e){let t=k(e);return t===null?this:this.getImmediateChild(t).getChild(j(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(t,n){if(g(n,`We should always be passing snapshot nodes`),t===`.priority`)return this.updatePriority(n);{let r=new L(t,n),i,a;n.isEmpty()?(i=this.children_.remove(t),a=this.indexMap_.removeFromIndexes(r,this.children_)):(i=this.children_.insert(t,n),a=this.indexMap_.addToIndexes(r,this.children_));let o=i.isEmpty()?Qn:this.priorityNode_;return new e(i,o,a)}}updateChild(e,t){let n=k(e);if(n===null)return t;{g(k(e)!==`.priority`||A(e)===1,`.priority must be the last token in a path`);let r=this.getImmediateChild(n).updateChild(j(e),t);return this.updateImmediateChild(n,r)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(t){if(this.isEmpty())return null;let n={},r=0,i=0,a=!0;if(this.forEachChild(V,(o,s)=>{n[o]=s.val(t),r++,a&&e.INTEGER_REGEXP_.test(o)?i=Math.max(i,Number(o)):a=!1}),!t&&a&&i<2*r){let e=[];for(let t in n)e[t]=n[t];return e}else return t&&!this.getPriority().isEmpty()&&(n[`.priority`]=this.getPriority().val()),n}hash(){if(this.lazyHash_===null){let e=``;this.getPriority().isEmpty()||(e+=`priority:`+zn(this.getPriority().val())+`:`),this.forEachChild(V,(t,n)=>{let r=n.hash();r!==``&&(e+=`:`+t+`:`+r)}),this.lazyHash_=e===``?``:ke(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){let r=this.resolveIndex_(n);if(r){let n=r.getPredecessorKey(new L(e,t));return n?n.name:null}else return this.children_.getPredecessorKey(e)}getFirstChildName(e){let t=this.resolveIndex_(e);if(t){let e=t.minKey();return e&&e.name}else return this.children_.minKey()}getFirstChild(e){let t=this.getFirstChildName(e);return t?new L(t,this.children_.get(t)):null}getLastChildName(e){let t=this.resolveIndex_(e);if(t){let e=t.maxKey();return e&&e.name}else return this.children_.maxKey()}getLastChild(e){let t=this.getLastChildName(e);return t?new L(t,this.children_.get(t)):null}forEachChild(e,t){let n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{let n=this.children_.getIteratorFrom(e.name,L.Wrap),r=n.peek();for(;r!=null&&t.compare(r,e)<0;)n.getNext(),r=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{let n=this.children_.getReverseIteratorFrom(e.name,L.Wrap),r=n.peek();for(;r!=null&&t.compare(r,e)>0;)n.getNext(),r=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===$n?-1:0}withIndex(t){if(t===Mn||this.indexMap_.hasIndex(t))return this;{let n=this.indexMap_.addIndex(t,this.children_);return new e(this.children_,this.priorityNode_,n)}}isIndexed(e){return e===Mn||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{let t=e;if(!this.getPriority().equals(t.getPriority()))return!1;if(this.children_.count()===t.children_.count()){let e=this.getIterator(V),n=t.getIterator(V),r=e.getNext(),i=n.getNext();for(;r&&i;){if(r.name!==i.name||!r.node.equals(i.node))return!1;r=e.getNext(),i=n.getNext()}return r===null&&i===null}else return!1}}resolveIndex_(e){return e===Mn?null:this.indexMap_.get(e.toString())}};H.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;var $n=new class extends H{constructor(){super(new z(In),H.EMPTY_NODE,Zn.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return H.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(L,{MIN:{value:new L(Re,H.EMPTY_NODE)},MAX:{value:new L(C,$n)}}),jn.__EMPTY_NODE=H.EMPTY_NODE,B.__childrenNodeConstructor=H,Rn($n),Gn($n);var er=!0;function U(e,t=null){if(e===null)return H.EMPTY_NODE;if(typeof e==`object`&&`.priority`in e&&(t=e[`.priority`]),g(t===null||typeof t==`string`||typeof t==`number`||typeof t==`object`&&`.sv`in t,`Invalid priority type found: `+typeof t),typeof e==`object`&&`.value`in e&&e[`.value`]!==null&&(e=e[`.value`]),typeof e!=`object`||`.sv`in e)return new B(e,U(t));if(!(e instanceof Array)&&er){let n=[],r=!1;if(T(e,(e,t)=>{if(e.substring(0,1)!==`.`){let i=U(t);i.isEmpty()||(r||=!i.getPriority().isEmpty(),n.push(new L(e,i)))}}),n.length===0)return H.EMPTY_NODE;let i=Jn(n,Fn,e=>e.name,In);if(r){let e=Jn(n,V.getCompare());return new H(i,U(t),new Zn({".priority":e},{".priority":V}))}else return new H(i,U(t),Zn.Default)}else{let n=H.EMPTY_NODE;return T(e,(t,r)=>{if(m(e,t)&&t.substring(0,1)!==`.`){let e=U(r);(e.isLeafNode()||!e.isEmpty())&&(n=n.updateImmediateChild(t,e))}}),n.updatePriority(U(t))}}Wn(U);var tr=class extends kn{constructor(e){super(),this.indexPath_=e,g(!N(e)&&k(e)!==`.priority`,`Can't create PathIndex with empty path or .priority key`)}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){let n=this.extractChild(e.node),r=this.extractChild(t.node),i=n.compareTo(r);return i===0?w(e.name,t.name):i}makePost(e,t){let n=U(e);return new L(t,H.EMPTY_NODE.updateChild(this.indexPath_,n))}maxPost(){return new L(C,H.EMPTY_NODE.updateChild(this.indexPath_,$n))}toString(){return fn(this.indexPath_,0).join(`/`)}},nr=new class extends kn{compare(e,t){let n=e.node.compareTo(t.node);return n===0?w(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return L.MIN}maxPost(){return L.MAX}makePost(e,t){return new L(t,U(e))}toString(){return`.value`}};function rr(e){return{type:`value`,snapshotNode:e}}function ir(e,t){return{type:`child_added`,snapshotNode:t,childName:e}}function ar(e,t){return{type:`child_removed`,snapshotNode:t,childName:e}}function or(e,t,n){return{type:`child_changed`,snapshotNode:t,childName:e,oldSnap:n}}function sr(e,t){return{type:`child_moved`,snapshotNode:t,childName:e}}var cr=class{constructor(e){this.index_=e}updateChild(e,t,n,r,i,a){g(e.isIndexed(this.index_),`A node must be indexed if only a child is updated`);let o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()||(a!=null&&(n.isEmpty()?e.hasChild(t)?a.trackChildChange(ar(t,o)):g(e.isLeafNode(),`A child remove without an old child only makes sense on a leaf node`):o.isEmpty()?a.trackChildChange(ir(t,n)):a.trackChildChange(or(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(e,t,n){return n!=null&&(e.isLeafNode()||e.forEachChild(V,(e,r)=>{t.hasChild(e)||n.trackChildChange(ar(e,r))}),t.isLeafNode()||t.forEachChild(V,(t,r)=>{if(e.hasChild(t)){let i=e.getImmediateChild(t);i.equals(r)||n.trackChildChange(or(t,r,i))}else n.trackChildChange(ir(t,r))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?H.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}},lr=class e{constructor(t){this.indexedFilter_=new cr(t.getIndex()),this.index_=t.getIndex(),this.startPost_=e.getStartPost_(t),this.endPost_=e.getEndPost_(t),this.startIsInclusive_=!t.startAfterSet_,this.endIsInclusive_=!t.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){let t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,a){return this.matches(new L(t,n))||(n=H.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,a)}updateFullNode(e,t,n){t.isLeafNode()&&(t=H.EMPTY_NODE);let r=t.withIndex(this.index_);r=r.updatePriority(H.EMPTY_NODE);let i=this;return t.forEachChild(V,(e,t)=>{i.matches(new L(e,t))||(r=r.updateImmediateChild(e,H.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){let t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){let t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}else return e.getIndex().maxPost()}},ur=class{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{let t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{let t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new lr(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,a){return this.rangedFilter_.matches(new L(t,n))||(n=H.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,a):this.fullLimitUpdateChild_(e,t,n,i,a)}updateFullNode(e,t,n){let r;if(t.isLeafNode()||t.isEmpty())r=H.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<t.numChildren()&&t.isIndexed(this.index_)){r=H.EMPTY_NODE.withIndex(this.index_);let e;e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){let t=e.getNext();if(this.withinDirectionalStart(t))if(this.withinDirectionalEnd(t))r=r.updateImmediateChild(t.name,t.node),n++;else break}}else{r=t.withIndex(this.index_),r=r.updatePriority(H.EMPTY_NODE);let e;e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let n=0;for(;e.hasNext();){let t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:r=r.updateImmediateChild(t.name,H.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let a;if(this.reverse_){let e=this.index_.getCompare();a=(t,n)=>e(n,t)}else a=this.index_.getCompare();let o=e;g(o.numChildren()===this.limit_,``);let s=new L(t,n),c=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),l=this.rangedFilter_.matches(s);if(o.hasChild(t)){let e=o.getImmediateChild(t),u=r.getChildAfterChild(this.index_,c,this.reverse_);for(;u!=null&&(u.name===t||o.hasChild(u.name));)u=r.getChildAfterChild(this.index_,u,this.reverse_);let d=u==null?1:a(u,s);if(l&&!n.isEmpty()&&d>=0)return i?.trackChildChange(or(t,n,e)),o.updateImmediateChild(t,n);{i?.trackChildChange(ar(t,e));let n=o.updateImmediateChild(t,H.EMPTY_NODE);return u!=null&&this.rangedFilter_.matches(u)?(i?.trackChildChange(ir(u.name,u.node)),n.updateImmediateChild(u.name,u.node)):n}}else if(n.isEmpty())return e;else if(l)return a(c,s)>=0?(i!=null&&(i.trackChildChange(ar(c.name,c.node)),i.trackChildChange(ir(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(c.name,H.EMPTY_NODE)):e;else return e}},dr=class e{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_=``,this.indexStartValue_=null,this.indexStartName_=``,this.indexEndValue_=null,this.indexEndName_=``,this.index_=V}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===``?this.startSet_:this.viewFrom_===`l`}getIndexStartValue(){return g(this.startSet_,`Only valid if start has been set`),this.indexStartValue_}getIndexStartName(){return g(this.startSet_,`Only valid if start has been set`),this.startNameSet_?this.indexStartName_:Re}hasEnd(){return this.endSet_}getIndexEndValue(){return g(this.endSet_,`Only valid if end has been set`),this.indexEndValue_}getIndexEndName(){return g(this.endSet_,`Only valid if end has been set`),this.endNameSet_?this.indexEndName_:C}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==``}getLimit(){return g(this.limitSet_,`Only valid if limit has been set`),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===V}copy(){let t=new e;return t.limitSet_=this.limitSet_,t.limit_=this.limit_,t.startSet_=this.startSet_,t.startAfterSet_=this.startAfterSet_,t.indexStartValue_=this.indexStartValue_,t.startNameSet_=this.startNameSet_,t.indexStartName_=this.indexStartName_,t.endSet_=this.endSet_,t.endBeforeSet_=this.endBeforeSet_,t.indexEndValue_=this.indexEndValue_,t.endNameSet_=this.endNameSet_,t.indexEndName_=this.indexEndName_,t.index_=this.index_,t.viewFrom_=this.viewFrom_,t}};function fr(e){return e.loadsAllData()?new cr(e.getIndex()):e.hasLimit()?new ur(e):new lr(e)}function pr(e){let t={};if(e.isDefault())return t;let n;if(e.index_===V?n=`$priority`:e.index_===nr?n=`$value`:e.index_===Mn?n=`$key`:(g(e.index_ instanceof tr,`Unrecognized index type!`),n=e.index_.toString()),t.orderBy=h(n),e.startSet_){let n=e.startAfterSet_?`startAfter`:`startAt`;t[n]=h(e.indexStartValue_),e.startNameSet_&&(t[n]+=`,`+h(e.indexStartName_))}if(e.endSet_){let n=e.endBeforeSet_?`endBefore`:`endAt`;t[n]=h(e.indexEndValue_),e.endNameSet_&&(t[n]+=`,`+h(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function mr(e){let t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;n===``&&(n=e.isViewFromLeft()?`l`:`r`),t.vf=n}return e.index_!==V&&(t.i=e.index_.toString()),t}var hr=class t extends an{reportStats(e){throw Error(`Method not implemented.`)}static getListenId_(e,t){return t===void 0?(g(e._queryParams.isDefault(),`should have a tag if it's not a default query.`),e._path.toString()):`tag$`+t}constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=Ne(`p:rest:`),this.listens_={}}listen(e,n,r,i){let a=e._path.toString();this.log_(`Listen called for `+a+` `+e._queryIdentifier);let o=t.getListenId_(e,r),s={};this.listens_[o]=s;let c=pr(e._queryParams);this.restRequest_(a+`.json`,c,(e,t)=>{let n=t;if(e===404&&(n=null,e=null),e===null&&this.onDataUpdate_(a,n,!1,r),ce(this.listens_,o)===s){let t;t=e?e===401?`permission_denied`:`rest_error:`+e:`ok`,i(t,null)}})}unlisten(e,n){let r=t.getListenId_(e,n);delete this.listens_[r]}get(e){let t=pr(e._queryParams),n=e._path.toString(),r=new _;return this.restRequest_(n+`.json`,t,(e,t)=>{let i=t;e===404&&(i=null,e=null),e===null?(this.onDataUpdate_(n,i,!1,null),r.resolve(i)):r.reject(Error(i))}),r.promise}refreshAuthToken(e){}restRequest_(t,n={},r){return n.format=`export`,Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,a])=>{i&&i.accessToken&&(n.auth=i.accessToken),a&&a.token&&(n.ac=a.token);let o=(this.repoInfo_.secure?`https://`:`http://`)+this.repoInfo_.host+t+`?ns=`+this.repoInfo_.namespace+ue(n);this.log_(`Sending REST request for `+o);let s=new XMLHttpRequest;s.onreadystatechange=()=>{if(r&&s.readyState===4){this.log_(`REST Response for `+o+` received. status:`,s.status,`response:`,s.responseText);let t=null;if(s.status>=200&&s.status<300){try{t=e(s.responseText)}catch{S(`Failed to parse JSON response for `+o+`: `+s.responseText)}r(null,t)}else s.status!==401&&s.status!==404&&S(`Got unsuccessful REST response for `+o+` Status: `+s.status),r(s.status);r=null}},s.open(`GET`,o,!0),s.send()})}},gr=class{constructor(){this.rootNode_=H.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}};function _r(){return{value:null,children:new Map}}function vr(e,t,n){if(N(t))e.value=n,e.children.clear();else if(e.value!==null)e.value=e.value.updateChild(t,n);else{let r=k(t);e.children.has(r)||e.children.set(r,_r());let i=e.children.get(r);t=j(t),vr(i,t,n)}}function yr(e,t){if(N(t))return e.value=null,e.children.clear(),!0;if(e.value!==null){if(e.value.isLeafNode())return!1;{let n=e.value;return e.value=null,n.forEachChild(V,(t,n)=>{vr(e,new D(t),n)}),yr(e,t)}}else if(e.children.size>0){let n=k(t);return t=j(t),e.children.has(n)&&yr(e.children.get(n),t)&&e.children.delete(n),e.children.size===0}else return!0}function br(e,t,n){e.value===null?xr(e,(e,r)=>{br(r,new D(t.toString()+`/`+e),n)}):n(t,e.value)}function xr(e,t){e.children.forEach((e,n)=>{t(n,e)})}var Sr=class{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),t={...e};return this.last_&&T(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}},Cr=10*1e3,wr=30*1e3,Tr=300*1e3,Er=class{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Sr(e);let n=Cr+(wr-Cr)*Math.random();$e(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){let e=this.statsListener_.get(),t={},n=!1;T(e,(e,r)=>{r>0&&m(this.statsToReport_,e)&&(t[e]=r,n=!0)}),n&&this.server_.reportStats(t),$e(this.reportStats_.bind(this),Math.floor(Math.random()*2*Tr))}},W;(function(e){e[e.OVERWRITE=0]=`OVERWRITE`,e[e.MERGE=1]=`MERGE`,e[e.ACK_USER_WRITE=2]=`ACK_USER_WRITE`,e[e.LISTEN_COMPLETE=3]=`LISTEN_COMPLETE`})(W||={});function Dr(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Or(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function kr(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}var Ar=class e{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=W.ACK_USER_WRITE,this.source=Dr()}operationForChild(t){if(!N(this.path))return g(k(this.path)===t,`operationForChild called for unrelated child.`),new e(j(this.path),this.affectedTree,this.revert);if(this.affectedTree.value!=null)return g(this.affectedTree.children.isEmpty(),`affectedTree should not have overlapping affected paths.`),this;{let n=this.affectedTree.subtree(new D(t));return new e(O(),n,this.revert)}}},jr=class e{constructor(e,t){this.source=e,this.path=t,this.type=W.LISTEN_COMPLETE}operationForChild(t){return N(this.path)?new e(this.source,O()):new e(this.source,j(this.path))}},Mr=class e{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=W.OVERWRITE}operationForChild(t){return N(this.path)?new e(this.source,O(),this.snap.getImmediateChild(t)):new e(this.source,j(this.path),this.snap)}},Nr=class e{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=W.MERGE}operationForChild(t){if(N(this.path)){let n=this.children.subtree(new D(t));return n.isEmpty()?null:n.value?new Mr(this.source,O(),n.value):new e(this.source,O(),n)}else return g(k(this.path)===t,`Can't get a merge for a child not on the path of the operation`),new e(this.source,j(this.path),this.children)}toString(){return`Operation(`+this.path+`: `+this.source.toString()+` merge: `+this.children.toString()+`)`}},G=class{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(N(e))return this.isFullyInitialized()&&!this.filtered_;let t=k(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}},Pr=class{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}};function Fr(e,t,n,r){let i=[],a=[];return t.forEach(t=>{t.type===`child_changed`&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&a.push(sr(t.childName,t.snapshotNode))}),Ir(e,i,`child_removed`,t,r,n),Ir(e,i,`child_added`,t,r,n),Ir(e,i,`child_moved`,a,r,n),Ir(e,i,`child_changed`,t,r,n),Ir(e,i,`value`,t,r,n),i}function Ir(e,t,n,r,i,a){let o=r.filter(e=>e.type===n);o.sort((t,n)=>Rr(e,t,n)),o.forEach(n=>{let r=Lr(e,n,a);i.forEach(i=>{i.respondsTo(n.type)&&t.push(i.createEvent(r,e.query_))})})}function Lr(e,t,n){return t.type===`value`||t.type===`child_removed`||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}function Rr(e,t,n){if(t.childName==null||n.childName==null)throw f(`Should only compare child_ events.`);let r=new L(t.childName,t.snapshotNode),i=new L(n.childName,n.snapshotNode);return e.index_.compare(r,i)}function zr(e,t){return{eventCache:e,serverCache:t}}function Br(e,t,n,r){return zr(new G(t,n,r),e.serverCache)}function Vr(e,t,n,r){return zr(e.eventCache,new G(t,n,r))}function Hr(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function K(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}var Ur,Wr=()=>(Ur||=new z(ze),Ur),q=class e{static fromObject(t){let n=new e(null);return T(t,(e,t)=>{n=n.set(new D(e),t)}),n}constructor(e,t=Wr()){this.value=e,this.children=t}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(this.value!=null&&t(this.value))return{path:O(),value:this.value};if(N(e))return null;{let n=k(e),r=this.children.get(n);if(r!==null){let i=r.findRootMostMatchingPathAndValue(j(e),t);return i==null?null:{path:M(new D(n),i.path),value:i.value}}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(t){if(N(t))return this;{let n=k(t),r=this.children.get(n);return r===null?new e(null):r.subtree(j(t))}}set(t,n){if(N(t))return new e(n,this.children);{let r=k(t),i=(this.children.get(r)||new e(null)).set(j(t),n),a=this.children.insert(r,i);return new e(this.value,a)}}remove(t){if(N(t))return this.children.isEmpty()?new e(null):new e(null,this.children);{let n=k(t),r=this.children.get(n);if(r){let i=r.remove(j(t)),a;return a=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),this.value===null&&a.isEmpty()?new e(null):new e(this.value,a)}else return this}}get(e){if(N(e))return this.value;{let t=k(e),n=this.children.get(t);return n?n.get(j(e)):null}}setTree(t,n){if(N(t))return n;{let r=k(t),i=(this.children.get(r)||new e(null)).setTree(j(t),n),a;return a=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new e(this.value,a)}}fold(e){return this.fold_(O(),e)}fold_(e,t){let n={};return this.children.inorderTraversal((r,i)=>{n[r]=i.fold_(M(e,r),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,O(),t)}findOnPath_(e,t,n){let r=this.value?n(t,this.value):!1;if(r)return r;if(N(e))return null;{let r=k(e),i=this.children.get(r);return i?i.findOnPath_(j(e),M(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,O(),t)}foreachOnPath_(t,n,r){if(N(t))return this;{this.value&&r(n,this.value);let i=k(t),a=this.children.get(i);return a?a.foreachOnPath_(j(t),M(n,i),r):new e(null)}}foreach(e){this.foreach_(O(),e)}foreach_(e,t){this.children.inorderTraversal((n,r)=>{r.foreach_(M(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}},J=class e{constructor(e){this.writeTree_=e}static empty(){return new e(new q(null))}};function Gr(e,t,n){if(N(t))return new J(new q(n));{let r=e.writeTree_.findRootMostValueAndPath(t);if(r!=null){let i=r.path,a=r.value,o=P(i,t);return a=a.updateChild(o,n),new J(e.writeTree_.set(i,a))}else{let r=new q(n);return new J(e.writeTree_.setTree(t,r))}}}function Kr(e,t,n){let r=e;return T(n,(e,n)=>{r=Gr(r,M(t,e),n)}),r}function qr(e,t){return N(t)?J.empty():new J(e.writeTree_.setTree(t,new q(null)))}function Jr(e,t){return Y(e,t)!=null}function Y(e,t){let n=e.writeTree_.findRootMostValueAndPath(t);return n==null?null:e.writeTree_.get(n.path).getChild(P(n.path,t))}function Yr(e){let t=[],n=e.writeTree_.value;return n==null?e.writeTree_.children.inorderTraversal((e,n)=>{n.value!=null&&t.push(new L(e,n.value))}):n.isLeafNode()||n.forEachChild(V,(e,n)=>{t.push(new L(e,n))}),t}function X(e,t){if(N(t))return e;{let n=Y(e,t);return n==null?new J(e.writeTree_.subtree(t)):new J(new q(n))}}function Xr(e){return e.writeTree_.isEmpty()}function Zr(e,t){return Qr(O(),e.writeTree_,t)}function Qr(e,t,n){if(t.value!=null)return n.updateChild(e,t.value);{let r=null;return t.children.inorderTraversal((t,i)=>{t===`.priority`?(g(i.value!==null,`Priority writes must always be leaf nodes`),r=i.value):n=Qr(M(e,t),i,n)}),!n.getChild(e).isEmpty()&&r!==null&&(n=n.updateChild(M(e,`.priority`),r)),n}}function $r(e,t){return xi(t,e)}function ei(e,t,n,r,i){g(r>e.lastWriteId,`Stacking an older write on top of newer ones`),i===void 0&&(i=!0),e.allWrites.push({path:t,snap:n,writeId:r,visible:i}),i&&(e.visibleWrites=Gr(e.visibleWrites,t,n)),e.lastWriteId=r}function ti(e,t){for(let n=0;n<e.allWrites.length;n++){let r=e.allWrites[n];if(r.writeId===t)return r}return null}function ni(e,t){let n=e.allWrites.findIndex(e=>e.writeId===t);g(n>=0,`removeWrite called with nonexistent writeId.`);let r=e.allWrites[n];e.allWrites.splice(n,1);let i=r.visible,a=!1,o=e.allWrites.length-1;for(;i&&o>=0;){let t=e.allWrites[o];t.visible&&(o>=n&&ri(t,r.path)?i=!1:F(r.path,t.path)&&(a=!0)),o--}if(!i)return!1;if(a)return ii(e),!0;if(r.snap)e.visibleWrites=qr(e.visibleWrites,r.path);else{let t=r.children;T(t,t=>{e.visibleWrites=qr(e.visibleWrites,M(r.path,t))})}return!0}function ri(e,t){if(e.snap)return F(e.path,t);for(let n in e.children)if(e.children.hasOwnProperty(n)&&F(M(e.path,n),t))return!0;return!1}function ii(e){e.visibleWrites=oi(e.allWrites,ai,O()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}function ai(e){return e.visible}function oi(e,t,n){let r=J.empty();for(let i=0;i<e.length;++i){let a=e[i];if(t(a)){let e=a.path,t;if(a.snap)F(n,e)?(t=P(n,e),r=Gr(r,t,a.snap)):F(e,n)&&(t=P(e,n),r=Gr(r,O(),a.snap.getChild(t)));else if(a.children){if(F(n,e))t=P(n,e),r=Kr(r,t,a.children);else if(F(e,n))if(t=P(e,n),N(t))r=Kr(r,O(),a.children);else{let e=ce(a.children,k(t));if(e){let n=e.getChild(j(t));r=Gr(r,O(),n)}}}else throw f(`WriteRecord should have .snap or .children`)}}return r}function si(e,t,n,r,i){if(!r&&!i){let r=Y(e.visibleWrites,t);if(r!=null)return r;{let r=X(e.visibleWrites,t);return Xr(r)?n:n==null&&!Jr(r,O())?null:Zr(r,n||H.EMPTY_NODE)}}else{let a=X(e.visibleWrites,t);return!i&&Xr(a)?n:!i&&n==null&&!Jr(a,O())?null:Zr(oi(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(F(e.path,t)||F(t,e.path))},t),n||H.EMPTY_NODE)}}function ci(e,t,n){let r=H.EMPTY_NODE,i=Y(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(V,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){let i=X(e.visibleWrites,t);return n.forEachChild(V,(e,t)=>{let n=Zr(X(i,new D(e)),t);r=r.updateImmediateChild(e,n)}),Yr(i).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}else return Yr(X(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}function li(e,t,n,r,i){g(r||i,`Either existingEventSnap or existingServerSnap must exist`);let a=M(t,n);if(Jr(e.visibleWrites,a))return null;{let t=X(e.visibleWrites,a);return Xr(t)?i.getChild(n):Zr(t,i.getChild(n))}}function ui(e,t,n,r){let i=M(t,n);return Y(e.visibleWrites,i)??(r.isCompleteForChild(n)?Zr(X(e.visibleWrites,i),r.getNode().getImmediateChild(n)):null)}function di(e,t){return Y(e.visibleWrites,t)}function fi(e,t,n,r,i,a,o){let s,c=X(e.visibleWrites,t),l=Y(c,O());if(l!=null)s=l;else if(n!=null)s=Zr(c,n);else return[];if(s=s.withIndex(o),!s.isEmpty()&&!s.isLeafNode()){let e=[],t=o.getCompare(),n=a?s.getReverseIteratorFrom(r,o):s.getIteratorFrom(r,o),c=n.getNext();for(;c&&e.length<i;)t(c,r)!==0&&e.push(c),c=n.getNext();return e}else return[]}function pi(){return{visibleWrites:J.empty(),allWrites:[],lastWriteId:-1}}function mi(e,t,n,r){return si(e.writeTree,e.treePath,t,n,r)}function hi(e,t){return ci(e.writeTree,e.treePath,t)}function gi(e,t,n,r){return li(e.writeTree,e.treePath,t,n,r)}function _i(e,t){return di(e.writeTree,M(e.treePath,t))}function vi(e,t,n,r,i,a){return fi(e.writeTree,e.treePath,t,n,r,i,a)}function yi(e,t,n){return ui(e.writeTree,e.treePath,t,n)}function bi(e,t){return xi(M(e.treePath,t),e.writeTree)}function xi(e,t){return{treePath:e,writeTree:t}}var Si=class{constructor(){this.changeMap=new Map}trackChildChange(e){let t=e.type,n=e.childName;g(t===`child_added`||t===`child_changed`||t===`child_removed`,`Only child changes supported for tracking`),g(n!==`.priority`,`Only non-priority child changes can be tracked.`);let r=this.changeMap.get(n);if(r){let i=r.type;if(t===`child_added`&&i===`child_removed`)this.changeMap.set(n,or(n,e.snapshotNode,r.snapshotNode));else if(t===`child_removed`&&i===`child_added`)this.changeMap.delete(n);else if(t===`child_removed`&&i===`child_changed`)this.changeMap.set(n,ar(n,r.oldSnap));else if(t===`child_changed`&&i===`child_added`)this.changeMap.set(n,ir(n,e.snapshotNode));else if(t===`child_changed`&&i===`child_changed`)this.changeMap.set(n,or(n,e.snapshotNode,r.oldSnap));else throw f(`Illegal combination of changes: `+e+` occurred after `+r)}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}},Ci=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}},wi=class{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){let t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{let t=this.optCompleteServerCache_==null?this.viewCache_.serverCache:new G(this.optCompleteServerCache_,!0,!1);return yi(this.writes_,e,t)}}getChildAfterChild(e,t,n){let r=this.optCompleteServerCache_==null?K(this.viewCache_):this.optCompleteServerCache_,i=vi(this.writes_,r,t,1,n,e);return i.length===0?null:i[0]}};function Ti(e){return{filter:e}}function Ei(e,t){g(t.eventCache.getNode().isIndexed(e.filter.getIndex()),`Event snap not indexed`),g(t.serverCache.getNode().isIndexed(e.filter.getIndex()),`Server snap not indexed`)}function Di(e,t,n,r,i){let a=new Si,o,s;if(n.type===W.OVERWRITE){let c=n;c.source.fromUser?o=ji(e,t,c.path,c.snap,r,i,a):(g(c.source.fromServer,`Unknown source.`),s=c.source.tagged||t.serverCache.isFiltered()&&!N(c.path),o=Ai(e,t,c.path,c.snap,r,i,s,a))}else if(n.type===W.MERGE){let c=n;c.source.fromUser?o=Ni(e,t,c.path,c.children,r,i,a):(g(c.source.fromServer,`Unknown source.`),s=c.source.tagged||t.serverCache.isFiltered(),o=Fi(e,t,c.path,c.children,r,i,s,a))}else if(n.type===W.ACK_USER_WRITE){let s=n;o=s.revert?Ri(e,t,s.path,r,i,a):Ii(e,t,s.path,s.affectedTree,r,i,a)}else if(n.type===W.LISTEN_COMPLETE)o=Li(e,t,n.path,r,a);else throw f(`Unknown operation type: `+n.type);let c=a.getChanges();return Oi(t,o,c),{viewCache:o,changes:c}}function Oi(e,t,n){let r=t.eventCache;if(r.isFullyInitialized()){let i=r.getNode().isLeafNode()||r.getNode().isEmpty(),a=Hr(e);(n.length>0||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(a)||!r.getNode().getPriority().equals(a.getPriority()))&&n.push(rr(Hr(t)))}}function ki(e,t,n,r,i,a){let o=t.eventCache;if(_i(r,n)!=null)return t;{let s,c;if(N(n))if(g(t.serverCache.isFullyInitialized(),`If change path is empty, we must have complete server data`),t.serverCache.isFiltered()){let n=K(t),i=hi(r,n instanceof H?n:H.EMPTY_NODE);s=e.filter.updateFullNode(t.eventCache.getNode(),i,a)}else{let n=mi(r,K(t));s=e.filter.updateFullNode(t.eventCache.getNode(),n,a)}else{let l=k(n);if(l===`.priority`){g(A(n)===1,`Can't have a priority with additional path components`);let i=o.getNode();c=t.serverCache.getNode();let a=gi(r,n,i,c);s=a==null?o.getNode():e.filter.updatePriority(i,a)}else{let u=j(n),d;if(o.isCompleteForChild(l)){c=t.serverCache.getNode();let e=gi(r,n,o.getNode(),c);d=e==null?o.getNode().getImmediateChild(l):o.getNode().getImmediateChild(l).updateChild(u,e)}else d=yi(r,l,t.serverCache);s=d==null?o.getNode():e.filter.updateChild(o.getNode(),l,d,u,i,a)}}return Br(t,s,o.isFullyInitialized()||N(n),e.filter.filtersNodes())}}function Ai(e,t,n,r,i,a,o,s){let c=t.serverCache,l,u=o?e.filter:e.filter.getIndexedFilter();if(N(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){let e=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),e,null)}else{let e=k(n);if(!c.isCompleteForPath(n)&&A(n)>1)return t;let i=j(n),a=c.getNode().getImmediateChild(e).updateChild(i,r);l=e===`.priority`?u.updatePriority(c.getNode(),a):u.updateChild(c.getNode(),e,a,i,Ci,null)}let d=Vr(t,l,c.isFullyInitialized()||N(n),u.filtersNodes());return ki(e,d,n,i,new wi(i,d,a),s)}function ji(e,t,n,r,i,a,o){let s=t.eventCache,c,l,u=new wi(i,t,a);if(N(n))l=e.filter.updateFullNode(t.eventCache.getNode(),r,o),c=Br(t,l,!0,e.filter.filtersNodes());else{let i=k(n);if(i===`.priority`)l=e.filter.updatePriority(t.eventCache.getNode(),r),c=Br(t,l,s.isFullyInitialized(),s.isFiltered());else{let a=j(n),l=s.getNode().getImmediateChild(i),d;if(N(a))d=r;else{let e=u.getCompleteChild(i);d=e==null?H.EMPTY_NODE:un(a)===`.priority`&&e.getChild(pn(a)).isEmpty()?e:e.updateChild(a,r)}c=l.equals(d)?t:Br(t,e.filter.updateChild(s.getNode(),i,d,a,u,o),s.isFullyInitialized(),e.filter.filtersNodes())}}return c}function Mi(e,t){return e.eventCache.isCompleteForChild(t)}function Ni(e,t,n,r,i,a,o){let s=t;return r.foreach((r,c)=>{let l=M(n,r);Mi(t,k(l))&&(s=ji(e,s,l,c,i,a,o))}),r.foreach((r,c)=>{let l=M(n,r);Mi(t,k(l))||(s=ji(e,s,l,c,i,a,o))}),s}function Pi(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function Fi(e,t,n,r,i,a,o,s){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let c=t,l;l=N(n)?r:new q(null).setTree(n,r);let u=t.serverCache.getNode();return l.children.inorderTraversal((n,r)=>{if(u.hasChild(n)){let l=Pi(e,t.serverCache.getNode().getImmediateChild(n),r);c=Ai(e,c,new D(n),l,i,a,o,s)}}),l.children.inorderTraversal((n,r)=>{let l=!t.serverCache.isCompleteForChild(n)&&r.value===null;if(!u.hasChild(n)&&!l){let l=Pi(e,t.serverCache.getNode().getImmediateChild(n),r);c=Ai(e,c,new D(n),l,i,a,o,s)}}),c}function Ii(e,t,n,r,i,a,o){if(_i(i,n)!=null)return t;let s=t.serverCache.isFiltered(),c=t.serverCache;if(r.value!=null){if(N(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return Ai(e,t,n,c.getNode().getChild(n),i,a,s,o);if(N(n)){let r=new q(null);return c.getNode().forEachChild(Mn,(e,t)=>{r=r.set(new D(e),t)}),Fi(e,t,n,r,i,a,s,o)}else return t}else{let l=new q(null);return r.foreach((e,t)=>{let r=M(n,e);c.isCompleteForPath(r)&&(l=l.set(e,c.getNode().getChild(r)))}),Fi(e,t,n,l,i,a,s,o)}}function Li(e,t,n,r,i){let a=t.serverCache;return ki(e,Vr(t,a.getNode(),a.isFullyInitialized()||N(n),a.isFiltered()),n,r,Ci,i)}function Ri(e,t,n,r,i,a){let o;if(_i(r,n)!=null)return t;{let s=new wi(r,t,i),c=t.eventCache.getNode(),l;if(N(n)||k(n)===`.priority`){let n;if(t.serverCache.isFullyInitialized())n=mi(r,K(t));else{let e=t.serverCache.getNode();g(e instanceof H,`serverChildren would be complete if leaf node`),n=hi(r,e)}n=n,l=e.filter.updateFullNode(c,n,a)}else{let i=k(n),u=yi(r,i,t.serverCache);u==null&&t.serverCache.isCompleteForChild(i)&&(u=c.getImmediateChild(i)),l=u==null?t.eventCache.getNode().hasChild(i)?e.filter.updateChild(c,i,H.EMPTY_NODE,j(n),s,a):c:e.filter.updateChild(c,i,u,j(n),s,a),l.isEmpty()&&t.serverCache.isFullyInitialized()&&(o=mi(r,K(t)),o.isLeafNode()&&(l=e.filter.updateFullNode(l,o,a)))}return o=t.serverCache.isFullyInitialized()||_i(r,O())!=null,Br(t,l,o,e.filter.filtersNodes())}}var zi=class{constructor(e,t){this.query_=e,this.eventRegistrations_=[];let n=this.query_._queryParams,r=new cr(n.getIndex()),i=fr(n);this.processor_=Ti(i);let a=t.serverCache,o=t.eventCache,s=r.updateFullNode(H.EMPTY_NODE,a.getNode(),null),c=i.updateFullNode(H.EMPTY_NODE,o.getNode(),null),l=new G(s,a.isFullyInitialized(),r.filtersNodes()),u=new G(c,o.isFullyInitialized(),i.filtersNodes());this.viewCache_=zr(u,l),this.eventGenerator_=new Pr(this.query_)}get query(){return this.query_}};function Bi(e){return e.viewCache_.serverCache.getNode()}function Vi(e,t){let n=K(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!N(t)&&!n.getImmediateChild(k(t)).isEmpty())?n.getChild(t):null}function Hi(e){return e.eventRegistrations_.length===0}function Ui(e,t){e.eventRegistrations_.push(t)}function Wi(e,t,n){let r=[];if(n){g(t==null,`A cancel should cancel all event registrations.`);let i=e.query._path;e.eventRegistrations_.forEach(e=>{let t=e.createCancelEvent(n,i);t&&r.push(t)})}if(t){let n=[];for(let r=0;r<e.eventRegistrations_.length;++r){let i=e.eventRegistrations_[r];if(!i.matches(t))n.push(i);else if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(r+1));break}}e.eventRegistrations_=n}else e.eventRegistrations_=[];return r}function Gi(e,t,n,r){t.type===W.MERGE&&t.source.queryId!==null&&(g(K(e.viewCache_),`We should always have a full cache before handling merges`),g(Hr(e.viewCache_),`Missing event cache, even though we have a server cache`));let i=e.viewCache_,a=Di(e.processor_,i,t,n,r);return Ei(e.processor_,a.viewCache),g(a.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),`Once a server snap is complete, it should never go back`),e.viewCache_=a.viewCache,qi(e,a.changes,a.viewCache.eventCache.getNode(),null)}function Ki(e,t){let n=e.viewCache_.eventCache,r=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(V,(e,t)=>{r.push(ir(e,t))}),n.isFullyInitialized()&&r.push(rr(n.getNode())),qi(e,r,n.getNode(),t)}function qi(e,t,n,r){let i=r?[r]:e.eventRegistrations_;return Fr(e.eventGenerator_,t,n,i)}var Ji,Yi=class{constructor(){this.views=new Map}};function Xi(e){g(!Ji,`__referenceConstructor has already been defined`),Ji=e}function Zi(){return g(Ji,`Reference.ts has not been loaded`),Ji}function Qi(e){return e.views.size===0}function $i(e,t,n,r){let i=t.source.queryId;if(i!==null){let a=e.views.get(i);return g(a!=null,`SyncTree gave us an op for an invalid query.`),Gi(a,t,n,r)}else{let i=[];for(let a of e.views.values())i=i.concat(Gi(a,t,n,r));return i}}function ea(e,t,n,r,i){let a=t._queryIdentifier,o=e.views.get(a);if(!o){let e=mi(n,i?r:null),a=!1;return e?a=!0:r instanceof H?(e=hi(n,r),a=!1):(e=H.EMPTY_NODE,a=!1),new zi(t,zr(new G(e,a,!1),new G(r,i,!1)))}return o}function ta(e,t,n,r,i,a){let o=ea(e,t,r,i,a);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),Ui(o,n),Ki(o,n)}function na(e,t,n,r){let i=t._queryIdentifier,a=[],o=[],s=Z(e);if(i==="default")for(let[t,i]of e.views.entries())o=o.concat(Wi(i,n,r)),Hi(i)&&(e.views.delete(t),i.query._queryParams.loadsAllData()||a.push(i.query));else{let t=e.views.get(i);t&&(o=o.concat(Wi(t,n,r)),Hi(t)&&(e.views.delete(i),t.query._queryParams.loadsAllData()||a.push(t.query)))}return s&&!Z(e)&&a.push(new(Zi())(t._repo,t._path)),{removed:a,events:o}}function ra(e){let t=[];for(let n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function ia(e,t){let n=null;for(let r of e.views.values())n||=Vi(r,t);return n}function aa(e,t){if(t._queryParams.loadsAllData())return sa(e);{let n=t._queryIdentifier;return e.views.get(n)}}function oa(e,t){return aa(e,t)!=null}function Z(e){return sa(e)!=null}function sa(e){for(let t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}var ca;function la(e){g(!ca,`__referenceConstructor has already been defined`),ca=e}function ua(){return g(ca,`Reference.ts has not been loaded`),ca}var da=1,fa=class{constructor(e){this.listenProvider_=e,this.syncPointTree_=new q(null),this.pendingWriteTree_=pi(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}};function pa(e,t,n,r,i){return ei(e.pendingWriteTree_,t,n,r,i),i?wa(e,new Mr(Dr(),t,n)):[]}function ma(e,t,n=!1){let r=ti(e.pendingWriteTree_,t);if(ni(e.pendingWriteTree_,t)){let t=new q(null);return r.snap==null?T(r.children,e=>{t=t.set(new D(e),!0)}):t=t.set(O(),!0),wa(e,new Ar(r.path,t,n))}else return[]}function ha(e,t,n){return wa(e,new Mr(Or(),t,n))}function ga(e,t,n){let r=q.fromObject(n);return wa(e,new Nr(Or(),t,r))}function _a(e,t){return wa(e,new jr(Or(),t))}function va(e,t,n){let r=Aa(e,n);if(r){let n=ja(r),i=n.path,a=n.queryId,o=P(i,t);return Ma(e,i,new jr(kr(a),o))}else return[]}function ya(e,t,n,r,i=!1){let a=t._path,o=e.syncPointTree_.get(a),s=[];if(o&&(t._queryIdentifier==="default"||oa(o,t))){let c=na(o,t,n,r);Qi(o)&&(e.syncPointTree_=e.syncPointTree_.remove(a));let l=c.removed;if(s=c.events,!i){let n=l.findIndex(e=>e._queryParams.loadsAllData())!==-1,i=e.syncPointTree_.findOnPath(a,(e,t)=>Z(t));if(n&&!i){let t=e.syncPointTree_.subtree(a);if(!t.isEmpty()){let n=Na(t);for(let t=0;t<n.length;++t){let r=n[t],i=r.query,a=Da(e,r);e.listenProvider_.startListening(Pa(i),Oa(e,i),a.hashFn,a.onComplete)}}}!i&&l.length>0&&!r&&(n?e.listenProvider_.stopListening(Pa(t),null):l.forEach(t=>{let n=e.queryToTagMap.get(ka(t));e.listenProvider_.stopListening(Pa(t),n)}))}Fa(e,l)}return s}function ba(e,t,n,r){let i=Aa(e,r);if(i!=null){let r=ja(i),a=r.path,o=r.queryId,s=P(a,t);return Ma(e,a,new Mr(kr(o),s,n))}else return[]}function xa(e,t,n,r){let i=Aa(e,r);if(i){let r=ja(i),a=r.path,o=r.queryId,s=P(a,t),c=q.fromObject(n);return Ma(e,a,new Nr(kr(o),s,c))}else return[]}function Sa(e,t,n,r=!1){let i=t._path,a=null,o=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{let n=P(e,i);a||=ia(t,n),o||=Z(t)});let s=e.syncPointTree_.get(i);s?(o||=Z(s),a||=ia(s,O())):(s=new Yi,e.syncPointTree_=e.syncPointTree_.set(i,s));let c;a==null?(c=!1,a=H.EMPTY_NODE,e.syncPointTree_.subtree(i).foreachChild((e,t)=>{let n=ia(t,O());n&&(a=a.updateImmediateChild(e,n))})):c=!0;let l=oa(s,t);if(!l&&!t._queryParams.loadsAllData()){let n=ka(t);g(!e.queryToTagMap.has(n),`View does not exist, but we have a tag`);let r=Ia();e.queryToTagMap.set(n,r),e.tagToQueryMap.set(r,n)}let u=$r(e.pendingWriteTree_,i),d=ta(s,t,n,u,a,c);if(!l&&!o&&!r){let n=aa(s,t);d=d.concat(La(e,t,n))}return d}function Ca(e,t,n){let r=e.pendingWriteTree_;return si(r,t,e.syncPointTree_.findOnPath(t,(e,n)=>{let r=ia(n,P(e,t));if(r)return r}),n,!0)}function wa(e,t){return Ta(t,e.syncPointTree_,null,$r(e.pendingWriteTree_,O()))}function Ta(e,t,n,r){if(N(e.path))return Ea(e,t,n,r);{let i=t.get(O());n==null&&i!=null&&(n=ia(i,O()));let a=[],o=k(e.path),s=e.operationForChild(o),c=t.children.get(o);if(c&&s){let e=n?n.getImmediateChild(o):null,t=bi(r,o);a=a.concat(Ta(s,c,e,t))}return i&&(a=a.concat($i(i,e,r,n))),a}}function Ea(e,t,n,r){let i=t.get(O());n==null&&i!=null&&(n=ia(i,O()));let a=[];return t.children.inorderTraversal((t,i)=>{let o=n?n.getImmediateChild(t):null,s=bi(r,t),c=e.operationForChild(t);c&&(a=a.concat(Ea(c,i,o,s)))}),i&&(a=a.concat($i(i,e,r,n))),a}function Da(e,t){let n=t.query,r=Oa(e,n);return{hashFn:()=>(Bi(t)||H.EMPTY_NODE).hash(),onComplete:t=>{if(t===`ok`)return r?va(e,n._path,r):_a(e,n._path);{let r=Ke(t,n);return ya(e,n,null,r)}}}}function Oa(e,t){let n=ka(t);return e.queryToTagMap.get(n)}function ka(e){return e._path.toString()+`$`+e._queryIdentifier}function Aa(e,t){return e.tagToQueryMap.get(t)}function ja(e){let t=e.indexOf(`$`);return g(t!==-1&&t<e.length-1,`Bad queryKey.`),{queryId:e.substr(t+1),path:new D(e.substr(0,t))}}function Ma(e,t,n){let r=e.syncPointTree_.get(t);return g(r,`Missing sync point for query tag that we're tracking`),$i(r,n,$r(e.pendingWriteTree_,t),null)}function Na(e){return e.fold((e,t,n)=>{if(t&&Z(t))return[sa(t)];{let e=[];return t&&(e=ra(t)),T(n,(t,n)=>{e=e.concat(n)}),e}})}function Pa(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(ua())(e._repo,e._path):e}function Fa(e,t){for(let n=0;n<t.length;++n){let r=t[n];if(!r._queryParams.loadsAllData()){let t=ka(r),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}function Ia(){return da++}function La(e,t,n){let r=t._path,i=Oa(e,t),a=Da(e,n),o=e.listenProvider_.startListening(Pa(t),i,a.hashFn,a.onComplete),s=e.syncPointTree_.subtree(r);if(i)g(!Z(s.value),`If we're adding a query, it shouldn't be shadowed`);else{let t=s.fold((e,t,n)=>{if(!N(e)&&t&&Z(t))return[sa(t).query];{let e=[];return t&&(e=e.concat(ra(t).map(e=>e.query))),T(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){let r=t[n];e.listenProvider_.stopListening(Pa(r),Oa(e,r))}}return o}var Ra=class e{constructor(e){this.node_=e}getImmediateChild(t){let n=this.node_.getImmediateChild(t);return new e(n)}node(){return this.node_}},za=class e{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(t){let n=M(this.path_,t);return new e(this.syncTree_,n)}node(){return Ca(this.syncTree_,this.path_)}},Ba=function(e){return e||={},e.timestamp=e.timestamp||new Date().getTime(),e},Va=function(e,t,n){if(!e||typeof e!=`object`)return e;if(g(`.sv`in e,`Unexpected leaf node or priority contents`),typeof e[`.sv`]==`string`)return Ha(e[`.sv`],t,n);if(typeof e[`.sv`]==`object`)return Ua(e[`.sv`],t);g(!1,`Unexpected server value: `+JSON.stringify(e,null,2))},Ha=function(e,t,n){switch(e){case`timestamp`:return n.timestamp;default:g(!1,`Unexpected server value: `+e)}},Ua=function(e,t,n){e.hasOwnProperty(`increment`)||g(!1,`Unexpected server value: `+JSON.stringify(e,null,2));let r=e.increment;typeof r!=`number`&&g(!1,`Unexpected increment value: `+r);let i=t.node();if(g(i!=null,`Expected ChildrenNode.EMPTY_NODE for nulls`),!i.isLeafNode())return r;let a=i.getValue();return typeof a==`number`?a+r:r},Wa=function(e,t,n,r){return Ka(t,new za(n,e),r)},Ga=function(e,t,n){return Ka(e,new Ra(t),n)};function Ka(e,t,n){let r=Va(e.getPriority().val(),t.getImmediateChild(`.priority`),n),i;if(e.isLeafNode()){let i=e,a=Va(i.getValue(),t,n);return a!==i.getValue()||r!==i.getPriority().val()?new B(a,U(r)):e}else{let a=e;return i=a,r!==a.getPriority().val()&&(i=i.updatePriority(new B(r))),a.forEachChild(V,(e,r)=>{let a=Ka(r,t.getImmediateChild(e),n);a!==r&&(i=i.updateImmediateChild(e,a))}),i}}var qa=class{constructor(e=``,t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}};function Ja(e,t){let n=t instanceof D?t:new D(t),r=e,i=k(n);for(;i!==null;){let e=ce(r.node.children,i)||{children:{},childCount:0};r=new qa(i,r,e),n=j(n),i=k(n)}return r}function Ya(e){return e.node.value}function Xa(e,t){e.node.value=t,ro(e)}function Za(e){return e.node.childCount>0}function Qa(e){return Ya(e)===void 0&&!Za(e)}function $a(e,t){T(e.node.children,(n,r)=>{t(new qa(n,e,r))})}function eo(e,t,n,r){n&&!r&&t(e),$a(e,e=>{eo(e,t,!0,r)}),n&&r&&t(e)}function to(e,t,n){let r=n?e:e.parent;for(;r!==null;){if(t(r))return!0;r=r.parent}return!1}function no(e){return new D(e.parent===null?e.name:no(e.parent)+`/`+e.name)}function ro(e){e.parent!==null&&io(e.parent,e.name,e)}function io(e,t,n){let r=Qa(n),i=m(e.node.children,t);r&&i?(delete e.node.children[t],e.node.childCount--,ro(e)):!r&&!i&&(e.node.children[t]=n.node,e.node.childCount++,ro(e))}var ao=/[\[\].#$\/\u0000-\u001F\u007F]/,oo=/[\[\].#$\u0000-\u001F\u007F]/,so=10*1024*1024,co=function(e){return typeof e==`string`&&e.length!==0&&!ao.test(e)},lo=function(e){return typeof e==`string`&&e.length!==0&&!oo.test(e)},uo=function(e){return e&&=e.replace(/^\/*\.info(\/|$)/,`/`),lo(e)},fo=function(e){return e===null||typeof e==`string`||typeof e==`number`&&!Ie(e)||e&&typeof e==`object`&&m(e,`.sv`)},po=function(e,t,n,r){r&&t===void 0||mo(l(e,`value`),t,n)},mo=function(e,t,n){let r=n instanceof D?new gn(n,e):n;if(t===void 0)throw Error(e+`contains undefined `+I(r));if(typeof t==`function`)throw Error(e+`contains a function `+I(r)+` with contents = `+t.toString());if(Ie(t))throw Error(e+`contains `+t.toString()+` `+I(r));if(typeof t==`string`&&t.length>so/3&&ie(t)>so)throw Error(e+`contains a string greater than 10485760 utf8 bytes `+I(r)+` ('`+t.substring(0,50)+`...')`);if(t&&typeof t==`object`){let n=!1,i=!1;if(T(t,(t,a)=>{if(t===`.value`)n=!0;else if(t!==`.priority`&&t!==`.sv`&&(i=!0,!co(t)))throw Error(e+` contains an invalid key (`+t+`) `+I(r)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);_n(r,t),mo(e,a,r),vn(r)}),n&&i)throw Error(e+` contains ".value" child `+I(r)+` in addition to actual children.`)}},ho=function(e,t){let n,r;for(n=0;n<t.length;n++){r=t[n];let i=fn(r);for(let t=0;t<i.length;t++)if(!(i[t]===`.priority`&&t===i.length-1)&&!co(i[t]))throw Error(e+`contains an invalid key (`+i[t]+`) in path `+r.toString()+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)}t.sort(mn);let i=null;for(n=0;n<t.length;n++){if(r=t[n],i!==null&&F(i,r))throw Error(e+`contains a path `+i.toString()+` that is ancestor of another path `+r.toString());i=r}},go=function(e,t,n,r){if(r&&t===void 0)return;let i=l(e,`values`);if(!(t&&typeof t==`object`)||Array.isArray(t))throw Error(i+` must be an object containing the children to replace.`);let a=[];T(t,(e,t)=>{let r=new D(e);if(mo(i,t,M(n,r)),un(r)===`.priority`&&!fo(t))throw Error(i+`contains an invalid value for '`+r.toString()+`', which must be a valid Firebase priority (a string, finite number, server value, or null).`);a.push(r)}),ho(i,a)},_o=function(e,t,n){if(!(n&&t===void 0)){if(Ie(t))throw Error(l(e,`priority`)+`is `+t.toString()+`, but must be a valid Firebase priority (a string, finite number, server value, or null).`);if(!fo(t))throw Error(l(e,`priority`)+`must be a valid Firebase priority (a string, finite number, server value, or null).`)}},vo=function(e,t,n,r){if(!(r&&n===void 0)&&!lo(n))throw Error(l(e,t)+`was an invalid path = "`+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},yo=function(e,t,n,r){n&&=n.replace(/^\/*\.info(\/|$)/,`/`),vo(e,t,n,r)},bo=function(e,t){if(k(t)===`.info`)throw Error(e+` failed = Can't modify data under /.info/`)},xo=function(e,t){let n=t.path.toString();if(typeof t.repoInfo.host!=`string`||t.repoInfo.host.length===0||!co(t.repoInfo.namespace)&&t.repoInfo.host.split(`:`)[0]!==`localhost`||n.length!==0&&!uo(n))throw Error(l(e,`url`)+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)},So=class{constructor(){this.eventLists_=[],this.recursionDepth_=0}};function Co(e,t){let n=null;for(let r=0;r<t.length;r++){let i=t[r],a=i.getPath();n!==null&&!hn(a,n.path)&&(e.eventLists_.push(n),n=null),n===null&&(n={events:[],path:a}),n.events.push(i)}n&&e.eventLists_.push(n)}function wo(e,t,n){Co(e,n),To(e,e=>hn(e,t))}function Q(e,t,n){Co(e,n),To(e,e=>F(e,t)||F(t,e))}function To(e,t){e.recursionDepth_++;let n=!0;for(let r=0;r<e.eventLists_.length;r++){let i=e.eventLists_[r];if(i){let a=i.path;t(a)?(Eo(e.eventLists_[r]),e.eventLists_[r]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function Eo(e){for(let t=0;t<e.events.length;t++){let n=e.events[t];if(n!==null){e.events[t]=null;let r=n.getEventRunner();y&&b(`event: `+n.toString()),Ze(r)}}}var Do=`repo_interrupt`,Oo=25,ko=class{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new So,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=_r(),this.transactionQueueTree_=new qa,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?`https://`:`http://`)+this.repoInfo_.host}};function Ao(e,t,n){if(e.stats_=bt(e.repoInfo_),e.forceRestClient_||Qe())e.server_=new hr(e.repoInfo_,(t,n,r,i)=>{No(e,t,n,r,i)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>Po(e,!0),0);else{if(n!=null){if(typeof n!=`object`)throw Error(`Only objects are supported for option databaseAuthVariableOverride`);try{h(n)}catch(e){throw Error(`Invalid authOverride provided: `+e)}}e.persistentConnection_=new On(e.repoInfo_,t,(t,n,r,i)=>{No(e,t,n,r,i)},t=>{Po(e,t)},t=>{Fo(e,t)},e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener(t=>{e.server_.refreshAuthToken(t)}),e.appCheckProvider_.addTokenChangeListener(t=>{e.server_.refreshAppCheckToken(t.token)}),e.statsReporter_=xt(e.repoInfo_,()=>new Er(e.stats_,e.server_)),e.infoData_=new gr,e.infoSyncTree_=new fa({startListening:(t,n,r,i)=>{let a=[],o=e.infoData_.getNode(t._path);return o.isEmpty()||(a=ha(e.infoSyncTree_,t._path,o),setTimeout(()=>{i(`ok`)},0)),a},stopListening:()=>{}}),Io(e,`connected`,!1),e.serverSyncTree_=new fa({startListening:(t,n,r,i)=>(e.server_.listen(t,r,n,(n,r)=>{let a=i(n,r);Q(e.eventQueue_,t._path,a)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function jo(e){let t=e.infoData_.getNode(new D(`.info/serverTimeOffset`)).val()||0;return new Date().getTime()+t}function Mo(e){return Ba({timestamp:jo(e)})}function No(e,t,n,r,i){e.dataUpdateCount++;let a=new D(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(i)if(r){let t=oe(n,e=>U(e));o=xa(e.serverSyncTree_,a,t,i)}else{let t=U(n);o=ba(e.serverSyncTree_,a,t,i)}else if(r){let t=oe(n,e=>U(e));o=ga(e.serverSyncTree_,a,t)}else{let t=U(n);o=ha(e.serverSyncTree_,a,t)}let s=a;o.length>0&&(s=Qo(e,a)),Q(e.eventQueue_,s,o)}function Po(e,t){Io(e,`connected`,t),t===!1&&zo(e)}function Fo(e,t){T(t,(t,n)=>{Io(e,t,n)})}function Io(e,t,n){let r=new D(`/.info/`+t),i=U(n);e.infoData_.updateSnapshot(r,i);let a=ha(e.infoSyncTree_,r,i);Q(e.eventQueue_,r,a)}function Lo(e){return e.nextWriteId_++}function Ro(e,t,n,r,i){qo(e,`set`,{path:t.toString(),value:n,priority:r});let a=Mo(e),o=U(n,r),s=Ga(o,Ca(e.serverSyncTree_,t),a),c=Lo(e),l=pa(e.serverSyncTree_,t,s,c,!0);Co(e.eventQueue_,l),e.server_.put(t.toString(),o.val(!0),(n,r)=>{let a=n===`ok`;a||S(`set at `+t+` failed: `+n);let o=ma(e.serverSyncTree_,c,!a);Q(e.eventQueue_,t,o),Jo(e,i,n,r)});let u=is(e,t);Qo(e,u),Q(e.eventQueue_,u,[])}function zo(e){qo(e,`onDisconnectEvents`);let t=Mo(e),n=_r();br(e.onDisconnect_,O(),(r,i)=>{let a=Wa(r,i,e.serverSyncTree_,t);vr(n,r,a)});let r=[];br(n,O(),(t,n)=>{r=r.concat(ha(e.serverSyncTree_,t,n)),Qo(e,is(e,t))}),e.onDisconnect_=_r(),Q(e.eventQueue_,O(),r)}function Bo(e,t,n){e.server_.onDisconnectCancel(t.toString(),(r,i)=>{r===`ok`&&yr(e.onDisconnect_,t),Jo(e,n,r,i)})}function Vo(e,t,n,r){let i=U(n);e.server_.onDisconnectPut(t.toString(),i.val(!0),(n,a)=>{n===`ok`&&vr(e.onDisconnect_,t,i),Jo(e,r,n,a)})}function Ho(e,t,n,r,i){let a=U(n,r);e.server_.onDisconnectPut(t.toString(),a.val(!0),(n,r)=>{n===`ok`&&vr(e.onDisconnect_,t,a),Jo(e,i,n,r)})}function Uo(e,t,n,i){if(r(n)){b(`onDisconnect().update() called with empty data. Don't do anything.`),Jo(e,i,`ok`,void 0);return}e.server_.onDisconnectMerge(t.toString(),n,(r,a)=>{r===`ok`&&T(n,(n,r)=>{let i=U(r);vr(e.onDisconnect_,M(t,n),i)}),Jo(e,i,r,a)})}function Wo(e,t,n){let r;r=k(t._path)===`.info`?Sa(e.infoSyncTree_,t,n):Sa(e.serverSyncTree_,t,n),wo(e.eventQueue_,t._path,r)}function Go(e,t,n){let r;r=k(t._path)===`.info`?ya(e.infoSyncTree_,t,n):ya(e.serverSyncTree_,t,n),wo(e.eventQueue_,t._path,r)}function Ko(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Do)}function qo(e,...t){let n=``;e.persistentConnection_&&(n=e.persistentConnection_.id+`:`),b(n,...t)}function Jo(e,t,n,r){t&&Ze(()=>{if(n===`ok`)t(null);else{let e=(n||`error`).toUpperCase(),i=e;r&&(i+=`: `+r);let a=Error(i);a.code=e,t(a)}})}function Yo(e,t,n){return Ca(e.serverSyncTree_,t,n)||H.EMPTY_NODE}function Xo(e,t=e.transactionQueueTree_){if(t||rs(e,t),Ya(t)){let n=ts(e,t);g(n.length>0,`Sending zero length transaction queue`),n.every(e=>e.status===0)&&Zo(e,no(t),n)}else Za(t)&&$a(t,t=>{Xo(e,t)})}function Zo(e,t,n){let r=Yo(e,t,n.map(e=>e.currentWriteId)),i=r,a=r.hash();for(let e=0;e<n.length;e++){let r=n[e];g(r.status===0,`tryToSendTransactionQueue_: items in queue should all be run.`),r.status=1,r.retryCount++;let a=P(t,r.path);i=i.updateChild(a,r.currentOutputSnapshotRaw)}let o=i.val(!0),s=t;e.server_.put(s.toString(),o,r=>{qo(e,`transaction put response`,{path:s.toString(),status:r});let i=[];if(r===`ok`){let r=[];for(let t=0;t<n.length;t++)n[t].status=2,i=i.concat(ma(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&r.push(()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved)),n[t].unwatcher();rs(e,Ja(e.transactionQueueTree_,t)),Xo(e,e.transactionQueueTree_),Q(e.eventQueue_,t,i);for(let e=0;e<r.length;e++)Ze(r[e])}else{if(r===`datastale`)for(let e=0;e<n.length;e++)n[e].status===3?n[e].status=4:n[e].status=0;else{S(`transaction at `+s.toString()+` failed: `+r);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=r}Qo(e,t)}},a)}function Qo(e,t){let n=es(e,t),r=no(n);return $o(e,ts(e,n),r),r}function $o(e,t,n){if(t.length===0)return;let r=[],i=[],a=t.filter(e=>e.status===0).map(e=>e.currentWriteId);for(let o=0;o<t.length;o++){let s=t[o],c=P(n,s.path),l=!1,u;if(g(c!==null,`rerunTransactionsUnderNode_: relativePath should not be null.`),s.status===4)l=!0,u=s.abortReason,i=i.concat(ma(e.serverSyncTree_,s.currentWriteId,!0));else if(s.status===0)if(s.retryCount>=Oo)l=!0,u=`maxretry`,i=i.concat(ma(e.serverSyncTree_,s.currentWriteId,!0));else{let n=Yo(e,s.path,a);s.currentInputSnapshot=n;let r=t[o].update(n.val());if(r!==void 0){mo(`transaction failed: Data returned `,r,s.path);let t=U(r);typeof r==`object`&&r&&m(r,`.priority`)||(t=t.updatePriority(n.getPriority()));let o=s.currentWriteId,c=Mo(e),l=Ga(t,n,c);s.currentOutputSnapshotRaw=t,s.currentOutputSnapshotResolved=l,s.currentWriteId=Lo(e),a.splice(a.indexOf(o),1),i=i.concat(pa(e.serverSyncTree_,s.path,l,s.currentWriteId,s.applyLocally)),i=i.concat(ma(e.serverSyncTree_,o,!0))}else l=!0,u=`nodata`,i=i.concat(ma(e.serverSyncTree_,s.currentWriteId,!0))}Q(e.eventQueue_,n,i),i=[],l&&(t[o].status=2,(function(e){setTimeout(e,0)})(t[o].unwatcher),t[o].onComplete&&(u===`nodata`?r.push(()=>t[o].onComplete(null,!1,t[o].currentInputSnapshot)):r.push(()=>t[o].onComplete(Error(u),!1,null))))}rs(e,e.transactionQueueTree_);for(let e=0;e<r.length;e++)Ze(r[e]);Xo(e,e.transactionQueueTree_)}function es(e,t){let n,r=e.transactionQueueTree_;for(n=k(t);n!==null&&Ya(r)===void 0;)r=Ja(r,n),t=j(t),n=k(t);return r}function ts(e,t){let n=[];return ns(e,t,n),n.sort((e,t)=>e.order-t.order),n}function ns(e,t,n){let r=Ya(t);if(r)for(let e=0;e<r.length;e++)n.push(r[e]);$a(t,t=>{ns(e,t,n)})}function rs(e,t){let n=Ya(t);if(n){let e=0;for(let t=0;t<n.length;t++)n[t].status!==2&&(n[e]=n[t],e++);n.length=e,Xa(t,n.length>0?n:void 0)}$a(t,t=>{rs(e,t)})}function is(e,t){let n=no(es(e,t)),r=Ja(e.transactionQueueTree_,t);return to(r,t=>{as(e,t)}),as(e,r),eo(r,t=>{as(e,t)}),n}function as(e,t){let n=Ya(t);if(n){let r=[],i=[],a=-1;for(let t=0;t<n.length;t++)n[t].status===3||(n[t].status===1?(g(a===t-1,`All SENT items should be at beginning of queue.`),a=t,n[t].status=3,n[t].abortReason=`set`):(g(n[t].status===0,`Unexpected transaction status in abort`),n[t].unwatcher(),i=i.concat(ma(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&r.push(n[t].onComplete.bind(null,Error(`set`),!1,null))));a===-1?Xa(t,void 0):n.length=a+1,Q(e.eventQueue_,no(t),i);for(let e=0;e<r.length;e++)Ze(r[e])}}function os(e){let t=``,n=e.split(`/`);for(let e=0;e<n.length;e++)if(n[e].length>0){let r=n[e];try{r=decodeURIComponent(r.replace(/\+/g,` `))}catch{}t+=`/`+r}return t}function ss(e){let t={};e.charAt(0)===`?`&&(e=e.substring(1));for(let n of e.split(`&`)){if(n.length===0)continue;let r=n.split(`=`);r.length===2?t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):S(`Invalid query segment '${n}' in query '${e}'`)}return t}var cs=function(e,t){let n=ls(e),r=n.namespace;n.domain===`firebase.com`&&x(n.host+` is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead`),(!r||r===`undefined`)&&n.domain!==`localhost`&&x(`Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com`),n.secure||Fe();let i=n.scheme===`ws`||n.scheme===`wss`;return{repoInfo:new mt(n.host,n.secure,r,i,t,``,r!==n.subdomain),path:new D(n.pathString)}},ls=function(e){let t=``,n=``,r=``,i=``,a=``,o=!0,s=`https`,c=443;if(typeof e==`string`){let l=e.indexOf(`//`);l>=0&&(s=e.substring(0,l-1),e=e.substring(l+2));let u=e.indexOf(`/`);u===-1&&(u=e.length);let d=e.indexOf(`?`);d===-1&&(d=e.length),t=e.substring(0,Math.min(u,d)),u<d&&(i=os(e.substring(u,d)));let f=ss(e.substring(Math.min(e.length,d)));l=t.indexOf(`:`),l>=0?(o=s===`https`||s===`wss`,c=parseInt(t.substring(l+1),10)):l=t.length;let ee=t.slice(0,l);if(ee.toLowerCase()===`localhost`)n=`localhost`;else if(ee.split(`.`).length<=2)n=ee;else{let e=t.indexOf(`.`);r=t.substring(0,e).toLowerCase(),n=t.substring(e+1),a=r}`ns`in f&&(a=f.ns)}return{host:t,port:c,domain:n,subdomain:r,secure:o,scheme:s,pathString:i,namespace:a}},us=`-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz`,ds=(function(){let e=0,t=[];return function(n){let r=n===e;e=n;let i,a=Array(8);for(i=7;i>=0;i--)a[i]=us.charAt(n%64),n=Math.floor(n/64);g(n===0,`Cannot push at time == 0`);let o=a.join(``);if(r){for(i=11;i>=0&&t[i]===63;i--)t[i]=0;t[i]++}else for(i=0;i<12;i++)t[i]=Math.floor(Math.random()*64);for(i=0;i<12;i++)o+=us.charAt(t[i]);return g(o.length===20,`nextPushId: Length should be 20.`),o}})(),fs=class{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){let e=this.snapshot.ref;return this.eventType===`value`?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+`:`+this.eventType+`:`+h(this.snapshot.exportVal())}},ps=class{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return`cancel`}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+`:cancel`}},ms=class{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return g(this.hasCancelCallback,`Raising a cancel event on a listener with no cancel callback`),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}},hs=class{constructor(e,t){this._repo=e,this._path=t}cancel(){let e=new _;return Bo(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){bo(`OnDisconnect.remove`,this._path);let e=new _;return Vo(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){bo(`OnDisconnect.set`,this._path),po(`OnDisconnect.set`,e,this._path,!1);let t=new _;return Vo(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){bo(`OnDisconnect.setWithPriority`,this._path),po(`OnDisconnect.setWithPriority`,e,this._path,!1),_o(`OnDisconnect.setWithPriority`,t,!1);let n=new _;return Ho(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){bo(`OnDisconnect.update`,this._path),go(`OnDisconnect.update`,e,this._path,!1);let t=new _;return Uo(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}},gs=class e{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return N(this._path)?null:un(this._path)}get ref(){return new _s(this._repo,this._path)}get _queryIdentifier(){let e=Ve(mr(this._queryParams));return e===`{}`?`default`:e}get _queryObject(){return mr(this._queryParams)}isEqual(t){if(t=v(t),!(t instanceof e))return!1;let n=this._repo===t._repo,r=hn(this._path,t._path),i=this._queryIdentifier===t._queryIdentifier;return n&&r&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+dn(this._path)}},_s=class e extends gs{constructor(e,t){super(e,t,new dr,!1)}get parent(){let t=pn(this._path);return t===null?null:new e(this._repo,t)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}},vs=class e{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(t){let n=new D(t),r=$(this.ref,t);return new e(this._node.getChild(n),r,V)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(t){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(n,r)=>t(new e(r,$(this.ref,n),V)))}hasChild(e){let t=new D(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}};function ys(e,t){return e=v(e),e._checkNotDeleted(`ref`),t===void 0?e._root:$(e._root,t)}function $(e,t){return e=v(e),k(e._path)===null?yo(`child`,`path`,t,!1):vo(`child`,`path`,t,!1),new _s(e._repo,M(e._path,t))}function bs(e){return e=v(e),new hs(e._repo,e._path)}function xs(e,t){e=v(e),bo(`push`,e._path),po(`push`,t,e._path,!0);let n=ds(jo(e._repo)),r=$(e,n),i=$(e,n),a;return a=t==null?Promise.resolve(i):Cs(i,t).then(()=>i),r.then=a.then.bind(a),r.catch=a.then.bind(a,void 0),r}function Ss(e){return bo(`remove`,e._path),Cs(e,null)}function Cs(e,t){e=v(e),bo(`set`,e._path),po(`set`,t,e._path,!1);let n=new _;return Ro(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}var ws=class e{constructor(e){this.callbackContext=e}respondsTo(e){return e===`value`}createEvent(e,t){let n=t._queryParams.getIndex();return new fs(`value`,this,new vs(e.snapshotNode,new _s(t._repo,t._path),n))}getEventRunner(e){return e.getEventType()===`cancel`?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ps(this,e,t):null}matches(t){return t instanceof e?!t.callbackContext||!this.callbackContext?!0:t.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}},Ts=class e{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t=e===`children_added`?`child_added`:e;return t=t===`children_removed`?`child_removed`:t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ps(this,e,t):null}createEvent(e,t){g(e.childName!=null,`Child events should have a childName.`);let n=$(new _s(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new fs(e.type,this,new vs(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return e.getEventType()===`cancel`?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(t){return t instanceof e?this.eventType===t.eventType&&(!this.callbackContext||!t.callbackContext||this.callbackContext.matches(t.callbackContext)):!1}hasAnyCallback(){return!!this.callbackContext}};function Es(e,t,n,r,i){let a;if(typeof r==`object`&&(a=void 0,i=r),typeof r==`function`&&(a=r),i&&i.onlyOnce){let t=n,r=(n,r)=>{Go(e._repo,e,s),t(n,r)};r.userCallback=n.userCallback,r.context=n.context,n=r}let o=new ms(n,a||void 0),s=t===`value`?new ws(o):new Ts(t,o);return Wo(e._repo,e,s),()=>Go(e._repo,e,s)}function Ds(e,t,n,r){return Es(e,`value`,t,n,r)}Xi(_s),la(_s);var Os=`FIREBASE_DATABASE_EMULATOR_HOST`,ks={},As=!1;function js(e,t,n,r){let i=t.lastIndexOf(`:`);e.repoInfo_=new mt(t,ee(t.substring(0,i)),e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0,n),r&&(e.authTokenProvider_=r)}function Ms(e,t,n,r,i){let a=r||e.options.databaseURL;a===void 0&&(e.options.projectId||x(`Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp().`),b(`Using default host for project `,e.options.projectId),a=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o=cs(a,i),s=o.repoInfo,c,l;typeof process<`u`&&(l={}[Os]),l?(c=!0,a=`http://${l}?ns=${s.namespace}`,o=cs(a,i),s=o.repoInfo):c=!o.repoInfo.secure;let u=i&&c?new nt(nt.OWNER):new tt(e.name,e.options,t);return xo(`Invalid Firebase Database URL`,o),N(o.path)||x(`Database URL must point to the root of a Firebase Database (not including a child path).`),new Fs(Ps(s,e,u,new et(e,n)),e)}function Ns(e,t){let n=ks[t];(!n||n[e.key]!==e)&&x(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Ko(e),delete n[e.key]}function Ps(e,t,n,r){let i=ks[t.name];i||(i={},ks[t.name]=i);let a=i[e.toURLString()];return a&&x(`Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.`),a=new ko(e,As,n,r),i[e.toURLString()]=a,a}var Fs=class{constructor(e,t){this._repoInternal=e,this.app=t,this.type=`database`,this._instanceStarted=!1}get _repo(){return this._instanceStarted||=(Ao(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),!0),this._repoInternal}get _root(){return this._rootInternal||=new _s(this._repo,O()),this._rootInternal}_delete(){return this._rootInternal!==null&&(Ns(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&x(`Cannot call `+e+` on a deleted database.`)}};function Is(e=ge(),t){let n=de(e,`database`).getImmediate({identifier:t});if(!n._instanceStarted){let e=a(`database`);e&&Ls(n,...e)}return n}function Ls(e,n,r,i={}){e=v(e),e._checkNotDeleted(`useEmulator`);let a=`${n}:${r}`,o=e._repoInternal;if(e._instanceStarted){if(a===e._repoInternal.repoInfo_.host&&s(i,o.repoInfo_.emulatorOptions))return;x(`connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.`)}let c;o.repoInfo_.nodeAdmin?(i.mockUserToken&&x(`mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".`),c=new nt(nt.OWNER)):i.mockUserToken&&(c=new nt(typeof i.mockUserToken==`string`?i.mockUserToken:t(i.mockUserToken,e.app.options.projectId))),ee(n)&&he(n),js(o,a,i,c)}function Rs(e){xe(le),ae(new _e(`database`,(e,{instanceIdentifier:t})=>Ms(e.getProvider(`app`).getImmediate(),e.getProvider(`auth-internal`),e.getProvider(`app-check-internal`),t),`PUBLIC`).setMultipleInstances(!0)),pe(ve,ye,e),pe(ve,ye,`esm2020`)}On.prototype.simpleListen=function(e,t){this.sendRequest(`q`,{p:e},t)},On.prototype.echo=function(e,t){this.sendRequest(`echo`,{d:e},t)},Rs();export{$ as child,Is as getDatabase,bs as onDisconnect,Ds as onValue,xs as push,ys as ref,Ss as remove,Cs as set};
@@ -0,0 +1 @@
1
+ import{d as e,f as t,p as n}from"./index.esm-B3ZTr43m.js";n(`firebase`,`12.15.0`,`app`);export{e as getApps,t as initializeApp};